Programs & Examples On #Static factory

Opening PDF String in new window with javascript

for the latest Chrome version, this works for me :

var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = 'iframe width="100%" height="100%" src="data:application/pdf;base64,"+base64+"></iframe>';

Thanks

expected assignment or function call: no-unused-expressions ReactJS

For me the error occured when using map. And I didn't use the return Statement inside the map.

{cart.map((cart_products,index) => {
    <span>{cart_products.id}</span>; 
})};

Above code produced error.

{cart.map((cart_products,index) => {
    return (<span>{cart_products.id}</span>); 
})};

Simply adding return solved it.

Remove useless zero digits from decimals in PHP

$value = preg_replace('~\.0+$~','',$value);

if var == False

Use not

var = False
if not var:
    print 'learnt stuff'

How do I disable a Pylint warning?

Starting from Pylint v. 0.25.3, you can use the symbolic names for disabling warnings instead of having to remember all those code numbers. E.g.:

# pylint: disable=locally-disabled, multiple-statements, fixme, line-too-long

This style is more instructive than cryptic error codes, and also more practical since newer versions of Pylint only output the symbolic name, not the error code.

The correspondence between symbolic names and codes can be found here.

A disable comment can be inserted on its own line, applying the disable to everything that comes after in the same block. Alternatively, it can be inserted at the end of the line for which it is meant to apply.

If Pylint outputs "Locally disabling" messages, you can get rid of them by including the disable locally-disabled first as in the example above.

WSDL/SOAP Test With soapui

A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.

The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.

How to use ES6 Fat Arrow to .filter() an array of objects

As simple as you can use const adults = family.filter(({ age }) => age > 18 );

_x000D_
_x000D_
const family =[{"name":"Jack",  "age": 26},_x000D_
              {"name":"Jill",  "age": 22},_x000D_
              {"name":"James", "age": 5 },_x000D_
              {"name":"Jenny", "age": 2 }];_x000D_
_x000D_
const adults = family.filter(({ age }) => age > 18 );_x000D_
_x000D_
console.log(adults)
_x000D_
_x000D_
_x000D_

Swift Beta performance: sorting arrays

tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].


Here is an in-place quicksort in Swift Beta:

func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
    if (end - start < 2){
        return
    }
    var p = a[start + (end - start)/2]
    var l = start
    var r = end - 1
    while (l <= r){
        if (a[l] < p){
            l += 1
            continue
        }
        if (a[r] > p){
            r -= 1
            continue
        }
        var t = a[l]
        a[l] = a[r]
        a[r] = t
        l += 1
        r -= 1
    }
    quicksort_swift(&a, start, r + 1)
    quicksort_swift(&a, r + 1, end)
}

And the same in C:

void quicksort_c(int *a, int n) {
    if (n < 2)
        return;
    int p = a[n / 2];
    int *l = a;
    int *r = a + n - 1;
    while (l <= r) {
        if (*l < p) {
            l++;
            continue;
        }
        if (*r > p) {
            r--;
            continue;
        }
        int t = *l;
        *l++ = *r;
        *r-- = t;
    }
    quicksort_c(a, r - a + 1);
    quicksort_c(l, a + n - l);
}

Both work:

var a_swift:CInt[] = [0,5,2,8,1234,-1,2]
var a_c:CInt[] = [0,5,2,8,1234,-1,2]

quicksort_swift(&a_swift, 0, a_swift.count)
quicksort_c(&a_c, CInt(a_c.count))

// [-1, 0, 2, 2, 5, 8, 1234]
// [-1, 0, 2, 2, 5, 8, 1234]

Both are called in the same program as written.

var x_swift = CInt[](count: n, repeatedValue: 0)
var x_c = CInt[](count: n, repeatedValue: 0)
for var i = 0; i < n; ++i {
    x_swift[i] = CInt(random())
    x_c[i] = CInt(random())
}

let swift_start:UInt64 = mach_absolute_time();
quicksort_swift(&x_swift, 0, x_swift.count)
let swift_stop:UInt64 = mach_absolute_time();

let c_start:UInt64 = mach_absolute_time();
quicksort_c(&x_c, CInt(x_c.count))
let c_stop:UInt64 = mach_absolute_time();

This converts the absolute times to seconds:

static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MSEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MSEC;

mach_timebase_info_data_t timebase_info;

uint64_t abs_to_nanos(uint64_t abs) {
    if ( timebase_info.denom == 0 ) {
        (void)mach_timebase_info(&timebase_info);
    }
    return abs * timebase_info.numer  / timebase_info.denom;
}

double abs_to_seconds(uint64_t abs) {
    return abs_to_nanos(abs) / (double)NANOS_PER_SEC;
}

Here is a summary of the compiler's optimazation levels:

[-Onone] no optimizations, the default for debug.
[-O]     perform optimizations, the default for release.
[-Ofast] perform optimizations and disable runtime overflow checks and runtime type checks.

Time in seconds with [-Onone] for n=10_000:

Swift:            0.895296452
C:                0.001223848

Here is Swift's builtin sort() for n=10_000:

Swift_builtin:    0.77865783

Here is [-O] for n=10_000:

Swift:            0.045478346
C:                0.000784666
Swift_builtin:    0.032513488

As you can see, Swift's performance improved by a factor of 20.

As per mweathers' answer, setting [-Ofast] makes the real difference, resulting in these times for n=10_000:

Swift:            0.000706745
C:                0.000742374
Swift_builtin:    0.000603576

And for n=1_000_000:

Swift:            0.107111846
C:                0.114957179
Swift_sort:       0.092688548

For comparison, this is with [-Onone] for n=1_000_000:

Swift:            142.659763258
C:                0.162065333
Swift_sort:       114.095478272

So Swift with no optimizations was almost 1000x slower than C in this benchmark, at this stage in its development. On the other hand with both compilers set to [-Ofast] Swift actually performed at least as well if not slightly better than C.

It has been pointed out that [-Ofast] changes the semantics of the language, making it potentially unsafe. This is what Apple states in the Xcode 5.0 release notes:

A new optimization level -Ofast, available in LLVM, enables aggressive optimizations. -Ofast relaxes some conservative restrictions, mostly for floating-point operations, that are safe for most code. It can yield significant high-performance wins from the compiler.

They all but advocate it. Whether that's wise or not I couldn't say, but from what I can tell it seems reasonable enough to use [-Ofast] in a release if you're not doing high-precision floating point arithmetic and you're confident no integer or array overflows are possible in your program. If you do need high performance and overflow checks / precise arithmetic then choose another language for now.

BETA 3 UPDATE:

n=10_000 with [-O]:

Swift:            0.019697268
C:                0.000718064
Swift_sort:       0.002094721

Swift in general is a bit faster and it looks like Swift's built-in sort has changed quite significantly.

FINAL UPDATE:

[-Onone]:

Swift:   0.678056695
C:       0.000973914

[-O]:

Swift:   0.001158492
C:       0.001192406

[-Ounchecked]:

Swift:   0.000827764
C:       0.001078914

Move cursor to end of file in vim

Hit Esc and then press: Shift + G

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

Using :after to clear floating elements

Use

.wrapper:after {
    content : '\n';
}

Much like solution provided by Roko. It allows to insert/change content using : after and :before psuedo. For details check http://www.quirksmode.org/css/content.html

How to test android apps in a real device with Android Studio?

I can run on my device at last, just I enabled the "USB debugging" and "Allow mock location" options from the Debug Menu of my device.

make an ID in a mysql table auto_increment (after the fact)

Yes, easy. Just run a data-definition query to update the tables, adding an AUTO_INCREMENT column.

If you have an existing database, be careful to preserve any foreign-key relationships that might already be there on the "artificially created" primary keys.

How to replace comma with a dot in the number (or any replacement)

From the function's definition (http://www.w3schools.com/jsref/jsref_replace.asp):

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

This method does not change the original string.

Hence, the line: tt.replace(/,/g, '.') does not change the value of tt; it just returns the new value.

You need to replace this line with: tt = tt.replace(/,/g, '.')

Is there a difference between /\s/g and /\s+/g?

In the first regex, each space character is being replaced, character by character, with the empty string.

In the second regex, each contiguous string of space characters is being replaced with the empty string because of the +.

However, just like how 0 multiplied by anything else is 0, it seems as if both methods strip spaces in exactly the same way.

If you change the replacement string to '#', the difference becomes much clearer:

var str = '  A B  C   D EF ';
console.log(str.replace(/\s/g, '#'));  // ##A#B##C###D#EF#
console.log(str.replace(/\s+/g, '#')); // #A#B#C#D#EF#

Pandas DataFrame to List of Lists

You could access the underlying array and call its tolist method:

>>> df = pd.DataFrame([[1,2,3],[3,4,5]])
>>> lol = df.values.tolist()
>>> lol
[[1L, 2L, 3L], [3L, 4L, 5L]]

Reading images in python

With matplotlib you can use (as shown in the matplotlib documentation)

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img=mpimg.imread('image_name.png')

And plot the image if you want

imgplot = plt.imshow(img)

Clone private git repo with dockerfile

Another option is to use a multi-stage docker build to ensure that your SSH keys are not included in the final image.

As described in my post you can prepare your intermediate image with the required dependencies to git clone and then COPY the required files into your final image.

Additionally if we LABEL our intermediate layers, we can even delete them from the machine when finished.

# Choose and name our temporary image.
FROM alpine as intermediate
# Add metadata identifying these images as our build containers (this will be useful later!)
LABEL stage=intermediate

# Take an SSH key as a build argument.
ARG SSH_KEY

# Install dependencies required to git clone.
RUN apk update && \
    apk add --update git && \
    apk add --update openssh

# 1. Create the SSH directory.
# 2. Populate the private key file.
# 3. Set the required permissions.
# 4. Add github to our list of known hosts for ssh.
RUN mkdir -p /root/.ssh/ && \
    echo "$SSH_KEY" > /root/.ssh/id_rsa && \
    chmod -R 600 /root/.ssh/ && \
    ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts

# Clone a repository (my website in this case)
RUN git clone [email protected]:janakerman/janakerman.git

# Choose the base image for our final image
FROM alpine

# Copy across the files from our `intermediate` container
RUN mkdir files
COPY --from=intermediate /janakerman/README.md /files/README.md

We can then build:

MY_KEY=$(cat ~/.ssh/id_rsa)
docker build --build-arg SSH_KEY="$MY_KEY" --tag clone-example .

Prove our SSH keys are gone:

docker run -ti --rm clone-example cat /root/.ssh/id_rsa

Clean intermediate images from the build machine:

docker rmi -f $(docker images -q --filter label=stage=intermediate)

Add error bars to show standard deviation on a plot in R

In addition to @csgillespie's answer, segments is also vectorised to help with this sort of thing:

plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)

enter image description here

What is System, out, println in System.out.println() in Java

System is a final class from the java.lang package.

out is a class variable of type PrintStream declared in the System class.

println is a method of the PrintStream class.

How to find substring inside a string (or how to grep a variable)?

expr is used instead of [ rather than inside it, and variables are only expanded inside double quotes, so try this:

if expr match "$LIST" "$SOURCE"; then

But I'm not really clear what SOURCE is supposed to represent.

It looks like your code will read in a pattern from standard input, and exit if it matches a database alias, otherwise it will echo "ok". Is that what you want?

Apache VirtualHost and localhost

I am running Ubuntu 16.04 (Xenial Xerus). This is what worked for me:

  1. Open up a terminal and cd to /etc/apache2/sites-available. There you will find a file called 000-default.conf.
  2. Copy that file: cp 000-default.conf example.local.conf
  3. Open that new file (I use Nano; use what you are comfortable with).
  4. You will see a lot of commented lines, which you can delete.
  5. Change <VirtualHost *:80> to <VirtualHost example.local:80>
  6. Change the document root to reflect the location of your files.
  7. Add the following line: ServerName example.local And if you need to, add this line: ServerAlias www.example.local
  8. Save the file and restart Apache: service Apache2 restart

Open a browser and navigate to example.local. You should see your website.

Capitalize only first character of string and leave others alone? (Rails)

str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

Error renaming a column in MySQL

SYNTAX

alter table table_name rename column old column name to new column name;

Example:

alter table library rename column cost to price;

How to iterate over rows in a DataFrame in Pandas

I was looking for How to iterate on rows and columns and ended here so:

for i, row in df.iterrows():
    for j, column in row.iteritems():
        print(column)

How to check if a string contains an element from a list in Python

It is better to parse the URL properly - this way you can handle http://.../file.doc?foo and http://.../foo.doc/file.exe correctly.

from urlparse import urlparse
import os
path = urlparse(url_string).path
ext = os.path.splitext(path)[1]
if ext in extensionsToCheck:
  print(url_string)

How to solve "The directory is not empty" error when running rmdir command in a batch script?

What worked for me is the following. I appears like the RMDir command will issue “The directory is not empty” nearly all the time...

:Cleanup_Temporary_Files_and_Folders

Erase /F /S /Q C:\MyDir

RMDir /S /Q C:\MyDir
If  Exist  C:\MyDir  GoTo Cleanup_Temporary_Files_and_Folders

Scanner vs. StringTokenizer vs. String.Split

Split is slow, but not as slow as Scanner. StringTokenizer is faster than split. However, I found that I could obtain double the speed, by trading some flexibility, to get a speed-boost, which I did at JFastParser https://github.com/hughperkins/jfastparser

Testing on a string containing one million doubles:

Scanner: 10642 ms
Split: 715 ms
StringTokenizer: 544ms
JFastParser: 290ms

How to detect when a UIScrollView has finished scrolling

The 320 implementations are so much better - here is a patch to get consistent start/ends of the scroll.

-(void)scrollViewDidScroll:(UIScrollView *)sender 
{   
[NSObject cancelPreviousPerformRequestsWithTarget:self];
    //ensure that the end of scroll is fired.
    [self performSelector:@selector(scrollViewDidEndScrollingAnimation:) withObject:sender afterDelay:0.3]; 

...
}

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
...
}

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

Hint: actively refused sounds like somewhat deeper technical trouble, but...

...actually, this response (and also specifically errno:10061) is also given, if one calls the bin/mongo executable and the mongodb service is simply not running on the target machine. This even applies to local machine instances (all happening on localhost).

? Always rule out for this trivial possibility first, i.e. simply by using the command line client to access your db.

See here.

How do I get to IIS Manager?

First of all, you need to check that the IIS is installed in your machine, for that you can go to:

Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'

If not, check it, and Press Accept to install it.

Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).

Edit: You should have something like this: enter image description here

Android AudioRecord example

Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues

What is the best way to concatenate two vectors?

Depends on whether you really need to physically concatenate the two vectors or you want to give the appearance of concatenation of the sake of iteration. The boost::join function

http://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/utilities/join.html

will give you this.

std::vector<int> v0;
v0.push_back(1);
v0.push_back(2);
v0.push_back(3);

std::vector<int> v1;
v1.push_back(4);
v1.push_back(5);
v1.push_back(6);
...

BOOST_FOREACH(const int & i, boost::join(v0, v1)){
    cout << i << endl;
}

should give you

1
2
3
4
5
6

Note boost::join does not copy the two vectors into a new container but generates a pair of iterators (range) that cover the span of both containers. There will be some performance overhead but maybe less that copying all the data to a new container first.

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

This technique is now deprecated.

This used to tell Google how to index the page.

https://developers.google.com/webmasters/ajax-crawling/

This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like www.example.com/ajax.html#!key=value, Google will check the URL www.example.com/ajax.html?_escaped_fragment_=key=value to fetch a non-AJAX version of the contents.

WCF - How to Increase Message Size Quota

I found the easy way

--- right click the webconfig or app config file and click EDIT WCF CONFIGURATION and got to bingdigs ans select yore service and right side show maxReciveMessageSize give a large number ---

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

