Programs & Examples On #Gb2312

How to deal with SettingWithCopyWarning in Pandas

You could avoid the whole problem like this, I believe:

return (
    pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64}
    .rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True)
    .ix[:,[0,3,2,1,4,5,8,9,30,31]]
    .assign(
        TClose=lambda df: df['TPrice'],
        RT=lambda df: 100 * (df['TPrice']/quote_df['TPCLOSE'] - 1),
        TVol=lambda df: df['TVol']/TVOL_SCALE,
        TAmt=lambda df: df['TAmt']/TAMT_SCALE,
        STK_ID=lambda df: df['STK'].str.slice(13,19),
        STK_Name=lambda df: df['STK'].str.slice(21,30)#.decode('gb2312'),
        TDate=lambda df: df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10]),
    )
)

Using Assign. From the documentation: Assign new columns to a DataFrame, returning a new object (a copy) with all the original columns in addition to the new ones.

See Tom Augspurger's article on method chaining in pandas: https://tomaugspurger.github.io/method-chaining

Regular Expressions: Is there an AND operator?

Look at this example:

We have 2 regexps A and B and we want to match both of them, so in pseudo-code it looks like this:

pattern = "/A AND B/"

It can be written without using the AND operator like this:

pattern = "/NOT (NOT A OR NOT B)/"

in PCRE:

"/(^(^A|^B))/"

regexp_match(pattern,data)

What does "select count(1) from table_name" on any database tables mean?

This is similar to the difference between

SELECT * FROM table_name and SELECT 1 FROM table_name.  

If you do

SELECT 1 FROM table_name

it will give you the number 1 for each row in the table. So yes count(*) and count(1) will provide the same results as will count(8) or count(column_name)

How to implement a binary search tree in Python?

The problem, or at least one problem with your code is here:-

def insert(self,node,someNumber):
    if node is None:
        node = Node(someNumber)
    else:
        if node.data > someNumber:
            self.insert(node.rchild,someNumber)
        else:
            self.insert(node.rchild, someNumber)
    return

You see the statement "if node.data > someNumber:" and the associated "else:" statement both have the same code after them. i.e you do the same thing whether the if statement is true or false.

I'd suggest you probably intended to do different things here, perhaps one of these should say self.insert(node.lchild, someNumber) ?

Passing javascript variable to html textbox

Pass the variable to the form element like this

your form element

<input type="text" id="mytext">

javascript

var test = "Hello";
document.getElementById("mytext").value = test;//Now you get the js variable inside your form element

How to make HTTP Post request with JSON body in Swift

Swift4 - Apple Solution "POST" and "Codable"

Uploading Data to a Website using request.httpmethod = "Post" and Codable Stucts:

@see: Listing 2 Configuring a URL request

let userlogin = User(username: username, password: password, deviceid:UIDevice.current.identifierForVendor!.uuidString)

    guard let uploadData = try? JSONEncoder().encode(userlogin) else {
        print("Error UploadData: ")
        return
    }

    let urlUser = URL(string: APPURL.apiURL)!

    var request = URLRequest(url: urlUser)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    var responseStatus = 0

    let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
        if let error = error {
            let code = (error as NSError).code
            print("Error:\(code) : \(error.localizedDescription)")
            completion(code)
            return
        }  
      guard let response = response as? HTTPURLResponse else {
            print("Invalid response")
            return
        }
// do your response handling here ...

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

The way you can exclude a destination directory while using the /mir is by making sure the destination directory also exists on the source. I went into my source drive and created blank directories with the same name as on the destination, and then added that directory name to the /xd. It successfully mirrored everything while excluding the directory on the source, thereby leaving the directory on the destination intact.

C++: Where to initialize variables in constructor

Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.

What is the difference between `new Object()` and object literal notation?

Also, according to some of the O'Really javascript books....(quoted)

Another reason for using literals as opposed to the Object constructor is that there is no scope resolution. Because it’s possible that you have created a local constructor with the same name, the interpreter needs to look up the scope chain from the place you are calling Object() all the way up until it finds the global Object constructor.

Printing string variable in Java

input.next();
String s = input.toString();

change it to

String s = input.next();

May be that's what you were trying to do.

Getting session value in javascript

For me this code worked in JavaScript like a charm!

<%= session.getAttribute("variableName")%>

hope it helps...

using OR and NOT in solr query

Instead of "NOT [condition]" use "(*:* NOT [condition])"

Looping over arrays, printing both index and value

INDEX=0
for i in $list; do 
    echo ${INDEX}_$i
    let INDEX=${INDEX}+1
done

How to launch an Activity from another Application in Android

I found the solution. In the manifest file of the application I found the package name: com.package.address and the name of the main activity which I want to launch: MainActivity The following code starts this application:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.package.address","com.package.address.MainActivity"));
startActivity(intent);

How to insert text at beginning of a multi-line selection in vi/Vim

In case someone's multi-line-selection is actually a paragraph, there is no need to manually select the lines. vim can do that for you:

  1. vip: select and mark the whole paragraph
  2. shift-i: insert text at line beginning
  3. escape: leave insert mode/enter normal mode [line beginnings still selected]
  4. escape: unselect line beginnings

Re-doing a reverted merge in Git

Instead of using git-revert you could have used this command in the devel branch to throw away (undo) the wrong merge commit (instead of just reverting it).

git checkout devel
git reset --hard COMMIT_BEFORE_WRONG_MERGE

This will also adjust the contents of the working directory accordingly. Be careful:

  • Save your changes in the develop branch (since the wrong merge) because they too will be erased by the git-reset. All commits after the one you specify as the git reset argument will be gone!
  • Also, don't do this if your changes were already pulled from other repositories because the reset will rewrite history.

I recommend to study the git-reset man-page carefully before trying this.

Now, after the reset you can re-apply your changes in devel and then do

git checkout devel
git merge 28s

This will be a real merge from 28s into devel like the initial one (which is now erased from git's history).

jQuery make global variable

You can avoid declaration of global variables by adding them directly to the global object:

(function(global) {

  ...

  global.varName = someValue;

  ...

}(this));

A disadvantage of this method is that global.varName won't exist until that specific line of code is executed, but that can be easily worked around.

You might also consider an application architecture where such globals are held in a closure common to all functions that need them, or as properties of a suitably accessible data storage object.

Jenkins returned status code 128 with github

To check are the following:

  1. if the right public key (id_rsa.pub) is uploaded to the git-server.
  2. if the right private key (id_rsa) is copied to /var/lib/jenkins/.ssh/
  3. if the known_hosts file is created inside ~/.ssh folder. Try ssh -vvv [email protected] to see debug logs. If thing goes well, github.com will be added to known_hosts.
  4. if the permission of id_rsa is set to 700 (chmod 700 id_rsa)

After all checks, try ssh -vvv [email protected].

repaint() in Java

Simply write :

frame.validate();
frame.repaint();

That will do .

Regards

C# Interfaces. Implicit implementation versus Explicit implementation

Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.

Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.

  1. By working directly with the interface, you are not acknowledging, and coupling your code to the underlying implementation.
  2. In the event that you already have, say, a public property Name in your code and you want to implement an interface that also has a Name property, doing it explicitly will keep the two separate. Even if they were doing the same thing I'd still delegate the explicit call to the Name property. You never know, you may want to change how Name works for the normal class and how Name, the interface property works later on.
  3. If you implement an interface implicitly then your class now exposes new behaviours that might only be relevant to a client of the interface and it means you aren't keeping your classes succinct enough (my opinion).

Cleanest way to build an SQL string in Java

I have been working on a Java servlet application that needs to construct very dynamic SQL statements for adhoc reporting purposes. The basic function of the app is to feed a bunch of named HTTP request parameters into a pre-coded query, and generate a nicely formatted table of output. I used Spring MVC and the dependency injection framework to store all of my SQL queries in XML files and load them into the reporting application, along with the table formatting information. Eventually, the reporting requirements became more complicated than the capabilities of the existing parameter mapping frameworks and I had to write my own. It was an interesting exercise in development and produced a framework for parameter mapping much more robust than anything else I could find.

The new parameter mappings looked as such:

select app.name as "App", 
       ${optional(" app.owner as "Owner", "):showOwner}
       sv.name as "Server", sum(act.trans_ct) as "Trans"
  from activity_records act, servers sv, applications app
 where act.server_id = sv.id
   and act.app_id = app.id
   and sv.id = ${integer(0,50):serverId}
   and app.id in ${integerList(50):appId}
 group by app.name, ${optional(" app.owner, "):showOwner} sv.name
 order by app.name, sv.name

The beauty of the resulting framework was that it could process HTTP request parameters directly into the query with proper type checking and limit checking. No extra mappings required for input validation. In the example query above, the parameter named serverId would be checked to make sure it could cast to an integer and was in the range of 0-50. The parameter appId would be processed as an array of integers, with a length limit of 50. If the field showOwner is present and set to "true", the bits of SQL in the quotes will be added to the generated query for the optional field mappings. field Several more parameter type mappings are available including optional segments of SQL with further parameter mappings. It allows for as complex of a query mapping as the developer can come up with. It even has controls in the report configuration to determine whether a given query will have the final mappings via a PreparedStatement or simply ran as a pre-built query.

For the sample Http request values:

showOwner: true
serverId: 20
appId: 1,2,3,5,7,11,13

It would produce the following SQL:

select app.name as "App", 
       app.owner as "Owner", 
       sv.name as "Server", sum(act.trans_ct) as "Trans"
  from activity_records act, servers sv, applications app
 where act.server_id = sv.id
   and act.app_id = app.id
   and sv.id = 20
   and app.id in (1,2,3,5,7,11,13)
 group by app.name,  app.owner,  sv.name
 order by app.name, sv.name

I really think that Spring or Hibernate or one of those frameworks should offer a more robust mapping mechanism that verifies types, allows for complex data types like arrays and other such features. I wrote my engine for only my purposes, it isn't quite read for general release. It only works with Oracle queries at the moment and all of the code belongs to a big corporation. Someday I may take my ideas and build a new open source framework, but I'm hoping one of the existing big players will take up the challenge.

How to compare LocalDate instances Java 8

Using equals() LocalDate does override equals:

int compareTo0(LocalDate otherDate) {
    int cmp = (year - otherDate.year);
    if (cmp == 0) {
        cmp = (month - otherDate.month);
        if (cmp == 0) {
            cmp = (day - otherDate.day);
        }
    }
    return cmp;
}

If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

Multiple Python versions on the same machine?

Package Managers - user-level

For a package manager that can install and manage multiple versions of python, these are good choices:

  • pyenv - only able to install and manage versions of python
  • asdf - able to install and manage many different languages

The advantages to these package managers is that it may be easier to set them up and install multiple versions of python with them than it is to install python from source. They also provide commands for easily changing the available python version(s) using shims and setting the python version per-directory.

This disadvantage is that, by default, they are installed at the user-level (inside your home directory) and require a little bit of user-level configuration - you'll need to edit your ~/.profile and ~/.bashrc or similar files. This means that it is not easy to use them to install multiple python versions globally for all users. In order to do this, you can install from source alongside the OS's existing python version.


Installation from source - system-wide

You'll need root privileges for this method.

See the official python documentation for building from source for additional considerations and options.

/usr/local is the designated location for a system administrator to install shared (system-wide) software, so it's subdirectories are a good place to download the python source and install. See section 4.9 of the Linux Foundation's File Hierarchy Standard.

Install any build dependencies. On Debian-based systems, use:

apt update
apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libsqlite3-dev libreadline-dev libffi-dev libbz2-dev

Choose which python version you want to install. See the Python Source Releases page for a listing.

Download and unzip file in /usr/local/src, replacing X.X.X below with the python version (i.e. 3.8.2).

cd /usr/local/src
wget https://www.python.org/ftp/python/X.X.X/Python-X.X.X.tgz
tar vzxf Python-X.X.X.tgz

Before building and installing, set the CFLAGS environment variable with C compiler flags necessary (see GNU's make documentation). This is usually not necessary for general use, but if, for example, you were going to create a uWSGI plugin with this python version, you might want to set the flags, -fPIC, with the following:

export CFLAGS='-fPIC'

Change the working directory to the unzipped python source directory, and configure the build. You'll probably want to use the --enable-optimizations option on the ./configure command for profile guided optimization. Use --prefix=/usr/local to install to the proper subdirectories (/usr/local/bin, /usr/local/lib, etc.).

cd Python-X.X.X
./configure --enable-optimizations --prefix=/usr/local

Build the project with make and install with make altinstall to avoid overriding any files when installing multiple versions. See the warning on this page of the python build documentation.

make -j 4
make altinstall

Then you should be able to run your new python and pip versions with pythonX.X and pipX.X (i.e python3.8 and pip3.8). Note that if the minor version of your new installation is the same as the OS's version (for example if you were installing python3.8.4 and the OS used python3.8.2), then you would need to specify the entire path (/usr/local/bin/pythonX.X) or set an alias to use this version.

What is the difference between prefix and postfix operators?

First, note that the function parameter named i and the variable named i in main() are two different variables. I think that doesn't matter that much to the present discussion, but it's important to know.

Second, you use the postincrement operator in fun(). That means the result of the expression is the value before i is incremented; the final value 11 of i is simply discarded, and the function returns 10. The variable i back in main, being a different variable, is assigned the value 10, which you then decrement to get 9.

PHP convert string to hex and hex to string

You can try the following code to convert the image to hex string

<?php
$image = 'sample.bmp';
$file = fopen($image, 'r') or die("Could not open $image");
while ($file && !feof($file)){
$chunk = fread($file, 1000000); # You can affect performance altering
this number. YMMV.
# This loop will be dog-slow, almost for sure...
# You could snag two or three bytes and shift/add them,
# but at 4 bytes, you violate the 7fffffff limit of dechex...
# You could maybe write a better dechex that would accept multiple bytes
# and use substr... Maybe.
for ($byte = 0; $byte < strlen($chunk); $byte++)){
echo dechex(ord($chunk[$byte]));
}
}
?>

I want to show all tables that have specified column name

SELECT      T.TABLE_NAME, C.COLUMN_NAME
FROM        INFORMATION_SCHEMA.COLUMNS C
            INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME = C.TABLE_NAME
WHERE       TABLE_TYPE = 'BASE TABLE'
            AND COLUMN_NAME = 'ColName'

This returns tables only and ignores views for anyone who is interested!

Difference between classification and clustering in data mining?

There are two definitions in data mining "Supervised" and "Unsupervised". When someone tells the computer, algorithm, code, ... that this thing is like an apple and that thing is like an orange, this is supervised learning and using supervised learning (like tags for each sample in a data set) for classifying the data, you'll get classification. But on the other hand if you let the computer find out what is what and differentiate between features of the given data set, in fact learning unsupervised, for classifying the data set this would be called clustering. In this case data that are fed to the algorithm don't have tags and the algorithm should find out different classes.

Solving Quadratic Equation

one liner solve quadratic equation

from math import sqrt
s = lambda a,b,c: {(-b-sqrt(d))/2*a,(-b+sqrt(d))/2*a} if (d:=b**2-4*a*c)>=0 else {}
roots_set = s(int(input('a=')),int(input('b=')),int(input('c=')))
print(roots_set,f'number of roots {len(roots_set)}')

one line python solve quadratic equations video

How do I find Waldo with Mathematica?

My guess at a "bulletproof way to do this" (think CIA finding Waldo in any satellite image any time, not just a single image without competing elements, like striped shirts)... I would train a Boltzmann machine on many images of Waldo - all variations of him sitting, standing, occluded, etc.; shirt, hat, camera, and all the works. You don't need a large corpus of Waldos (maybe 3-5 will be enough), but the more the better.

This will assign clouds of probabilities to various elements occurring in whatever the correct arrangement, and then establish (via segmentation) what an average object size is, fragment the source image into cells of objects which most resemble individual people (considering possible occlusions and pose changes), but since Waldo pictures usually include a LOT of people at about the same scale, this should be a very easy task, then feed these segments of the pre-trained Boltzmann machine. It will give you probability of each one being Waldo. Take one with the highest probability.

This is how OCR, ZIP code readers, and strokeless handwriting recognition work today. Basically you know the answer is there, you know more or less what it should look like, and everything else may have common elements, but is definitely "not it", so you don't bother with the "not it"s, you just look of the likelihood of "it" among all possible "it"s you've seen before" (in ZIP codes for example, you'd train BM for just 1s, just 2s, just 3s, etc., then feed each digit to each machine, and pick one that has most confidence). This works a lot better than a single neural network learning features of all numbers.

How do I find ' % ' with the LIKE operator in SQL Server?

You can use ESCAPE:

WHERE columnName LIKE '%\%%' ESCAPE '\'

Optional args in MATLAB functions

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?

Two decimal places using printf( )

Try using a format like %d.%02d

int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);