Since your content-type is application/x-www-form-urlencoded you'll need to encode the POST body, especially if it contains characters like & which have special meaning in a form.

Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.

Here are a couple links for reference.

CSS/HTML: Create a glowing border around an Input Field

_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').focus(function() {_x000D_
    $(this).parent().addClass('open');_x000D_
});_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').blur(function() {_x000D_
    $(this).parent().removeClass('open');_x000D_
});
_x000D_
.open {_x000D_
  color:red;   _x000D_
}_x000D_
.form-fild {_x000D_
 position: relative;_x000D_
 margin: 30px 0;_x000D_
}_x000D_
.form-fild label {_x000D_
 position: absolute;_x000D_
 top: 5px;_x000D_
 left: 10px;_x000D_
 padding:5px;_x000D_
}_x000D_
_x000D_
.form-fild.open label {_x000D_
 top: -25px;_x000D_
 left: 10px;_x000D_
 /*background: #ffffff;*/_x000D_
}_x000D_
.form-fild input[type="text"] {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild textarea {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild.open textarea, _x000D_
.form-fild.open input[type="text"] {_x000D_
 padding-left: 10px;_x000D_
}_x000D_
textarea,_x000D_
input[type="text"] {_x000D_
 padding: 10px;_x000D_
 width: 100%;_x000D_
}_x000D_
textarea,_x000D_
input,_x000D_
.form-fild.open label,_x000D_
.form-fild label {_x000D_
 -webkit-transition: all 0.2s ease-in-out;_x000D_
       -moz-transition: all 0.2s ease-in-out;_x000D_
         -o-transition: all 0.2s ease-in-out;_x000D_
            transition: all 0.2s ease-in-out;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
 <div class="row">_x000D_
     <form>_x000D_
        <div class="form-fild">_x000D_
            <label>Name :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Email :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Number :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Message :</label>_x000D_
            <textarea cols="10" rows="5"></textarea>_x000D_
        </div>_x000D_
    </form>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

AttributeError: 'dict' object has no attribute 'predictors'

The dict.items iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items() will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The class dict does not have any predictors attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

Dealing with commas in a CSV file

The simplest solution I've found is the one LibreOffice uses:

  1. Replace all literal " by
  2. Put double quotes around your string

You can also use the one that Excel uses:

  1. Replace all literal " by ""
  2. Put double quotes around your string

Notice other people recommended to do only step 2 above, but that doesn't work with lines where a " is followed by a ,, like in a CSV where you want to have a single column with the string hello",world, as the CSV would read:

"hello",world"

Which is interpreted as a row with two columns: hello and world"

How to read .pem file to get private and public key

To get the public key you can simply do:

public static PublicKey getPublicKeyFromCertFile(final String certfile){

     return new X509CertImpl(new FileInputStream(new File(certfile))).getPublicKey();

To get the private key is trickier, you can:

public static PrivateKey getPrivateKeyFromKeyFile(final String keyfile){
    try {
        Process p;
        p = Runtime.getRuntime().exec("openssl pkcs8 -nocrypt -topk8 -inform PEM " +
                "-in " + keyfile + " -outform DER -out " + keyfile + ".der");

        p.waitFor();
        System.out.println("Command executed" + (p.exitValue() == 0 ? " successfully" : " with error" ));
    } catch ( IOException | InterruptedException e) {
        e.printStackTrace();
        System.exit(1);
    }

    PrivateKey myPrivKey = null;
    try {
        byte[] keyArray = Files.readAllBytes(Paths.get(keyfile + ".der"));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyArray);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        myPrivKey = keyFactory.generatePrivate(keySpec);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e){
        e.printStackTrace();
        System.exit(1);
    }

    return myPrivKey;
}

Converting JSON to XLS/CSV in Java

You could only convert a JSON array into a CSV file.

Lets say, you have a JSON like the following :

{"infile": [{"field1": 11,"field2": 12,"field3": 13},
            {"field1": 21,"field2": 22,"field3": 23},
            {"field1": 31,"field2": 32,"field3": 33}]}

Lets see the code for converting it to csv :

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSON2CSV {
    public static void main(String myHelpers[]){
        String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}";

        JSONObject output;
        try {
            output = new JSONObject(jsonString);


            JSONArray docs = output.getJSONArray("infile");

            File file=new File("/tmp2/fromJSON.csv");
            String csv = CDL.toString(docs);
            FileUtils.writeStringToFile(file, csv);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
    }

}

Now you got the CSV generated from JSON.

It should look like this:

field1,field2,field3
11,22,33
21,22,23
31,32,33

The maven dependency was like,

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>

Update Dec 13, 2019:

Updating the answer, since now we can support complex JSON Arrays as well.

import java.nio.file.Files;
import java.nio.file.Paths;

import com.github.opendevl.JFlat;

public class FlattenJson {

    public static void main(String[] args) throws Exception {
        String str = new String(Files.readAllBytes(Paths.get("path_to_imput.json")));

        JFlat flatMe = new JFlat(str);

        //get the 2D representation of JSON document
        flatMe.json2Sheet().headerSeparator("_").getJsonAsSheet();

        //write the 2D representation in csv format
        flatMe.write2csv("path_to_output.csv");
    }

}

dependency and docs details are in link

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

In your AndroidManifest.xml add this two-line.

android:usesCleartextTraffic="true"  
<uses-library android:name="org.apache.http.legacy" android:required="false"/>

See this below code

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning">
        <activity android:name=".activity.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    </application>

Call external javascript functions from java code

Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js

jsfunctions.js

var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}

Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
  engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
  Invocable invocable = (Invocable) engine;
  Object result;
  result = invocable.invokeFunction("display", helloWorld);
  System.out.println(result);
  System.out.println(result.getClass());
  } catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
    e.printStackTrace();
    }
  }
}

Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.

How can I check for Python version in a program that uses new language features?

Probably the best way to do do this version comparison is to use the sys.hexversion. This is important because comparing version tuples will not give you the desired result in all python versions.

import sys
if sys.hexversion < 0x02060000:
    print "yep!"
else:
    print "oops!"

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved

This helped me: I created a new maven project which was working fine in my old workspace, but gave above errors in the new workspace. I had to do the following: - Open old workspace on Eclipse - open Preferences tab - Search Maven in filter - Copy the path for settings.xml from User Settings - User Settings - Switch to new workspace - Update the preferences - Maven - User Settings - User Settings path

After the build is completed, all errors are resolved.

Hadoop: «ERROR : JAVA_HOME is not set»

You should set JAVA_HOME in the hadoop-env.sh file also which is in the Hadoop configuration directory. By default the JAVA_HOME setting line is commented.

Updating .class file in jar

A JAR file is just a .zip in disguise. The zipped folder contains .class files.

If you're on macOS:

  1. Rename the file to possess the '.zip' extension. e.g. myJar.jar -> myJar.zip.
  2. Decompress the '.zip' (double click on it). A new folder called 'myJar' will appear
  3. Find and replace the .class file with your new .class file.
  4. Select all the contents of the folder 'myJar' and choose 'Compress x items'. DO NOT ZIP THE FOLDER ITSELF, ONLY ITS CONTENTS

Miscellaneous - Compiling a single .class file, with reference to a original jar, on macOS

  1. Make a file myClass.java, containing your code.
  2. Open terminal from Spotlight.
  3. javac -classpath originalJar.jar myClass.java This will create your compiled class called myClass.class.

From here, follow the steps above. You can also use Eclipse to compile it, simply reference the original jar by right clicking on the project, 'Build Path' -> 'Add External Archives'. From here you should be able to compile it as a jar, and use the zip technique above to retrieve the class from the jar.

Java generics - why is "extends T" allowed but not "implements T"?

It may be that the base type is a generic parameter, so the actual type may be an interface of a class. Consider:

class MyGen<T, U extends T> {

Also from client code perspective interfaces are almost indistinguishable from classes, whereas for subtype it is important.

Capturing window.onbeforeunload

You have to return from the onbeforeunload:

window.onbeforeunload = function() {
    saveFormData();
    return null;
}

function saveFormData() {
    console.log('saved');
}

UPDATE

as per comments, alert does not seem to be working on newer versions anymore, anything else goes :)

FROM MDN

Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.

It is also suggested to use this through the addEventListener interface:

You can and should handle this event through window.addEventListener() and the beforeunload event.

The updated code will now look like this:

window.addEventListener("beforeunload", function (e) {
  saveFormData();

  (e || window.event).returnValue = null;
  return null;
});

How to save a bitmap on internal storage

Modify onClick() as follows:

@Override
public void onClick(View v) {
    if(v == btn) {
        canvas=sv.getHolder().lockCanvas();
        if(canvas!=null) {
            canvas.drawBitmap(bitmap, 100, 100, null);
            sv.getHolder().unlockCanvasAndPost(canvas);
        }
    } else if(v == btn1) {
        saveBitmapToInternalStorage(bitmap);
    }
}

There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.

I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:

if(v == btn) {
    ...
    btn1.setEnabled(true);
}

How to delete items from a dictionary while iterating over it?

You can use a dictionary comprehension.

d = {k:d[k] for k in d if d[k] != val}

MySQL SELECT only not null values

SELECT * FROM TABLE_NAME
where COLUMN_NAME <> '';

Convert textbox text to integer

Example:

int x = Convert.ToInt32(this.txtboxname.Text) + 1 //You dont need the "this"
txtboxname.Text = x.ToString();

The x.ToString() makes the integer into string to show that in the text box.

Result:

  1. You put number in the text box.
  2. You click on the button or something running the function.
  3. You see your number just bigger than your number by one in your text box.

:)

Why I've got no crontab entry on OS X when using vim?

As the previous posts didn't work for me because of some permissions issues, I found that creating a separate crontab file and adding it to the user's crontab with the -u parameter while root worked for me.

sudo crontab -u {USERNAME} ~/{PATH_TO_CRONTAB_FILE}

Can a CSS class inherit one or more other classes?

An element can take multiple classes:

.classOne { font-weight: bold; }
.classTwo { font-famiy:  verdana; }

<div class="classOne classTwo">
  <p>I'm bold and verdana.</p>
</div>

And that's about as close as you're going to get unfortunately. I'd love to see this feature, along with class-aliases someday.

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

Update date + one year in mysql

For multiple interval types use a nested construction as in:

 UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)

For updating a given date in the column date to 1 year + 1 day

Sending a notification from a service in Android

Well, I'm not sure if my solution is best practice. Using the NotificationBuilder my code looks like that:

private void showNotification() {
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent contentIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, builder.build());
    }

Manifest:

    <activity
        android:name=".MainActivity"
        android:launchMode="singleInstance"
    </activity>

and here the Service:

    <service
        android:name=".services.ProtectionService"
        android:launchMode="singleTask">
    </service>

I don't know if there really is a singleTask at Service but this works properly at my application...

Mockito verify order / sequence of method calls

InOrder helps you to do that.

ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);

Mockito.doNothing().when(firstMock).methodOne();   
Mockito.doNothing().when(secondMock).methodTwo();  

//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);

//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();

Rename master branch for both local and remote Git repositories

git checkout -b new-branch-name
git push remote-name new-branch-name :old-branch-name

You may have to manually switch to new-branch-name before deleting old-branch-name

How can I disable an <option> in a <select> based on its value in JavaScript?

I would like to give you also the idea to disable an <option> with a given defined value (not innerhtml). I recommend to it with jQuery to get the simplest way. See my sample below.

HTML

Status:  
<div id="option">
   <select class="status">
      <option value="hand" selected>Hand</option>
      <option value="simple">Typed</option>
      <option value="printed">Printed</option>
   </select>
</div>

Javascript

The idea here is how to disable Printed option when current Status is Hand

var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;

You may see how it works here:

https://jsfiddle.net/chetabahana/f7ejxhnk/28/

JavaScript private methods

var TestClass = function( ) {

    var privateProperty = 42;

    function privateMethod( ) {
        alert( "privateMethod, " + privateProperty );
    }

    this.public = {
        constructor: TestClass,

        publicProperty: 88,
        publicMethod: function( ) {
            alert( "publicMethod" );
            privateMethod( );
        }
    };
};
TestClass.prototype = new TestClass( ).public;


var myTestClass = new TestClass( );

alert( myTestClass.publicProperty );
myTestClass.publicMethod( );

alert( myTestClass.privateMethod || "no privateMethod" );

Similar to georgebrock but a little less verbose (IMHO) Any problems with doing it this way? (I haven't seen it anywhere)

edit: I realised this is kinda useless since every independent instantiation has its own copy of the public methods, thus undermining the use of the prototype.

Take a screenshot via a Python script on Linux

Just for completeness: Xlib - But it's somewhat slow when capturing the whole screen:

from Xlib import display, X
import Image #PIL

W,H = 200,200
dsp = display.Display()
try:
    root = dsp.screen().root
    raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff)
    image = Image.fromstring("RGB", (W, H), raw.data, "raw", "BGRX")
    image.show()
finally:
    dsp.close()

One could try to trow some types in the bottleneck-files in PyXlib, and then compile it using Cython. That could increase the speed a bit.


Edit: We can write the core of the function in C, and then use it in python from ctypes, here is something I hacked together:

#include <stdio.h>
#include <X11/X.h>
#include <X11/Xlib.h>
//Compile hint: gcc -shared -O3 -lX11 -fPIC -Wl,-soname,prtscn -o prtscn.so prtscn.c

void getScreen(const int, const int, const int, const int, unsigned char *);
void getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data) 
{
   Display *display = XOpenDisplay(NULL);
   Window root = DefaultRootWindow(display);

   XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap);

   unsigned long red_mask   = image->red_mask;
   unsigned long green_mask = image->green_mask;
   unsigned long blue_mask  = image->blue_mask;
   int x, y;
   int ii = 0;
   for (y = 0; y < H; y++) {
       for (x = 0; x < W; x++) {
         unsigned long pixel = XGetPixel(image,x,y);
         unsigned char blue  = (pixel & blue_mask);
         unsigned char green = (pixel & green_mask) >> 8;
         unsigned char red   = (pixel & red_mask) >> 16;

         data[ii + 2] = blue;
         data[ii + 1] = green;
         data[ii + 0] = red;
         ii += 3;
      }
   }
   XDestroyImage(image);
   XDestroyWindow(display, root);
   XCloseDisplay(display);
}

And then the python-file:

import ctypes
import os
from PIL import Image

LibName = 'prtscn.so'
AbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName
grab = ctypes.CDLL(AbsLibPath)

def grab_screen(x1,y1,x2,y2):
    w, h = x2-x1, y2-y1
    size = w * h
    objlength = size * 3

    grab.getScreen.argtypes = []
    result = (ctypes.c_ubyte*objlength)()

    grab.getScreen(x1,y1, w, h, result)
    return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1)
    
if __name__ == '__main__':
  im = grab_screen(0,0,1440,900)
  im.show()

How to sort a data frame by alphabetic order of a character variable in R?

#sort dataframe by col
sort.df <- with(df,  df[order(sortbythiscolumn) , ])

#can also sort by more than one variable: sort by col1 and then by col2
sort2.df <- with(df, df[order(col1, col2) , ])

#sort in reverse order
sort2.df <- with(df, df[order(col1, -col2) , ])

How do I iterate and modify Java Sets?

You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().

however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.

Set<Integer> s; //contains your Integers
...
Set<Integer> temp = new Set<Integer>();
for(Integer i : s)
    temp.add(i+1);
s.clear();
s.addAll(temp);

How to uninstall Eclipse?

The steps are very simple and it'll take just few mins. 1.Go to your C drive and in that go to the 'USER' section. 2.Under 'USER' section go to your 'name(e.g-'user1') and then find ".eclipse" folder and delete that folder 3.Along with that folder also delete "eclipse" folder and you can find that you're work has been done completely.

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

this works with "NA" not for NA

comments = c("no","yes","NA")
  for (l in 1:length(comments)) {
    #if (!is.na(comments[l])) print(comments[l])
    if (comments[l] != "NA") print(comments[l])
  }

background-size in shorthand background property (CSS3)

You can do as

 body{
        background:url('equote.png'),url('equote.png');
        background-size:400px 100px,50px 50px;
    }

How to implement the --verbose or -v option into a script?

Use the logging module:

import logging as log
…
args = p.parse_args()
if args.verbose:
    log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
    log.info("Verbose output.")
else:
    log.basicConfig(format="%(levelname)s: %(message)s")

log.info("This should be verbose.")
log.warning("This is a warning.")
log.error("This is an error.")

All of these automatically go to stderr:

% python myprogram.py
WARNING: This is a warning.
ERROR: This is an error.

% python myprogram.py -v
INFO: Verbose output.
INFO: This should be verbose.
WARNING: This is a warning.
ERROR: This is an error.

For more info, see the Python Docs and the tutorials.

How to call JavaScript function instead of href in HTML

href is optional for a elements.

It's completely sufficient to use

<a onclick="ShowOld(2367,146986,2)">link text</a>

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

I had the same problem while trying to consume net.tcp wcf service endpoint in a http asmx service.

As I saw no one wrote specific answer WHY is this problem occurring, but only how to be handled properly.

I've been struggling with it several days in a row and finally I found out where the problem comes from in my case.

Initially I thought that when you make a reference to a service the config file will be configured regarding security tag the same way as it's in the source, but that was not the case and I should take care of it manually. In my case I had only

<netTcpBinding>
    <binding name="NetTcpBinding_IAuthenticationLoggerService"
    </binding>