Another approach is to type cast it to double before printing it using %f like this:

printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);

My 2 cents :)

How to insert element into arrays at specific position?

array_slice() can be used to extract parts of the array, and the union array operator (+) can recombine the parts.

$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array)-3, true);

This example:

$array = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array) - 1, true) ;
print_r($res);

gives:

Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [my_key] => my_value
    [three] => 3
)

Using JQuery to check if no radio button in a group has been checked

Use .length refer to http://api.jquery.com/checked-selector/

if ($('input[name="html_elements"]:checked').length === 0) alert("Not checked");
else alert("Checked");

How to capitalize the first letter of a String in Java?

Existing answers are either

  • incorrect: they think that char is a separate character (code point), while it is a UTF-16 word which can be a half of a surrogate pair, or
  • use libraries which is not bad itself but requires adding dependencies to your project, or
  • use Java 8 Streams which is perfectly valid but not always possible.

Let's look at surrogate characters (every such character consist of two UTF-16 words — Java chars) and can have upper and lowercase variants:

IntStream.rangeClosed(0x01_0000, 0x10_FFFF)
    .filter(ch -> Character.toUpperCase(ch) != Character.toLowerCase(ch))
    .forEach(ch -> System.out.print(new String(new int[] { ch }, 0, 1)));

Many of them may look like 'tofu' (?) for you but they are mostly valid characters of rare scripts and some typefaces support them.

For example, let's look at Deseret Small Letter Long I (), U+10428, "\uD801\uDC28":

System.out.println("U+" + Integer.toHexString(
        "\uD801\uDC28".codePointAt(0)
)); // U+10428

System.out.println("U+" + Integer.toHexString(
        Character.toTitleCase("\uD801\uDC28".codePointAt(0))
)); // U+10400 — ok! capitalized character is another code point

System.out.println("U+" + Integer.toHexString(new String(new char[] {
        Character.toTitleCase("\uD801\uDC28".charAt(0)), "\uD801\uDC28".charAt(1)
}).codePointAt(0))); // U+10428 — oops! — cannot capitalize an unpaired surrogate

So, a code point can be capitalized even in cases when char cannot be. Considering this, let's write a correct (and Java 1.5 compatible!) capitalizer:

@Contract("null -> null")
public static CharSequence capitalize(CharSequence input) {
    int length;
    if (input == null || (length = input.length()) == 0) return input;

    return new StringBuilder(length)
            .appendCodePoint(Character.toTitleCase(Character.codePointAt(input, 0)))
            .append(input, Character.offsetByCodePoints(input, 0, 1), length);
}

And check whether it works:

public static void main(String[] args) {
    // ASCII
    System.out.println(capitalize("whatever")); // w -> W

    // UTF-16, no surrogate
    System.out.println(capitalize("???-??")); // ? -> ?

    // UTF-16 with surrogate pairs
    System.out.println(capitalize("\uD801\uDC28")); //  -> 
}

See also:

How can I insert into a BLOB column from an insert statement in sqldeveloper?

  1. insert into mytable(id, myblob) values (1,EMPTY_BLOB);
  2. SELECT * FROM mytable mt where mt.id=1 for update
  3. Click on the Lock icon to unlock for editing
  4. Click on the ... next to the BLOB to edit
  5. Select the appropriate tab and click open on the top left.
  6. Click OK and commit the changes.

How do you append to a file?

Here's my script, which basically counts the number of lines, then appends, then counts them again so you have evidence it worked.

shortPath  = "../file_to_be_appended"
short = open(shortPath, 'r')

## this counts how many line are originally in the file:
long_path = "../file_to_be_appended_to" 
long = open(long_path, 'r')
for i,l in enumerate(long): 
    pass
print "%s has %i lines initially" %(long_path,i)
long.close()

long = open(long_path, 'a') ## now open long file to append
l = True ## will be a line
c = 0 ## count the number of lines you write
while l: 
    try: 
        l = short.next() ## when you run out of lines, this breaks and the except statement is run
        c += 1
        long.write(l)

    except: 
        l = None
        long.close()
        print "Done!, wrote %s lines" %c 

## finally, count how many lines are left. 
long = open(long_path, 'r')
for i,l in enumerate(long): 
    pass
print "%s has %i lines after appending new lines" %(long_path, i)
long.close()

How to delete session cookie in Postman?

new version of postman app has the ability to do that programmatically in pre-request or tests scripts since 2019/08

see more examples here: Delete cookies programmatically · Issue #3312 · postmanlabs/postman-app-support

clear all cookies

const jar = pm.cookies.jar();

jar.clear(pm.request.url, function (error) {
  // error - <Error>
});

get all cookies

const jar = pm.cookies.jar();

jar.getAll('http://example.com', function (error, cookies) {
  // error - <Error>
  // cookies - <PostmanCookieList>
  // PostmanCookieList: https://www.postmanlabs.com/postman-collection/CookieList.html
});

get specific cookie

const jar = pm.cookies.jar();

jar.get('http://example.com', 'token', function (error, value) {
  // error - <Error>
  // value - <String>
});

multiple plot in one figure in Python

EDIT: I just realised after reading your question again, that i did not answer your question. You want to enter multiple lines in the same plot. However, I'll leave it be, because this served me very well multiple times. I hope you find usefull someday

I found this a while back when learning python

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure() 
# create figure window

gs = gridspec.GridSpec(a, b)
# Creates grid 'gs' of a rows and b columns 


ax = plt.subplot(gs[x, y])
# Adds subplot 'ax' in grid 'gs' at position [x,y]


ax.set_ylabel('Foo') #Add y-axis label 'Foo' to graph 'ax' (xlabel for x-axis)


fig.add_subplot(ax) #add 'ax' to figure

you can make different sizes in one figure as well, use slices in that case:

 gs = gridspec.GridSpec(3, 3)
 ax1 = plt.subplot(gs[0,:]) # row 0 (top) spans all(3) columns

consult the docs for more help and examples. This little bit i typed up for myself once, and is very much based/copied from the docs as well. Hope it helps... I remember it being a pain in the #$% to get acquainted with the slice notation for the different sized plots in one figure. After that i think it's very simple :)

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

Word-wrap in an HTML table

As mentioned, putting the text within div almost works. You just have to specify the width of the div, which is fortunate for layouts which are static.

This works on FF 3.6, IE 8, Chrome.

<td>
  <div style="width: 442px; word-wrap: break-word">
    <!-- Long Content Here-->
  </div>
</td>

'AND' vs '&&' as operator

which version are you using?

If the coding standards for the particular codebase I am writing code for specifies which operator should be used, I'll definitely use that. If not, and the code dictates which should be used (not often, can be easily worked around) then I'll use that. Otherwise, probably &&.

Is 'and' more readable than '&&'?

Is it more readable to you. The answer is yes and no depending on many factors including the code around the operator and indeed the person reading it!

|| there is ~ difference?

Yes. See logical operators for || and bitwise operators for ~.

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

if [ ! -z "$var" ] && [ -e "$var" ]; then
      # something ...
fi

PHP pass variable to include

OPTION 1 worked for me, in PHP 7, and for sure it does in PHP 5 too. And the global scope declaration is not necessary for the included file for variables access, the included - or "required" - files are part of the script, only be sure you make the "include" AFTER the variable declaration. Maybe you have some misconfiguration with variables global scope in your PHP.ini?

Try in first file:

  <?php 
  $myvariable="from first file";
  include ("./mysecondfile.php"); // in same folder as first file LOLL
  ?>

mysecondfile.php

  <?php 
  echo "this is my variable ". $myvariable;
  ?>

It should work... if it doesn't just try to reinstall PHP.

Where are shared preferences stored?

Use http://facebook.github.io/stetho/ library to access your app's local storage with chrome inspect tools. You can find sharedPreference file under Local storage -> < your app's package name >

enter image description here

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Not best answer but you can reuse an already created ca bundle using --cert option of pip, for instance:

pip install SQLAlchemy==1.1.15 --cert="C:\Users\myUser\certificates\my_ca-bundle.crt"

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

Getting CheckBoxList Item values

Try to use this :

 private void button1_Click(object sender, EventArgs e)
    {

        for (int i = 0; i < chBoxListTables.Items.Count; i++)
            if (chBoxListTables.GetItemCheckState(i) == CheckState.Checked)
            {
               txtBx.text += chBoxListTables.Items[i].ToString() + " \n"; 

            }
    }

How can I Convert HTML to Text in C#?

This is another solution to convert HTML to Text or RTF in C#:

    SautinSoft.HtmlToRtf h = new SautinSoft.HtmlToRtf();
    h.OutputFormat = HtmlToRtf.eOutputFormat.TextUnicode;
    string text = h.ConvertString(htmlString);

This library is not free, this is commercial product and it is my own product.

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

See if this helps. I can set variables for Elapsed Days, Hours, Minutes, Seconds. You can format this to your liking or include in a user defined function.

Note: Don't use DateDiff(hh,@Date1,@Date2). It is not reliable! It rounds in unpredictable ways

Given two dates... (Sample Dates: two days, three hours, 10 minutes, 30 seconds difference)

declare @Date1 datetime = '2013-03-08 08:00:00'
declare @Date2 datetime = '2013-03-10 11:10:30'
declare @Days decimal
declare @Hours decimal
declare @Minutes decimal
declare @Seconds decimal

select @Days = DATEDIFF(ss,@Date1,@Date2)/60/60/24 --Days
declare @RemainderDate as datetime = @Date2 - @Days
select @Hours = datediff(ss, @Date1, @RemainderDate)/60/60 --Hours
set @RemainderDate = @RemainderDate - (@Hours/24.0)
select @Minutes = datediff(ss, @Date1, @RemainderDate)/60 --Minutes
set @RemainderDate = @RemainderDate - (@Minutes/24.0/60)
select @Seconds = DATEDIFF(SS, @Date1, @RemainderDate)    
select @Days as ElapsedDays, @Hours as ElapsedHours, @Minutes as ElapsedMinutes, @Seconds as ElapsedSeconds

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

How to populate options of h:selectOneMenu from database?

Roll-your-own generic converter for complex objects as selected item

The Balusc gives a very useful overview answer on this subject. But there is one alternative he does not present: The Roll-your-own generic converter that handles complex objects as the selected item. This is very complex to do if you want to handle all cases, but pretty simple for simple cases.