</netTcpBinding>`

Later I saw that the security part is missing and it should looks like this

<netTcpBinding>
    <binding name="NetTcpBinding_IAuthenticationLoggerService" transferMode="Buffered">
      <security mode="None">
        <transport clientCredentialType="None"/>
      </security>
    </binding>
  </netTcpBinding>

The second problem in my case was that I was using transferMode="Streamed" on my source WCF service and in the client I had nothing specific about it, which was bad, because the default transferMode is Buffered and it's important on both places source and client to be configured in the same way.

WebSocket with SSL

The WebSocket connection starts its life with an HTTP or HTTPS handshake. When the page is accessed through HTTP, you can use WS or WSS (WebSocket secure: WS over TLS) . However, when your page is loaded through HTTPS, you can only use WSS - browsers don't allow to "downgrade" security.

How can I find the location of origin/master in git, and how do I change it?

I am struggling with this problem and none of the previous answers tackle the question as I see it. I have stripped the problem back down to its basics to see if I can make my problem clear.

I create a new repository (rep1), put one file in it and commit it.

mkdir rep1
cd rep1
git init
echo "Line1" > README
git add README
git commit -m "Commit 1"

I create a clone of rep1 and call it rep2. I look inside rep2 and see the file is correct.

cd ~
git clone ~/rep1 rep2
cat ~/rep2/README

In rep1 I make a single change to the file and commit it. Then in rep1 I create a remote to point to rep2 and push the changes.

cd ~/rep1
<change file and commit>
git remote add rep2 ~/rep2
git push rep2 master

Now when I go into rep2 and do a 'git status' I get told I am ahead of origin.

# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   README
#

README in rep2 is as it was originally, before the second commit. The only modifications I have done are to rep1 and all I wanted to do was push them out to rep2. What is it I am not grasping?

Cannot issue data manipulation statements with executeQuery()

Use executeUpdate() to issue data manipulation statements. executeQuery() is only meant for SELECT queries (i.e. queries that return a result set).

Swift programmatically navigate to another view controller/scene

Swift 5

The default modal presentation style is a card. This shows the previous view controller at the top and allows the user to swipe away the presented view controller.

To retain the old style you need to modify the view controller you will be presenting like this:

newViewController.modalPresentationStyle = .fullScreen

This is the same for both programmatically created and storyboard created controllers.

Swift 3

With a programmatically created Controller

If you want to navigate to Controller created Programmatically, then do this:

let newViewController = NewViewController()
self.navigationController?.pushViewController(newViewController, animated: true)

With a StoryBoard created Controller

If you want to navigate to Controller on StoryBoard with Identifier "newViewController", then do this:

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
        self.present(newViewController, animated: true, completion: nil)

How to change UIPickerView height

As of iOS 9, you can freely change UIPickerView's width and height. No need to use the above mentioned transform hacks.

Where does Visual Studio look for C++ header files?

Visual Studio looks for headers in this order:

  • In the current source directory.
  • In the Additional Include Directories in the project properties (Project -> [project name] Properties, under C/C++ | General).
  • In the Visual Studio C++ Include directories under Tools ? Options ? Projects and Solutions ? VC++ Directories.
  • In new versions of Visual Studio (2015+) the above option is deprecated and a list of default include directories is available at Project Properties ? Configuration ? VC++ Directories

In your case, add the directory that the header is to the project properties (Project Properties ? Configuration ? C/C++ ? General ? Additional Include Directories).

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

What does `dword ptr` mean?

Consider the figure enclosed in this other question. ebp-4 is your first local variable and, seen as a dword pointer, it is the address of a 32 bit integer that has to be cleared. Maybe your source starts with

Object x = null;

Find length (size) of an array in jquery

Integer has no method length. Try string

var testvar={};
testvar[1]="2";
alert(testvar[1].length);

Checking if a folder exists using a .bat file

For a file:

if exist yourfilename (
  echo Yes 
) else (
  echo No
)

Replace yourfilename with the name of your file.

For a directory:

if exist yourfoldername\ (
  echo Yes 
) else (
  echo No
)

Replace yourfoldername with the name of your folder.

A trailing backslash (\) seems to be enough to distinguish between directories and ordinary files.

Bootstrap collapse animation not smooth

For others like me who had a different but similar issue where the animation was not occurring at all:

From what I could find it may be something in my browser setting which preferred less motion for accessibility purposes. I could not find any setting in my browser, but I was able to get the animation working by downloading a local copy of bootstrap and commenting out this section of the CSS file:

@media (prefers-reduced-motion: reduce) {
  .collapsing {
    -webkit-transition: none;
    transition: none;
  }
}

iPhone hide Navigation Bar only on first page

Swift 4:

In the view controller you want to hide the navigation bar from.

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(true, animated: animated)
    super.viewWillAppear(animated)
}

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(false, animated: animated)
    super.viewWillDisappear(animated)
}

Center form submit buttons HTML / CSS

/* here is what works for me - set up as a class */

.button {
    text-align: center;
    display: block;
    margin: 0 auto;
}

/* you can set padding and width to whatever works best */

How to do a newline in output

Use "\n" instead of '\n'

Using jQuery to test if an input has focus

An alternative to using classes to mark the state of an element is the internal data store functionality.

P.S.: You are able to store booleans and whatever you desire using the data() function. It's not just about strings :)

$("...").mouseover(function ()
{
    // store state on element
}).mouseout(function ()
{
    // remove stored state on element
});

And then it's just a matter of accessing the state of elements.

Set a cookie to never expire

Never and forever are two words that I avoid using due to the unpredictability of life.

The latest time since 1 January 1970 that can be stored using a signed 32-bit integer is 03:14:07 on Tuesday, 19 January 2038 (231-1 = 2,147,483,647 seconds after 1 January 1970). This limitation is known as the Year 2038 problem

setCookie("name", "value", strtotime("2038-01-19 03:14:07"));

c# regex matches example

This pattern should work:

#\d

foreach(var match in System.Text.RegularExpressions.RegEx.Matches(input, "#\d"))
{
    Console.WriteLine(match.Value);
}

(I'm not in front of Visual Studio, but even if that doesn't compile as-is, it should be close enough to tweak into something that works).

Determine when a ViewPager changes pages

You can also use ViewPager.SimpleOnPageChangeListener instead of ViewPager.OnPageChangeListener and override only those methods you want to use.

viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

    // optional 
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

    // optional 
    @Override
    public void onPageSelected(int position) { }

    // optional 
    @Override
    public void onPageScrollStateChanged(int state) { }
});

Hope this help :)

Edit: As per android APIs, setOnPageChangeListener (ViewPager.OnPageChangeListener listener) is deprecated. Please check this url:- Android ViewPager API

PHP: merge two arrays while keeping keys instead of reindexing?

Try array_replace_recursive or array_replace functions

$a = array('userID' => 1, 'username'=> 2);
array (
  userID => 1,
  username => 2
)
$b = array('userID' => 1, 'companyID' => 3);
array (
  'userID' => 1,
  'companyID' => 3
)
$c = array_replace_recursive($a,$b);
array (
  userID => 1,
  username => 2,
  companyID => 3
)

http://php.net/manual/en/function.array-replace-recursive.php

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

Editing the first line of this file worked to me:

MBP-de-Jose:~ josejunior$ which python3

/usr/local/Cellar/python/3.7.3/bin/python3

MBP-de-Jose:~ josejunior$

before

#!/usr/local/opt/python/bin/python3.7

after

#!/usr/local/Cellar/python/3.7.3/bin/python3

CSS3 gradient background set on body doesn't stretch but instead repeats?

Here's what I did to solve this problem... it will show the gradient for the full length of the content, then simply fallback to the background color (normally the last color in the gradient).

_x000D_
_x000D_
   html {_x000D_
     background: #cbccc8;_x000D_
   }_x000D_
   body {_x000D_
     background-repeat: no-repeat;_x000D_
     background: #cbccc8;_x000D_
     background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbccc8));_x000D_
     background: -moz-linear-gradient(top, #fff, #cbccc8);_x000D_
     filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#cbccc8');_x000D_
   }
_x000D_
<body>_x000D_
  <h1>Hello world!</h1>_x000D_
</body>
_x000D_
_x000D_
_x000D_

I've tested this in FireFox 3.6, Safari 4, and Chrome, I keep the background-color in the body for any browsers that for some reason don't support styling the HTML tag.

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

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

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

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

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

php - How do I fix this illegal offset type error

Use trim($source) before $s[$source].

Update Jenkins from a war file

I use this groovy script to download new war file

import java.util.concurrent.atomic.AtomicInteger

class ThreadHelper{
    static done = false;
    static starttime = System.currentTimeMillis()
    static synchronized printx (message) {    printf ("%5s seconds: %20s",(System.currentTimeMillis()-starttime)/1000.0 , message); println("") }
    def download(address)
    {
    def filename = new File(System.getenv()['CI_HOME'] + '/' + address.tokenize("/")[-1])
    println(filename.getCanonicalPath())
    def file = new FileOutputStream(filename)
    def out = new BufferedOutputStream(file)
    out << new URL(address).openStream()
    out.close()
    done=true;
    }

}

println("executing from ... "+ new File(".").getCanonicalPath())

def counter = new AtomicInteger();
    th = Thread.start {
    while(!ThreadHelper.done) {
    sleep 1000
    counter.incrementAndGet()
    print '.'
    }
}

th2 = Thread.start { new ThreadHelper().download("http://mirrors.jenkins-ci.org/war/latest/jenkins.war") }
th.join()
th2.join()

ThreadHelper.printx('done')

And another script shutsdown tomcat - copies the war and restarts it

We host it on windows 2008 and tomcat, I use sc query, sc config, sc stop, sc start to manage windows services

    set warname=jenkins

if '%name%' == 'trak' set warname=trak

pushd .
if '%name%'=='' goto badname
if '%warname%'=='' goto badname

if '%ci_home%'=='' goto badcihome

REM =====================================================
REM stop windows service
sc stop %name%

REM sleep for 5 seconds see http:\\stackoverflow.com\questions\1672338\how-to-sleep-for-5-seconds-in-windowss-command-prompt-or-dos
ping 1.1.1.1 -n 1 -w 3000 > nul

rem replace forward slash with backward slash
set tomcat_dir=%ci_home:/=\%\instances\tomcat7-%name%

REM Create sub directory called bak-yymmdd-hhmmss
REM where yymmdd-hhmmss is a date-time stamp like 120601-142907

set hh=%time:~0,2%

REM Since there is no leading zero for times before 10 am, have to put in
REM a zero when this is run before 10 am.

if "%time:~0,1%"==" " set hh=0%hh:~1,1%

set yymmdd_hhmmss=%date:~12,2%%date:~4,2%%date:~7,2%-%hh%%time:~3,2%%time:~6,2%

set backupdir=bak-%yymmdd_hhmmss%

REM =====================================================
md %tomcat_dir%\logs\%backupdir%

cd %tomcat_dir%\logs

dir bak*
echo "nothing-to-log" >> force.log

REM move command will fail if there is nothing to move hence the force log statement above

call move *.* %backupdir%

REM =====================================================
rmdir %tomcat_dir%\webapps\%name% /q/s

echo f|xcopy %ci_home%\%warname%.war %tomcat_dir%\webapps\%name%.war /y

REM TODO===== something about jenkins plugins

REM =====================================================
cd "%tomcat_dir%\bin"
call catalina version

echo =====================================================
echo ====== removing %name%
call service remove %name%

echo =====================================================
echo ====== installing %name%
call service install %name%

echo on

REM setting service to start automatically, note that space before the word auto IS REQUIRED
sc config %name% start= auto

REM =====================================================
sc start %name%

popd

exit 0

goto done

:badname
echo 'name required - this will be used as windows service name as well'
pause
exit 1

:badcihome
echo 'CI home env var required - ci_home'
pause
exit 1

:done

How to resolve Unneccessary Stubbing exception

Looking at a part of your stack trace it looks like you are stubbing the dao.doSearch() elsewhere. More like repeatedly creating the stubs of the same method.

Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at service.Test.testDoSearch(Test.java:72)
Please remove unnecessary stubbings or use 'silent' option. More info: javadoc for UnnecessaryStubbingException class.

Consider the below Test Class for example:

@RunWith(MockitoJUnitRunner.class)
public class SomeTest {
    @Mock
    Service1 svc1Mock1;

    @Mock
    Service2 svc2Mock2;

    @InjectMock
    TestClass class;

    //Assume you have many dependencies and you want to set up all the stubs 
    //in one place assuming that all your tests need these stubs.

    //I know that any initialization code for the test can/should be in a 
    //@Before method. Lets assume there is another method just to create 
    //your stubs.

    public void setUpRequiredStubs() {
        when(svc1Mock1.someMethod(any(), any())).thenReturn(something));
        when(svc2Mock2.someOtherMethod(any())).thenReturn(somethingElse);
    }

    @Test
    public void methodUnderTest_StateUnderTest_ExpectedBehavior() {
        // You forget that you defined the stub for svcMock1.someMethod or 
        //thought you could redefine it. Well you cannot. That's going to be 
        //a problem and would throw your UnnecessaryStubbingException.
       when(svc1Mock1.someMethod(any(),any())).thenReturn(anyThing);//ERROR!
       setUpRequiredStubs();
    }
}

I would rather considering refactoring your tests to stub where necessary.

Is module __file__ attribute absolute or relative?

From the documentation:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

From the mailing list thread linked by @kindall in a comment to the question:

I haven't tried to repro this particular example, but the reason is that we don't want to have to call getpwd() on every import nor do we want to have some kind of in-process variable to cache the current directory. (getpwd() is relatively slow and can sometimes fail outright, and trying to cache it has a certain risk of being wrong.)

What we do instead, is code in site.py that walks over the elements of sys.path and turns them into absolute paths. However this code runs before '' is inserted in the front of sys.path, so that the initial value of sys.path is ''.

For the rest of this, consider sys.path not to include ''.

So, if you are outside the part of sys.path that contains the module, you'll get an absolute path. If you are inside the part of sys.path that contains the module, you'll get a relative path.

If you load a module in the current directory, and the current directory isn't in sys.path, you'll get an absolute path.

If you load a module in the current directory, and the current directory is in sys.path, you'll get a relative path.

Error 1022 - Can't write; duplicate key in table

From the two linksResolved Successfully and Naming Convention, I easily solved this same problem which I faced. i.e., for the foreign key name, give as fk_colName_TableName. This naming convention is non-ambiguous and also makes every ForeignKey in your DB Model unique and you will never get this error.

Error 1022: Can't write; duplicate key in table

sweet-alert display HTML code in text

Sweet alerts also has an 'html' option, set it to true.

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    html: true,
    text: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

How to change port number for apache in WAMP

In addition of the modification of the file C:\wamp64\bin\apache\apache2.4.27\conf\httpd.conf.
To get the url shortcuts working, edit the file C:\wamp64\wampmanager.conf and change the port:

[apache]
apachePortUsed = "8080"

Then exit and relaunch wamp.

Eclipse error: indirectly referenced from required .class files?

I got this exception because eclipse was working in a different version of jdk, just changed to the correct, clean and build and worked!

Recursively add the entire folder to a repository

In my case, there was a .git folder in the subdirectory because I had previously initialized a git repo there. When I added the subdirectory it simply added it as a subproject without adding any of the contained files.

I solved the issue by removing the git repository from the subdirectory and then re-adding the folder.

jQuery equivalent of JavaScript's addEventListener method

Here is an excellent treatment on the Mozilla Development Network (MDN) of this issue for standard JavaScript (if you do not wish to rely on jQuery or understand it better in general):

https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener

Here is a discussion of event flow from a link in the above treatment:

http://www.w3.org/TR/DOM-Level-3-Events/#event-flow

Some key points are:

  • It allows adding more than a single handler for an event
  • It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
  • It works on any DOM element, not just HTML elements
  • The value of "this" passed to the event is not the global object (window), but the element from which the element is fired. This is very convenient.
  • Code for legacy IE browsers is simple and included under the heading "Legacy Internet Explorer and attachEvent"
  • You can include parameters if you enclose the handler in an anonymous function

How to trigger a file download when clicking an HTML button or JavaScript

you can add tag without any text but with link. and when you click the button like you have in code , just run the $("yourlinkclass").click() function.

how to query LIST using linq

Well, the code you've given is invalid to start with - List is a generic type, and it has an Add method instead of add etc.

But you could do something like:

List<Person> list = new List<Person>
{
    new person{ID=1,Name="jhon",salary=2500},
    new person{ID=2,Name="Sena",salary=1500},
    new person{ID=3,Name="Max",salary=5500}.
    new person{ID=4,Name="Gen",salary=3500}
};

// The "Where" LINQ operator filters a sequence
var highEarners = list.Where(p => p.salary > 3000);

foreach (var person in highEarners)
{
    Console.WriteLine(person.Name);
}

If you want to learn details of what all the LINQ operators do, and how they can be implemented in LINQ to Objects, you might be interested in my Edulinq blog series.

Fastest way to reset every value of std::vector<int> to 0

I had the same question but about rather short vector<bool> (afaik the standard allows to implement it internally differently than just a continuous array of boolean elements). Hence I repeated the slightly modified tests by Fabio Fracassi. The results are as follows (times, in seconds):

            -O0       -O3
         --------  --------
memset     0.666     1.045
fill      19.357     1.066
iterator  67.368     1.043
assign    17.975     0.530
for i     22.610     1.004

So apparently for these sizes, vector<bool>::assign() is faster. The code used for tests:

#include <vector>
#include <cstring>
#include <cstdlib>

#define TEST_METHOD 5
const size_t TEST_ITERATIONS = 34359738;
const size_t TEST_ARRAY_SIZE = 200;

using namespace std;

int main(int argc, char** argv) {

    std::vector<int> v(TEST_ARRAY_SIZE, 0);

    for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
        memset(&v[0], false, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
        std::fill(v.begin(), v.end(), false);
   #elif TEST_METHOD == 3
        for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
            *it = 0;
        }
   #elif TEST_METHOD == 4
      v.assign(v.size(),false);
   #elif TEST_METHOD == 5
      for (size_t i = 0; i < TEST_ARRAY_SIZE; i++) {
          v[i] = false;
      }
#endif
    }

    return EXIT_SUCCESS;
}

I used GCC 7.2.0 compiler on Ubuntu 17.10. The command line for compiling:

g++ -std=c++11 -O0 main.cpp
g++ -std=c++11 -O3 main.cpp

What's the difference between Cache-Control: max-age=0 and no-cache?

I'm hardly a caching expert, but Mark Nottingham is. Here are his caching docs. He also has excellent links in the References section.

Based on my reading of those docs, it looks like max-age=0 could allow the cache to send a cached response to requests that came in at the "same time" where "same time" means close enough together they look simultaneous to the cache, but no-cache would not.

Retina displays, high-res background images

Here's a solution that also includes High(er)DPI (MDPI) devices > ~160 dots per inch like quite a few non-iOS Devices (f.e.: Google Nexus 7 2012):

.box {
    background: url( 'img/box-bg.png' ) no-repeat top left;
    width: 200px;
    height: 200px;
}
@media only screen and ( -webkit-min-device-pixel-ratio: 1.3 ),
       only screen and (    min--moz-device-pixel-ratio: 1.3 ),
       only screen and (      -o-min-device-pixel-ratio: 2.6/2 ), /* returns 1.3, see Dev.Opera */
       only screen and (         min-device-pixel-ratio: 1.3 ),
       only screen and ( min-resolution: 124.8dpi ),
       only screen and ( min-resolution: 1.3dppx ) {

       .box {
           background: url( 'img/[email protected]' ) no-repeat top left / 200px 200px;
       }

}

As @3rror404 included in his edit after receiving feedback from the comments, there's a world beyond Webkit/iPhone. One thing that bugs me with most solutions around so far like the one referenced as source above at CSS-Tricks, is that this isn't taken fully into account.
The original source went already further.

As an example the Nexus 7 (2012) screen is a TVDPI screen with a weird device-pixel-ratio of 1.325. When loading the images with normal resolution they are upscaled via interpolation and therefore blurry. For me applying this rule in the media query to include those devices succeeded in best customer feedback.

how to display full stored procedure code?

To see the full code(query) written in stored procedure/ functions, Use below Command:

sp_helptext procedure/function_name

for function name and procedure name don't add prefix 'dbo.' or 'sys.'.

don't add brackets at the end of procedure or function name and also don't pass the parameters.

use sp_helptext keyword and then just pass the procedure/ function name.

use below command to see full code written for Procedure:

sp_helptext ProcedureName

use below command to see full code written for function:

sp_helptext FunctionName

Replace preg_replace() e modifier with preg_replace_callback

In a regular expression, you can "capture" parts of the matched string with (brackets); in this case, you are capturing the (^|_) and ([a-z]) parts of the match. These are numbered starting at 1, so you have back-references 1 and 2. Match 0 is the whole matched string.

The /e modifier takes a replacement string, and substitutes backslash followed by a number (e.g. \1) with the appropriate back-reference - but because you're inside a string, you need to escape the backslash, so you get '\\1'. It then (effectively) runs eval to run the resulting string as though it was PHP code (which is why it's being deprecated, because it's easy to use eval in an insecure way).

The preg_replace_callback function instead takes a callback function and passes it an array containing the matched back-references. So where you would have written '\\1', you instead access element 1 of that parameter - e.g. if you have an anonymous function of the form function($matches) { ... }, the first back-reference is $matches[1] inside that function.

So a /e argument of

'do_stuff(\\1) . "and" . do_stuff(\\2)'

could become a callback of

function($m) { return do_stuff($m[1]) . "and" . do_stuff($m[2]); }

Or in your case

'strtoupper("\\2")'

could become

function($m) { return strtoupper($m[2]); }

Note that $m and $matches are not magic names, they're just the parameter name I gave when declaring my callback functions. Also, you don't have to pass an anonymous function, it could be a function name as a string, or something of the form array($object, $method), as with any callback in PHP, e.g.

function stuffy_callback($things) {
    return do_stuff($things[1]) . "and" . do_stuff($things[2]);
}
$foo = preg_replace_callback('/([a-z]+) and ([a-z]+)/', 'stuffy_callback', 'fish and chips');

As with any function, you can't access variables outside your callback (from the surrounding scope) by default. When using an anonymous function, you can use the use keyword to import the variables you need to access, as discussed in the PHP manual. e.g. if the old argument was

'do_stuff(\\1, $foo)'

then the new callback might look like

function($m) use ($foo) { return do_stuff($m[1], $foo); }

Gotchas

  • Use of preg_replace_callback is instead of the /e modifier on the regex, so you need to remove that flag from your "pattern" argument. So a pattern like /blah(.*)blah/mei would become /blah(.*)blah/mi.
  • The /e modifier used a variant of addslashes() internally on the arguments, so some replacements used stripslashes() to remove it; in most cases, you probably want to remove the call to stripslashes from your new callback.

React Native: Possible unhandled promise rejection

You should add the catch() to the end of the Api call. When your code hits the catch() it doesn't return anything, so data is undefined when you try to use setState() on it. The error message actually tells you this too :)

Increment value in mysql update query

Who needs to update string and numbers SET @a = 0; UPDATE obj_disposition SET CODE = CONCAT('CD_', @a:=@a+1);

How does a ArrayList's contains() method evaluate objects?

Just wanted to note that the following implementation is wrong when value is not a primitive type:

public class Thing
{
    public Object value;  

    public Thing (Object x)
    {
        this.value = x;
    }

    @Override
    public boolean equals(Object object)
    {
        boolean sameSame = false;

        if (object != null && object instanceof Thing)
        {
            sameSame = this.value == ((Thing) object).value;
        }

        return sameSame;
    }
}

In that case I propose the following:

public class Thing {
    public Object value;  

    public Thing (Object x) {
        value = x;
    }

    @Override
    public boolean equals(Object object) {

        if (object != null && object instanceof Thing) {
            Thing thing = (Thing) object;
            if (value == null) {
                return (thing.value == null);
            }
            else {
                return value.equals(thing.value);
            }
        }

        return false;
    }
}

Detect click outside React component

Alternatively:

const onClickOutsideListener = () => {
    alert("click outside")
    document.removeEventListener("click", onClickOutsideListener)
  }

...

return (
  <div
    onMouseLeave={() => {
          document.addEventListener("click", onClickOutsideListener)
        }}
  >
   ...
  </div>

How to go to a specific element on page?

The standard technique in plugin form would look something like this:

(function($) {
    $.fn.goTo = function() {
        $('html, body').animate({
            scrollTop: $(this).offset().top + 'px'
        }, 'fast');
        return this; // for chaining...
    }
})(jQuery);

Then you could just say $('#div_element2').goTo(); to scroll to <div id="div_element2">. Options handling and configurability is left as an exercise for the reader.

MySQL: How to set the Primary Key on phpMyAdmin?

You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go

openCV video saving in python

Try this. It's working for me (Windows 10).

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

How do I combine 2 select statements into one?

I think that's what you're looking for:

SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*
FROM WorkItems t1
WHERE (TextField01, TimeStamp) IN(
  SELECT TextField01, MAX(TimeStamp)
  FROM WorkItems t2
  GROUP BY t2.TextField01
  )
AND TimeStamp > '2009-02-12 18:00:00'

If you're in Oracle or in MS SQL 2005 and above, then you could do:

SELECT *
FROM (
  SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*,
     ROW_NUMBER() OVER (PARTITION BY TextField01 ORDER BY TimeStamp DESC) AS rn
  FROM WorkItems t1
) to
WHERE rn = 1

, it's more efficient.

How to create a property for a List<T>

Either specify the type of T, or if you want to make it generic, you'll need to make the parent class generic.

public class MyClass<T>
{
  etc

jQuery iframe load() event?

You may use the jquery's Contents method to get the content of the iframe.

What is the proper way to format a multi-line dict in Python?

Generally, you would not include the comma after the final entry, but Python will correct that for you.

How to style icon color, size, and shadow of Font Awesome Icons

Looks like the FontAwesome icon color responds to text-info, text-error, etc.

<div style="font-size: 44px;">
   <i class="icon-umbrella icon-large text-error"></i>
</div>

Programmatically change the src of an img tag

<img src="../template/edit.png" name="edit-save" onclick="this.src = '../template/save.png'" />

Missing .map resource?

jQuery recently started using source maps.

For example, let's look at the minified jQuery 2.0.3 file's first few lines.

/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/

Excerpt from Introduction to JavaScript Source Maps:

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.

emphasis mine

It's incredibly useful, and will only download if the user opens dev tools.

Solution

Remove the source mapping line, or do nothing. It isn't really a problem.


Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.

Why can't I use background image and color together?

background:url(directoryName/imageName.extention) bottom left no-repeat; 
background-color: red;

"Exception has been thrown by the target of an invocation" error (mscorlib)

This is may have 2 reasons

1.I found the connection string error in my web.config file i had changed the connection string and its working.

  1. Connection string is proper then check with the control panel>services> SQL Server Browser > start or not

Recommended way of making React component/div draggable

Here's a 2020 answer with a Hook:

function useDragging() {
  const [isDragging, setIsDragging] = useState(false);
  const [pos, setPos] = useState({ x: 0, y: 0 });
  const ref = useRef(null);

  function onMouseMove(e) {
    if (!isDragging) return;
    setPos({
      x: e.x - ref.current.offsetWidth / 2,
      y: e.y - ref.current.offsetHeight / 2,
    });
    e.stopPropagation();
    e.preventDefault();
  }

  function onMouseUp(e) {
    setIsDragging(false);
    e.stopPropagation();
    e.preventDefault();
  }

  function onMouseDown(e) {
    if (e.button !== 0) return;
    setIsDragging(true);

    setPos({
      x: e.x - ref.current.offsetWidth / 2,
      y: e.y - ref.current.offsetHeight / 2,
    });

    e.stopPropagation();
    e.preventDefault();
  }

  // When the element mounts, attach an mousedown listener
  useEffect(() => {
    ref.current.addEventListener("mousedown", onMouseDown);

    return () => {
      ref.current.removeEventListener("mousedown", onMouseDown);
    };
  }, [ref.current]);

  // Everytime the isDragging state changes, assign or remove
  // the corresponding mousemove and mouseup handlers
  useEffect(() => {
    if (isDragging) {
      document.addEventListener("mouseup", onMouseUp);
      document.addEventListener("mousemove", onMouseMove);
    } else {
      document.removeEventListener("mouseup", onMouseUp);
      document.removeEventListener("mousemove", onMouseMove);
    }
    return () => {
      document.removeEventListener("mouseup", onMouseUp);
      document.removeEventListener("mousemove", onMouseMove);
    };
  }, [isDragging]);

  return [ref, pos.x, pos.y, isDragging];
}

Then a component that uses the hook:


function Draggable() {
  const [ref, x, y, isDragging] = useDragging();

  return (
    <div
      ref={ref}
      style={{
        position: "absolute",
        width: 50,
        height: 50,
        background: isDragging ? "blue" : "gray",
        left: x,
        top: y,
      }}
    ></div>
  );
}

Git diff against a stash

@Magne's answer is the only one to (very late) date that answers the most flexible/useful interpretation of the question, but its a fair bit more complicated than necessary. Rather than committing and resetting, just stash your working copy, compare, then unstash.

git stash save "temp"
git diff stash@{0} stash@{1}
git stash pop

That shows you the differences between the top of the stash stack and your working folder by temporarily making your working folder changes become the top of the stash stack (stash@{0}), moving the original top down one (stash@{1}) then comparing using the original top in the 'new set' position so you see the changes that would result from applying it on top of your current work.

"But what if I don't have any current work?" Then you are in the normal boring case. Just use @Amber's answer

git stash show

or @czerasz's answer

git diff stash@{0}

or admit that stashing and unstashing is fast and easy anyway, just unstash the changes and inspect them. If you don't want them at the moment throw them (the current index/working folder changes) away. In full that's

git stash apply
git diff
git reset
git checkout

Import CSV to mysql table

To load data from text file or csv file the command is

load data local infile 'file-name.csv'
into table table-name
fields terminated by '' enclosed by '' lines terminated by '\n' (column-name);

In above command, in my case there is only one column to be loaded so there is no "terminated by" and "enclosed by" so I kept it empty else programmer can enter the separating character . for e.g . ,(comma) or " or ; or any thing.

**for people who are using mysql version 5 and above **

Before loading the file into mysql must ensure that below tow line are added in side etc/mysql/my.cnf

to edit my.cnf command is

sudo vi /etc/mysql/my.cnf

[mysqld]  
local-infile

[mysql]  
local-infile  

Gridview with two columns and auto resized images

Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"/>

</FrameLayout>

Make a custom ImageView that maintains its aspect ratio:

src/com/example/graphicstest/SquareImageView.java

public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

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

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
    }
}

Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:

res/layout/grid_item.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <com.example.graphicstest.SquareImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"/>

</FrameLayout>

Now make some sort of adapter for your GridView:

src/com/example/graphicstest/MyAdapter.java

private final class MyAdapter extends BaseAdapter {
    private final List<Item> mItems = new ArrayList<Item>();
    private final LayoutInflater mInflater;

    public MyAdapter(Context context) {
        mInflater = LayoutInflater.from(context);

        mItems.add(new Item("Red",       R.drawable.red));
        mItems.add(new Item("Magenta",   R.drawable.magenta));
        mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
        mItems.add(new Item("Gray",      R.drawable.gray));
        mItems.add(new Item("Green",     R.drawable.green));
        mItems.add(new Item("Cyan",      R.drawable.cyan));
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Item getItem(int i) {
        return mItems.get(i);
    }

    @Override
    public long getItemId(int i) {
        return mItems.get(i).drawableId;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        ImageView picture;
        TextView name;

        if (v == null) {
            v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
            v.setTag(R.id.picture, v.findViewById(R.id.picture));
            v.setTag(R.id.text, v.findViewById(R.id.text));
        }

        picture = (ImageView) v.getTag(R.id.picture);
        name = (TextView) v.getTag(R.id.text);

        Item item = getItem(i);

        picture.setImageResource(item.drawableId);
        name.setText(item.name);

        return v;
    }

    private static class Item {
        public final String name;
        public final int drawableId;

        Item(String name, int drawableId) {
            this.name = name;
            this.drawableId = drawableId;
        }
    }
}

Set that adapter to your GridView:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GridView gridView = (GridView)findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(this));
}

And enjoy the results:

Example GridView

How to set a CMake option() at command line

An additional option is to go to your build folder and use the command ccmake .

This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.

The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .

Measuring text height to be drawn on Canvas ( Android )

There are different ways to measure the height depending on what you need.

getTextBounds

If you are doing something like precisely centering a small amount of fixed text, you probably want getTextBounds. You can get the bounding rectangle like this

Rect bounds = new Rect();
mTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
int height = bounds.height();

As you can see for the following images, different strings will give different heights (shown in red).

enter image description here

These differing heights could be a disadvantage in some situations when you just need a constant height no matter what the text is. See the next section.

Paint.FontMetrics

You can calculate the hight of the font from the font metrics. The height is always the same because it is obtained from the font, not any particular text string.

Paint.FontMetrics fm = mTextPaint.getFontMetrics();
float height = fm.descent - fm.ascent;

The baseline is the line that the text sits on. The descent is generally the furthest a character will go below the line and the ascent is generally the furthest a character will go above the line. To get the height you have to subtract ascent because it is a negative value. (The baseline is y=0 and y descreases up the screen.)

Look at the following image. The heights for both of the strings are 234.375.

enter image description here

If you want the line height rather than just the text height, you could do the following:

float height = fm.bottom - fm.top + fm.leading; // 265.4297

These are the bottom and top of the line. The leading (interline spacing) is usually zero, but you should add it anyway.

The images above come from this project. You can play around with it to see how Font Metrics work.

StaticLayout

For measuring the height of multi-line text you should use a StaticLayout. I talked about it in some detail in this answer, but the basic way to get this height is like this:

String text = "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.";

TextPaint myTextPaint = new TextPaint();
myTextPaint.setAntiAlias(true);
myTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
myTextPaint.setColor(0xFF000000);

int width = 200;
Layout.Alignment alignment = Layout.Alignment.ALIGN_NORMAL;
float spacingMultiplier = 1;
float spacingAddition = 0;
boolean includePadding = false;

StaticLayout myStaticLayout = new StaticLayout(text, myTextPaint, width, alignment, spacingMultiplier, spacingAddition, includePadding);

float height = myStaticLayout.getHeight(); 

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

How to change XML Attribute

Here's the beginnings of a parser class to get you started. This ended up being my solution to a similar problem:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace XML
{
    public class Parser
    {

        private string _FilePath = string.Empty;

        private XDocument _XML_Doc = null;


        public Parser(string filePath)
        {
            _FilePath = filePath;
            _XML_Doc = XDocument.Load(_FilePath);
        }


        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in all elements.
        /// </summary>
        /// <param name="attributeName"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string attributeName, string newValue)
        {
            ReplaceAtrribute(string.Empty, attributeName, new List<string> { }, newValue);
        }

        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in elements with a given name (elementName).
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, string newValue)
        {
            ReplaceAtrribute(elementName, attributeName, new List<string> { }, newValue);
        }


        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) and value (oldValue)  
        /// with the specified new value (newValue) in elements with a given name (elementName).
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="oldValue"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, string oldValue, string newValue)
        {
            ReplaceAtrribute(elementName, attributeName, new List<string> { oldValue }, newValue);              
        }


        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName), which has one of a list of values (oldValues), 
        /// with the specified new value (newValue) in elements with a given name (elementName).
        /// If oldValues is empty then oldValues will be ignored.
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="oldValues"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, List<string> oldValues, string newValue)
        {
            List<XElement> elements = _XML_Doc.Elements().Descendants().ToList();

            foreach (XElement element in elements)
            {
                if (elementName == string.Empty | element.Name.LocalName.ToString() == elementName)
                {
                    if (element.Attribute(attributeName) != null)
                    {

                        if (oldValues.Count == 0 || oldValues.Contains(element.Attribute(attributeName).Value))
                        { element.Attribute(attributeName).Value = newValue; }
                    }
                }
            }

        }

        public void SaveChangesToFile()
        {
            _XML_Doc.Save(_FilePath);
        }

    }
}

Use PHP to create, edit and delete crontab jobs?

Its simple You can you curl to do so, make sure curl installed on server :

for triggering every minute : * * * * * curl --request POST 'https://glassdoor.com/admin/sendBdayNotification'

        • *

    minute hour day month week

Let say you want to send this notification 2:15 PM everyday You may change POST/GET based on your API:

15 14 * * * curl --request POST 'url of ur API'

How can I get all a form's values that would be submitted without submitting

The jquery form plugin offers an easy way to iterate over your form elements and put them in a query string. It might also be useful for whatever else you need to do with these values.

var queryString = $('#myFormId').formSerialize();

From http://malsup.com/jquery/form

Or using straight jquery:

var queryString = $('#myFormId').serialize();

How can I reference a dll in the GAC from Visual Studio?

I've created a tool which is completely free, that will help you to achieve your goal. Muse VSReferences will allow you to add a Global Assembly Cache reference to the project from Add GAC Reference menu item.

Hope this helps Muse VSExtensions

Generic Property in C#

Okay, I'll bite. You want something like this: If you declare a "property" like this:

Update: I'm now pretty sure that Fredrik Mörk answered your question and gave a solution. I'm not really happy with the idea, but it seems to answer exactly what I understood from your question.

public class PropertyFoo {
  public MyProp<String> Name;
}

this ends up as

public class PropertyFoo {
  public string Name {
    get { /* do predefined stuff here */ }
    set { /*other predefined stuff here */ }
  }
}

No. Not possible and not a property, really. Look for template/snippet support in your IDE.

I need to learn Web Services in Java. What are the different types in it?

Q1) Here are couple things to read or google more :

Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest

It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.

Q2) Here are couple of good tutorials for soap (I had them bookmarked) :

http://united-coders.com/phillip-steffensen/developing-a-simple-soap-webservice-using-spring-301-and-apache-cxf-226

http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/

http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html

Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.

SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.

Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).

Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.

If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development. It's fantastic, not hard to read and not too big either (win win).

TypeError: can only concatenate list (not "str") to list

I have a solution for this. First thing that add is already having a string value as input() function by default takes the input as string. Second thing that you can use append method to append value of add variable in your list.

Please do check my code I have done some modification : - {1} You can enter command in capital or small or mix {2} If user entered wrong command then your program will ask to input command again

inventory = ["sword","potion","armour","bow"] print(inventory) print("\ncommands : use (remove item) and pickup (add item)") selection=input("choose a command [use/pickup] : ") while True: if selection.lower()=="use": print(inventory) remove_item=input("What do you want to use? ") inventory.remove(remove_item) print(inventory) break

 elif selection.lower()=="pickup":
      print(inventory)
      add_item=input("What do you want to pickup? ")
      inventory.append(add_item)
      print(inventory)
      break
 
 else:
      print("Invalid Command. Please check your input")
      selection=input("Once again choose a command [use/pickup] : ")

How to delete a file or folder?

To remove all files in folder

import os
import glob

files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
    os.remove(file)

To remove all folders in a directory

from shutil import rmtree
import os

// os.path.join()  # current working directory.

for dirct in os.listdir(os.path.join('path/to/folder')):
    rmtree(os.path.join('path/to/folder',dirct))

Return back to MainActivity from another activity

use

Intent returnBtn = new Intent(getApplicationContext(),
                    MainActivity.class);

startActivity(returnBtn);

make the main activity's launchmode to singleTask in Android Manifest if you don't want to create new one every time.

android:launchMode="singleTask" 

How to list all the available keyspaces in Cassandra?

  1. login to cqlsh

  2. use below command to get names/list of keyspaces present

         SELECT keyspace_name FROM system_schema.keyspaces;
    

Write a formula in an Excel Cell using VBA

The correct character to use in this case is a full colon (:), not a semicolon (;).

Git, fatal: The remote end hung up unexpectedly

Based on the protocol you are using to push to your repo

HTTP

git config --global http.postBuffer 157286400

References:

SSH

Add the following in ~/.ssh/config file in your linux machine

Host your-gitlab-server.com
  ServerAliveInterval 60
  ServerAliveCountMax 5
  IPQoS throughput

References:

Delete duplicate records from a SQL table without a primary key

You could create a temporary table #tempemployee containing a select distinct of your employee table. Then delete from employee. Then insert into employee select from #tempemployee.

Like Josh said - even if you know the duplicates, deleting them will be impossile since you cannot actually refer to a specific record if it is an exact duplicate of another record.

How to debug Angular JavaScript Code

For Visual Studio Code (Not Visual Studio) do Ctrl+Shift+P

Type Debugger for Chrome in the search bar, install it and enable it.

In your launch.json file add this config :

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Launch localhost with sourcemaps",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost/mypage.html",
            "webRoot": "${workspaceRoot}/app/files",
            "sourceMaps": true
        },
        {
            "name": "Launch index.html (without sourcemaps)",
            "type": "chrome",
            "request": "launch",
            "file": "${workspaceRoot}/index.html"
        },
    ]
}

You must launch Chrome with remote debugging enabled in order for the extension to attach to it.

  • Windows

Right click the Chrome shortcut, and select properties In the "target" field, append --remote-debugging-port=9222 Or in a command prompt, execute /chrome.exe --remote-debugging-port=9222

  • OS X

In a terminal, execute /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222

  • Linux

In a terminal, launch google-chrome --remote-debugging-port=9222

Find More ===>

Terminal Commands: For loop with echo

The default shell on OS X is bash. You could write this:

for i in {1..100}; do echo http://www.example.com/${i}.jpg; done

Here is a link to the reference manual of bash concerning loop constructs.

Pass in an enum as a method parameter

First change the method parameter Enum supportedPermissions to SupportedPermissions supportedPermissions.

Then create your file like this

file = new File
{  
    Name = name,
    Id = id,
    Description = description,
    SupportedPermissions = supportedPermissions
};

And the call to your method should be

CreateFile(id, name, description, SupportedPermissions.basic);

How to find index of all occurrences of element in array?

const indexes = cars
    .map((car, i) => car === "Nano" ? i : null)
    .filter(i => i !== null)

Powershell 2 copy-item which creates a folder if doesn't exist

I have stumbled here twice, and this last time was a unique situation and even though I ditch using copy-item I wanted to post the solution I used.

Had a list of nothing but files with the full path and in majority of the case the files have no extensions. the -Recurse -Force option would not work for me so I ditched copy-item function and fell back to something like below using xcopy as I still wanted to keep it a one liner. Initially I tied with Robocopy but it is apparently looking for a file extension and since many of mine had no extension it considered it a directory.

$filelist = @("C:\Somepath\test\location\here\file","C:\Somepath\test\location\here2\file2")

$filelist | % { echo f | xcopy $_  $($_.Replace("somepath", "somepath_NEW")) }

Hope it helps someone.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

For swift

var dateString:String = "2014-05-20";
var dateFmt = NSDateFormatter()
// the format you want
dateFmt.dateFormat = "yyyy-MM-dd"
var date1:NSDate = dateFmt.dateFromString(dateString)!;

How to sort a list of objects based on an attribute of the objects?

It looks much like a list of Django ORM model instances.

Why not sort them on query like this:

ut = Tag.objects.order_by('-count')

Laravel 5 - How to access image uploaded in storage within View?

According to Laravel 5.2 docs, your publicly accessible files should be put in directory

storage/app/public

To make them accessible from the web, you should create a symbolic link from public/storage to storage/app/public.

ln -s /path/to/laravel/storage/app/public /path/to/laravel/public/storage

Now you can create in your view an URL to the files using the asset helper:

echo asset('storage/file.txt');

BeautifulSoup Grab Visible Webpage Text

I completely respect using Beautiful Soup to get rendered content, but it may not be the ideal package for acquiring the rendered content on a page.

I had a similar problem to get rendered content, or the visible content in a typical browser. In particular I had many perhaps atypical cases to work with such a simple example below. In this case the non displayable tag is nested in a style tag, and is not visible in many browsers that I have checked. Other variations exist such as defining a class tag setting display to none. Then using this class for the div.

<html>
  <title>  Title here</title>

  <body>

    lots of text here <p> <br>
    <h1> even headings </h1>

    <style type="text/css"> 
        <div > this will not be visible </div> 
    </style>


  </body>

</html>

One solution posted above is:

html = Utilities.ReadFile('simple.html')
soup = BeautifulSoup.BeautifulSoup(html)
texts = soup.findAll(text=True)
visible_texts = filter(visible, texts)
print(visible_texts)


[u'\n', u'\n', u'\n\n        lots of text here ', u' ', u'\n', u' even headings ', u'\n', u' this will not be visible ', u'\n', u'\n']

This solution certainly has applications in many cases and does the job quite well generally but in the html posted above it retains the text that is not rendered. After searching SO a couple solutions came up here BeautifulSoup get_text does not strip all tags and JavaScript and here Rendered HTML to plain text using Python

I tried both these solutions: html2text and nltk.clean_html and was surprised by the timing results so thought they warranted an answer for posterity. Of course, the speeds highly depend on the contents of the data...

One answer here from @Helge was about using nltk of all things.

import nltk

%timeit nltk.clean_html(html)
was returning 153 us per loop

It worked really well to return a string with rendered html. This nltk module was faster than even html2text, though perhaps html2text is more robust.

betterHTML = html.decode(errors='ignore')
%timeit html2text.html2text(betterHTML)
%3.09 ms per loop

Extract regression coefficient values

To answer your question, you can explore the contents of the model's output by saving the model as a variable and clicking on it in the environment window. You can then click around to see what it contains and what is stored where.

Another way is to type yourmodelname$ and select the components of the model one by one to see what each contains. When you get to yourmodelname$coefficients, you will see all of beta-, p, and t- values you desire.

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

How to correctly use the extern keyword in C

In C, 'extern' is implied for function prototypes, as a prototype declares a function which is defined somewhere else. In other words, a function prototype has external linkage by default; using 'extern' is fine, but is redundant.

(If static linkage is required, the function must be declared as 'static' both in its prototype and function header, and these should normally both be in the same .c file).

How to merge 2 JSON objects from 2 files using jq?

Use jq -s add:

$ echo '{"a":"foo","b":"bar"} {"c":"baz","a":0}' | jq -s add
{
  "a": 0,
  "b": "bar",
  "c": "baz"
}

This reads all JSON texts from stdin into an array (jq -s does that) then it "reduces" them.

(add is defined as def add: reduce .[] as $x (null; . + $x);, which iterates over the input array's/object's values and adds them. Object addition == merge.)

How to view .img files?

.img is way too unspecific. This file extension is widely used for a variety of (raw) file formats. It is an abbreviation for “image” and that can be any image you can imagine—or cannot imagine at all, as you have never heard of it.

For example, .IMG used to be a GEM bitmap image file. Does anyone remember GEM at all? It was the Windows competitor from Digital Research. The Atari ST version was widely used, but there was also a DOS version of GEM. One of the stripped down versions (which was necessary to avoid copyright claims from Apple) was ViewMAX included in DR DOS 3.41, 5.0 and 6.0 as well as Novell DOS 7.0. It is now open source and can be downloaded freely as OpenGEM. Still requires DOS and is included in the FreeDOS distribution. For viewing GEM bitmap images, Windows programs of that time (around DOS-based Windows 3.0) such as Ventura Publisher could open and consequently convert such “GEM images” or “Atari ST images” into other, more widely used formats.

But I doubt that this kind of .img-file is what you meant. Still, you have to be more specific.

Most widely .img is used as a raw filesystem image of e.g. a floppy disk. As mentioned by others, such images can be opened by a number of programs. Or directly mounted under Unix-like systems like BSD and Linux. 7-Zip is also able to extract files from such images for supported filesystems, such as FAT. At least the command-line version. Just type 7z x image.img and it will extract the included files.

Note however that there are also other image formats out there, such as IBM's .dsk, sometimes using different file extensions. Such files can be raw floppy images, but they can also be in IBM's SAVEDSKF/LOADDSKF format. These files are basically raw files with stripped zeros at the end, but with a header at the beginning of the files. I doubt that 7-Zip can extract such images, even though it would only be necessary to find the appropriate offset. Anyhow, since the image past the header is basically raw and uncompressed, using dd you can extract the image and make it a raw .img floppy image. Suppose the header is hex:291 bytes long (which you will have to figure out by looking inside the file e.g. using a hex editor). This equals 657 bytes to skip, resulting in dd if=image.dsk of=rawimage.img bs=1 skip=657. The resulting rawimage.img would however be non-standard in size. This can be fixed, again, by using dd. dd if=/der/zero of=rawimage.img count=0 bs=1 seek=1474560 – this will make a sparse file out of it, resulting in the correct file size for a 1.44 MB floppy image and returning zeros at unused positions. Works with most programs under Linux.

But in general, .img can be any file that is classified as “an image”, thus any application can include a (proprietory) file with this extension. Such files can than only be used (opened) by said application.

How to determine the current shell I'm working on

The following will always give the actual shell used - it gets the name of the actual executable and not the shell name (i.e. ksh93 instead of ksh, etc.). For /bin/sh, it will show the actual shell used, i.e. dash.

ls -l /proc/$$/exe | sed 's%.*/%%'

I know that there are many who say the ls output should never be processed, but what is the probability you'll have a shell you are using that is named with special characters or placed in a directory named with special characters? If this is still the case, there are plenty of other examples of doing it differently.

As pointed out by Toby Speight, this would be a more proper and cleaner way of achieving the same:

basename $(readlink /proc/$$/exe)

generate model using user:references vs user_id:integer

For the former, convention over configuration. Rails default when you reference another table with

 belongs_to :something

is to look for something_id.

references, or belongs_to is actually newer way of writing the former with few quirks.

Important is to remember that it will not create foreign keys for you. In order to do that, you need to set it up explicitly using either:

t.references :something, foreign_key: true
t.belongs_to :something_else, foreign_key: true

or (note the plural):

add_foreign_key :table_name, :somethings
add_foreign_key :table_name, :something_elses`

Debugging Stored Procedure in SQL Server 2008

  • Yes, although it can be tricky to get debugging working, especially if trying to debug SQL on a remote SQL server from your own development machine.
  • In the first instance I'd recommend getting this working by debugging directly on the server first, if possible.
  • Log to the SQL server using an account that has sysadmin rights, or ask your DBA to to do this.
  • Then, for your own Windows account, create a 'login' in SQL Server, if it isn't already there:

enter image description here

  • Right-click the account > properties - ensure that the login is a member of the 'sysadmin' role:

enter image description here

  • (also ensure that the account is 'owner' of any databases that you want to debug scripts (e.g. stored procs) for:

enter image description here

  • Then, login directly onto the SQL server using your Windows account.
  • Login to SQL server using Windows Authentication (using the account you've just used to log into the server)
  • Now 'Debug' the query in SQL management studio, setting breakpoints as necessary. You can step into stored procs using F11:

enter image description here

  • Here's a useful guide to debugging:

http://blogs.msdn.com/b/billramo/archive/2009/04/11/transact-sql-debugger-for-sql-server-2008-part-1.aspx

  • If you need to remotely debug, then once you've got this part working, you can try setting up remote debugging:

http://blogs.msdn.com/b/billramo/archive/2009/04/11/transact-sql-debugger-for-sql-server-2008-part-2.aspx

How to center canvas in html5

Just center the div in HTML:

  #test {
     width: 100px;
     height:100px;
     margin: 0px auto;
     border: 1px solid red;
   }


<div id="test">
   <canvas width="100" height="100"></canvas>
</div>

Just change the height and width to whatever and you've got a centered div

http://jsfiddle.net/BVghc/2/

How do I format a number to a dollar amount in PHP

If you just want something simple:

'$' . number_format($money, 2);

number_format()

Get MIME type from filename extension

I like the work that Samuel Neff did, but not the idea and overhead of creating a dictionary every time.

I restructured things as a switch case. Yes you can't iterate over it but in my case I only ever use it to quickly look up a value. Especially because it is done in a web service, the last thing I want is a bunch of overhead as the application prepares its structures. The compiler will turn this into a hashed lookup and so it will be very fast.

public static string GetMimeType(string extension)
{
  if (extension == null)
    throw new ArgumentNullException("extension");

  if (extension.StartsWith("."))
    extension = extension.Substring(1);


  switch (extension.ToLower())
{
    #region Big freaking list of mime types
    case "323": return "text/h323";
    case "3g2": return "video/3gpp2";
    case "3gp": return "video/3gpp";
    case "3gp2": return "video/3gpp2";
    case "3gpp": return "video/3gpp";
    case "7z": return "application/x-7z-compressed";
    case "aa": return "audio/audible";
    case "aac": return "audio/aac";
    case "aaf": return "application/octet-stream";
    case "aax": return "audio/vnd.audible.aax";
    case "ac3": return "audio/ac3";
    case "aca": return "application/octet-stream";
    case "accda": return "application/msaccess.addin";
    case "accdb": return "application/msaccess";
    case "accdc": return "application/msaccess.cab";
    case "accde": return "application/msaccess";
    case "accdr": return "application/msaccess.runtime";
    case "accdt": return "application/msaccess";
    case "accdw": return "application/msaccess.webapplication";
    case "accft": return "application/msaccess.ftemplate";
    case "acx": return "application/internet-property-stream";
    case "addin": return "text/xml";
    case "ade": return "application/msaccess";
    case "adobebridge": return "application/x-bridge-url";
    case "adp": return "application/msaccess";
    case "adt": return "audio/vnd.dlna.adts";
    case "adts": return "audio/aac";
    case "afm": return "application/octet-stream";
    case "ai": return "application/postscript";
    case "aif": return "audio/x-aiff";
    case "aifc": return "audio/aiff";
    case "aiff": return "audio/aiff";
    case "air": return "application/vnd.adobe.air-application-installer-package+zip";
    case "amc": return "application/x-mpeg";
    case "application": return "application/x-ms-application";
    case "art": return "image/x-jg";
    case "asa": return "application/xml";
    case "asax": return "application/xml";
    case "ascx": return "application/xml";
    case "asd": return "application/octet-stream";
    case "asf": return "video/x-ms-asf";
    case "ashx": return "application/xml";
    case "asi": return "application/octet-stream";
    case "asm": return "text/plain";
    case "asmx": return "application/xml";
    case "aspx": return "application/xml";
    case "asr": return "video/x-ms-asf";
    case "asx": return "video/x-ms-asf";
    case "atom": return "application/atom+xml";
    case "au": return "audio/basic";
    case "avi": return "video/x-msvideo";
    case "axs": return "application/olescript";
    case "bas": return "text/plain";
    case "bcpio": return "application/x-bcpio";
    case "bin": return "application/octet-stream";
    case "bmp": return "image/bmp";
    case "c": return "text/plain";
    case "cab": return "application/octet-stream";
    case "caf": return "audio/x-caf";
    case "calx": return "application/vnd.ms-office.calx";
    case "cat": return "application/vnd.ms-pki.seccat";
    case "cc": return "text/plain";
    case "cd": return "text/plain";
    case "cdda": return "audio/aiff";
    case "cdf": return "application/x-cdf";
    case "cer": return "application/x-x509-ca-cert";
    case "chm": return "application/octet-stream";
    case "class": return "application/x-java-applet";
    case "clp": return "application/x-msclip";
    case "cmx": return "image/x-cmx";
    case "cnf": return "text/plain";
    case "cod": return "image/cis-cod";
    case "config": return "application/xml";
    case "contact": return "text/x-ms-contact";
    case "coverage": return "application/xml";
    case "cpio": return "application/x-cpio";
    case "cpp": return "text/plain";
    case "crd": return "application/x-mscardfile";
    case "crl": return "application/pkix-crl";
    case "crt": return "application/x-x509-ca-cert";
    case "cs": return "text/plain";
    case "csdproj": return "text/plain";
    case "csh": return "application/x-csh";
    case "csproj": return "text/plain";
    case "css": return "text/css";
    case "csv": return "text/csv";
    case "cur": return "application/octet-stream";
    case "cxx": return "text/plain";
    case "dat": return "application/octet-stream";
    case "datasource": return "application/xml";
    case "dbproj": return "text/plain";
    case "dcr": return "application/x-director";
    case "def": return "text/plain";
    case "deploy": return "application/octet-stream";
    case "der": return "application/x-x509-ca-cert";
    case "dgml": return "application/xml";
    case "dib": return "image/bmp";
    case "dif": return "video/x-dv";
    case "dir": return "application/x-director";
    case "disco": return "text/xml";
    case "dll": return "application/x-msdownload";
    case "dll.config": return "text/xml";
    case "dlm": return "text/dlm";
    case "doc": return "application/msword";
    case "docm": return "application/vnd.ms-word.document.macroenabled.12";
    case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    case "dot": return "application/msword";
    case "dotm": return "application/vnd.ms-word.template.macroenabled.12";
    case "dotx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
    case "dsp": return "application/octet-stream";
    case "dsw": return "text/plain";
    case "dtd": return "text/xml";
    case "dtsconfig": return "text/xml";
    case "dv": return "video/x-dv";
    case "dvi": return "application/x-dvi";
    case "dwf": return "drawing/x-dwf";
    case "dwp": return "application/octet-stream";
    case "dxr": return "application/x-director";
    case "eml": return "message/rfc822";
    case "emz": return "application/octet-stream";
    case "eot": return "application/octet-stream";
    case "eps": return "application/postscript";
    case "etl": return "application/etl";
    case "etx": return "text/x-setext";
    case "evy": return "application/envoy";
    case "exe": return "application/octet-stream";
    case "exe.config": return "text/xml";
    case "fdf": return "application/vnd.fdf";
    case "fif": return "application/fractals";
    case "filters": return "application/xml";
    case "fla": return "application/octet-stream";
    case "flr": return "x-world/x-vrml";
    case "flv": return "video/x-flv";
    case "fsscript": return "application/fsharp-script";
    case "fsx": return "application/fsharp-script";
    case "generictest": return "application/xml";
    case "gif": return "image/gif";
    case "group": return "text/x-ms-group";
    case "gsm": return "audio/x-gsm";
    case "gtar": return "application/x-gtar";
    case "gz": return "application/x-gzip";
    case "h": return "text/plain";
    case "hdf": return "application/x-hdf";
    case "hdml": return "text/x-hdml";
    case "hhc": return "application/x-oleobject";
    case "hhk": return "application/octet-stream";
    case "hhp": return "application/octet-stream";
    case "hlp": return "application/winhlp";
    case "hpp": return "text/plain";
    case "hqx": return "application/mac-binhex40";
    case "hta": return "application/hta";
    case "htc": return "text/x-component";
    case "htm": return "text/html";
    case "html": return "text/html";
    case "htt": return "text/webviewhtml";
    case "hxa": return "application/xml";
    case "hxc": return "application/xml";
    case "hxd": return "application/octet-stream";
    case "hxe": return "application/xml";
    case "hxf": return "application/xml";
    case "hxh": return "application/octet-stream";
    case "hxi": return "application/octet-stream";
    case "hxk": return "application/xml";
    case "hxq": return "application/octet-stream";
    case "hxr": return "application/octet-stream";
    case "hxs": return "application/octet-stream";
    case "hxt": return "text/html";
    case "hxv": return "application/xml";
    case "hxw": return "application/octet-stream";
    case "hxx": return "text/plain";
    case "i": return "text/plain";
    case "ico": return "image/x-icon";
    case "ics": return "application/octet-stream";
    case "idl": return "text/plain";
    case "ief": return "image/ief";
    case "iii": return "application/x-iphone";
    case "inc": return "text/plain";
    case "inf": return "application/octet-stream";
    case "inl": return "text/plain";
    case "ins": return "application/x-internet-signup";
    case "ipa": return "application/x-itunes-ipa";
    case "ipg": return "application/x-itunes-ipg";
    case "ipproj": return "text/plain";
    case "ipsw": return "application/x-itunes-ipsw";
    case "iqy": return "text/x-ms-iqy";
    case "isp": return "application/x-internet-signup";
    case "ite": return "application/x-itunes-ite";
    case "itlp": return "application/x-itunes-itlp";
    case "itms": return "application/x-itunes-itms";
    case "itpc": return "application/x-itunes-itpc";
    case "ivf": return "video/x-ivf";
    case "jar": return "application/java-archive";
    case "java": return "application/octet-stream";
    case "jck": return "application/liquidmotion";
    case "jcz": return "application/liquidmotion";
    case "jfif": return "image/pjpeg";
    case "jnlp": return "application/x-java-jnlp-file";
    case "jpb": return "application/octet-stream";
    case "jpe": return "image/jpeg";
    case "jpeg": return "image/jpeg";
    case "jpg": return "image/jpeg";
    case "js": return "application/x-javascript";
    case "jsx": return "text/jscript";
    case "jsxbin": return "text/plain";
    case "latex": return "application/x-latex";
    case "library-ms": return "application/windows-library+xml";
    case "lit": return "application/x-ms-reader";
    case "loadtest": return "application/xml";
    case "lpk": return "application/octet-stream";
    case "lsf": return "video/x-la-asf";
    case "lst": return "text/plain";
    case "lsx": return "video/x-la-asf";
    case "lzh": return "application/octet-stream";
    case "m13": return "application/x-msmediaview";
    case "m14": return "application/x-msmediaview";
    case "m1v": return "video/mpeg";
    case "m2t": return "video/vnd.dlna.mpeg-tts";
    case "m2ts": return "video/vnd.dlna.mpeg-tts";
    case "m2v": return "video/mpeg";
    case "m3u": return "audio/x-mpegurl";
    case "m3u8": return "audio/x-mpegurl";
    case "m4a": return "audio/m4a";
    case "m4b": return "audio/m4b";
    case "m4p": return "audio/m4p";
    case "m4r": return "audio/x-m4r";
    case "m4v": return "video/x-m4v";
    case "mac": return "image/x-macpaint";
    case "mak": return "text/plain";
    case "man": return "application/x-troff-man";
    case "manifest": return "application/x-ms-manifest";
    case "map": return "text/plain";
    case "master": return "application/xml";
    case "mda": return "application/msaccess";
    case "mdb": return "application/x-msaccess";
    case "mde": return "application/msaccess";
    case "mdp": return "application/octet-stream";
    case "me": return "application/x-troff-me";
    case "mfp": return "application/x-shockwave-flash";
    case "mht": return "message/rfc822";
    case "mhtml": return "message/rfc822";
    case "mid": return "audio/mid";
    case "midi": return "audio/mid";
    case "mix": return "application/octet-stream";
    case "mk": return "text/plain";
    case "mmf": return "application/x-smaf";
    case "mno": return "text/xml";
    case "mny": return "application/x-msmoney";
    case "mod": return "video/mpeg";
    case "mov": return "video/quicktime";
    case "movie": return "video/x-sgi-movie";
    case "mp2": return "video/mpeg";
    case "mp2v": return "video/mpeg";
    case "mp3": return "audio/mpeg";
    case "mp4": return "video/mp4";
    case "mp4v": return "video/mp4";
    case "mpa": return "video/mpeg";
    case "mpe": return "video/mpeg";
    case "mpeg": return "video/mpeg";
    case "mpf": return "application/vnd.ms-mediapackage";
    case "mpg": return "video/mpeg";
    case "mpp": return "application/vnd.ms-project";
    case "mpv2": return "video/mpeg";
    case "mqv": return "video/quicktime";
    case "ms": return "application/x-troff-ms";
    case "msi": return "application/octet-stream";
    case "mso": return "application/octet-stream";
    case "mts": return "video/vnd.dlna.mpeg-tts";
    case "mtx": return "application/xml";
    case "mvb": return "application/x-msmediaview";
    case "mvc": return "application/x-miva-compiled";
    case "mxp": return "application/x-mmxp";
    case "nc": return "application/x-netcdf";
    case "nsc": return "video/x-ms-asf";
    case "nws": return "message/rfc822";
    case "ocx": return "application/octet-stream";
    case "oda": return "application/oda";
    case "odc": return "text/x-ms-odc";
    case "odh": return "text/plain";
    case "odl": return "text/plain";
    case "odp": return "application/vnd.oasis.opendocument.presentation";
    case "ods": return "application/oleobject";
    case "odt": return "application/vnd.oasis.opendocument.text";
    case "one": return "application/onenote";
    case "onea": return "application/onenote";
    case "onepkg": return "application/onenote";
    case "onetmp": return "application/onenote";
    case "onetoc": return "application/onenote";
    case "onetoc2": return "application/onenote";
    case "orderedtest": return "application/xml";
    case "osdx": return "application/opensearchdescription+xml";
    case "p10": return "application/pkcs10";
    case "p12": return "application/x-pkcs12";
    case "p7b": return "application/x-pkcs7-certificates";
    case "p7c": return "application/pkcs7-mime";
    case "p7m": return "application/pkcs7-mime";
    case "p7r": return "application/x-pkcs7-certreqresp";
    case "p7s": return "application/pkcs7-signature";
    case "pbm": return "image/x-portable-bitmap";
    case "pcast": return "application/x-podcast";
    case "pct": return "image/pict";
    case "pcx": return "application/octet-stream";
    case "pcz": return "application/octet-stream";
    case "pdf": return "application/pdf";
    case "pfb": return "application/octet-stream";
    case "pfm": return "application/octet-stream";
    case "pfx": return "application/x-pkcs12";
    case "pgm": return "image/x-portable-graymap";
    case "pic": return "image/pict";
    case "pict": return "image/pict";
    case "pkgdef": return "text/plain";
    case "pkgundef": return "text/plain";
    case "pko": return "application/vnd.ms-pki.pko";
    case "pls": return "audio/scpls";
    case "pma": return "application/x-perfmon";
    case "pmc": return "application/x-perfmon";
    case "pml": return "application/x-perfmon";
    case "pmr": return "application/x-perfmon";
    case "pmw": return "application/x-perfmon";
    case "png": return "image/png";
    case "pnm": return "image/x-portable-anymap";
    case "pnt": return "image/x-macpaint";
    case "pntg": return "image/x-macpaint";
    case "pnz": return "image/png";
    case "pot": return "application/vnd.ms-powerpoint";
    case "potm": return "application/vnd.ms-powerpoint.template.macroenabled.12";
    case "potx": return "application/vnd.openxmlformats-officedocument.presentationml.template";
    case "ppa": return "application/vnd.ms-powerpoint";
    case "ppam": return "application/vnd.ms-powerpoint.addin.macroenabled.12";
    case "ppm": return "image/x-portable-pixmap";
    case "pps": return "application/vnd.ms-powerpoint";
    case "ppsm": return "application/vnd.ms-powerpoint.slideshow.macroenabled.12";
    case "ppsx": return "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
    case "ppt": return "application/vnd.ms-powerpoint";
    case "pptm": return "application/vnd.ms-powerpoint.presentation.macroenabled.12";
    case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
    case "prf": return "application/pics-rules";
    case "prm": return "application/octet-stream";
    case "prx": return "application/octet-stream";
    case "ps": return "application/postscript";
    case "psc1": return "application/powershell";
    case "psd": return "application/octet-stream";
    case "psess": return "application/xml";
    case "psm": return "application/octet-stream";
    case "psp": return "application/octet-stream";
    case "pub": return "application/x-mspublisher";
    case "pwz": return "application/vnd.ms-powerpoint";
    case "qht": return "text/x-html-insertion";
    case "qhtm": return "text/x-html-insertion";
    case "qt": return "video/quicktime";
    case "qti": return "image/x-quicktime";
    case "qtif": return "image/x-quicktime";
    case "qtl": return "application/x-quicktimeplayer";
    case "qxd": return "application/octet-stream";
    case "ra": return "audio/x-pn-realaudio";
    case "ram": return "audio/x-pn-realaudio";
    case "rar": return "application/octet-stream";
    case "ras": return "image/x-cmu-raster";
    case "rat": return "application/rat-file";
    case "rc": return "text/plain";
    case "rc2": return "text/plain";
    case "rct": return "text/plain";
    case "rdlc": return "application/xml";
    case "resx": return "application/xml";
    case "rf": return "image/vnd.rn-realflash";
    case "rgb": return "image/x-rgb";
    case "rgs": return "text/plain";
    case "rm": return "application/vnd.rn-realmedia";
    case "rmi": return "audio/mid";
    case "rmp": return "application/vnd.rn-rn_music_package";
    case "roff": return "application/x-troff";
    case "rpm": return "audio/x-pn-realaudio-plugin";
    case "rqy": return "text/x-ms-rqy";
    case "rtf": return "application/rtf";
    case "rtx": return "text/richtext";
    case "ruleset": return "application/xml";
    case "s": return "text/plain";
    case "safariextz": return "application/x-safari-safariextz";
    case "scd": return "application/x-msschedule";
    case "sct": return "text/scriptlet";
    case "sd2": return "audio/x-sd2";
    case "sdp": return "application/sdp";
    case "sea": return "application/octet-stream";
    case "searchconnector-ms": return "application/windows-search-connector+xml";
    case "setpay": return "application/set-payment-initiation";
    case "setreg": return "application/set-registration-initiation";
    case "settings": return "application/xml";
    case "sgimb": return "application/x-sgimb";
    case "sgml": return "text/sgml";
    case "sh": return "application/x-sh";
    case "shar": return "application/x-shar";
    case "shtml": return "text/html";
    case "sit": return "application/x-stuffit";
    case "sitemap": return "application/xml";
    case "skin": return "application/xml";
    case "sldm": return "application/vnd.ms-powerpoint.slide.macroenabled.12";
    case "sldx": return "application/vnd.openxmlformats-officedocument.presentationml.slide";
    case "slk": return "application/vnd.ms-excel";
    case "sln": return "text/plain";
    case "slupkg-ms": return "application/x-ms-license";
    case "smd": return "audio/x-smd";
    case "smi": return "application/octet-stream";
    case "smx": return "audio/x-smd";
    case "smz": return "audio/x-smd";
    case "snd": return "audio/basic";
    case "snippet": return "application/xml";
    case "snp": return "application/octet-stream";
    case "sol": return "text/plain";
    case "sor": return "text/plain";
    case "spc": return "application/x-pkcs7-certificates";
    case "spl": return "application/futuresplash";
    case "src": return "application/x-wais-source";
    case "srf": return "text/plain";
    case "ssisdeploymentmanifest": return "text/xml";
    case "ssm": return "application/streamingmedia";
    case "sst": return "application/vnd.ms-pki.certstore";
    case "stl": return "application/vnd.ms-pki.stl";
    case "sv4cpio": return "application/x-sv4cpio";
    case "sv4crc": return "application/x-sv4crc";
    case "svc": return "application/xml";
    case "swf": return "application/x-shockwave-flash";
    case "t": return "application/x-troff";
    case "tar": return "application/x-tar";
    case "tcl": return "application/x-tcl";
    case "testrunconfig": return "application/xml";
    case "testsettings": return "application/xml";
    case "tex": return "application/x-tex";
    case "texi": return "application/x-texinfo";
    case "texinfo": return "application/x-texinfo";
    case "tgz": return "application/x-compressed";
    case "thmx": return "application/vnd.ms-officetheme";
    case "thn": return "application/octet-stream";
    case "tif": return "image/tiff";
    case "tiff": return "image/tiff";
    case "tlh": return "text/plain";
    case "tli": return "text/plain";
    case "toc": return "application/octet-stream";
    case "tr": return "application/x-troff";
    case "trm": return "application/x-msterminal";
    case "trx": return "application/xml";
    case "ts": return "video/vnd.dlna.mpeg-tts";
    case "tsv": return "text/tab-separated-values";
    case "ttf": return "application/octet-stream";
    case "tts": return "video/vnd.dlna.mpeg-tts";
    case "txt": return "text/plain";
    case "u32": return "application/octet-stream";
    case "uls": return "text/iuls";
    case "user": return "text/plain";
    case "ustar": return "application/x-ustar";
    case "vb": return "text/plain";
    case "vbdproj": return "text/plain";
    case "vbk": return "video/mpeg";
    case "vbproj": return "text/plain";
    case "vbs": return "text/vbscript";
    case "vcf": return "text/x-vcard";
    case "vcproj": return "application/xml";
    case "vcs": return "text/plain";
    case "vcxproj": return "application/xml";
    case "vddproj": return "text/plain";
    case "vdp": return "text/plain";
    case "vdproj": return "text/plain";
    case "vdx": return "application/vnd.ms-visio.viewer";
    case "vml": return "text/xml";
    case "vscontent": return "application/xml";
    case "vsct": return "text/xml";
    case "vsd": return "application/vnd.visio";
    case "vsi": return "application/ms-vsi";
    case "vsix": return "application/vsix";
    case "vsixlangpack": return "text/xml";
    case "vsixmanifest": return "text/xml";
    case "vsmdi": return "application/xml";
    case "vspscc": return "text/plain";
    case "vss": return "application/vnd.visio";
    case "vsscc": return "text/plain";
    case "vssettings": return "text/xml";
    case "vssscc": return "text/plain";
    case "vst": return "application/vnd.visio";
    case "vstemplate": return "text/xml";
    case "vsto": return "application/x-ms-vsto";
    case "vsw": return "application/vnd.visio";
    case "vsx": return "application/vnd.visio";
    case "vtx": return "application/vnd.visio";
    case "wav": return "audio/wav";
    case "wave": return "audio/wav";
    case "wax": return "audio/x-ms-wax";
    case "wbk": return "application/msword";
    case "wbmp": return "image/vnd.wap.wbmp";
    case "wcm": return "application/vnd.ms-works";
    case "wdb": return "application/vnd.ms-works";
    case "wdp": return "image/vnd.ms-photo";
    case "webarchive": return "application/x-safari-webarchive";
    case "webtest": return "application/xml";
    case "wiq": return "application/xml";
    case "wiz": return "application/msword";
    case "wks": return "application/vnd.ms-works";
    case "wlmp": return "application/wlmoviemaker";
    case "wlpginstall": return "application/x-wlpg-detect";
    case "wlpginstall3": return "application/x-wlpg3-detect";
    case "wm": return "video/x-ms-wm";
    case "wma": return "audio/x-ms-wma";
    case "wmd": return "application/x-ms-wmd";
    case "wmf": return "application/x-msmetafile";
    case "wml": return "text/vnd.wap.wml";
    case "wmlc": return "application/vnd.wap.wmlc";
    case "wmls": return "text/vnd.wap.wmlscript";
    case "wmlsc": return "application/vnd.wap.wmlscriptc";
    case "wmp": return "video/x-ms-wmp";
    case "wmv": return "video/x-ms-wmv";
    case "wmx": return "video/x-ms-wmx";
    case "wmz": return "application/x-ms-wmz";
    case "wpl": return "application/vnd.ms-wpl";
    case "wps": return "application/vnd.ms-works";
    case "wri": return "application/x-mswrite";
    case "wrl": return "x-world/x-vrml";
    case "wrz": return "x-world/x-vrml";
    case "wsc": return "text/scriptlet";
    case "wsdl": return "text/xml";
    case "wvx": return "video/x-ms-wvx";
    case "x": return "application/directx";
    case "xaf": return "x-world/x-vrml";
    case "xaml": return "application/xaml+xml";
    case "xap": return "application/x-silverlight-app";
    case "xbap": return "application/x-ms-xbap";
    case "xbm": return "image/x-xbitmap";
    case "xdr": return "text/plain";
    case "xht": return "application/xhtml+xml";
    case "xhtml": return "application/xhtml+xml";
    case "xla": return "application/vnd.ms-excel";
    case "xlam": return "application/vnd.ms-excel.addin.macroenabled.12";
    case "xlc": return "application/vnd.ms-excel";
    case "xld": return "application/vnd.ms-excel";
    case "xlk": return "application/vnd.ms-excel";
    case "xll": return "application/vnd.ms-excel";
    case "xlm": return "application/vnd.ms-excel";
    case "xls": return "application/vnd.ms-excel";
    case "xlsb": return "application/vnd.ms-excel.sheet.binary.macroenabled.12";
    case "xlsm": return "application/vnd.ms-excel.sheet.macroenabled.12";
    case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    case "xlt": return "application/vnd.ms-excel";
    case "xltm": return "application/vnd.ms-excel.template.macroenabled.12";
    case "xltx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
    case "xlw": return "application/vnd.ms-excel";
    case "xml": return "text/xml";
    case "xmta": return "application/xml";
    case "xof": return "x-world/x-vrml";
    case "xoml": return "text/plain";
    case "xpm": return "image/x-xpixmap";
    case "xps": return "application/vnd.ms-xpsdocument";
    case "xrm-ms": return "text/xml";
    case "xsc": return "application/xml";
    case "xsd": return "text/xml";
    case "xsf": return "text/xml";
    case "xsl": return "text/xml";
    case "xslt": return "text/xml";
    case "xsn": return "application/octet-stream";
    case "xss": return "application/xml";
    case "xtp": return "application/octet-stream";
    case "xwd": return "image/x-xwindowdump";
    case "z": return "application/x-compress";
    case "zip": return "application/x-zip-compressed";
  #endregion
    default: return "application/octet-stream";
  }
}

How do I compare strings in Java?

== performs a reference equality check, whether the 2 objects (strings in this case) refer to the same object in the memory.

The equals() method will check whether the contents or the states of 2 objects are the same.

Obviously == is faster, but will (might) give false results in many cases if you just want to tell if 2 Strings hold the same text.

Definitely the use of the equals() method is recommended.

Don't worry about the performance. Some things to encourage using String.equals():

  1. Implementation of String.equals() first checks for reference equality (using ==), and if the 2 strings are the same by reference, no further calculation is performed!
  2. If the 2 string references are not the same, String.equals() will next check the lengths of the strings. This is also a fast operation because the String class stores the length of the string, no need to count the characters or code points. If the lengths differ, no further check is performed, we know they cannot be equal.
  3. Only if we got this far will the contents of the 2 strings be actually compared, and this will be a short-hand comparison: not all the characters will be compared, if we find a mismatching character (at the same position in the 2 strings), no further characters will be checked.

When all is said and done, even if we have a guarantee that the strings are interns, using the equals() method is still not that overhead that one might think, definitely the recommended way. If you want an efficient reference check, then use enums where it is guaranteed by the language specification and implementation that the same enum value will be the same object (by reference).

What is SYSNAME data type in SQL Server?

sysname is used by sp_send_dbmail, a stored procedure that "Sends an e-mail message to the specified recipients" and located in the msdb database.

According to Microsoft,

[ @profile_name = ] 'profile_name'  

Is the name of the profile to send the message from. The profile_name is of type sysname, with a default of NULL. The profile_name must be the name of an existing Database Mail profile. When no profile_name is specified, sp_send_dbmail uses the default private profile for the current user. If the user does not have a default private profile, sp_send_dbmail uses the default public profile for the msdb database. If the user does not have a default private profile and there is no default public profile for the database, @profile_name must be specified.

Singletons vs. Application Context in Android?

Application is not the same as the Singleton.The reasons are:

  1. Application's method(such as onCreate) is called in the ui thread;
  2. singleton's method can be called in any thread;
  3. In the method "onCreate" of Application,you can instantiate Handler;
  4. If the singleton is executed in none-ui thread,you could not instantiate Handler;
  5. Application has the ability to manage the life cycle of the activities in the app.It has the method "registerActivityLifecycleCallbacks".But the singletons has not the ability.

Maven package/install without test (skip tests)

You can pass the maven.test.skip flag as a JVM argument, to skip running tests when the package phase (and the previous ones in the default lifecycle) is run:

mvn package -Dmaven.test.skip=true

You can also pass the skipTests flag alone to the mvn executable. If you want to include this information in your POM, you can create a new profile where you can configure the maven-surefire-plugin to skip tests.

How to get the Power of some Integer in Swift language?

To calculate power(2, n), simply use:

let result = 2 << (n-1)

Jquery button click() function is not working

After making the id unique across the document ,You have to use event delegation

$("#container").on("click", "buttonid", function () {
  alert("Hi");
});

How do I download/extract font from chrome developers tools?

Open chrome

Right click => inspect => navigate to application tab

In Frames section, all the statically available assets(resources) such as css, JavaScript, fonts are listed.

How to tell if a JavaScript function is defined

Try:

if (typeof(callback) == 'function')

"Default Activity Not Found" on Android Studio upgrade

TL;DR:

Make sure that you not only check the action and category name, but the path. Especially if you did a refactor.

The solution for me was to closely check the AndroidManifest file. I did a refactor, and it not only updated the intent-filters, but it also updated the path of the intent filter name:

 //type and value were added to the path here when I did the refactor
 <action android:name="android.intent.type.MAIN"/>
 <category android:name="android.intent.value.LAUNCHER"/>

It should be:

<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>

How to upload multiple files using PHP, jQuery and AJAX

HTML

<form enctype="multipart/form-data" action="upload.php" method="post">
    <input name="file[]" type="file" />
    <button class="add_more">Add More Files</button>
    <input type="button" value="Upload File" id="upload"/>
</form>

Javascript

 $(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' type='file'/>");
    });
});