The code below contains an example of such a converter. It works in the same spirit as the OmniFaces SelectItemsConverter as it looks through the children of a component for UISelectItem(s) containing objects. The difference is that it only handles bindings to either simple collections of entity objects, or to strings. It does not handle item groups, collections of SelectItems, arrays and probably a lot of other things.

The entities that the component binds to must implement the IdObject interface. (This could be solved in other way, such as using toString.)

Note that the entities must implement equals in such a way that two entities with the same ID compares equal.

The only thing that you need to do to use it is to specify it as converter on the select component, bind to an entity property and a list of possible entities:

<h:selectOneMenu value="#{bean.user}" converter="selectListConverter">
  <f:selectItem itemValue="unselected" itemLabel="Select user..."/>
  <f:selectItem itemValue="empty" itemLabel="No user"/>
  <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

Converter:

/**
 * A converter for select components (those that have select items as children).
 * 
 * It convertes the selected value string into one of its element entities, thus allowing
 * binding to complex objects.
 * 
 * It only handles simple uses of select components, in which the value is a simple list of
 * entities. No ItemGroups, arrays or other kinds of values.
 * 
 * Items it binds to can be strings or implementations of the {@link IdObject} interface.
 */
@FacesConverter("selectListConverter")
public class SelectListConverter implements Converter {

  public static interface IdObject {
    public String getDisplayId();
  }

  @Override
  public Object getAsObject(FacesContext context, UIComponent component, String value) {
    if (value == null || value.isEmpty()) {
      return null;
    }

    return component.getChildren().stream()
      .flatMap(child -> getEntriesOfItem(child))
      .filter(o -> value.equals(o instanceof IdObject ? ((IdObject) o).getDisplayId() : o))
      .findAny().orElse(null);
  }

  /**
   * Gets the values stored in a {@link UISelectItem} or a {@link UISelectItems}.
   * For other components returns an empty stream.
   */
  private Stream<?> getEntriesOfItem(UIComponent child) {
    if (child instanceof UISelectItem) {
      UISelectItem item = (UISelectItem) child;
      if (!item.isNoSelectionOption()) {
        return Stream.of(item.getValue());
      }

    } else if (child instanceof UISelectItems) {
      Object value = ((UISelectItems) child).getValue();

      if (value instanceof Collection) {
        return ((Collection<?>) value).stream();
      } else {
        throw new IllegalStateException("Unsupported value of UISelectItems: " + value);
      }
    }

    return Stream.empty();
  }

  @Override
  public String getAsString(FacesContext context, UIComponent component, Object value) {
    if (value == null) return null;
    if (value instanceof String) return (String) value;
    if (value instanceof IdObject) return ((IdObject) value).getDisplayId();

    throw new IllegalArgumentException("Unexpected value type");
  }

}

SVN how to resolve new tree conflicts when file is added on two branches

What if the incoming changes are the ones you want? I'm unable to run svn resolve --accept theirs-full

svn resolve --accept base

Regex for string contains?

I'm a few years late, but why not this?

[Tt][Ee][Ss][Tt]

select into in mysql

In MySQL, It should be like this

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

MySQL Documentation

Class name does not name a type in C++

Include "B.h" in "A.h". That brings in the declaration of 'B' for the compiler while compiling 'A'.

The first bullet holds in the case of OP.

$3.4.1/7 -

"A name used in the definition of a class X outside of a member function body or nested class definition27) shall be declared in one of the following ways:

before its use in class X or be a member of a base class of X (10.2), or

— if X is a nested class of class Y (9.7), before the definition of X in Y, or shall be a member of a base class of Y (this lookup applies in turn to Y’s enclosing classes, starting with the innermost enclosing class),28) or

— if X is a local class (9.8) or is a nested class of a local class, before the definition of class X in a block enclosing the definition of class X, or

— if X is a member of namespace N, or is a nested class of a class that is a member of N, or is a local class or a nested class within a local class of a function that is a member of N, before the definition of class X in namespace N or in one of N’s enclosing namespaces."

HighCharts Hide Series Name from the Legend

Looks like HighChart 2.2.0 has resolved this issue. I tried it here with the same code you have, and the first series is hidden now. Could you try it with HighChart 2.2.0?

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

How to send email attachments?

Here is the modified version from Oli for python 3

import smtplib
from pathlib import Path
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders


def send_mail(send_from, send_to, subject, message, files=[],
              server="localhost", port=587, username='', password='',
              use_tls=True):
    """Compose and send email with provided info and attachments.

    Args:
        send_from (str): from name
        send_to (list[str]): to name(s)
        subject (str): message title
        message (str): message body
        files (list[str]): list of file paths to be attached to email
        server (str): mail server host name
        port (int): port number
        username (str): server auth username
        password (str): server auth password
        use_tls (bool): use TLS mode
    """
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(message))

    for path in files:
        part = MIMEBase('application', "octet-stream")
        with open(path, 'rb') as file:
            part.set_payload(file.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="{}"'.format(Path(path).name))
        msg.attach(part)

    smtp = smtplib.SMTP(server, port)
    if use_tls:
        smtp.starttls()
    smtp.login(username, password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit()

How to extend / inherit components?

As far as I know component inheritance has not been implemented yet in Angular 2 and I'm not sure if they have plans to, however since Angular 2 is using typescript (if you've decided to go that route) you can use class inheritance by doing class MyClass extends OtherClass { ... }. For component inheritance I'd suggest getting involved with the Angular 2 project by going to https://github.com/angular/angular/issues and submitting a feature request!

change cursor from block or rectangle to line?

You're in replace mode. Press the Insert key on your keyboard to switch back to insert mode. Many applications that handle text have this in common.

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

How to convert std::string to lower case?

std::ctype::tolower() from the standard C++ Localization library will correctly do this for you. Here is an example extracted from the tolower reference page

#include <locale>
#include <iostream>

int main () {
  std::locale::global(std::locale("en_US.utf8"));
  std::wcout.imbue(std::locale());
  std::wcout << "In US English UTF-8 locale:\n";
  auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());
  std::wstring str = L"HELLo, wORLD!";
  std::wcout << "Lowercase form of the string '" << str << "' is ";
  f.tolower(&str[0], &str[0] + str.size());
  std::wcout << "'" << str << "'\n";
}

How to get first 5 characters from string

Use substr():

$result = substr($myStr, 0, 5);

decompiling DEX into Java sourcecode

Since no one mentioned this, there's one more tool: DED homepage

Install how-to and some explanations: Installation.

It was used in a quite interesting study of the security of top market apps(not really related, just if you're curious): A Survey of Android Application Security

jQuery AutoComplete Trigger Change Event

Well it works for me just binding a keypress event to the search input, like this:

... Instantiate your autofill here...

    $("#CompanyList").bind("keypress", function(){
    if (nowDoing==1) {
        nowDoing = 0;
        $('#form_459174').clearForm();
    }        
});

How can I center <ul> <li> into div

<div id="container">
  <table width="100%" height="100%">
    <tr>
      <td align="center" valign="middle">
        <ul>
          <li>item 1</li>
          <li>item 2</li>
          <li>item 3</li>
        </ul>
      </td>
    </tr>
  </table>
</div>

Using prepared statements with JDBCTemplate

Try the following:

PreparedStatementCreator creator = new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement updateSales = con.prepareStatement(
        "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
        updateSales.setInt(1, 75); 
        updateSales.setString(2, "Colombian"); 
        return updateSales;
    }
};

How do I convert an array object to a string in PowerShell?

1> $a = "This", "Is", "a", "cat"

2> [system.String]::Join(" ", $a)

Line two performs the operation and outputs to host, but does not modify $a:

3> $a = [system.String]::Join(" ", $a)

4> $a

This Is a cat

5> $a.Count

1

Best way to encode text data for XML in Java?

You could use the Enterprise Security API (ESAPI) library, which provides methods like encodeForXML and encodeForXMLAttribute. Take a look at the documentation of the Encoder interface; it also contains examples of how to create an instance of DefaultEncoder.

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

Try to update the below two parameters as they must be having default values.

innodb_lock_wait_timeout = 50

innodb_rollback_on_timeout = ON

For checking parameter value you can use the below SQL.

SHOW GLOBAL VARIABLES LIKE 'innodb_rollback_on_timeout';

Update data on a page without refreshing

In general, if you don't know how something works, look for an example which you can learn from.

For this problem, consider this DEMO

You can see loading content with AJAX is very easily accomplished with jQuery:

$(function(){
    // don't cache ajax or content won't be fresh
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";

    // load() functions
    var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
    $("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

// end  
});

Try to understand how this works and then try replicating it. Good luck.

You can find the corresponding tutorial HERE

Update

Right now the following event starts the ajax load function:

$("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

You can also do this periodically: How to fire AJAX request Periodically?

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);) the content is updated.

You can also just load the data immediately:

$("#result").html(ajax_load).load(loadUrl);

Which has THIS corresponding demo.

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

public static final String tryClob2String(final Object value)
{
    final Clob clobValue = (Clob) value;
    String result = null;

    try
    {
        final long clobLength = clobValue.length();

        if (clobLength < Integer.MIN_VALUE || clobLength > Integer.MAX_VALUE)
        {
            log.debug("CLOB size too big for String!");
        }
        else
        {
            result = clobValue.getSubString(1, (int) clobValue.length());
        }
    }
    catch (SQLException e)
    {
        log.error("tryClob2String ERROR: {}", e);
    }
    finally
    {
        if (clobValue != null)
        {
            try
            {
                clobValue.free();
            }
            catch (SQLException e)
            {
                log.error("CLOB FREE ERROR: {}", e);
            }
        }
    }

    return result;
}

Java: How to stop thread?

You can create a boolean field and check it inside run:

public class Task implements Runnable {

   private volatile boolean isRunning = true;

   public void run() {

     while (isRunning) {
         //do work
     }
   }

   public void kill() {
       isRunning = false;
   }

}

To stop it just call

task.kill();

This should work.

How to pass a null variable to a SQL Stored Procedure from C#.net code

You can pass the DBNull.Value into the parameter's .Value property:

    SqlParameters[0] = new SqlParameter("LedgerID", SqlDbType.BigInt );
    SqlParameters[0].Value = DBNull.Value;

Just adjust for your two DateTime parameters, obviously - just showing how to use the DBNull.Value property value here.

Marc

How to copy a string of std::string type in C++?

strcpy example:

#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]="Sample string" ;
  char str2[40] ;
  strcpy (str2,str1) ;
  printf ("str1: %s\n",str1) ;
  return 0 ;
}

Output: str1: Sample string

Your case:

A simple = operator should do the job.

string str1="Sample string" ;
string str2 = str1 ;

How to list the size of each file and directory and sort by descending size in Bash?

Command

du -h --max-depth=0 * | sort -hr

Output

3,5M    asdf.6000.gz
3,4M    asdf.4000.gz
3,2M    asdf.2000.gz
2,5M    xyz.PT.gz
136K    xyz.6000.gz
116K    xyz.6000p.gz
88K test.4000.gz
76K test.4000p.gz
44K test.2000.gz
8,0K    desc.common.tcl
8,0K    wer.2000p.gz
8,0K    wer.2000.gz
4,0K    ttree.3

Explanation

  • du displays "disk usage"
  • h is for "human readable" (both, in sort and in du)
  • max-depth=0 means du will not show sizes of subfolders (remove that if you want to show all sizes of every file in every sub-, subsub-, ..., folder)
  • r is for "reverse" (biggest file first)

ncdu

When I came to this question, I wanted to clean up my file system. The command line tool ncdu is way better suited to this task.

Installation on Ubuntu:

$ sudo apt-get install ncdu

Usage:

Just type ncdu [path] in the command line. After a few seconds for analyzing the path, you will see something like this:

$ ncdu 1.11 ~ Use the arrow keys to navigate, press ? for help
--- / ---------------------------------------------------------
.  96,1 GiB [##########] /home
.  17,7 GiB [#         ] /usr
.   4,5 GiB [          ] /var
    1,1 GiB [          ] /lib
  732,1 MiB [          ] /opt
. 275,6 MiB [          ] /boot
  198,0 MiB [          ] /storage
. 153,5 MiB [          ] /run
.  16,6 MiB [          ] /etc
   13,5 MiB [          ] /bin
   11,3 MiB [          ] /sbin
.   8,8 MiB [          ] /tmp
.   2,2 MiB [          ] /dev
!  16,0 KiB [          ] /lost+found
    8,0 KiB [          ] /media
    8,0 KiB [          ] /snap
    4,0 KiB [          ] /lib64
e   4,0 KiB [          ] /srv
!   4,0 KiB [          ] /root
e   4,0 KiB [          ] /mnt
e   4,0 KiB [          ] /cdrom
.   0,0   B [          ] /proc
.   0,0   B [          ] /sys
@   0,0   B [          ]  initrd.img.old
@   0,0   B [          ]  initrd.img
@   0,0   B [          ]  vmlinuz.old
@   0,0   B [          ]  vmlinuz

Delete the currently highlighted element with d, exit with CTRL + c

Apache won't run in xampp

In my case, it was something else. One day earlier I tried to install Magento using bitnami of xampp. And I deleted That Module

I opened the httpd.conf and found this line:

Include "C:/xampp/apps/magento/conf/httpd-prefix.conf"

I just commented it with #,

Now it's running fine. :)

Use of Finalize/Dispose method in C#

Pattern from msdn

public class BaseResource: IDisposable
{
   private IntPtr handle;
   private Component Components;
   private bool disposed = false;
   public BaseResource()
   {
   }
   public void Dispose()
   {
      Dispose(true);      
      GC.SuppressFinalize(this);
   }
   protected virtual void Dispose(bool disposing)
   {
      if(!this.disposed)
      {        
         if(disposing)
         {
            Components.Dispose();
         }         
         CloseHandle(handle);
         handle = IntPtr.Zero;
       }
      disposed = true;         
   }
   ~BaseResource()      
   {      Dispose(false);
   }
   public void DoSomething()
   {
      if(this.disposed)
      {
         throw new ObjectDisposedException();
      }
   }
}
public class MyResourceWrapper: BaseResource
{
   private ManagedResource addedManaged;
   private NativeResource addedNative;
   private bool disposed = false;
   public MyResourceWrapper()
   {
   }
   protected override void Dispose(bool disposing)
   {
      if(!this.disposed)
      {
         try
         {
            if(disposing)
            {             
               addedManaged.Dispose();         
            }
            CloseHandle(addedNative);
            this.disposed = true;
         }
         finally
         {
            base.Dispose(disposing);
         }
      }
   }
}

How to detect the swipe left or Right in Android?

this should help you maybe...

private final GestureDetector.SimpleOnGestureListener onGestureListener = new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onDoubleTap(MotionEvent e) {
        Log.i("gestureDebug333", "doubleTapped:" + e);
        return super.onDoubleTap(e);
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        Log.i("gestureDebug333", "doubleTappedEvent:" + e);

        return super.onDoubleTapEvent(e);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        Log.i("gestureDebug333", "onDown:" + e);


        return super.onDown(e);

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {


        Log.i("gestureDebug333", "flinged:" + e1 + "---" + e2);
        Log.i("gestureDebug333", "fling velocity:" + velocityX + "---" + velocityY);
        if (e1.getAction() == MotionEvent.ACTION_DOWN && e1.getX() > (e2.getX() + 300)){
           // Toast.makeText(context, "flinged right to left", Toast.LENGTH_SHORT).show();
            goForward();
        }
        if (e1.getAction() == MotionEvent.ACTION_DOWN && e2.getX() > (e1.getX() + 300)){
            //Toast.makeText(context, "flinged left to right", Toast.LENGTH_SHORT).show();
            goBack();
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public void onLongPress(MotionEvent e) {
        super.onLongPress(e);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    @Override
    public void onShowPress(MotionEvent e) {
        super.onShowPress(e);
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        return super.onSingleTapConfirmed(e);
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return super.onSingleTapUp(e);
    }
};

Get my phone number in android

From the documentation:

Returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.

So you have done everything right, but there is no phone number stored.

If you get null, you could display something to get the user to input the phone number on his/her own.

CKEditor automatically strips classes from div

Disabling content filtering

The easiest solution is going to the config.js and setting:

config.allowedContent = true;

(Remember to clear browser's cache). Then CKEditor stops filtering the inputted content at all. However, this will totally disable content filtering which is one of the most important CKEditor features.

Configuring content filtering

You can also configure CKEditor's content filter more precisely to allow only these element, classes, styles and attributes which you need. This solution is much better, because CKEditor will still remove a lot of crappy HTML which browsers produce when copying and pasting content, but it will not strip the content you want.

For example, you can extend the default CKEditor's configuration to accept all div classes:

config.extraAllowedContent = 'div(*)';

Or some Bootstrap stuff:

config.extraAllowedContent = 'div(col-md-*,container-fluid,row)';

Or you can allow description lists with optional dir attributes for dt and dd elements:

config.extraAllowedContent = 'dl; dt dd[dir]';

These were just very basic examples. You can write all kind of rules - requiring attributes, classes or styles, matching only special elements, matching all elements. You can also disallow stuff and totally redefine CKEditor's rules. Read more about:

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:

$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});

If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:

$.post('/url/to/page', {'someKeyName': ['value','value']});

If you want to pass a JavaScript array then you can do:

$.post('/url/to/page', {'someKeyName': variableName});

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

Eclipse JPA Project Change Event Handler (waiting)

I still have the same issue in Neon.2 My solution is to disable the JPA Configurator.

Open the Eclipse Preferences (not the project prefs!). Go to Maven --> Java EE Integration and disable the JPA Configurator. I also disabled the JAX-RS Configurator and the JSF Configurator.

From that point on the JPA Project Change Event Handler doesn't show up anymore.

Restart Eclipse if the change does not take effect immediately.

nodemon not found in npm

I got this issue while deploying on Heroku. The problem is on Heroku the don't include the devDependencies on its own. To fix this issue, simply run the command in the terminal:

heroku config:set NPM_CONFIG_PRODUCTION=false

Make sure to include nodemon in your devDependencies

"devDependencies": {
    "nodemon": "^2.0.6"
  }

Incase your error is not in Heroku

I would suggest uninstalling nodemon and then reinstalling it

https://www.npmjs.com/package/nodemon

Or try changing the script

"scripts": {
    "start": "nodemon fileName.js",
    "start:dev": "nodemon fileName.js"
 }

Hope it would help :)

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

Google reCAPTCHA: How to get user response and validate in the server side?

A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.

Check the success field for true or false

private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
    JsonObject jsonObject = null;
    URLConnection connection = null;
    InputStream is = null;
    String charset = java.nio.charset.StandardCharsets.UTF_8.name();

    String url = "https://www.google.com/recaptcha/api/siteverify";
    try {            
        String query = String.format("secret=%s&response=%s&remoteip=%s", 
        URLEncoder.encode(secret, charset), 
        URLEncoder.encode(response, charset),
        URLEncoder.encode(remoteip, charset));

        connection = new URL(url + "?" + query).openConnection();
        is = connection.getInputStream();
        JsonReader rdr = Json.createReader(is);
        jsonObject = rdr.readObject();

    } catch (IOException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }

        }
    }
    return jsonObject;
}

How to check if an element is visible with WebDriver

public boolean isElementFound( String text) {
        try{
            WebElement webElement = appiumDriver.findElement(By.xpath(text));
            System.out.println("isElementFound : true :"+text + "true");
        }catch(NoSuchElementException e){
            System.out.println("isElementFound : false :"+text);
            return false;
        }
        return true;
    }

    text is the xpath which you would be passing when calling the function.
the return value will be true if the element is present else false if element is not pressent

Print raw string from variable? (not getting the answers)

Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:

    test = 'C:\\Windows\Users\alexb\'
    rawtest = r'%s' %test

Java Serializable Object to Byte Array

Spring Framework org.springframework.util.SerializationUtils

byte[] data = SerializationUtils.serialize(obj);

How to replace all special character into a string using C#

Also, It can be done with LINQ

var str = "Hello@Hello&Hello(Hello)";
var characters = str.Select(c => char.IsLetter(c) ? c : ',')).ToArray();             
var output = new string(characters);
Console.WriteLine(output);

In git, what is the difference between merge --squash and rebase?

Both git merge --squash and git rebase --interactive can produce a "squashed" commit.
But they serve different purposes.

will produce a squashed commit on the destination branch, without marking any merge relationship.
(Note: it does not produce a commit right away: you need an additional git commit -m "squash branch")
This is useful if you want to throw away the source branch completely, going from (schema taken from SO question):

 git checkout stable

      X                   stable
     /                   
a---b---c---d---e---f---g tmp

to:

git merge --squash tmp
git commit -m "squash tmp"

      X-------------------G stable
     /                   
a---b---c---d---e---f---g tmp

and then deleting tmp branch.


Note: git merge has a --commit option, but it cannot be used with --squash. It was never possible to use --commit and --squash together.
Since Git 2.22.1 (Q3 2019), this incompatibility is made explicit:

See commit 1d14d0c (24 May 2019) by Vishal Verma (reloadbrain).
(Merged by Junio C Hamano -- gitster -- in commit 33f2790, 25 Jul 2019)

merge: refuse --commit with --squash

Previously, when --squash was supplied, 'option_commit' was silently dropped. This could have been surprising to a user who tried to override the no-commit behavior of squash using --commit explicitly.

git/git builtin/merge.c#cmd_merge() now includes:

if (option_commit > 0)
    die(_("You cannot combine --squash with --commit."));

replays some or all of your commits on a new base, allowing you to squash (or more recently "fix up", see this SO question), going directly to:

git checkout tmp
git rebase -i stable

      stable
      X-------------------G tmp
     /                     
a---b

If you choose to squash all commits of tmp (but, contrary to merge --squash, you can choose to replay some, and squashing others).

So the differences are:

  • squash does not touch your source branch (tmp here) and creates a single commit where you want.
  • rebase allows you to go on on the same source branch (still tmp) with:
    • a new base
    • a cleaner history

How can I make a float top with CSS?

The trick that worked for me was to change the writing-mode for the duration of the div-alignment.

_x000D_
_x000D_
.outer{  _x000D_
  /* Limit height of outer div so there has to be a line-break*/_x000D_
  height:100px;_x000D_
  _x000D_
  /*  Tell the browser we are writing chinese. This makes everything that is text_x000D_
  top-bottom then left to right. */_x000D_
  writing-mode:vertical-lr;_x000D_
_x000D_
}_x000D_
_x000D_
.outer > div{_x000D_
  /* float:left behaves like float:top because this block is beeing aligned top-bottom first _x000D_
  */_x000D_
  float:left;_x000D_
  width:40px;  _x000D_
  _x000D_
  /* Switch back to normal writing mode. If you leave this out, everything inside the_x000D_
  div will also be top-bottom. */_x000D_
  writing-mode:horizontal-tb;_x000D_
_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div>one</div>_x000D_
  <div>two</div>_x000D_
  <div>three</div>_x000D_
  <div>four</div>_x000D_
  <div>one</div>_x000D_
  <div>two</div>_x000D_
  <div>three</div>_x000D_
  <div>four</div>_x000D_
  <div>one</div>_x000D_
  <div>two</div>_x000D_
  <div>three</div>_x000D_
  <div>four</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add an image to the emulator gallery in android studio?

It's a very old question but I will answer this for future references.

To add any file to emulator just drag and drop the file.

The file will be copied to downloads folder of internal storage.

To access the file

Go to settings

Click On Storage & USB

Click On Internal Storage

Click On Explore (at the end)

and you got it in the downloads folder

now you will get notification to setup virtual SD card, follow the setup. after the successful setup you will be able to see pictures in gallery.

How to read/process command line arguments?

One way to do it is using sys.argv. This will print the script name as the first argument and all the other parameters that you pass to it.

import sys

for arg in sys.argv:
    print arg

How to change line color in EditText

i think the best way is by theme:

<style name="MyEditTextTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorControlNormal">@color/black</item>
        <item name="colorControlActivated">@color/action_blue</item>
        <item name="colorControlHighlight">@color/action_blue</item>
</style>

<style name="AddressBookStyle" parent="Theme.AppCompat.Light.DarkActionBar">
     <item name="android:layout_width">match_parent</item>
     <item name="android:layout_height">wrap_content</item>
     <item name="android:textSize">13sp</item>
     <item name="android:theme">@style/MyEditTextTheme</item>
</style>

<android.support.v7.widget.AppCompatEditText
            style="@style/AddressBookStyle"/>

How to completely remove borders from HTML table

In a bootstrap environment here is my solution:

    <table style="border-collapse: collapse; border: none;">
        <tr style="border: none;">
            <td style="border: none;">
            </td>
        </tr>
    </table>    

How Exactly Does @param Work - Java

It is basically a comment. As we know, a number of people working on the same project must have knowledge about the code changes. We are making some notes in the program about the parameters.

How can I verify a Google authentication API access token?

Ok, most answers are valid but not quite right. The idea of JWT is that you can validate the token without the need to contact the issuer everytime. You must check the id and verify the signature of the token with the known public key of the certificate google used to sign the token.

See the next post why and how to do this.

http://ncona.com/2015/02/consuming-a-google-id-token-from-a-server/

Bringing a subview to be in front of all other views

Let me make a conclusion. In Swift 5

You can choose to addSubview to keyWindow, if you add the view in the last. Otherwise, you can bringSubViewToFront.

let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)

You can also set the zPosition. But the drawback is that you can not change the gesture responding order.

view.layer.zPosition = 1

How do you install Boost on MacOS?

Download MacPorts, and run the following command:

sudo port install boost 

Send a base64 image in HTML email

An alternative approach may be to embed images in the email using the cid method. (Basically including the image as an attachment, and then embedding it). In my experience, this approach seems to be well supported these days.

enter image description here

Source: https://www.campaignmonitor.com/blog/how-to/2008/08/embedding-images-revisited/

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Answering the question at hand...
No it's not enough to have these attributes, to be able to autoplay a media with audio you need to have an user-gesture registered on your document.

But, this limitation is very weak: if you did receive this user-gesture on the parent document, and your video got loaded from an iframe, then you could play it...

So take for instance this fiddle, which is only

<video src="myvidwithsound.webm" autoplay=""></video>

At first load, and if you don't click anywhere, it will not run, because we don't have any event registered yet.
But once you click the "Run" button, then the parent document (jsfiddle.net) did receive an user-gesture, and now the video plays, even though it is technically loaded in a different document.

But the following snippet, since it requires you to actually click the Run code snippet button, will autoplay.

_x000D_
_x000D_
<video src="https://upload.wikimedia.org/wikipedia/commons/transcoded/2/22/Volcano_Lava_Sample.webm/Volcano_Lava_Sample.webm.360p.webm" autoplay=""></video>
_x000D_
_x000D_
_x000D_