for ajax upload

$('#upload').click(function() {
    var filedata = document.getElementsByName("file"),
            formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    var i = 0, len = filedata.files.length, img, reader, file;

    for (; i < len; i++) {
        file = filedata.files[i];

        if (window.FileReader) {
            reader = new FileReader();
            reader.onloadend = function(e) {
                showUploadedItem(e.target.result, file.fileName);
            };
            reader.readAsDataURL(file);
        }
        if (formdata) {
            formdata.append("file", file);
        }
    }
    if (formdata) {
        $.ajax({
            url: "/path to upload/",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function(res) {

            },       
            error: function(res) {

             }       
             });
            }
        });

PHP

for($i=0; $i<count($_FILES['file']['name']); $i++){
    $target_path = "uploads/";
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
        echo "The file has been uploaded successfully <br />";
    } else{
        echo "There was an error uploading the file, please try again! <br />";
    }
}

/** 
    Edit: $target_path variable need to be reinitialized and should 
    be inside for loop to avoid appending previous file name to new one. 
*/

Please use the script above script for ajax upload. It will work

Get value from hashmap based on key to JSTL

if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:

<c:out value="${map['key']}"/>

where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.

How can I express that two values are not equal to eachother?

If the class implements comparable, you could also do

int compRes = a.compareTo(b);
if(compRes < 0 || compRes > 0)
    System.out.println("not equal");
else
    System.out.println("equal);

doesn't use a !, though not particularly useful, or readable....

Bash Script : what does #!/bin/bash mean?

In bash script, what does #!/bin/bash at the 1st line mean ?

In Linux system, we have shell which interprets our UNIX commands. Now there are a number of shell in Unix system. Among them, there is a shell called bash which is very very common Linux and it has a long history. This is a by default shell in Linux.

When you write a script (collection of unix commands and so on) you have a option to specify which shell it can be used. Generally you can specify which shell it wold be by using Shebang(Yes that's what it's name).

So if you #!/bin/bash in the top of your scripts then you are telling your system to use bash as a default shell.

Now coming to your second question :Is there a difference between #!/bin/bash and #!/bin/sh ?

The answer is Yes. When you tell #!/bin/bash then you are telling your environment/ os to use bash as a command interpreter. This is hard coded thing.

Every system has its own shell which the system will use to execute its own system scripts. This system shell can be vary from OS to OS(most of the time it will be bash. Ubuntu recently using dash as default system shell). When you specify #!/bin/sh then system will use it's internal system shell to interpreting your shell scripts.

Visit this link for further information where I have explained this topic.

Hope this will eliminate your confusions...good luck.

Critical t values in R

Extending @Ryogi answer above, you can take advantage of the lower.tail parameter like so:

qt(0.25/2, 40, lower.tail = FALSE) # 75% confidence

qt(0.01/2, 40, lower.tail = FALSE) # 99% confidence

Nested classes' scope?

In Python mutable objects are passed as reference, so you can pass a reference of the outer class to the inner class.

class OuterClass:
    def __init__(self):
        self.outer_var = 1
        self.inner_class = OuterClass.InnerClass(self)
        print('Inner variable in OuterClass = %d' % self.inner_class.inner_var)

    class InnerClass:
        def __init__(self, outer_class):
            self.outer_class = outer_class
            self.inner_var = 2
            print('Outer variable in InnerClass = %d' % self.outer_class.outer_var)

Android: Expand/collapse animation

Making use of Kotlin Extension Functions this is tested and shortest answer

Just call animateVisibility(expand/collapse) on any View.

fun View.animateVisibility(setVisible: Boolean) {
    if (setVisible) expand(this) else collapse(this)
}

private fun expand(view: View) {
    view.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
    val initialHeight = 0
    val targetHeight = view.measuredHeight

    // Older versions of Android (pre API 21) cancel animations for views with a height of 0.
    //v.getLayoutParams().height = 1;
    view.layoutParams.height = 0
    view.visibility = View.VISIBLE

    animateView(view, initialHeight, targetHeight)
}

private fun collapse(view: View) {
    val initialHeight = view.measuredHeight
    val targetHeight = 0

    animateView(view, initialHeight, targetHeight)
}

private fun animateView(v: View, initialHeight: Int, targetHeight: Int) {
    val valueAnimator = ValueAnimator.ofInt(initialHeight, targetHeight)
    valueAnimator.addUpdateListener { animation ->
        v.layoutParams.height = animation.animatedValue as Int
        v.requestLayout()
    }
    valueAnimator.addListener(object : Animator.AnimatorListener {
        override fun onAnimationEnd(animation: Animator) {
            v.layoutParams.height = targetHeight
        }

        override fun onAnimationStart(animation: Animator) {}
        override fun onAnimationCancel(animation: Animator) {}
        override fun onAnimationRepeat(animation: Animator) {}
    })
    valueAnimator.duration = 300
    valueAnimator.interpolator = DecelerateInterpolator()
    valueAnimator.start()
}

Limit results in jQuery UI Autocomplete

Plugin: jquery-ui-autocomplete-scroll with scroller and limit results are beautiful

$('#task').autocomplete({
  maxShowItems: 5,
  source: myarray
});

Git reset single file in feature branch to be the same as in master

If you want to revert the file to its state in master:

git checkout origin/master [filename]

How to exclude a directory in find . command

I find the following easier to reason about than other proposed solutions:

find build -not \( -path build/external -prune \) -name \*.js
# you can also exclude multiple paths
find build -not \( -path build/external -prune \) -not \( -path build/blog -prune \) -name \*.js

Important Note: the paths you type after -path must exactly match what find would print without the exclusion. If this sentence confuses you just make sure to use full paths through out the whole command like this: find /full/path/ -not \( -path /full/path/exclude/this -prune \) .... See note [1] if you'd like a better understanding.

Inside \( and \) is an expression that will match exactly build/external (see important note above), and will, on success, avoid traversing anything below. This is then grouped as a single expression with the escaped parenthesis, and prefixed with -not which will make find skip anything that was matched by that expression.

One might ask if adding -not will not make all other files hidden by -prune reappear, and the answer is no. The way -prune works is that anything that, once it is reached, the files below that directory are permanently ignored.

This comes from an actual use case, where I needed to call yui-compressor on some files generated by wintersmith, but leave out other files that need to be sent as-is.


Note [1]: If you want to exclude /tmp/foo/bar and you run find like this "find /tmp \(..." then you must specify -path /tmp/foo/bar. If on the other hand you run find like this cd /tmp; find . \(... then you must specify -path ./foo/bar.

What is the standard naming convention for html/css ids and classes?

I just recently started learning XML. The underscore version helps me separate everything XML-related (DOM, XSD, etc.) from programming languages like Java, JavaScript (camel case). And I agree with you that using identifiers which are allowed in programming languages looks better.

Edit: Might be unrelated, but here is a link for rules and recommendations on naming XML elements which I follow when naming ids (sections "XML Naming Rules" and "Best Naming Practices").

http://www.w3schools.com/xml/xml_elements.asp

Validate SSL certificates with Python

PycURL does this beautifully.

Below is a short example. It will throw a pycurl.error if something is fishy, where you get a tuple with error code and a human readable message.

import pycurl

curl = pycurl.Curl()
curl.setopt(pycurl.CAINFO, "myFineCA.crt")
curl.setopt(pycurl.SSL_VERIFYPEER, 1)
curl.setopt(pycurl.SSL_VERIFYHOST, 2)
curl.setopt(pycurl.URL, "https://internal.stuff/")

curl.perform()

You will probably want to configure more options, like where to store the results, etc. But no need to clutter the example with non-essentials.

Example of what exceptions might be raised:

(60, 'Peer certificate cannot be authenticated with known CA certificates')
(51, "common name 'CN=something.else.stuff,O=Example Corp,C=SE' does not match 'internal.stuff'")

Some links that I found useful are the libcurl-docs for setopt and getinfo.

Expand a div to fill the remaining width

This is fairly easy using flexbox. See the snippet below. I've added a wrapper container to control flow and set a global height. Borders have been added as well to identify the elements. Notice that divs now expand to the full height as well, as required. Vendor prefixes should be used for flexbox in a real world scenario since is not yet fully supported.

I've developed a free tool to understand and design layouts using flexbox. Check it out here: http://algid.com/Flex-Designer

_x000D_
_x000D_
.container{_x000D_
    height:180px;_x000D_
    border:3px solid #00f;_x000D_
    display:flex;_x000D_
    align-items:stretch;_x000D_
}_x000D_
div {_x000D_
    display:flex;_x000D_
    border:3px solid #0f0;_x000D_
}_x000D_
.second {_x000D_
    display:flex;_x000D_
    flex-grow:1;_x000D_
    border:3px solid #f00;_x000D_
}
_x000D_
<div class="container">_x000D_
    <div>Tree</div>_x000D_
    <div class="second">View</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

WAMP/XAMPP is responding very slow over localhost

Power plan was the problem.Changed Balanced to High performance.

How to disable the resize grabber of <textarea>?

<textarea style="resize:none" name="name" cols="num" rows="num"></textarea>

Just an example

How do I get client IP address in ASP.NET CORE?

try this.

var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                 ipAddress = ip.ToString();
            }
        }