This means that your ad was probably able to play because you did provide an user-gesture to the main page.


Now, note that Safari and Mobile Chrome have stricter rules than that, and will require you to actually trigger at least once the play() method programmatically on the <video> or <audio> element from the user-event handler itself.

_x000D_
_x000D_
btn.onclick = e => {_x000D_
  // mark our MediaElement as user-approved_x000D_
  vid.play().then(()=>vid.pause());_x000D_
  // now we can do whatever we want at any time with this MediaElement_x000D_
  setTimeout(()=> vid.play(), 3000);_x000D_
};
_x000D_
<button id="btn">play in 3s</button>_x000D_
<video_x000D_
  src="https://upload.wikimedia.org/wikipedia/commons/transcoded/2/22/Volcano_Lava_Sample.webm/Volcano_Lava_Sample.webm.360p.webm" id="vid"></video>
_x000D_
_x000D_
_x000D_

And if you don't need the audio, then simply don't attach it to your media, a video with only a video track is also allowed to autoplay, and will reduce your user's bandwidth usage.

Extracting a parameter from a URL in WordPress

Why not just use the WordPress get_query_var() function? WordPress Code Reference

// Test if the query exists at the URL
if ( get_query_var('ppc') ) {

    // If so echo the value
    echo get_query_var('ppc');

}

Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php by adding an action during initialization:

add_action('init','add_get_val');
function add_get_val() { 
    global $wp; 
    $wp->add_query_var('ppc'); 
}

Or by adding a hook to the query_vars filter:

function add_query_vars_filter( $vars ){
  $vars[] = "ppc";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

Short rot13 function - Python

For arbitrary values, something like this works for 2.x

from string import ascii_uppercase as uc, ascii_lowercase as lc, maketrans                                                                                                            

rotate = 13 # ROT13                                                                    
rot = "".join([(x[:rotate][::-1] + x[rotate:][::-1])[::-1] for x in (uc,lc)])   

def rot_func(text, encode=True):                                                
    ascii = uc + lc                                                             
    src, trg = (ascii, rot) if encode else (rot, ascii)                         
    trans = maketrans(src, trg)                                                 
    return text.translate(trans)                                                

text = "Text to ROT{}".format(rotate)                                           
encode = rot_func(text)                                                         
decode = rot_func(encode, False)

Database cluster and load balancing

From SQL Server point of view:

Clustering will give you an active - passive configuration. Meaning in a 2 node cluster, one of them will be the active (serving) and the other one will be passive (waiting to take over when the active node fails). It's a high availability from hardware point of view.

You can have an active-active cluster, but it will require multiple instances of SQL Server running on each node. (i.e. Instance 1 on Node A failing over to Instance 2 on Node B, and instance 1 on Node B failing over to instance 2 on Node A).

Load balancing (at least from SQL Server point of view) does not exists (at least in the same sense of web server load balancing). You can't balance load that way. However, you can split your application to run on some database on server 1 and also run on some database on server 2, etc. This is the primary mean of "load balancing" in SQL world.

Add a linebreak in an HTML text area

If you're inserting text from a database or such (which one usually do), convert all "<br />"'s to &vbCrLf. Works great for me :)

Column name or number of supplied values does not match table definition

The problem is that you are trying to insert data into the database without using columns. Sql server gives you that error message.

error: insert into users values('1', '2','3') - this works fine as long you only have 3 columns

if you have 4 columns but only want to insert into 3 of them

correct: insert into users (firstName,lastName,city) values ('Tom', 'Jones', 'Miami')

hope this helps

simple custom event

You haven't created an event. To do that write:

public event EventHandler<Progress> Progress;

Then, you can call Progress from within the class where it was declared like normal function or delegate:

Progress(this, new Progress("some status"));

So, if you want to report progress in TestClass, the event should be in there too and it should be also static. You can the subscribe to it from your form like this:

TestClass.Progress += SetStatus;

Also, you should probably rename Progress to ProgressEventArgs, so that it's clear what it is.

Socket.IO handling disconnect event

For those like @sha1 wondering why the OP's code doesn't work -

OP's logic for deleting player at server side is in the handler for DelPlayer event, and the code that emits this event (DelPlayer) is in inside disconnected event callback of client.

The server side code that emits this disconnected event is inside the disconnect event callback which is fired when the socket loses connection. Since the socket already lost connection, disconnected event doesn't reach the client.


Accepted solution executes the logic on disconnect event at server side, which is fired when the socket disconnects, hence works.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The Accept Ranges header (the bit in writeHead()) is required for the HTML5 video controls to work.

I think instead of just blindly send the full file, you should first check the Accept Ranges header in the REQUEST, then read in and send just that bit. fs.createReadStream support start, and end option for that.

So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream to send the requested part to the client.

var fs = require("fs"),
    http = require("http"),
    url = require("url"),
    path = require("path");

http.createServer(function (req, res) {
  if (req.url != "/movie.mp4") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
  } else {
    var file = path.resolve(__dirname,"movie.mp4");
    fs.stat(file, function(err, stats) {
      if (err) {
        if (err.code === 'ENOENT') {
          // 404 Error if file not found
          return res.sendStatus(404);
        }
      res.end(err);
      }
      var range = req.headers.range;
      if (!range) {
       // 416 Wrong range
       return res.sendStatus(416);
      }
      var positions = range.replace(/bytes=/, "").split("-");
      var start = parseInt(positions[0], 10);
      var total = stats.size;
      var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
      var chunksize = (end - start) + 1;

      res.writeHead(206, {
        "Content-Range": "bytes " + start + "-" + end + "/" + total,
        "Accept-Ranges": "bytes",
        "Content-Length": chunksize,
        "Content-Type": "video/mp4"
      });

      var stream = fs.createReadStream(file, { start: start, end: end })
        .on("open", function() {
          stream.pipe(res);
        }).on("error", function(err) {
          res.end(err);
        });
    });
  }
}).listen(8888);

How to store Emoji Character in MySQL Database

Emoji support for application having tech stack - mysql, java, springboot, hibernate

Apply below changes in mysql for unicode support.

  1. ALTER DATABASE <database-name> CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
  2. ALTER TABLE <table-name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

DB Connection - jdbc url change:

jdbc:mysql://localhost:3306/<database-name>?useUnicode=yes&characterEncoding=UTF-8

Note - If the above step is not working please update mysql-connector version to 8.0.15. (mysql 5.7 works with connector version 8.0.15 for unicode support)

Python check if list items are integers?

The usual way to check whether something can be converted to an int is to try it and see, following the EAFP principle:

try:
    int_value = int(string_value)
except ValueError:
    # it wasn't an int, do something appropriate
else:
    # it was an int, do something appropriate

So, in your case:

for item in mylist:
    try:
        int_value = int(item)
    except ValueError:
        pass
    else:
        mynewlist.append(item) # or append(int_value) if you want numbers

In most cases, a loop around some trivial code that ends with mynewlist.append(item) can be turned into a list comprehension, generator expression, or call to map or filter. But here, you can't, because there's no way to put a try/except into an expression.

But if you wrap it up in a function, you can:

def raises(func, *args, **kw):
    try:
        func(*args, **kw)
    except:
        return True
    else:
        return False

mynewlist = [item for item in mylist if not raises(int, item)]

… or, if you prefer:

mynewlist = filter(partial(raises, int), item)

It's cleaner to use it this way:

def raises(exception_types, func, *args, **kw):
    try:
        func(*args, **kw)
    except exception_types:
        return True
    else:
        return False

This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True, but if any unexpected exceptions are raised, they'll propagate out. So:

mynewlist = [item for item in mylist if not raises(ValueError, int, item)]

… will do what you want, but:

mynewlist = [item for item in mylist if not raises(ValueError, item, int)]

… will raise a TypeError, as it should.

Tomcat Servlet: Error 404 - The requested resource is not available

You definitely need to map your servlet onto some URL. If you use Java EE 6 (that means at least Servlet API 3.0) then you can annotate your servlet like

@WebServlet(name="helloServlet", urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
     //rest of the class

Then you can just go to the localhost:8080/yourApp/hello and the value should be displayed. In case you can't use Servlet 3.0 API than you need to register this servlet into web.xml file like

<servlet>
    <servlet-name>helloServlet</servlet-name>
    <servlet-class>crunch.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>helloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

C: What is the difference between ++i and i++?

They both increment the number. ++i is equivalent to i = i + 1.

i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluated, whereas i++ increments the number after the expression is evaluated.

Example:

int i = 1;
int x = i++; //x is 1, i is 2
int y = ++i; //y is 3, i is 3

What is the difference between document.location.href and document.location?

Here is an example of the practical significance of the difference and how it can bite you if you don't realize it (document.location being an object and document.location.href being a string):

We use MonoX Social CMS (http://mono-software.com) free version at http://social.ClipFlair.net and we wanted to add the language bar WebPart at some pages to localize them, but at some others (e.g. at discussions) we didn't want to use localization. So we made two master pages to use at all our .aspx (ASP.net) pages, in the first one we had the language bar WebPart and the other one had the following script to remove the /lng/el-GR etc. from the URLs and show the default (English in our case) language instead for those pages

<script>
  var curAddr = document.location; //MISTAKE
  var newAddr = curAddr.replace(new RegExp("/lng/[a-z]{2}-[A-Z]{2}", "gi"), "");
  if (curAddr != newAddr)
    document.location = newAddr;
</script>

But this code isn't working, replace function just returns Undefined (no exception thrown) so it tries to navigate to say x/lng/el-GR/undefined instead of going to url x. Checking it out with Mozilla Firefox's debugger (F12 key) and moving the cursor over the curAddr variable it was showing lots of info instead of some simple string value for the URL. Selecting Watch from that popup you could see in the watch pane it was writing "Location -> ..." instead of "..." for the url. That made me realize it was an object

One would have expected replace to throw an exception or something, but now that I think of it the problem was that it was trying to call some non-existent "replace" method on the URL object which seems to just give back "undefined" in Javascript.

The correct code in that case is:

<script>
  var curAddr = document.location.href; //CORRECT
  var newAddr = curAddr.replace(new RegExp("/lng/[a-z]{2}-[A-Z]{2}", "gi"), "");
  if (curAddr != newAddr)
    document.location = newAddr;
</script>

How can I get a Dialog style activity window to fill the screen?

Matthias' answer is mostly right but it's still not filling the entire screen as it has a small padding on each side (pointed out by @Holmes). In addition to his code, we could fix this by extending Theme.Dialog style and add some attributes like this.

<style name="MyDialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowNoTitle">true</item>
</style>

Then we simply declare Activity with theme set to MyDialog:

<activity
    android:name=".FooActivity"
    android:theme="@style/MyDialog" />

How to install pandas from pip on windows cmd?

Since both pip nor python commands are not installed along Python in Windows, you will need to use the Windows alternative py, which is included by default when you installed Python. Then you have the option to specify a general or specific version number after the py command.

C:\> py      -m pip install pandas  %= one of Python on the system =%
C:\> py -2   -m pip install pandas  %= one of Python 2 on the system =%
C:\> py -2.7 -m pip install pandas  %= only for Python 2.7 =%
C:\> py -3   -m pip install pandas  %= one of Python 3 on the system =%
C:\> py -3.6 -m pip install pandas  %= only for Python 3.6 =%

Alternatively, in order to get pip to work without py -m part, you will need to add pip to the PATH environment variable.

C:\> setx PATH "%PATH%;C:\<path\to\python\folder>\Scripts"

Now you can run the following command as expected.

C:\> pip install pandas

Troubleshooting:


Problem:

connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

Solution:

This is caused by your SSL certificate is unable to verify the host server. You can add pypi.python.org to the trusted host or specify an alternative SSL certificate. For more information, please see this post. (Thanks to Anuj Varshney for suggesting this)

C:\> py -m pip install --trusted-host pypi.python.org pip pandas

Problem:

PermissionError: [WinError 5] Access is denied

Solution:

This is a caused by when you don't permission to modify the Python site-package folders. You can avoid this with one of the following methods:

  • Run Windows Command Prompt as administrator (thanks to DataGirl's suggestion) by:

    1. Windows-Key + R to open run
    2. type in cmd.exe in the search box
    3. CTRL + SHIFT + ENTER
    4. An alternative method for step 1-3 would be to manually locate cmd.exe, right click, then click Run as Administrator.
  • Run pip in user mode by adding --user option when installing with pip. Which typically install the package to the local %APPDATA% Python folder.

C:\> py -m pip install --user pandas
C:\> py -m venv c:\path\to\new\venv
C:\> <path\to\the\new\venv>\Scripts\activate.bat

How to round up a number to nearest 10?

For people who want to do it with raw SQL, without using php, java, python etc. SET SQL_SAFE_UPDATES = 0; UPDATE db.table SET value=ceil(value/10)*10 where value not like '%0';

Angular window resize event

Here is a better way to do it. Based on Birowsky's answer.

Step 1: Create an angular service with RxJS Observables.

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable()
export class WindowService {
    height$: Observable<number>;
    //create more Observables as and when needed for various properties
    hello: string = "Hello";
    constructor() {
        let windowSize$ = new BehaviorSubject(getWindowSize());

        this.height$ = (windowSize$.pluck('height') as Observable<number>).distinctUntilChanged();

        Observable.fromEvent(window, 'resize')
            .map(getWindowSize)
            .subscribe(windowSize$);
    }

}

function getWindowSize() {
    return {
        height: window.innerHeight
        //you can sense other parameters here
    };
};

Step 2: Inject the above service and subscribe to any of the Observables created within the service wherever you would like to receive the window resize event.

import { Component } from '@angular/core';
//import service
import { WindowService } from '../Services/window.service';

@Component({
    selector: 'pm-app',
    templateUrl: './componentTemplates/app.component.html',
    providers: [WindowService]
})
export class AppComponent { 

    constructor(private windowService: WindowService) {

        //subscribe to the window resize event
        windowService.height$.subscribe((value:any) => {
            //Do whatever you want with the value.
            //You can also subscribe to other observables of the service
        });
    }

}

A sound understanding of Reactive Programming will always help in overcoming difficult problems. Hope this helps someone.

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

Might sound obvious but do you definitely have AjaxControlToolkit.dll in your bin?

Refresh Page C# ASP.NET

I use

Response.Redirect(Page.Request.Path);

If you have to check for the Request.Params when the page is refresh use below. This will not rewrite the Request.Params to the URL.

Response.Redirect(Page.Request.Path + "?Remove=1");

Date validation with ASP.NET validator

I think the following is the easiest way to do it.

<asp:TextBox ID="DateControl" runat="server" Visible="False"></asp:TextBox>
<asp:RangeValidator ID ="rvDate" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator>

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;");

Showing all errors and warnings

You can see a detailed description here.

ini_set('display_errors', 1);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Changelog

  • 5.4.0 E_STRICT became part of E_ALL

  • 5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.

  • 5.2.0 E_RECOVERABLE_ERROR introduced.

  • 5.0.0 E_STRICT introduced (not part of E_ALL).

How to install JDK 11 under Ubuntu?

First check the default-jdk package, good chance it already provide you an OpenJDK >= 11.
ref: https://packages.ubuntu.com/search?keywords=default-jdk&searchon=names&suite=all&section=all

Ubuntu 18.04 LTS +

So starting from Ubuntu 18.04 LTS it should be ok.

sudo apt update -qq
sudo apt install -yq default-jdk

note: don't forget to set JAVA_HOME

export JAVA_HOME=/usr/lib/jvm/default-java
mvn -version

Ubuntu 16.04 LTS

For Ubuntu 16.04 LTS, only openjdk-8-jdk is provided in the official repos so you need to find it in a ppa:

sudo add-apt-repository -y ppa:openjdk-r/ppa
sudo apt update -qq
sudo apt install -yq openjdk-11-jdk

note: don't forget to set JAVA_HOME

export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
mvn -version

How to allow CORS in react.js?

You just have to add cors to your backend server.js file in order to do cross-origin API Calls.

const cors = require('cors');
app.use(cors())

Count character occurrences in a string in C++

public static void main(String[] args) {
        char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
        char[][] countArr = new char[array.length][2];
        int lastIndex = 0;
        for (char c : array) {
            int foundIndex = -1;
            for (int i = 0; i < lastIndex; i++) {
                if (countArr[i][0] == c) {
                    foundIndex = i;
                    break;
                }
            }
            if (foundIndex >= 0) {
                int a = countArr[foundIndex][1];
                countArr[foundIndex][1] = (char) ++a;
            } else {
                countArr[lastIndex][0] = c;
                countArr[lastIndex][1] = '1';
                lastIndex++;
            }
        }
        for (int i = 0; i < lastIndex; i++) {
            System.out.println(countArr[i][0] + " " + countArr[i][1]);
        }
    }

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

Please have a look at the below code sample;

Swift 4:

@IBDesignable class DesignableUITextField: UITextField {

    let border = CALayer()

    @IBInspectable var borderColor: UIColor? {
        didSet {
            setup()
        }
    }

    @IBInspectable var borderWidth: CGFloat = 0.5 {
        didSet {
            setup()
        }
    }

    func setup() {
        border.borderColor = self.borderColor?.cgColor

        border.borderWidth = borderWidth
        self.layer.addSublayer(border)
        self.layer.masksToBounds = true
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        border.frame = CGRect(x: 0, y: self.frame.size.height - borderWidth, width:  self.frame.size.width, height: self.frame.size.height)
    }
 }

The import javax.servlet can't be resolved

You need to set the scope of the dependency to 'provided' in your POM.

http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope

<dependency>  
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.4</version>
  <scope>provided</scope>
</dependency>

Then everything will be fine.

Remove Trailing Spaces and Update in Columns in SQL Server

To remove Enter:

Update [table_name] set
[column_name]=Replace(REPLACE([column_name],CHAR(13),''),CHAR(10),'')

To remove Tab:

Update [table_name] set
[column_name]=REPLACE([column_name],CHAR(9),'')

Using a scanner to accept String input and storing in a String Array

Please correct me if I'm wrong.`

public static void main(String[] args) {

    Scanner na = new Scanner(System.in);
    System.out.println("Please enter the number of contacts: ");
    int num = na.nextInt();

    String[] contactName = new String[num];
    String[] contactPhone = new String[num];
    String[] contactAdd1 = new String[num];
    String[] contactAdd2 = new String[num];

    Scanner input = new Scanner(System.in);

    for (int i = 0; i < num; i++) {

        System.out.println("Enter contacts name: " + (i+1));
        contactName[i] = input.nextLine();

        System.out.println("Enter contacts addressline1: " + (i+1));
        contactAdd1[i] = input.nextLine();

        System.out.println("Enter contacts addressline2: " + (i+1));
        contactAdd2[i] = input.nextLine();

        System.out.println("Enter contact phone number: " + (i+1));
        contactPhone[i] = input.nextLine();

    }

    for (int i = 0; i < num; i++) {
        System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
        System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
        System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
        System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
    }
}

`

Xcode 'CodeSign error: code signing is required'

In file /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/SDKSettings.plist

change the CODE_SIGNING_REQUIRED YES

to

CODE_SIGNING_REQUIRED NO

Restart Xcode

Java : Cannot format given Object as a Date

public static String showDate(){
    SimpleDateFormat df=new SimpleDateFormat("\nTime:yyyy-MM-dd HH:mm:ss");
    System.out.println(df.format(new Date()));
    String s=df.format(new Date());
    return s;
}

I think this code may solve your problem.

General error: 1364 Field 'user_id' doesn't have a default value

I've had a similar issue with User registration today and I was getting a

SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value (SQL: insert into users

I fixed it by adding password to my protected $fillable array and it worked

protected $fillable = [
  'name',
  'email',
  'password',
];

I hope this helps.

Pandas - Plotting a stacked Bar Chart

If you want to change the size of plot the use arg figsize

df.groupby(['NFF', 'ABUSE']).size().unstack()
      .plot(kind='bar', stacked=True, figsize=(15, 5))

How to get an absolute file path in Python

This always gets the right filename of the current script, even when it is called from within another script. It is especially useful when using subprocess.

import sys,os

filename = sys.argv[0]

from there, you can get the script's full path with:

>>> os.path.abspath(filename)
'/foo/bar/script.py'

It also makes easier to navigate folders by just appending /.. as many times as you want to go 'up' in the directories' hierarchy.

To get the cwd:

>>> os.path.abspath(filename+"/..")
'/foo/bar'

For the parent path:

>>> os.path.abspath(filename+"/../..")
'/foo'

By combining "/.." with other filenames, you can access any file in the system.

How to remove all the null elements inside a generic list in one go?

There is another simple and elegant option:

parameters.OfType<EmailParameterClass>();

This will remove all elements that are not of type EmailParameterClass which will obviously filter out any elements of type null.

Here's a test:

class Test { }
class Program
{
    static void Main(string[] args)
    {
        var list = new List<Test>();
        list.Add(null);
        Console.WriteLine(list.OfType<Test>().Count());// 0
        list.Add(new Test());
        Console.WriteLine(list.OfType<Test>().Count());// 1
        Test test = null;
        list.Add(test);
        Console.WriteLine(list.OfType<Test>().Count());// 1
        Console.ReadKey();
    }
}

Want custom title / image / description in facebook share link from a flash app

I had this same problem a week ago.

First of all I noticed your URL has an ampersand preceding the parameter string, but it probably needs to have a question mark instead to begin the parameter string, followed by an ampersand between each additional parameter.

Now, you do need to escape your URL but also double-escape the URL parameters (title or other content you need to provide content in the Share) you are passing to the URL, as follows:

var myParams = 't=' + escape('Some title here.') + '&id=' + escape('some content ID or any other value I want to load');
var fooBar = 'http://www.facebook.com/share.php?u=' + escape('http://foobar.com/superDuperSharingPage.php?' + myParams);

Now, you need to create the above-linked superDuperSharingPage.php, which should provide the dynamic title, description, and image content you desire. Something like this should suffice:

<?php
    // get our URL query parameters
    $title = $_GET['t'];
    $id = $_GET['id'];
    // maybe we want to load some content with the id I'll pretend we loaded a
    // description from some database in the sky which is magically arranged thusly:
    $desciption = $databaseInTheSky[$id]['description'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title><?php echo $title;?></title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <meta name="title" content="<?php echo $title;?>" />
  <meta name="description" content="<?php echo $desciption;?>" />
  <!-- the following line redirects to wherever we want the USER to land -->
  <!-- Facebook won't follow it. you may or may not actually want || need this. -->
  <meta http-equiv="refresh" content="1;URL=http://foobar.com" />
</head>
<body>
  <p><?php echo $desciption;?></p>
  <p><img src="image_a_<?php echo $id;?>.jpg" alt="Alt tags are always a good idea." /></p>
  <p><img src="image_b_<?php echo $id;?>.jpg" alt="Make the web more accessible to the blind!" /></p>
</body>
</html>

Let me know if this works for you, it's essentially what did for me :)

How to call a function from a string stored in a variable?

Complementing the answer of @Chris K if you want to call an object's method, you can call it using a single variable with the help of a closure:

function get_method($object, $method){
    return function() use($object, $method){
        $args = func_get_args();
        return call_user_func_array(array($object, $method), $args);           
    };
}

class test{        

    function echo_this($text){
        echo $text;
    }
}

$test = new test();
$echo = get_method($test, 'echo_this');
$echo('Hello');  //Output is "Hello"

I posted another example here

How do I tidy up an HTML file's indentation in VI?

None of the answers worked for me because all my HTML was in a single line.

Basically you need first to break each line with the following command that substitutes >< with the same characters but with a line break in the middle.

:%s/></>\r</g

Then the command

gg=G

will indent the file.

jQuery selector to get form by name

For detecting if the form is present, I'm using

if($('form[name="frmSave"]').length > 0) {
    //do something
}

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

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

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

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

Or, simply:

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

Difference between add(), replace(), and addToBackStack()

The FragmentManger's function add and replace can be described as these 1. add means it will add the fragment in the fragment back stack and it will show at given frame you are providing like

getFragmentManager.beginTransaction.add(R.id.contentframe,Fragment1.newInstance(),null)

2.replace means that you are replacing the fragment with another fragment at the given frame

getFragmentManager.beginTransaction.replace(R.id.contentframe,Fragment1.newInstance(),null)

The Main utility between the two is that when you are back stacking the replace will refresh the fragment but add will not refresh previous fragment.

How do I check if file exists in Makefile so I can delete it?

It's strange to see so many people using shell scripting for this. I was looking for a way to use native makefile syntax, because I'm writing this outside of any target. You can use the wildcard function to check if file exists:

 ifeq ($(UNAME),Darwin)
     SHELL := /opt/local/bin/bash
     OS_X  := true
 else ifneq (,$(wildcard /etc/redhat-release))
     OS_RHEL := true
 else
     OS_DEB  := true
     SHELL := /bin/bash
 endif 

Update:

I found a way which is really working for me:

ifneq ("$(wildcard $(PATH_TO_FILE))","")
    FILE_EXISTS = 1
else
    FILE_EXISTS = 0
endif

php_network_getaddresses: getaddrinfo failed: Name or service not known

Try to set ENV PATH. Add PHP path in to ENV PATH.

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libeay32.dll

http://php.net/manual/en/openssl.installation.php

"Char cannot be dereferenced" error

I guess ch is a declared as char. Since char is a primitive data type and not and object, you can't call any methof from it. You should use Character.isLetter(ch).

Display a jpg image on a JPanel

I would use a Canvas that I add to the JPanel, and draw the image on the Canvas. But Canvas is a quite heavy object, sine it is from awt.

PHP - print all properties of an object

try using Pretty Dump it works great for me

How to push files to an emulator instance using Android Studio

Update (May 2020): Android studio have new tool called Device File Explorer. You can access it in two way:

  1. By clicking on Device File Explorer icon in right bottom corner of android studio window.
  2. If you could not find its icon, inside Android Studio press shift button twice. Quick search window will appear, then type Device File in it and Device File Explorer will appear in search result and you can click it. open Device File Explorer

Then you can navigate to folder which you want to push your file in it. Right click on that folder and select upload(or press Ctrl+Shift+O). Select file you want to upload and it will upload file to desired location.

enter image description here

Push file using adb.exe:

In Android 6.0+, you should use same process but your android application cannot access files which pushed inside SDCARD using DDMS File Explorer. It is the same if you try commands like this:

adb push myfile.txt /mnt/sdcard/myfile.txt

If you face EACCES (Permission denied) exception when you try to read file inside your application, it means you have no access to files inside external storage, since it requires a dangerous permission.

For this situation, you need to request granting access manually using new permission system in Android 6.0 and upper version. For details you can have a look in android tutorial and this link.

Solution for old android studio version:

If you want to do it using graphical interface you can follow this inside android studio menus:

Tools --> Android --> Android Device Monitor

enter image description here

Afterward, Android Device Monitor(DDMS) window will open and you can upload files using File Explorer. You can select an address like /mnt/sdcard and then push your file into sdcard. enter image description here

How to convert unsigned long to string

const int n = snprintf(NULL, 0, "%lu", ulong_value);
assert(n > 0);
char buf[n+1];
int c = snprintf(buf, n+1, "%lu", ulong_value);
assert(buf[n] == '\0');
assert(c == n);

How to distinguish mouse "click" and "drag"

You could do this:

_x000D_
_x000D_
var div = document.getElementById("div");
div.addEventListener("mousedown", function() {
  window.addEventListener("mousemove", drag);
  window.addEventListener("mouseup", lift);
  var didDrag = false;
  function drag() {
    //when the person drags their mouse while holding the mouse button down
    didDrag = true;
    div.innerHTML = "drag"
  }
  function lift() {
    //when the person lifts mouse
    if (!didDrag) {
      //if the person didn't drag
      div.innerHTML = "click";
    } else div.innerHTML = "drag";
    //delete event listeners so that it doesn't keep saying drag
    window.removeEventListener("mousemove", drag)
    window.removeEventListener("mouseup", this)
  }
})
_x000D_
body {
  outline: none;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: Arial, Helvetica, sans-serif;
  overflow: hidden;
}
#div {
  /* calculating -5px for each side of border in case border-box doesn't work */
  width: calc(100vw - 10px);
  height: calc(100vh - 10px);
  border: 5px solid orange;
  background-color: yellow;
  font-weight: 700;
  display: grid;
  place-items: center;
  user-select: none;
  cursor: pointer;
  padding: 0;
  margin: 0;
}
_x000D_
<html>
  <body>
    <div id="div">Click me or drag me.</div>
  </body>
</html>
_x000D_
_x000D_
_x000D_

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Knockout validation

Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.

Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.

How do you run a single test/spec file in RSpec?

Lets say, you're running test for creating todo. You can always run that specific todo spec code using the file crete_spec.rb file as below.

      rspec/spec/features/controller/spec_file_name.rb

   Example:

   Creating  rspec spec/features/todos/create_spec.rb
   Editing   rspec spec/features/todos/edit_spec.rb
   Deleting  rspec spec/features/todos/destroy_spec.rb

If you want to run all the specs in one single short.

   rspec 

If you want to run all the specs in a specific controller user this.

  rspec/spec/feaures/controller_name

  Example:   rspec/spec/features/todos

Hope it gives you more understanding!

UIImageView - How to get the file name of the image assigned?

Or you can use the restoration identifier, like this:

let myImageView = UIImageView()
myImageView.image = UIImage(named: "anyImage")
myImageView.restorationIdentifier = "anyImage" // Same name as image's name!

// Later, in UI Tests:
print(myImageView.restorationIdentifier!) // Prints "anyImage"

Basically in this solution you're using the restoration identifier to hold the image's name, so you can use it later anywhere. If you update the image, you must also update the restoration identifier, like this:

myImageView.restorationIdentifier = "newImageName"

I hope that helps you, good luck!

Can someone explain how to append an element to an array in C programming?

You can have a counter (freePosition), which will track the next free place in an array of size n.

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

There are two competing concerns: with less training data, your parameter estimates have greater variance. With less testing data, your performance statistic will have greater variance. Broadly speaking you should be concerned with dividing data such that neither variance is too high, which is more to do with the absolute number of instances in each category rather than the percentage.

If you have a total of 100 instances, you're probably stuck with cross validation as no single split is going to give you satisfactory variance in your estimates. If you have 100,000 instances, it doesn't really matter whether you choose an 80:20 split or a 90:10 split (indeed you may choose to use less training data if your method is particularly computationally intensive).

Assuming you have enough data to do proper held-out test data (rather than cross-validation), the following is an instructive way to get a handle on variances:

  1. Split your data into training and testing (80/20 is indeed a good starting point)
  2. Split the training data into training and validation (again, 80/20 is a fair split).
  3. Subsample random selections of your training data, train the classifier with this, and record the performance on the validation set
  4. Try a series of runs with different amounts of training data: randomly sample 20% of it, say, 10 times and observe performance on the validation data, then do the same with 40%, 60%, 80%. You should see both greater performance with more data, but also lower variance across the different random samples
  5. To get a handle on variance due to the size of test data, perform the same procedure in reverse. Train on all of your training data, then randomly sample a percentage of your validation data a number of times, and observe performance. You should now find that the mean performance on small samples of your validation data is roughly the same as the performance on all the validation data, but the variance is much higher with smaller numbers of test samples

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Adding label tags around the radio buttons using regular HTML will fix the 'labelfor' issue as well:

<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>

Clicking on the text now selects the appropriate radio button.

PHP - Copy image to my server direct from URL

$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);

you must have allow_url_fopen set to on

Why extend the Android Application class?

I think you can use the Application class for many things, but they are all tied to your need to do some stuff BEFORE any of your Activities or Services are started. For instance, in my application I use custom fonts. Instead of calling

Typeface.createFromAsset()

from every Activity to get references for my fonts from the Assets folder (this is bad because it will result in memory leak as you are keeping a reference to assets every time you call that method), I do this from the onCreate() method in my Application class:

private App appInstance;
Typeface quickSandRegular;
...
public void onCreate() {
    super.onCreate();

    appInstance = this;
    quicksandRegular = Typeface.createFromAsset(getApplicationContext().getAssets(),
                       "fonts/Quicksand-Regular.otf");
   ...
   }

Now, I also have a method defined like this:

public static App getAppInstance() {
    return appInstance;
}

and this:

public Typeface getQuickSandRegular() {
    return quicksandRegular;
}

So, from anywhere in my application, all I have to do is:

App.getAppInstance().getQuickSandRegular()

Another use for the Application class for me is to check if the device is connected to the Internet BEFORE activities and services that require a connection actually start and take necessary action.

How can I detect when the mouse leaves the window?

Please keep in mind that my answer has aged a lot.

This type of behavior is usually desired while implementing drag-drop behavior on an html page. The solution below was tested on IE 8.0.6, FireFox 3.6.6, Opera 10.53, and Safari 4 on an MS Windows XP machine.
First a little function from Peter-Paul Koch; cross browser event handler:

function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);
    }
}

And then use this method to attach an event handler to the document objects mouseout event:

addEvent(document, "mouseout", function(e) {
    e = e ? e : window.event;
    var from = e.relatedTarget || e.toElement;
    if (!from || from.nodeName == "HTML") {
        // stop your drag event here
        // for now we can just use an alert
        alert("left window");
    }
});

Finally, here is an html page with the script embedded for debugging:

<html>
<head>
<script type="text/javascript">
function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);
    }
}
addEvent(window,"load",function(e) {
    addEvent(document, "mouseout", function(e) {
        e = e ? e : window.event;
        var from = e.relatedTarget || e.toElement;
        if (!from || from.nodeName == "HTML") {
            // stop your drag event here
            // for now we can just use an alert
            alert("left window");
        }
    });
});
</script>
</head>
<body></body>
</html>

How can one see the structure of a table in SQLite?

If you are using PHP you can get it this way:

<?php
    $dbname = 'base.db';
    $db = new SQLite3($dbname);
    $sturturequery = $db->query("SELECT sql FROM sqlite_master WHERE name='foo'");

    $table = $sturturequery->fetchArray();
    echo '<pre>' . $table['sql'] . '</pre>';

    $db->close();
?>

Can I call a constructor from another constructor (do constructor chaining) in C++?

Another option that has not been shown yet is to split your class into two, wrapping a lightweight interface class around your original class in order to achieve the effect you are looking for:

class Test_Base {
    public Test_Base() {
        DoSomething();
    }
};

class Test : public Test_Base {
    public Test() : Test_Base() {
    }

    public Test(int count) : Test_Base() {
        DoSomethingWithCount(count);
    }
};

This could get messy if you have many constructors that must call their "next level up" counterpart, but for a handful of constructors, it should be workable.

The Use of Multiple JFrames: Good or Bad Practice?

I'm just wondering whether it is good practice to use multiple JFrames?

Bad (bad, bad) practice.

  • User unfriendly: The user sees multiple icons in their task bar when expecting to see only one. Plus the side effects of the coding problems..
  • A nightmare to code and maintain:
    • A modal dialog offers the easy opportunity to focus attention on the content of that dialog - choose/fix/cancel this, then proceed. Multiple frames do not.
    • A dialog (or floating tool-bar) with a parent will come to front when the parent is clicked on - you'd have to implement that in frames if that was the desired behavior.

There are any number of ways of displaying many elements in one GUI, e.g.:

  • CardLayout (short demo.). Good for:
    1. Showing wizard like dialogs.
    2. Displaying list, tree etc. selections for items that have an associated component.
    3. Flipping between no component and visible component.
  • JInternalFrame/JDesktopPane typically used for an MDI.
  • JTabbedPane for groups of components.
  • JSplitPane A way to display two components of which the importance between one or the other (the size) varies according to what the user is doing.
  • JLayeredPane far many well ..layered components.
  • JToolBar typically contains groups of actions or controls. Can be dragged around the GUI, or off it entirely according to user need. As mentioned above, will minimize/restore according to the parent doing so.
  • As items in a JList (simple example below).
  • As nodes in a JTree.
  • Nested layouts.

But if those strategies do not work for a particular use-case, try the following. Establish a single main JFrame, then have JDialog or JOptionPane instances appear for the rest of the free-floating elements, using the frame as the parent for the dialogs.

Many images

In this case where the multiple elements are images, it would be better to use either of the following instead:

  1. A single JLabel (centered in a scroll pane) to display whichever image the user is interested in at that moment. As seen in ImageViewer.
  2. A single row JList. As seen in this answer. The 'single row' part of that only works if they are all the same dimensions. Alternately, if you are prepared to scale the images on the fly, and they are all the same aspect ratio (e.g. 4:3 or 16:9).

Using Default Arguments in a Function

I would propose changing the function declaration as follows so you can do what you want:

function foo($blah, $x = null, $y = null) {
    if (null === $x) {
        $x = "some value";
    }

    if (null === $y) {
        $y = "some other value";
    }

    code here!

}

This way, you can make a call like foo('blah', null, 'non-default y value'); and have it work as you want, where the second parameter $x still gets its default value.

With this method, passing a null value means you want the default value for one parameter when you want to override the default value for a parameter that comes after it.

As stated in other answers,

default parameters only work as the last arguments to the function. If you want to declare the default values in the function definition, there is no way to omit one parameter and override one following it.

If I have a method that can accept varying numbers of parameters, and parameters of varying types, I often declare the function similar to the answer shown by Ryan P.

Here is another example (this doesn't answer your question, but is hopefully informative:

public function __construct($params = null)
{
    if ($params instanceof SOMETHING) {
        // single parameter, of object type SOMETHING
    } elseif (is_string($params)) {
        // single argument given as string
    } elseif (is_array($params)) {
        // params could be an array of properties like array('x' => 'x1', 'y' => 'y1')
    } elseif (func_num_args() == 3) {
        $args = func_get_args();

        // 3 parameters passed
    } elseif (func_num_args() == 5) {
        $args = func_get_args();
        // 5 parameters passed
    } else {
        throw new \InvalidArgumentException("Could not figure out parameters!");
    }
}

How to convert Javascript datetime to C# datetime?

UPDATE: From .NET Version 4.6 use the FromUnixTimeMilliseconds method of the DateTimeOffset structure instead:

DateTimeOffset.FromUnixTimeMilliseconds(1310522400000).DateTime

How to hide "Showing 1 of N Entries" with the dataTables.js library

try this for hide

$('#table_id').DataTable({
  "info": false
});

and try this for change label

$('#table_id').DataTable({
 "oLanguage": {
               "sInfo" : "Showing _START_ to _END_ of _TOTAL_ entries",// text you want show for info section
            },

});

Find Locked Table in SQL Server

sp_lock

When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003073)

EDIT :

There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/

When should an Excel VBA variable be killed or set to Nothing?

VB6/VBA uses deterministic approach to destoying objects. Each object stores number of references to itself. When the number reaches zero, the object is destroyed.

Object variables are guaranteed to be cleaned (set to Nothing) when they go out of scope, this decrements the reference counters in their respective objects. No manual action required.

There are only two cases when you want an explicit cleanup:

  1. When you want an object to be destroyed before its variable goes out of scope (e.g., your procedure is going to take long time to execute, and the object holds a resource, so you want to destroy the object as soon as possible to release the resource).

  2. When you have a circular reference between two or more objects.

    If objectA stores a references to objectB, and objectB stores a reference to objectA, the two objects will never get destroyed unless you brake the chain by explicitly setting objectA.ReferenceToB = Nothing or objectB.ReferenceToA = Nothing.

The code snippet you show is wrong. No manual cleanup is required. It is even harmful to do a manual cleanup, as it gives you a false sense of more correct code.

If you have a variable at a class level, it will be cleaned/destroyed when the class instance is destructed. You can destroy it earlier if you want (see item 1.).

If you have a variable at a module level, it will be cleaned/destroyed when your program exits (or, in case of VBA, when the VBA project is reset). You can destroy it earlier if you want (see item 1.).

Access level of a variable (public vs. private) does not affect its life time.

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

I am just adding this answer for an awkward situation from DB provider.

what happened in our case is the primary and secondary db shifted reversely (primary to secondary and vice versa) and we are getting the same error.

so please check in the configuration settings for database status which may help you.

What's the difference between xsd:include and xsd:import?

Use xsd:include to bring in an XSD from the same or no namespace.

Use xsd:import to bring in an XSD from a different namespace.

How to join multiple lines of file names into one with custom delimiter?

Quick Perl version with trailing slash handling:

ls -1 | perl -E 'say join ", ", map {chomp; $_} <>'

To explain:

  • perl -E: execute Perl with features supports (say, ...)
  • say: print with a carrier return
  • join ", ", ARRAY_HERE: join an array with ", "
  • map {chomp; $_} ROWS: remove from each line the carrier return and return the result
  • <>: stdin, each line is a ROW, coupling with a map it will create an array of each ROW

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

Windows 8 64bit runs both 32bit and 64bit applications. You want chromedriver 32bit for the 32bit version of chrome you're using.

The current release of chromedriver (v2.16) has been mentioned as running much smoother since it's older versions (there were a lot of issues before). This post mentions this and some of the slight differences between chromedriver and running the normal firefox driver:

http://seleniumsimplified.com/2015/07/recent-course-source-code-changes-for-webdriver-2-46-0/

What you mentioned about "doesn't call main method" is an odd remark. You may want to elaborate.

Is it worth using Python's re.compile?

FWIW:

$ python -m timeit -s "import re" "re.match('hello', 'hello world')"
100000 loops, best of 3: 3.82 usec per loop

$ python -m timeit -s "import re; h=re.compile('hello')" "h.match('hello world')"
1000000 loops, best of 3: 1.26 usec per loop

so, if you're going to be using the same regex a lot, it may be worth it to do re.compile (especially for more complex regexes).

The standard arguments against premature optimization apply, but I don't think you really lose much clarity/straightforwardness by using re.compile if you suspect that your regexps may become a performance bottleneck.

Update:

Under Python 3.6 (I suspect the above timings were done using Python 2.x) and 2018 hardware (MacBook Pro), I now get the following timings:

% python -m timeit -s "import re" "re.match('hello', 'hello world')"
1000000 loops, best of 3: 0.661 usec per loop

% python -m timeit -s "import re; h=re.compile('hello')" "h.match('hello world')"
1000000 loops, best of 3: 0.285 usec per loop

% python -m timeit -s "import re" "h=re.compile('hello'); h.match('hello world')"
1000000 loops, best of 3: 0.65 usec per loop

% python --version
Python 3.6.5 :: Anaconda, Inc.

I also added a case (notice the quotation mark differences between the last two runs) that shows that re.match(x, ...) is literally [roughly] equivalent to re.compile(x).match(...), i.e. no behind-the-scenes caching of the compiled representation seems to happen.

C# - Winforms - Global Variables

yes you can by using static class. like this:

static class Global
{
    private static string _globalVar = "";

    public static string GlobalVar
    {
        get { return _globalVar; }
        set { _globalVar = value; }
    }
}

and for using any where you can write:

GlobalClass.GlobalVar = "any string value"

jQuery: If this HREF contains

Along with the points made by others, the $= selector is the "ends with" selector. You will want the *= (contains) selector, like so:

$('a').each(function() {
    if ($(this).is('[href*="?"')) {
        alert("Contains questionmark");
    }
});

Here's a live demo ->

As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:

$('a[href*="?"]').each(function() {
    alert("Contains questionmark");
});

Push git commits & tags simultaneously

@since Git 2.4

git push --atomic origin <branch name> <tag>

How to get milliseconds from LocalDateTime in Java 8

To get the current time in milliseconds (since the epoch), use System.currentTimeMillis().

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

Then number of columns must match between both parts of the union.

In order to build the full path, you need to "aggregate" all values of the Location column. You still need to select the id and other columns inside the CTE in order to be able to join properly. You get "rid" of them by simply not selecting them in the outer select:

with q as 
(
   select ID, PartOf_LOC_id, Location, ' > ' + Location as path
   from tblLocation 
   where ID = 1 

   union all

   select child.ID, child.PartOf_LOC_id, Location, parent.path + ' > ' + child.Location 
   from tblLocation child
     join q parent on parent.ID = t.LOC_PartOf_ID
)
select path
from q;

How do I create a random alpha-numeric string in C++?

Let's make random convenient again!

I made up a nice C++11 header only solution. You could easily add one header file to your project and then add your tests or use random strings for another purposes.

That's a quick description, but you can follow the link to check full code. The main part of solution is in class Randomer:

class Randomer {
    // random seed by default
    std::mt19937 gen_;
    std::uniform_int_distribution<size_t> dist_;

public:
    /* ... some convenience ctors ... */

    Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
        : gen_{seed}, dist_{min, max} {
    }

    // if you want predictable numbers
    void SetSeed(unsigned int seed) {
        gen_.seed(seed);
    }

    size_t operator()() {
        return dist_(gen_);
    }
};

Randomer incapsulates all random stuff and you can add your own functionality to it easily. After we have Randomer, it's very easy to generate strings:

std::string GenerateString(size_t len) {
    std::string str;
    auto rand_char = [](){ return alphabet[randomer()]; };
    std::generate_n(std::back_inserter(str), len, rand_char);
    return str;
}

Write your suggestions for improvement below. https://gist.github.com/VjGusev/e6da2cb4d4b0b531c1d009cd1f8904ad

How do I programmatically click on an element in JavaScript?

Are you trying to actually follow the link or trigger the onclick? You can trigger an onclick with something like this:

var link = document.getElementById(linkId);
link.onclick.call(link);

HTML5 iFrame Seamless Attribute

Updated: October 2016

The seamless attribute no longer exists. It was originally pitched to be included in the first HTML5 spec, but subsequently dropped. An unrelated attribute of the same name made a brief cameo in the HTML5.1 draft, but that too was ditched mid-2016:

So I think the gist of it all both from the implementor side and the web-dev side is that seamless as-specced doesn’t seem to be what anybody wanted to begin with. Or at least it’s more than anybody actually wanted. And anyway like @annevk says, it’s seems a lot of it’s since been “overcome by events” in light of Shadow DOM.

In other words: purge the seamless attribute from your memory, and pretend it never existed.

For posterity's sake, here's my original answer from five years ago:

Original answer: April 2011

The attribute is in draft mode at the moment. For that reason, none of the current browsers are supporting it yet (as the implementation is subject to change). In the meantime, it's best just to use CSS to strip the borders/scrollbars from the iframe:

iframe[seamless]{
    background-color: transparent;
    border: 0px none transparent;
    padding: 0px;
    overflow: hidden;
}

There's more to the seamless attribute than what can be added with CSS: part of the reasoning behind the attribute was to allow nested content to inherit the same styles applied to the iframe (acting as though the embedded document was one big nested inside the element, for example).

Lastly, versions of Internet Explorer (8 and earlier) require additional attributes in order to remove the borders, scrollbars and background colour:

<iframe frameborder="0" allowtransparency="true" scrolling="no" src="..."></iframe>

Naturally, this doesn't validate. So it's up to you how to handle it. My (picky) approach would be to sniff the agent string and add the attributes for IE versions earlier than 9.

Hope that helps. :)

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

Just to add something more: nchar - adds trailing spaces to the data. nvarchar - does not add trailing spaces to the data.

So, if you are going to filter your dataset by an 'nchar' field, you may want to use RTRIM to remove the spaces. E.g. nchar(10) field called BRAND stores the word NIKE. It adds 6 spaces to the right of the word. So, when filtering, the expression should read: RTRIM(Fields!BRAND.Value) = "NIKE"

Hope this helps someone out there because I was struggling with it for a bit just now!

How to get time difference in minutes in PHP

A more universal version that returns result in days, hours, minutes or seconds including fractions/decimals:

function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
    $nInterval = strtotime($sDate2) - strtotime($sDate1);
    if ($sUnit=='D') { // days
        $nInterval = $nInterval/60/60/24;
    } else if ($sUnit=='H') { // hours
        $nInterval = $nInterval/60/60;
    } else if ($sUnit=='M') { // minutes
        $nInterval = $nInterval/60;
    } else if ($sUnit=='S') { // seconds
    }
    return $nInterval;
} //DateDiffInterval

Best practice to return errors in ASP.NET Web API

You can use custom ActionFilter in Web Api to validate model:

public class DRFValidationFilters : ActionFilterAttribute
{

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request
                .CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);

            //BadRequest(actionContext.ModelState);
        }
    }

    public override Task OnActionExecutingAsync(HttpActionContext actionContext,
        CancellationToken cancellationToken)
    {

        return Task.Factory.StartNew(() =>
        {
            if (!actionContext.ModelState.IsValid)
            {
                actionContext.Response = actionContext.Request
                    .CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        });
    }

    public class AspirantModel
    {
        public int AspirantId { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string AspirantType { get; set; }
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
            ErrorMessage = "Not a valid Phone number")]
        public string MobileNumber { get; set; }
        public int StateId { get; set; }
        public int CityId { get; set; }
        public int CenterId { get; set; }


        [HttpPost]
        [Route("AspirantCreate")]
        [DRFValidationFilters]
        public IHttpActionResult Create(AspirantModel aspirant)
        {
            if (aspirant != null)
            {

            }
            else
            {
                return Conflict();
            }

            return Ok();
        }
    }
}

Register CustomAttribute class in webApiConfig.cs config.Filters.Add(new DRFValidationFilters());

How can I add an empty directory to a Git repository?

Create an empty file called .gitkeep in the directory, and add that.

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

Get child Node of another Node, given node name

//xn=list of parent nodes......                
foreach (XmlNode xn in xnList)
{                                           
    foreach (XmlNode child in xn.ChildNodes) 
    {
        if (child.Name.Equals("name")) 
        {
            name = child.InnerText; 
        }
        if (child.Name.Equals("age"))
        {
            age = child.InnerText; 
        }
    }
}

Convert categorical data in pandas dataframe

If your concern was only that you making a extra column and deleting it later, just dun use a new column at the first place.

dataframe = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'),  'col3':list('ababb')})
dataframe.col3 = pd.Categorical.from_array(dataframe.col3).codes

You are done. Now as Categorical.from_array is deprecated, use Categorical directly

dataframe.col3 = pd.Categorical(dataframe.col3).codes

If you also need the mapping back from index to label, there is even better way for the same

dataframe.col3, mapping_index = pd.Series(dataframe.col3).factorize()

check below

print(dataframe)
print(mapping_index.get_loc("c"))

Extending an Object in Javascript

Mozilla 'announces' object extending from ECMAScript 6.0:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends

NOTE: This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.

class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);
    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;     } 
}

This technology is available in Gecko (Google Chrome / Firefox) - 03/2015 nightly builds.

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

Getting attributes of a class

def props(cls):   
  return [i for i in cls.__dict__.keys() if i[:1] != '_']

properties = props(MyClass)

What are the obj and bin folders (created by Visual Studio) used for?

One interesting fact about the obj directory: If you have publishing set up in a web project, the files that will be published are staged to obj\Release\Package\PackageTmp. If you want to publish the files yourself rather than use the integrated VS feature, you can grab the files that you actually need to deploy here, rather than pick through all the digital debris in the bin directory.

Get the ID of a drawable in ImageView

Digging StackOverflow for answers on the similar issue I found people usually suggesting 2 approaches:

  • Load a drawable into memory and compare ConstantState or bitmap itself to other one.
  • Set a tag with drawable id into a view and compare tags when you need that.

Personally, I like the second approach for performance reason but tagging bunch of views with appropriate tags is painful and time consuming. This could be very frustrating in a big project. In my case I need to write a lot of Espresso tests which require comparing TextView drawables, ImageView resources, View background and foreground. A lot of work.

So I eventually came up with a solution to delegate a 'dirty' work to the custom inflater. In every inflated view I search for a specific attributes and and set a tag to the view with a resource id if any is found. This approach is pretty much the same guys from Calligraphy used. I wrote a simple library for that: TagView

If you use it, you can retrieve any of predefined tags, containing drawable resource id that was set in xml layout file:

TagViewUtils.getTag(view, ViewTag.IMAGEVIEW_SRC.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_LEFT.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_TOP.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_RIGHT.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_BOTTOM.id)
TagViewUtils.getTag(view, ViewTag.VIEW_BACKGROUND.id)
TagViewUtils.getTag(view, ViewTag.VIEW_FOREGROUND.id)

The library supports any attribute, actually. You can add them manually, just look into the Custom attributes section on Github. If you set a drawable in runtime you can use convenient library methods:

setImageViewResource(ImageView view, int id)

In this case tagging is done for you internally. If you use Kotlin you can write a handy extensions to call view itself. Something like this:

fun ImageView.setImageResourceWithTag(@DrawableRes int id) {
    TagViewUtils.setImageViewResource(this, id)
}

You can find additional info in Tagging in runtime

Bitbucket git credentials if signed up with Google

One way to skip this is by creating a specific app password variable.

  1. Settings
  2. App passwords
  3. Create app password

And you can use that generated password to access or to push commits from your terminal, when using a Google Account to sign in into Bitbucket.

How get permission for camera in android.(Specifically Marshmallow)

Requesting Permissions In the following code, we will ask for camera permission:

in java

EasyPermissions is a wrapper library to simplify basic system permissions logic when targeting Android M or higher.

Installation EasyPermissions is installed by adding the following dependency to your build.gradle file:

dependencies {

    // For developers using AndroidX in their applications
    implementation 'pub.devrel:easypermissions:3.0.0'

    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'

}


private void askAboutCamera(){

        EasyPermissions.requestPermissions(
                this,
                "A partir deste ponto a permissão de câmera é necessária.",
                CAMERA_REQUEST_CODE,
                Manifest.permission.CAMERA );
}