Photoshop text tool adds punctuation to the beginning of text

You can try : go to edit>preferencec>type.. select type > choose text engine options select east asian. Restart photoshop. Create new peroject. Try text tool again.

(if you want to use your project created with other text engine type) copy /paste all layers to new project.

Entity Framework Core: A second operation started on this context before a previous operation completed

I managed to get that error by passing an IQueryable into a method that then used that IQueryable 'list' as part of a another query to the same context.

public void FirstMethod()
{
    // This is returning an IQueryable
    var stockItems = _dbContext.StockItems
        .Where(st => st.IsSomething);

    SecondMethod(stockItems);
}

public void SecondMethod(IEnumerable<Stock> stockItems)
{
    var grnTrans = _dbContext.InvoiceLines
        .Where(il => stockItems.Contains(il.StockItem))
        .ToList();
}

To stop that happening I used the approach here and materialised that list before passing it the second method, by changing the call to SecondMethod to be SecondMethod(stockItems.ToList()

Get total of Pandas column

You should use sum:

Total = df['MyColumn'].sum()
print (Total)
319

Then you use loc with Series, in that case the index should be set as the same as the specific column you need to sum:

df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index = ['MyColumn'])
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

because if you pass scalar, the values of all rows will be filled:

df.loc['Total'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A        84   13.0   69.0
1        B        76   77.0  127.0
2        C        28   69.0   16.0
3        D        28   28.0   31.0
4        E        19   20.0   85.0
5        F        84  193.0   70.0
Total  319       319  319.0  319.0

Two other solutions are with at, and ix see the applications below:

df.at['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

df.ix['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

Note: Since Pandas v0.20, ix has been deprecated. Use loc or iloc instead.