Programs & Examples On #Static functions

How do I test a private function or a class that has private methods, fields or inner classes?

Having tried Cem Catikkas' solution using reflection for Java, I'd have to say his was a more elegant solution than I have described here. However, if you're looking for an alternative to using reflection, and have access to the source you're testing, this will still be an option.

There is possible merit in testing private methods of a class, particularly with test-driven development, where you would like to design small tests before you write any code.

Creating a test with access to private members and methods can test areas of code which are difficult to target specifically with access only to public methods. If a public method has several steps involved, it can consist of several private methods, which can then be tested individually.


  • Can test to a finer granularity


  • Test code must reside in the same file as source code, which can be more difficult to maintain
  • Similarly with .class output files, they must remain within the same package as declared in source code

However, if continuous testing requires this method, it may be a signal that the private methods should be extracted, which could be tested in the traditional, public way.

Here is a convoluted example of how this would work:

// Import statements and package declarations

public class ClassToTest
    private int decrement(int toDecrement) {
        return toDecrement;

    // Constructor and the rest of the class

    public static class StaticInnerTest extends TestCase
        public StaticInnerTest(){

        public void testDecrement(){
            int number = 10;
            ClassToTest toTest= new ClassToTest();
            int decremented = toTest.decrement(number);
            assertEquals(9, decremented);

        public static void main(String[] args) {

The inner class would be compiled to ClassToTest$StaticInnerTest.

See also: Java Tip 106: Static inner classes for fun and profit

Eclipse - debugger doesn't stop at breakpoint

Project -> Clean seemed to work for me on on JRE 8

Install mysql-python (Windows)

You're going to want to add Python to your Path Environment Variable in this way. Go to:

  1. My Computer
  2. System Properties
  3. Advance System Settings
  4. Under the "Advanced" tab click the button that says "Environment Variables"
  5. Then under System Variables you are going to want to add / change the following variables: PYTHONPATH and Path. Here is a paste of what my variables look like:




C:\Program Files\MySQL\MySQL Utilities 1.3.5\;C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts

Your Path's might be different, so please adjust them, but this configuration works for me and you should be able to run MySQL after making these changes.

Post form data using HttpWebRequest

Try this:

var request = (HttpWebRequest)WebRequest.Create("");

var postData = "thing1=hello";
    postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
    stream.Write(data, 0, data.Length);

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

detect key press in python?

For Windows you could use msvcrt like this:

   import msvcrt
   while True:
       if msvcrt.kbhit():
           key = msvcrt.getch()
           print(key)   # just to show the result

Is it possible to do a sparse checkout without checking out the whole repository first?

I had a similar use case, except I wanted to checkout only the commit for a tag and prune the directories. Using --depth 1 makes it really sparse and can really speed things up.

mkdir myrepo
cd myrepo
git init
git config core.sparseCheckout true
git remote add origin <url>  # Note: no -f option
echo "path/within_repo/to/subdir/" > .git/info/sparse-checkout
git fetch --depth 1 origin tag <tagname>
git checkout <tagname>

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Try this, it will convert True into 1 and False into 0:

data.frame$  <- as.numeric(data.frame$

Then you can convert into factor if you want:

data.frame$ <- as .factor(data.frame$

What are the differences between the BLOB and TEXT datatypes in MySQL?

BLOB stores binary data which are more than 2 GB. Max size for BLOB is 4 GB. Binary data means unstructured data i.e images audio files vedio files digital signature

Text is used to store large string.

Serializing enums with Jackson

Use @JsonCreator annotation, create method getType(), is serialize with toString or object working



{"type": "ATIVO", "descricao": "Ativo"}


import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SituacaoUsuario {

    PENDENTE_VALIDACAO("Pendente de Validação"),
     * Usuarios cadastrados pelos clientes que não possuem acesso a aplicacao,
     * caso venham a se cadastrar este status deve ser alterado
    NAO_REGISTRADO("Não Registrado");

    private SituacaoUsuario(String descricao) {
        this.descricao = descricao;

    private String descricao;

    public String getDescricao() {
        return descricao;

    // TODO - Adicionar metodos dinamicamente
    public String getType() {
        return this.toString();

    public String getPropertieKey() {
        StringBuilder sb = new StringBuilder("enum.");
        return sb.toString().toLowerCase();

    public static SituacaoUsuario fromObject(JsonNode node) {
        String type = null;
        if (node.getNodeType().equals(JsonNodeType.STRING)) {
            type = node.asText();
        } else {
            if (!node.has("type")) {
                throw new IllegalArgumentException();
            type = node.get("type").asText();
        return valueOf(type);


Convert .pem to .crt and .key

This is what I did on windows.

  1. Download a zip file that contains the open ssl exe from Google
  2. Unpack the zip file and go into the bin folder.
  3. Go to the address bar in the bin folder and type cmd. This will open a command prompt at this folder.
  4. move/Put the .pem file into this bin folder.
  5. Run two commands. One creates the cert and the second the key file
openssl x509 -outform der -in yourPemFilename.pem -out certfileOutName.crt
openssl rsa -in yourPemFilename.pem -out keyfileOutName.key

identifier "string" undefined?

<string.h> is the old C header. C++ provides <string>, and then it should be referred to as std::string.

Converting RGB to grayscale/intensity

These values vary from person to person, especially for people who are colorblind.

SQL Server Linked Server Example Query

You need to specify the schema/owner (dbo by default) as part of the reference. Also, it would be preferable to use the newer (ANSI-92) join style.

    from databaseserver1.db1.dbo.table1 foo
        inner join databaseserver2.db1.dbo.table1 bar 
            on =

Jackson with JSON: Unrecognized field, not marked as ignorable

I have tried the below method and it works for such JSON format reading with Jackson. Use the already suggested solution of: annotating getter with @JsonProperty("wrapper")

Your wrapper class

public Class Wrapper{ 
  private List<Student> students;
  //getters & setters here 

My Suggestion of wrapper class

public Class Wrapper{ 

  private StudentHelper students; 

  //getters & setters here 
  // Annotate getter
  StudentHelper getStudents() {
    return students;

public class StudentHelper {

  public List<Student> students; 

  //CTOR, getters and setters
  //NOTE: If students is private annotate getter with the annotation @JsonProperty("Student")

This would however give you the output of the format:


Also for more information refer to

Hope this helps

Stretch background image css?

You can't stretch a background image (until CSS 3).

You would have to use absolute positioning, so that you can put an image tag inside the cell and stretch it to cover the entire cell, then put the content on top of the image.

table {_x000D_
  width: 230px;_x000D_
.style1 {_x000D_
  text-align: center;_x000D_
  height: 35px;_x000D_
.bg {_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
.bg img {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
.bg .linkcontainer {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
<table cellpadding="0" cellspacing="0" border="10">_x000D_
    <td class="style1">_x000D_
      <div class="bg">_x000D_
        <img src="" alt="" />_x000D_
        <div class="linkcontainer">_x000D_
          <a class="link" href="#">_x000D_

How do I update all my CPAN modules to their latest versions?

Try perl -MCPAN -e "upgrade /(.\*)/". It works fine for me.

jQuery changing css class to div

You can add and remove classes with jQuery like so:

// remove a class

By the way you can set multiple classes in your markup right away separated with a whitespace

<div class="second first"></div>

What do the return values of Comparable.compareTo mean in Java?

Official Definition

From the reference docs of Comparable.compareTo(T):

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.

My Version

In short:



  • a negative int if this < that
  • 0 if this == that
  • a positive int if this > that

where the implementation of this method determines the actual semantics of < > and == (I don't mean == in the sense of java's object identity operator)



will yield something smaller than 0 as abc is alphabetically before def.


will yield something larger than 0 because 2 is larger than 1.

Some additional points

Note: It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs.

Note: you should read at least one of the following:

Warning: you should never rely on the return values of compareTo being -1, 0 and 1. You should always test for x < 0, x == 0, x > 0, respectively.

SQL DROP TABLE foreign key constraint

Here is a complete script to implement a solution:

create Procedure [dev].DeleteTablesFromSchema
    @schemaName varchar(500)
    declare @constraintSchemaName nvarchar(128), @constraintTableName nvarchar(128),  @constraintName nvarchar(128)
    declare @sql nvarchar(max)
    -- delete FK first
    declare cur1 cursor for
    select distinct 
    CASE WHEN t2.[object_id] is NOT NULL  THEN ELSE END as SchemaName,
    CASE WHEN t2.[object_id] is NOT NULL  THEN ELSE END as TableName,
    CASE WHEN t2.[object_id] is NOT NULL  THEN  OBJECT_NAME(d2.constraint_object_id) ELSE OBJECT_NAME(d.constraint_object_id) END as ConstraintName
    from sys.objects t 
        inner join sys.schemas s 
            on t.[schema_id] = s.[schema_id]
        left join sys.foreign_key_columns d 
            on  d.parent_object_id = t.[object_id]
        left join sys.foreign_key_columns d2 
            on  d2.referenced_object_id = t.[object_id]
        inner join sys.objects t2 
            on  d2.parent_object_id = t2.[object_id]
        inner join sys.schemas s2 
            on  t2.[schema_id] = s2.[schema_id]
    WHERE t.[type]='U' 
        AND t2.[type]='U'
        AND t.is_ms_shipped = 0 
        AND t2.is_ms_shipped = 0 
        AND s.Name=@schemaName
    open cur1
    fetch next from cur1 into @constraintSchemaName, @constraintTableName, @constraintName
    while @@fetch_status = 0
        set @sql ='ALTER TABLE ' + @constraintSchemaName + '.' + @constraintTableName+' DROP CONSTRAINT '+@constraintName+';'
        fetch next from cur1 into @constraintSchemaName, @constraintTableName, @constraintName
    close cur1
    deallocate cur1

    DECLARE @tableName nvarchar(128)
    declare cur2 cursor for
    select s.Name, p.Name
    from sys.objects p
        INNER JOIN sys.schemas s ON p.[schema_id] = s.[schema_id]
    WHERE p.[type]='U' and is_ms_shipped = 0 
    AND s.Name=@schemaName
    ORDER BY s.Name, p.Name
    open cur2

    fetch next from cur2 into @schemaName,@tableName
    while @@fetch_status = 0
        set @sql ='DROP TABLE ' + @schemaName + '.' + @tableName
        fetch next from cur2 into @schemaName,@tableName

    close cur2
    deallocate cur2


Is it possible to decompile a compiled .pyc file into a .py file?


I use uncompyle6 decompile (even support latest Python 3.8.0):

uncompyle6 utils.cpython-38.pyc >

and the origin python and decompiled python comparing look like this:

pyc uncompile utils

so you can see, ALMOST same, decompile effect is VERY GOOD.

In TensorFlow, what is the difference between and Tensor.eval()?

In tensorflow you create graphs and pass values to that graph. Graph does all the hardwork and generate the output based on the configuration that you have made in the graph. Now When you pass values to the graph then first you need to create a tensorflow session.


Once session is initialized then you are supposed to use that session because all the variables and settings are now part of the session. So, there are two ways to pass external values to the graph so that graph accepts them. One is to call the .run() while you are using the session being executed.

Other way which is basically a shortcut to this is to use .eval(). I said shortcut because the full form of .eval() is


You can check that yourself. At the place of values.eval() run tf.get_default_session().run(values). You must get the same behavior.

what eval is doing is using the default session and then executing run().

What is the list of supported languages/locales on Android?

Arabic, Egypt (ar_EG)
Arabic, Israel (ar_IL)
Bulgarian, Bulgaria (bg_BG)
Catalan, Spain (ca_ES)
Czech, Czech Republic (cs_CZ)
Danish, Denmark(da_DK)
German, Austria (de_AT)
German, Switzerland (de_CH)
German, Germany (de_DE)
German, Liechtenstein (de_LI)
Greek, Greece (el_GR)
English, Australia (en_AU)
English, Canada (en_CA)
English, Britain (en_GB)
English, Ireland (en_IE)
English, India (en_IN)
English, New Zealand (en_NZ)
English, Singapore(en_SG)
English, US (en_US)
English, South Africa (en_ZA)
Spanish (es_ES)
Spanish, US (es_US)
Finnish, Finland (fi_FI)
French, Belgium (fr_BE)
French, Canada (fr_CA)
French, Switzerland (fr_CH)
French, France (fr_FR)
Hebrew, Israel (he_IL)
Hindi, India (hi_IN)
Croatian, Croatia (hr_HR)
Hungarian, Hungary (hu_HU)
Indonesian, Indonesia (id_ID)
Italian, Switzerland (it_CH)
Italian, Italy (it_IT)
Japanese (ja_JP)
Korean (ko_KR)
Lithuanian, Lithuania (lt_LT)
Latvian, Latvia (lv_LV)
Norwegian bokmål, Norway (nb_NO)
Dutch, Belgium (nl_BE)
Dutch, Netherlands (nl_NL)
Polish (pl_PL)
Portuguese, Brazil (pt_BR)
Portuguese, Portugal (pt_PT)
Romanian, Romania (ro_RO)
Russian (ru_RU)
Slovak, Slovakia (sk_SK)
Slovenian, Slovenia (sl_SI)
Serbian (sr_RS)
Swedish, Sweden (sv_SE)
Thai, Thailand (th_TH)
Tagalog, Philippines (tl_PH)
Turkish, Turkey (tr_TR)
Ukrainian, Ukraine (uk_UA)
Vietnamese, Vietnam (vi_VN)
Chinese, PRC (zh_CN)
Chinese, Taiwan (zh_TW)

Regular expression for not allowing spaces in the input field

While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:

var regexp = /^\S*$/; // a string consisting only of non-whitespaces

How can I change NULL to 0 when getting a single value from a SQL function?



SELECT NVL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

This SQL statement would return 0 if the SUM(Price) returned a null value. Otherwise, it would return the SUM(Price) value.

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

How to create new folder?

Have you tried os.mkdir?

You might also try this little code snippet:

mypath = ...
if not os.path.isdir(mypath):

makedirs creates multiple levels of directories, if needed.

REST URI convention - Singular or plural name of resource while creating it

With naming conventions, it's usually safe to say "just pick one and stick to it", which makes sense.

However, after having to explain REST to lots of people, representing endpoints as paths on a file system is the most expressive way of doing it.
It is stateless (files either exist or don't exist), hierarchical, simple, and familiar - you already knows how to access static files, whether locally or via http.

And within that context, linguistic rules can only get you as far as the following:

A directory can contain multiple files and/or sub-directories, and therefore its name should be in plural form.

And I like that.
Although, on the other hand - it's your directory, you can name it "a-resource-or-multiple-resources" if that's what you want. That's not really the important thing.

What's important is that if you put a file named "123" under a directory named "resourceS" (resulting in /resourceS/123), you cannot then expect it to be accessible via /resource/123.

Don't try to make it smarter than it has to be - changing from plural to singluar depending on the count of resources you're currently accessing may be aesthetically pleasing to some, but it's not effective and it doesn't make sense in a hierarchical system.

Note: Technically, you can make "symbolic links", so that /resources/123 can also be accessed via /resource/123, but the former still has to exist!

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

What is a user agent stylesheet?

I had the same problem as one of my <div>'s had the margin set by the browser. It was quite annoying but then I figured out as most of the people said, it's a markup error.

I went back and checked my <head> section and my CSS link was like below:

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

I included type in it and made it like below:

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

My problem was solved.

Clone an image in cv2 python

My favorite method uses cv2.copyMakeBorder with no border, like so.

copy = cv2.copyMakeBorder(original,0,0,0,0,cv2.BORDER_REPLICATE)

How to disable or enable viewpager swiping in android

In your custom view pager adapter, override those methods in ViewPager.

public boolean onInterceptTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;

public boolean onTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;

And to enable, just return each super method:

super.onInterceptTouchEvent(event) and super.onTouchEvent(event).

git replace local version with remote version

I would checkout the remote file from the "master" (the remote/origin repository) like this:

git checkout master <FileWithPath>

Example: git checkout master components/indexTest.html

Is there 'byte' data type in C++?

No, there is no type called "byte" in C++. What you want instead is unsigned char (or, if you need exactly 8 bits, uint8_t from <cstdint>, since C++11). Note that char is not necessarily an accurate alternative, as it means signed char on some compilers and unsigned char on others.

JQuery ajax call default timeout value

The XMLHttpRequest.timeout property represents a number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout. An important note the timeout shouldn't be used for synchronous XMLHttpRequests requests, used in a document environment or it will throw an InvalidAccessError exception. You may not use a timeout for synchronous requests with an owning window.

IE10 and 11 do not support synchronous requests, with support being phased out in other browsers too. This is due to detrimental effects resulting from making them.

More info can be found here.

jQuery to remove an option from drop down list, given option's text/value

I have used the above option to .hide entries from 2 drops down boxes (first you select the city, then you selected the area within that city). It works fine on screen but the hidden options are still selectable via keyboard inputs.

iPhone Safari Web App opens links in new window

This code works for iOS 5 (it worked for me):

In the head tag:

<script type="text/javascript">
    function OpenLink(theLink){
        window.location.href = theLink.href;

In the link that you want to be opened in the same window:

<a href="(your website here)" onclick="OpenLink(this); return false"> Link </a>

I got this code from this comment: iphone web app meta tags

How to get a string after a specific substring?

In Python 3.9, a new removeprefix method is being added:

>>> 'TestHook'.removeprefix('Test')
>>> 'BaseTestCase'.removeprefix('Test')

Get an image extension from an uploaded file in Laravel

The Laravel way

Try this:

$foo = \File::extension($filename);

CSS media queries for screen sizes

For all smartphones and large screens use this format of media query

/* Smartphones (portrait and landscape) ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */

/* Smartphones (landscape) ----------- */

@media only screen and (min-width : 321px) {
/* Styles */

/* Smartphones (portrait) ----------- */

@media only screen and (max-width : 320px) {
/* Styles */

/* iPads (portrait and landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */

/* iPads (landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */

/* iPads (portrait) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */

iPad 3

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */

/* Desktops and laptops ----------- */

@media only screen  and (min-width : 1224px) {
/* Styles */

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */

/* iPhone 4 ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */

/* iPhone 5 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */

/* iPhone 6 ----------- */

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */

/* iPhone 6+ ----------- */

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */

/* Samsung Galaxy S3 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */

/* Samsung Galaxy S5 ----------- */

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */

C/C++ NaN constant (literal)?

yes, by the concept of pointer you can do it like this for an int variable:

int *a;
int b=0;
a=NULL; // or a=&b; for giving the value of b to a

it is very simple and straitforward. it worked for me in Arduino IDE.

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I had the same issue on Windows 10 where I tried to SSH into a Vagrant box. This seems like a bug in the old OpenSSH version. What worked for me:

  1. Install the latest OpenSSH from
  2. where.exe ssh

(Note the ".exe" if you are using Powershell)

You might see something like:

C:\Program Files\OpenSSH\bin\ssh.exe

Note that in the above example the latest OpenSSH is second in the path so it won't execute.

To change the order:

  1. Right-click Windows button -> Settings -> "Edit the System Environment Variables"
  2. On the "Advance" tab click "Environment Variables..."
  3. Under System Variables edit "Path".
  4. Select "C:\Program Files\OpenSSH\bin" and "Move Up" so that it appears on the top.
  5. Click OK
  6. Restart your Console so that the new environment variables may apply.

How to implement a ViewPager with different Fragments / Layouts

As this is a very frequently asked question, I wanted to take the time and effort to explain the ViewPager with multiple Fragments and Layouts in detail. Here you go.

ViewPager with multiple Fragments and Layout files - How To

The following is a complete example of how to implement a ViewPager with different fragment Types and different layout files.

In this case, I have 3 Fragment classes, and a different layout file for each class. In order to keep things simple, the fragment-layouts only differ in their background color. Of course, any layout-file can be used for the Fragments. has a orange background layout, has a green background layout and has a red background layout. Furthermore, each Fragment displays a different text, depending on which class it is from and which instance it is.

Also be aware that I am using the support-library's Fragment: (Initializes the Viewpager and has the adapter for it as an inner class). Again have a look at the imports. I am using the package.

import android.os.Bundle;

public class MainActivity extends FragmentActivity {

    protected void onCreate(Bundle savedInstanceState) {

        ViewPager pager = (ViewPager) findViewById(;
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

    private class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {

        public Fragment getItem(int pos) {
            switch(pos) {

            case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
            case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
            case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
            case 3: return ThirdFragment.newInstance("ThirdFragment, Instance 2");
            case 4: return ThirdFragment.newInstance("ThirdFragment, Instance 3");
            default: return ThirdFragment.newInstance("ThirdFragment, Default");

        public int getCount() {
            return 5;

activity_main.xml (The MainActivitys .xml file) - a simple layout file, only containing the ViewPager that fills the whole screen.


The Fragment classes, import;

public class FirstFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.first_frag, container, false);

        TextView tv = (TextView) v.findViewById(;

        return v;

    public static FirstFragment newInstance(String text) {

        FirstFragment f = new FirstFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);


        return f;


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:background="@android:color/holo_orange_dark" >

        android:text="TextView" />

public class SecondFragment extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.second_frag, container, false);

    TextView tv = (TextView) v.findViewById(;

    return v;

public static SecondFragment newInstance(String text) {

    SecondFragment f = new SecondFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);


    return f;


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:background="@android:color/holo_green_dark" >

        android:text="TextView" />


public class ThirdFragment extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.third_frag, container, false);

    TextView tv = (TextView) v.findViewById(;      

    return v;

public static ThirdFragment newInstance(String text) {

    ThirdFragment f = new ThirdFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);


    return f;


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:background="@android:color/holo_red_light" >

        android:text="TextView" />


The end result is the following:

The Viewpager holds 5 Fragments, Fragments 1 is of type FirstFragment, and displays the first_frag.xml layout, Fragment 2 is of type SecondFragment and displays the second_frag.xml, and Fragment 3-5 are of type ThirdFragment and all display the third_frag.xml.

enter image description here

Above you can see the 5 Fragments between which can be switched via swipe to the left or right. Only one Fragment can be displayed at the same time of course.

Last but not least:

I would recommend that you use an empty constructor in each of your Fragment classes.

Instead of handing over potential parameters via constructor, use the newInstance(...) method and the Bundle for handing over parameters.

This way if detached and re-attached the object state can be stored through the arguments. Much like Bundles attached to Intents.

How to export data from Spark SQL to CSV

You can use below statement to write the contents of dataframe in CSV format df.write.csv("/data/home/csv")

If you need to write the whole dataframe into a single CSV file, then use df.coalesce(1).write.csv("/data/home/sample.csv")

For spark 1.x, you can use spark-csv to write the results into CSV files

Below scala snippet would help

import org.apache.spark.sql.hive.HiveContext
// sc - existing spark context
val sqlContext = new HiveContext(sc)
val df = sqlContext.sql("SELECT * FROM testtable")

To write the contents into a single file

import org.apache.spark.sql.hive.HiveContext
// sc - existing spark context
val sqlContext = new HiveContext(sc)
val df = sqlContext.sql("SELECT * FROM testtable")

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

With the below code you have to set PermissionLevel=External on your project properties before you deploy, and change the database to trust external code (be sure to read elsewhere about security risks and alternatives [like certificates]) by running "ALTER DATABASE database_name SET TRUSTWORTHY ON".

using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SqlServer.Server;

    public struct CommaDelimit : IBinarySerialize

 private class StringList : List<string>
 { }

 private StringList List;

 public void Init()
  this.List = new StringList();

 public void Accumulate(SqlString value)
  if (!value.IsNull)

 private void Add(string value)
  if (!this.List.Contains(value))

 public void Merge(CommaDelimit group)
  foreach (string s in group.List)

 void IBinarySerialize.Read(BinaryReader reader)
    IFormatter formatter = new BinaryFormatter();
    this.List = (StringList)formatter.Deserialize(reader.BaseStream);

 public SqlString Terminate()
  if (this.List.Count == 0)
   return SqlString.Null;

  const string Separator = ", ";


  return new SqlString(String.Join(Separator, this.List.ToArray()));

 void IBinarySerialize.Write(BinaryWriter writer)
  IFormatter formatter = new BinaryFormatter();
  formatter.Serialize(writer.BaseStream, this.List);

I've tested this using a query that looks like:

 dbo.CommaDelimit(X.value) [delimited] 
  SELECT 'D' [value] 
  UNION ALL SELECT 'B' [value] 
  UNION ALL SELECT 'B' [value] -- intentional duplicate
  UNION ALL SELECT 'A' [value] 
  UNION ALL SELECT 'C' [value] 
 ) X 

And yields: A, B, C, D

File Upload ASP.NET MVC 3.0

Simple way to save multiple files


@using (Html.BeginForm("Index","Home",FormMethod.Post,new { enctype = "multipart/form-data" }))
    <label for="file">Upload Files:</label>
    <input type="file" multiple name="files" id="files" /><br><br>
    <input type="submit" value="Upload Files" />


        public ActionResult Index(HttpPostedFileBase[] files)
            foreach (HttpPostedFileBase file in files)
                if (file != null && file.ContentLength > 0)
                        string path = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName));
                        ViewBag.Message = "File uploaded successfully";
                    catch (Exception ex)
                        ViewBag.Message = "ERROR:" + ex.Message.ToString();

                    ViewBag.Message = "You have not specified a file.";
            return View();

How to get screen width and height

Display display = getActivity().getWindowManager().getDefaultDisplay(); 
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
Log.d("Tag", "Getting Width >> " + screenWidth);
Log.d("Tag", "Getting Height >> " + screenHeight);

This worked properly in my application

Adding items in a Listbox with multiple columns

select propety

Row Source Type => Value List

Code :


ListbName.AddItem "value column1;value column2"

Does Java read integers in little endian or big endian?

Use the network byte order (big endian), which is the same as Java uses anyway. See man htons for the different translators in C.


We have just been going through this same issue, but the other way around. That is, we store dollar amounts as DECIMAL, but now we're finding that, for example, MySQL was calculating a value of 4.389999999993, but when storing this into the DECIMAL field, it was storing it as 4.38 instead of 4.39 like we wanted it to. So, though DOUBLE may cause rounding issues, it seems that DECIMAL can cause some truncating issues as well.

jQuery: Check if special characters exists in string

If you really want to check for all those special characters, it's easier to use a regular expression:

var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
    alert('Your search string contains illegal characters.');

The above will only allow strings consisting entirely of characters on the ranges a-z, A-Z, 0-9, plus the hyphen an space characters. A string containing any other character will cause the alert.

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

I had this problem while using QT 5.6, Anaconda 4.3.23, python 3.5.2 and pyinstaller 3.3. I had created a python program with an interface developed using QTcreator, but had to deploy it to other computers, therefore I needed to make an executable, using pyinstaller.

I've found that the problem was solved on my computer if I set the following environment variables:


QTDIR: C:\Miniconda3\pkgs\qt-5.6.2-vc14_3\Library

But this solution only worked on my PC that had conda and qt installed in those folders.

To solve this and make the executable work on any computer, I've had to edit the ".spec" (file first generated by pyinstaller) to include the following line:

datas=[( 'C:\Miniconda3\pkgs\qt-5.6.2-vc14_3\Library\plugins\platforms*.dll', 'platforms' ),]

This solution is based on the answers of Jim G. and CrippledTable

How to retrieve the hash for the current commit in Git?

Commit hash

git show -s --format=%H

Abbreviated commit hash

git show -s --format=%h

Click here for more git show examples.

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.


#pragma comment( lib, "yourLibrary.lib" )

Windows CMD command for accessing usb?

Try this batch :

@echo off
Title List of connected external devices by Hackoo
Mode con cols=100 lines=20 & Color 9E
wmic LOGICALDISK where driveType=2 get deviceID > wmic.txt
for /f "skip=1" %%b IN ('type wmic.txt') DO (echo %%b & pause & Dir %%b)
Del wmic.txt

How to compare 2 files fast using .NET?

Here are some utility functions that allow you to determine if two files (or two streams) contain identical data.

I have provided a "fast" version that is multi-threaded as it compares byte arrays (each buffer filled from what's been read in each file) in different threads using Tasks.

As expected, it's much faster (around 3x faster) but it consumes more CPU (because it's multi threaded) and more memory (because it needs two byte array buffers per comparison thread).

    public static bool AreFilesIdenticalFast(string path1, string path2)
        return AreFilesIdentical(path1, path2, AreStreamsIdenticalFast);

    public static bool AreFilesIdentical(string path1, string path2)
        return AreFilesIdentical(path1, path2, AreStreamsIdentical);

    public static bool AreFilesIdentical(string path1, string path2, Func<Stream, Stream, bool> areStreamsIdentical)
        if (path1 == null)
            throw new ArgumentNullException(nameof(path1));

        if (path2 == null)
            throw new ArgumentNullException(nameof(path2));

        if (areStreamsIdentical == null)
            throw new ArgumentNullException(nameof(path2));

        if (!File.Exists(path1) || !File.Exists(path2))
            return false;

        using (var thisFile = new FileStream(path1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var valueFile = new FileStream(path2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                if (valueFile.Length != thisFile.Length)
                    return false;

                if (!areStreamsIdentical(thisFile, valueFile))
                    return false;
        return true;

    public static bool AreStreamsIdenticalFast(Stream stream1, Stream stream2)
        if (stream1 == null)
            throw new ArgumentNullException(nameof(stream1));

        if (stream2 == null)
            throw new ArgumentNullException(nameof(stream2));

        const int bufsize = 80000; // 80000 is below LOH (85000)

        var tasks = new List<Task<bool>>();
            // consumes more memory (two buffers for each tasks)
            var buffer1 = new byte[bufsize];
            var buffer2 = new byte[bufsize];

            int read1 = stream1.Read(buffer1, 0, buffer1.Length);
            if (read1 == 0)
                int read3 = stream2.Read(buffer2, 0, 1);
                if (read3 != 0) // not eof
                    return false;


            // both stream read could return different counts
            int read2 = 0;
                int read3 = stream2.Read(buffer2, read2, read1 - read2);
                if (read3 == 0)
                    return false;

                read2 += read3;
            while (read2 < read1);

            // consumes more cpu
            var task = Task.Run(() =>
                return IsSame(buffer1, buffer2);
        while (true);

        return !tasks.Any(t => !t.Result);

    public static bool AreStreamsIdentical(Stream stream1, Stream stream2)
        if (stream1 == null)
            throw new ArgumentNullException(nameof(stream1));

        if (stream2 == null)
            throw new ArgumentNullException(nameof(stream2));

        const int bufsize = 80000; // 80000 is below LOH (85000)
        var buffer1 = new byte[bufsize];
        var buffer2 = new byte[bufsize];

        var tasks = new List<Task<bool>>();
            int read1 = stream1.Read(buffer1, 0, buffer1.Length);
            if (read1 == 0)
                return stream2.Read(buffer2, 0, 1) == 0; // check not eof

            // both stream read could return different counts
            int read2 = 0;
                int read3 = stream2.Read(buffer2, read2, read1 - read2);
                if (read3 == 0)
                    return false;

                read2 += read3;
            while (read2 < read1);

            if (!IsSame(buffer1, buffer2))
                return false;
        while (true);

    public static bool IsSame(byte[] bytes1, byte[] bytes2)
        if (bytes1 == null)
            throw new ArgumentNullException(nameof(bytes1));

        if (bytes2 == null)
            throw new ArgumentNullException(nameof(bytes2));

        if (bytes1.Length != bytes2.Length)
            return false;

        for (int i = 0; i < bytes1.Length; i++)
            if (bytes1[i] != bytes2[i])
                return false;
        return true;

Android background music service

i had problem to run it and i make some changes to run it with mp3 source. here is file. consider that my mp3 file is in my sdcard in my phone .

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;

    public IBinder onBind(Intent arg0) {

        return null;

    public void onCreate() {
        Log.d("service", "onCreate");
        player = new MediaPlayer();
        try {
            player.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/your file.mp3");
        } catch (IOException e) {
        player.setLooping(true); // Set looping
        player.setVolume(100, 100);


    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("service", "onStartCommand");
        try {
        } catch (IOException e) {
        return 1;

    public void onStart(Intent intent, int startId) {
        // TO DO

    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;

    public void onStop() {


    public void onPause() {


    public void onDestroy() {

    public void onLowMemory() {

} cannot open shared object file

I had the same problem, and it turned out I hadn't installed the library.

this link was super usefull.

How can I list all tags for a Docker image on a remote registry?

I've managed to get it working using curl:

curl -u <username>:<password> https://myrepo.example/v1/repositories/<username>/<image_name>/tags

Note that image_name should not contain user details etc. For example if you're pushing image named myrepo.example/username/x then image_name should be x.

how to use python2.7 pip instead of default pip

as noted here, this is what worked best for me:

sudo apt-get install python3 python3-pip python3-setuptools

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

Why am I getting Unknown error in line 1 of pom.xml?

same problem for me, original code from spring starter demo gives unknown error on line 1:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""
    <relativePath/> <!-- lookup parent from repository -->

Changing just the version of 2.1.6.RELEASE to 2.1.4.RELEASE fixes the problem.

Change tab bar item selected color in a storyboard

In Swift, using xcode 7 (and later), you can add the following to your AppDelegate.swift file:

UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)

This is the what the complete method looks like:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    // I added this line
    UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)

    return true

In the example above my item will be white. The "/255.0" is needed because it expects a value from 0 to 1. For white, I could have just used 1. But for other color you'll probably be using RGB values.

Pandas: Return Hour from Datetime Column Directly

Now we can use:

sales['time_hour'] = sales['timestamp'].apply(lambda x: x.hour)

Scroll to bottom of div with Vue.js

In the related question you posted, we already have a way to achieve that in plain javascript, so we only need to get the js reference to the dom node we want to scroll.

The ref attribute can be used to declare reference to html elements to make them available in vue's component methods.

Or, if the method in the component is a handler for some UI event, and the target is related to the div you want to scroll in space, you can simply pass in the event object along with your wanted arguments, and do the scroll like scroll(

Copy Data from a table in one Database to another separate database

Try this

INSERT INTO dbo.DB1.TempTable

This will only fail if an item in dbo.DB2.TempTable is in already in dbo.DB1.TempTable.

Equivalent to 'app.config' for a library (DLL)

use from configurations must be very very easy like this :

var config = new MiniConfig("setting.conf");

config.AddOrUpdate("port", "1580");

if (config.TryGet("port", out int port)) // if config exist

for more details see MiniConfig

Python: fastest way to create a list of n lists

Here are two methods, one sweet and simple(and conceptual), the other more formal and can be extended in a variety of situations, after having read a dataset.

Method 1: Conceptual

X2 thus has [[1,2,3],[4,5,6]] ie a list of lists. 

Method 2 : Formal and extensible

Another elegant way to store a list as a list of lists of different numbers - which it reads from a file. (The file here has the dataset train) Train is a data-set with say 50 rows and 20 columns. ie. Train[0] gives me the 1st row of a csv file, train[1] gives me the 2nd row and so on. I am interested in separating the dataset with 50 rows as one list, except the column 0 , which is my explained variable here, so must be removed from the orignal train dataset, and then scaling up list after list- ie a list of a list. Here's the code that does that.

Note that I am reading from "1" in the inner loop since I am interested in explanatory variables only. And I re-initialize X1=[] in the other loop, else the X2.append([0:(len(train[0])-1)]) will rewrite X1 over and over again - besides it more memory efficient.

for j in range(0,len(train)):
    for k in range(1,len(train[0])):

Segmentation fault on large array sizes

You array is being allocated on the stack in this case attempt to allocate an array of the same size using alloc.

Matplotlib scatter plot with different text at each data point

In case anyone is trying to apply the above solutions to a .scatter() instead of a .subplot(),

I tried running the following code

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.scatter(z, y)

for i, txt in enumerate(n):
    ax.annotate(txt, (z[i], y[i]))

But ran into errors stating "cannot unpack non-iterable PathCollection object", with the error specifically pointing at codeline fig, ax = plt.scatter(z, y)

I eventually solved the error using the following code

plt.scatter(z, y)

for i, txt in enumerate(n):
    plt.annotate(txt, (z[i], y[i]))

I didn't expect there to be a difference between .scatter() and .subplot() I should have known better.

symfony2 : failed to write cache directory

If the folder is already writable so thats not the problem.

You can also just navigate to /www/projet_etienne/app/cache/ and manualy remove the folders in there (dev, dev_new, dev_old).

Make sure to SAVE a copy of those folder somewhere to put back if this doesn't fix the problem

I know this is not the way it should be done but it worked for me a couple of times now.

Atom menu is missing. How do I re-enable

Same happened to me, I had to go into Packages and re-enable Tabs and Tree-View (both part of core).

How to call a parent class function from derived class function?

In MSVC there is a Microsoft specific keyword for that: __super

MSDN: Allows you to explicitly state that you are calling a base-class implementation for a function that you are overriding.

// deriv_super.cpp
// compile with: /c
struct B1 {
   void mf(int) {}

struct B2 {
   void mf(short) {}

   void mf(char) {}

struct D : B1, B2 {
   void mf(short) {
      __super::mf(1);   // Calls B1::mf(int)
      __super::mf('s');   // Calls B2::mf(char)

Unfinished Stubbing Detected in Mockito

You're nesting mocking inside of mocking. You're calling getSomeList(), which does some mocking, before you've finished the mocking for MyMainModel. Mockito doesn't like it when you do this.


public myTest(){
    MyMainModel mainModel =  Mockito.mock(MyMainModel.class);
    Mockito.when(mainModel.getList()).thenReturn(getSomeList()); --> Line 355


public myTest(){
    MyMainModel mainModel =  Mockito.mock(MyMainModel.class);
    List<SomeModel> someModelList = getSomeList();

To understand why this causes a problem, you need to know a little about how Mockito works, and also be aware in what order expressions and statements are evaluated in Java.

Mockito can't read your source code, so in order to figure out what you are asking it to do, it relies a lot on static state. When you call a method on a mock object, Mockito records the details of the call in an internal list of invocations. The when method reads the last of these invocations off the list and records this invocation in the OngoingStubbing object it returns.

The line


causes the following interactions with Mockito:

  • Mock method mainModel.getList() is called,
  • Static method when is called,
  • Method thenReturn is called on the OngoingStubbing object returned by the when method.

The thenReturn method can then instruct the mock it received via the OngoingStubbing method to handle any suitable call to the getList method to return someModelList.

In fact, as Mockito can't see your code, you can also write your mocking as follows:


This style is somewhat less clear to read, especially since in this case the null has to be casted, but it generates the same sequence of interactions with Mockito and will achieve the same result as the line above.

However, the line


causes the following interactions with Mockito:

  1. Mock method mainModel.getList() is called,
  2. Static method when is called,
  3. A new mock of SomeModel is created (inside getSomeList()),
  4. Mock method model.getName() is called,

At this point Mockito gets confused. It thought you were mocking mainModel.getList(), but now you're telling it you want to mock the model.getName() method. To Mockito, it looks like you're doing the following:

// ...

This looks silly to Mockito as it can't be sure what you're doing with mainModel.getList().

Note that we did not get to the thenReturn method call, as the JVM needs to evaluate the parameters to this method before it can call the method. In this case, this means calling the getSomeList() method.

Generally it is a bad design decision to rely on static state, as Mockito does, because it can lead to cases where the Principle of Least Astonishment is violated. However, Mockito's design does make for clear and expressive mocking, even if it leads to astonishment sometimes.

Finally, recent versions of Mockito add an extra line to the error message above. This extra line indicates you may be in the same situation as this question:

3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

How to set array length in c# dynamically

You could use List inside the method and transform it to an array at the end. But i think if we talk about an max-value of 20, your code is faster.

    private Update BuildMetaData(MetaData[] nvPairs)
        Update update = new Update();
        List<InputProperty> ip = new List<InputProperty>();
        for (int i = 0; i < nvPairs.Length; i++)
            if (nvPairs[i] == null) break;
            ip[i] = new InputProperty();
            ip[i].Name = "udf:" + nvPairs[i].Name;
            ip[i].Val = nvPairs[i].Value;
        update.Items = ip.ToArray();
        return update;

JavaScript: undefined !== undefined?

A). I never have and never will trust any tool which purports to produce code without the user coding, which goes double where it's a graphical tool.

B). I've never had any problem with this with Facebook Connect. It's all still plain old JavaScript code running in a browser and undefined===undefined wherever you are.

In short, you need to provide evidence that your object.x really really was undefined and not null or otherwise, because I believe it is impossible for what you're describing to actually be the case - no offence :) - I'd put money on the problem existing in the Tersus code.

Must issue a STARTTLS command first

    String username = "[email protected]";
    String password = "some-password";
    String recipient = "[email protected]");

    Properties props = new Properties();

    props.put("", "");
    props.put("mail.from", "[email protected]");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.port", "587");
    props.setProperty("mail.debug", "true");

    Session session = Session.getInstance(props, null);
    MimeMessage msg = new MimeMessage(session);

    msg.setRecipients(Message.RecipientType.TO, recipient);
    msg.setSubject("JavaMail hello world example");
    msg.setSentDate(new Date());
    msg.setText("Hello, world!\n");

    Transport transport = session.getTransport("smtp");

    transport.connect(username, password);
    transport.sendMessage(msg, msg.getAllRecipients());

How to change background color of cell in table using java script

document.getElementById('id1').bgColor = '#00FF00';

seems to work. I don't think .style.backgroundColor does.

Delete duplicate records from a SQL table without a primary key

Add a Primary Key (code below)

Run the correct delete (code below)

Consider WHY you woudln't want to keep that primary key.

Assuming MSSQL or compatible:

ALTER TABLE Employee ADD EmployeeID int identity(1,1) PRIMARY KEY;

    DELETE FROM Employee WHERE EmployeeID IN 
        SELECT MIN(EmployeeID) as [DeleteID]
        FROM Employee
        GROUP BY EmpID, EmpSSN
        HAVING COUNT(*) > 1

HTML table needs spacing between columns, not rows

<table cellpadding="pixels"cellspacing="pixels"></table>
<td align="position"valign="position"></td>

cellpadding="length in pixels" ~ The cellpadding attribute, used in the <table> tag, specifies how much blank space to display in between the content of each table cell and its respective border. The value is defined as a length in pixels. Hence, a cellpadding="10" attribute-value pair will display 10 pixels of blank space on all four sides of the content of each cell in that table.

cellspacing="length in pixels" ~ The cellspacing attribute, also used in the <table> tag, defines how much blank space to display in between adjacent table cells and in between table cells and the table border. The value is defined as a length in pixels. Hence, a cellspacing="10" attribute-value pair will horizontally and vertically separate all adjacent cells in the respective table by a length of 10 pixels. It will also offset all cells from the table's frame on all four sides by a length of 10 pixels.

How can I insert data into a MySQL database?

#Server Connection to MySQL:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
x = conn.cursor()

   x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))


edit working for me:

>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>> #setup cursor
... cursor = db.cursor()
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
>>> sql = """CREATE TABLE anooog1 (
...          COL1 INT,  
...          COL2 INT )"""
>>> cursor.execute(sql)
>>> #insert to table
... try:
...     cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
...     db.commit()
... except:     
...     db.rollback()
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
>>> print cursor.fetchall()
((188L, 90L),)
>>> db.close()

table in mysql;

mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SELECT * FROM anooog1;
| COL1 | COL2 |
|  188 |   90 |
1 row in set (0.00 sec)


How do you perform a left outer join using linq extension methods

Improving on Ocelot20's answer, if you have a table you're left outer joining with where you just want 0 or 1 rows out of it, but it could have multiple, you need to Order your joined table:

var qry = Foos.GroupJoin(
      Bars.OrderByDescending(b => b.Id),
      foo => foo.Foo_Id,
      bar => bar.Foo_Id,
      (f, bs) => new { Foo = f, Bar = bs.FirstOrDefault() });

Otherwise which row you get in the join is going to be random (or more specifically, whichever the db happens to find first).

Max length for client ip address

Take it from someone who has tried it all three ways... just use a varchar(39)

The slightly less efficient storage far outweighs any benefit of having to convert it on insert/update and format it when showing it anywhere.

URL Encoding using C#

Ideally these would go in a class called "FileNaming" or maybe just rename Encode to "FileNameEncode". Note: these are not designed to handle Full Paths, just the folder and/or file names. Ideally you would Split("/") your full path first and then check the pieces. And obviously instead of a union, you could just add the "%" character to the list of chars not allowed in Windows, but I think it's more helpful/readable/factual this way. Decode() is exactly the same but switches the Replace(Uri.HexEscape(s[0]), s) "escaped" with the character.

public static List<string> urlEncodedCharacters = new List<string>
  "/", "\\", "<", ">", ":", "\"", "|", "?", "%" //and others, but not *
//Since this is a superset of urlEncodedCharacters, we won't be able to only use UrlEncode() - instead we'll use HexEncode
public static List<string> specialCharactersNotAllowedInWindows = new List<string>
  "/", "\\", "<", ">", ":", "\"", "|", "?", "*" //windows dissallowed character set

    public static string Encode(string fileName)
        //CheckForFullPath(fileName); // optional: make sure it's not a path?
        List<string> charactersToChange = new List<string>(specialCharactersNotAllowedInWindows);
            Where(x => !urlEncodedCharacters.Union(specialCharactersNotAllowedInWindows).Contains(x)));   // add any non duplicates (%)

        charactersToChange.ForEach(s => fileName = fileName.Replace(s, Uri.HexEscape(s[0])));   // "?" => "%3f"

        return fileName;

Thanks @simon-tewsi for the very usefull table above!

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

As suggested in an earlier answer, we need to include two additional files - jquery.fileupload-process.js and then jquery.fileupload-validate.js However as I need to perform some additional ajax calls while adding a file, I am subscribing to the fileuploadadd event to perform those calls. Regarding such a usage the author of this plugin suggested the following

Please have a look here:

Adding additional event listeners via bind (or on method with jQuery 1.7+) method is the preferred option to preserve callback settings by the jQuery File Upload UI version.

Alternatively, you can also simply start the processing in your own callback, like this:

Using the combination of the two suggested options, the following code works perfectly for me

    url: 'upload_url',
    type: 'POST',
    dataType: 'json',
    autoUpload: false,
    disableValidation: false,
    maxFileSize: 1024 * 1024,
    messages: {
        maxFileSize: 'File exceeds maximum allowed size of 1MB',

$fileInput.on('fileuploadadd', function(evt, data) {
    var $this = $(this);
    var validation = data.process(function () {
        return $this.fileupload('process', data);

    validation.done(function() {
        makeAjaxCall('some_other_url', { fileName: data.files[0].name, fileSizeInBytes: data.files[0].size })
            .done(function(resp) {
                data.formData = data.formData || {};
                data.formData.someData = resp.SomeData;
    }); {
        console.log('Upload error: ' + data.files[0].error);

<embed> vs. <object>

Probably the best cross browser solution for pdf display on web pages is to use the Mozilla PDF.js project code, it can be run as a node.js service and used as follows

<iframe style="width:100%;height:500px" src="""></iframe>

A tutorial on how to use pdf.js can be found at this ejectamenta blog article

Change UITextField and UITextView Cursor / Caret Color

I think If you want some custom colors you can go to Assets.xcassets folder, right click and select New Color Set, once you created you color you set, give it a name to reuse it.

And you can use it just like this :

import UIKit 

class ViewController: UIViewController {
    override func viewDidLoad() {
        UITextField.appearance().tintColor = UIColor(named: "YOUR-COLOR-NAME")  #here

Tested on macOS 10.15 / iOS 13 / Swift 5

__proto__ VS. prototype in JavaScript


The __proto__ property of an object is a property that maps to the prototype of the constructor function of the object. In other words:

instance.__proto__ === constructor.prototype // true

This is used to form the prototype chain of an object. The prototype chain is a lookup mechanism for properties on an object. If an object's property is accessed, JavaScript will first look on the object itself. If the property isn't found there, it will climb all the way up to protochain until it is found (or not)


function Person (name, city) {_x000D_ = name;_x000D_
Person.prototype.age = 25;_x000D_
const willem = new Person('Willem');_x000D_
console.log(willem.__proto__ === Person.prototype); // the __proto__ property on the instance refers to the prototype of the constructor_x000D_
console.log(willem.age); // 25 doesn't find it at willem object but is present at prototype_x000D_
console.log(willem.__proto__.age); // now we are directly accessing the prototype of the Person function 

Our first log results to true, this is because as mentioned the __proto__ property of the instance created by the constructor refers to the prototype property of the constructor. Remember, in JavaScript, functions are also Objects. Objects can have properties, and a default property of any function is one property named prototype.

Then, when this function is utilized as a constructor function, the object instantiated from it will receive a property called __proto__. And this __proto__ property refers to the prototype property of the constructor function (which by default every function has).

Why is this useful?

JavaScript has a mechanism when looking up properties on Objects which is called 'prototypal inheritance', here is what it basically does:

  • First, it's checked if the property is located on the Object itself. If so, this property is returned.
  • If the property is not located on the object itself, it will 'climb up the protochain'. It basically looks at the object referred to by the __proto__ property. There, it checks if the property is available on the object referred to by __proto__.
  • If the property isn't located on the __proto__ object, it will climb up the __proto__ chain, all the way up to Object object.
  • If it cannot find the property anywhere on the object and its prototype chain, it will return undefined.

For example:

function Person (name) {_x000D_ = name;_x000D_
let mySelf = new Person('Willem');_x000D_
console.log(mySelf.__proto__ === Person.prototype);_x000D_
console.log(mySelf.__proto__.__proto__ === Object.prototype);

Regex to extract URLs from href attribute in HTML with Python

import re

url = '<p>Hello World</p><a href="">More Examples</a><a href="">Even More Examples</a>'

urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)

>>> print urls
['', '']

Parse JSON from HttpURLConnection object

You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestProperty("Content-length", "0");
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                return sb.toString();

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    return null;

And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);

There is a sample of AuthMsg class:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    public void setCode(int code) {
        this.code = code;

    public String getMessage() {
        return message;
    public void setMessage(String message) {
        this.message = message;

JSON returned by http://localhost/authmanager.php must look like this:

{"code":1,"message":"Logged in"}


How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

If your're looking to set the current datetime for a dateTime column (like i was when I googled), use this way


css width: calc(100% -100px); alternative using jquery

Try jQuery animate() method, ex.


Multi-gradient shapes

You can layer gradient shapes in the xml using a layer-list. Imagine a button with the default state as below, where the second item is semi-transparent. It adds a sort of vignetting. (Please excuse the custom-defined colours.)

<!-- Normal state. -->
                    android:centerColor="@color/grey_mediumtodark" />
                    android:color="@color/grey_dark" />
                    android:radius="5dp" />
                    android:centerY="0" />
                    android:color="@color/grey_dark" />
                    android:radius="5dp" />

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

How to check if a Ruby object is a Boolean

I find this to be concise and self-documenting:

[true, false].include? foo

If using Rails or ActiveSupport, you can even do a direct query using in? [true, false]

Checking against all possible values isn't something I'd recommend for floats, but feasible when there are only two possible values!

Chrome / Safari not filling 100% height of flex parent

Solution: Remove height: 100% in .item-inner and add display: flex in .item


Loop in react-native

You can create render the results (payments) and use a fancy way to iterate over items instead of adding a for loop.

const noGuest = 3;_x000D_
Array(noGuest).fill(noGuest).map(guest => {_x000D_


renderPayments(noGuest) {
  return Array(noGuest).fill(noGuest).map((guess, index) => {
      <View key={index}>
        <View><TextInput /></View>
        <View><TextInput /></View>
        <View><TextInput /></View>

Then use it where you want it

render() {
     const { guest } = this.state;

Hope you got the idea.

If you want to understand this in simple Javascript check Array.prototype.fill()

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

Apply these changes in phpmyconfig/ Type in your username and password that you have set:

$cfg['Servers'][$i]['user']                 = 'user';
$cfg['Servers'][$i]['password']             = 'password';
$cfg['Servers'][$i]['AllowNoPassword']      = false;

This works for me.

How to log out user from web site using BASIC authentication?

This is working for IE/Netscape/Chrome :

      function ClearAuthentication(LogOffPage) 
     var IsInternetExplorer = false;    

         var agt=navigator.userAgent.toLowerCase();
         if (agt.indexOf("msie") != -1) { IsInternetExplorer = true; }
         IsInternetExplorer = false;    

     if (IsInternetExplorer) 
        // Logoff Internet Explorer
        window.location = LogOffPage;
        // Logoff every other browsers
         username: 'unknown',
         password: 'WrongPassword',
             url: './cgi-bin/PrimoCgi',
         type: 'GET',
         beforeSend: function(xhr)
            xhr.setRequestHeader("Authorization", "Basic AAAAAAAAAAAAAAAAAAA=");

                 error: function(err)
                    window.location = LogOffPage;

  $(document).ready(function () 
      $('#Btn1').click(function () 
         // Call Clear Authentication 

python ValueError: invalid literal for float()

Watch out for possible unintended literals in your argument

for example you can have a space within your argument, rendering it to a string / literal:

float(' 0.33')

After making sure the unintended space did not make it into the argument, I was left with:


Like this it works like a charm.

Take away is: Pay Attention for unintended literals (e.g. spaces that you didn't see) within your input.

Delete files older than 15 days using PowerShell

Another alternative (15. gets typed to [timespan] automatically):

ls -file | where { (get-date) - $_.creationtime -gt 15. } | Remove-Item -Verbose

JavaScript variable assignments from tuples

I made a tuple implementation that works quite well. This solution allows for array destructuring, as well as basic type-cheking.

const Tuple = (function() {
    function Tuple() {
        // Tuple needs at least one element
        if (arguments.length < 1) {
            throw new Error('Tuple needs at least one element');

        const args = { ...arguments };

        // Define a length property (equal to the number of arguments provided)
        Object.defineProperty(this, 'length', {
            value: arguments.length,
            writable: false

        // Assign values to enumerable properties
        for (let i in args) {
            Object.defineProperty(this, i, {
                enumerable: true,
                get() {
                    return args[+i];
                // Checking if the type of the provided value matches that of the existing value
                set(value) {
                    if (typeof value !== typeof args[+i]) {
                        throw new Error('Cannot assign ' + typeof value + ' on ' + typeof args[+i]);

                    args[+i] = value;

        // Implementing iteration with Symbol.iterator (allows for array destructuring as well for...of loops)
        this[Symbol.iterator] = function() {
            const tuple = this;

            return {
                current: 0,
                last: tuple.length - 1,
                next() {
                    if (this.current <= this.last) {
                        let val = { done: false, value: tuple[this.current] };
                        return val;
                    } else {
                        return { done: true };

        // Sealing the object to make sure no more values can be added to tuple

    // check if provided object is a tuple
    Tuple.isTuple = function(obj) {
        return obj instanceof Tuple;

    // Misc. for making the tuple more readable when printing to the console
    Tuple.prototype.toString = function() {
        const copyThis = { ...this };
        const values = Object.values(copyThis);
        return `(${values.join(', ')})`;

    // conctat two instances of Tuple
    Tuple.concat = function(obj1, obj2) {
        if (!Tuple.isTuple(obj1) || !Tuple.isTuple(obj2)) {
            throw new Error('Cannot concat Tuple with ' + typeof (obj1 || obj2));

        const obj1Copy = { ...obj1 };
        const obj2Copy = { ...obj2 };

        const obj1Items = Object.values(obj1Copy);
        const obj2Items = Object.values(obj2Copy);

        return new Tuple(...obj1Items, ...obj2Items);

    return Tuple;

const SNAKE_COLOR = new Tuple(0, 220, 10);

const [red, green, blue] = SNAKE_COLOR;
console.log(green); // => 220

How do I finish the merge after resolving my merge conflicts?

A merge conflict occurs when two branches you're trying to merge both changed the same part of the same file. You can generate a list of conflicts with git status.

When the conflicted line is encountered, Git will edit the content of the affected files with visual indicators that mark both sides of the conflicting content.

<<<<<<< HEAD
conflicted text from HEAD
conflicted text from merging_branch
>>>>>>> merging_branch

When you fix your conflicted files and you are ready to merge, all you have to do is run git add and git commit to generate the merge commit. Once the commit was made ,git push the changes to the branch.

Reference article: Git merge.

How to get the filename without the extension from a path in Python?

In python 3 pathlib "The pathlib module offers high-level path objects." so,

>>> from pathlib import Path
>>> p = Path("/a/b/c.txt")
>>> print(p.with_suffix(''))
>>> print(p.stem)

How to unlock android phone through ADB

If you have USB-Debugging/ADB enabled on your phone and your PC is authorized for debugging on your phone then you can try one of the follwing tools:


scrcpy connects over adb to your device and executes a temporary app to stream the contents of your screen to your PC and you're able to remote control your device. It works on GNU/Linux, Windows and macOS.


Vysor is a chrome web app that connects to your device via adb and installs a companion app to stream your screen content to the PC. You can then remote control your device with your mouse.


MonkeyRemote is a remote control tool written by myself before I found Vysor. It also connects through adb and lets you control your device by mouse but in contrast to Vysor, the streamed screen content updates very slow (~1 frame per second). The upside is that there is no need for a companion app to be installed.

OAuth 2.0 Authorization Header

You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.

It's documented in this spec:


   GET /resource HTTP/1.1
   Authorization: Bearer mF_9.B5f-4.1JqM

Where mF_9.B5f-4.1JqM is your OAuth access token.

Output (echo/print) everything from a PHP Array

You can use print_r to get human-readable output.


Max size of an iOS application

With the release of iOS 7 (September 18th, 2013) apple increased the over-the-air cellular download limit to 100MBs.

Maximum app size remains 2GBs.


What GRANT USAGE ON SCHEMA exactly do?

For a production system, you can use this configuration :


GRANT  USAGE   ON SCHEMA public  TO user;

GRANT SELECT                         ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT ALL                            ON ALL TABLES IN SCHEMA public TO admin ;

Fatal error: unexpectedly found nil while unwrapping an Optional values

I was having this issue as well and the problem was in the view controllers. I'm not sure how your application is structured, so I'll just explain what I found. I'm pretty new to xcode and coding, so bear with me.

I was trying to programmatically change the text on a UILabel. Using "self.mylabel.text" worked fine until I added another view controller under the same class that didn't also include that label. That is when I got the error that you're seeing. When I added the same UILabel and connected it into that additional view controller, the error went away.

In short, it seems that in Swift, all view controllers assigned to the same class have to reference the code you have in there, or else you get an error. If you have two different view controllers with different code, assign them to different classes. This worked for me and hopefully applies to what you're doing.

gdb: "No symbol table is loaded"

You have to add extra parameter -g, which generates source level debug information. It will look like:

gcc -g prog.c

After that you can use gdb in common way.

EditorFor() and html properties

Because the question is for EditorFor not TextBoxFor WEFX's suggestion doesn't work.

For changing individual input boxes, you can process the output of the EditorFor method:

<%: new HtmlString(Html.EditorFor(m=>m.propertyname).ToString().Replace("class=\"text-box single-line\"", "class=\"text-box single-line my500pxWideClass\"")) %>

It is also possible to change ALL your EditorFors as it turns out MVC sets the class of EditorFor text boxes with .text-box, therefore you can just override this style, in your stylesheet or on the page.

.text-box {
    width: 80em;

Additionally, you could set the style for

input[type="text"] {
    width: 200px;
  • this overrides .text-box and will change all input text boxes, EditorFor or otherwise.

fastest way to export blobs from table into individual files

For me what worked by combining all the posts I have read is:

1.Enable OLE automation - if not enabled

sp_configure 'show advanced options', 1;  
sp_configure 'Ole Automation Procedures', 1;  

2.Create a folder where the generated files will be stored:


3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
enter image description here

CREATE TABLE [dbo].[Document](
    [Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [Extension] [varchar](50) NULL,
    [FileName] [varchar](200) NULL,
    [Doc_Content] [varbinary](max) NULL   

INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
    SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)

Important note!

Don't forget to add in Doc_Content column the varbinary of file you want to generate!

4.Run the below script

DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max) 
, @fPath varchar(max)  
, @folderPath  varchar(max)

--Get Data into temp Table variable so that we can iterate over it 
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num]  varchar(100) , [FileName]  varchar(100), [Doc_Content] varBinary(max) )

INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM  [dbo].[Document]

SELECT @i = COUNT(1) FROM @Doctable   

WHILE @i >= 1   


    @data = [Doc_Content],
    @fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
    @folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;  
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+  @fPath   

--Reset the variables for next use
SELECT @data = NULL  
, @init = NULL
, @fPath = NULL  
, @folderPath = NULL
SET @i -= 1

5.The results is shown below: enter image description here

Android Studio how to run gradle sync manually?

Shortcut (Ubuntu, Windows):

Ctrl + F5

Will sync the project with Gradle files.

What's the difference between utf8_general_ci and utf8_unicode_ci?

This post describes it very nicely.

In short: utf8_unicode_ci uses the Unicode Collation Algorithm as defined in the Unicode standards, whereas utf8_general_ci is a more simple sort order which results in "less accurate" sorting results.

Call a function on click event in Angular 2

This worked for me: :)

<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
  alert('PlanId:' + planId + '    ParticipantId:' + participantId);

How to show/hide if variable is null

<div ng-hide="myvar == null"></div>


<div ng-show="myvar != null"></div>

conflicting types error when compiling c program using gcc

To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.

A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.

Include of non-modular header inside framework module

I had this problem when I added Swift source code to an existing ObjC static framework (dynamic framework with Mach-O type "Static Library").

The fix was setting CLANG_ENABLE_MODULES ("Enable Modules" in build settings) to YES

JavaScript displaying a float to 2 decimal places

let a = 0.0500


How to set Sqlite3 to be case insensitive when string comparing?

you can use the like query for comparing the respective string with table vales.

select column name from table_name where column name like 'respective comparing value';

What are the differences between a HashMap and a Hashtable in Java?

Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtables methods are synchronised. So in your case as you are not multi-threading, HashMaps are your best bet.

What is the difference between "expose" and "publish" in Docker?

Short answer:

  • EXPOSE is a way of documenting
  • --publish (or -p) is a way of mapping a host port to a running container port

Notice below that:

  • EXPOSE is related to Dockerfiles ( documenting )
  • --publish is related to docker run ... ( execution / run-time )

Exposing and publishing ports

In Docker networking, there are two different mechanisms that directly involve network ports: exposing and publishing ports. This applies to the default bridge network and user-defined bridge networks.

  • You expose ports using the EXPOSE keyword in the Dockerfile or the --expose flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional.

  • You publish ports using the --publish or --publish-all flag to docker run. This tells Docker which ports to open on the container’s network interface. When a port is published, it is mapped to an available high-order port (higher than 30000) on the host machine, unless you specify the port to map to on the host machine at runtime. You cannot specify the port to map to on the host machine when you build the image (in the Dockerfile), because there is no way to guarantee that the port will be available on the host machine where you run the image.

from: Docker container networking

Update October 2019: the above piece of text is no longer in the docs but an archived version is here:

Maybe the current documentation is the below:

Published ports

By default, when you create a container, it does not publish any of its ports to the outside world. To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the --publish or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host.

and can be found here:



...The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published.

from: Dockerfile reference

Service access when EXPOSE / --publish are not defined:

At @Golo Roden's answer it is stated that::

"If you do not specify any of those, the service in the container will not be accessible from anywhere except from inside the container itself."

Maybe that was the case at the time the answer was being written, but now it seems that even if you do not use EXPOSE or --publish, the host and other containers of the same network will be able to access a service you may start inside that container.

How to test this:

I've used the following Dockerfile. Basically, I start with ubuntu and install a tiny web-server:

FROM ubuntu
RUN apt-get update && apt-get install -y mini-httpd

I build the image as "testexpose" and run a new container with:

docker run --rm -it testexpose bash

Inside the container, I launch a few instances of mini-httpd:

root@fb8f7dd1322d:/# mini_httpd -p 80
root@fb8f7dd1322d:/# mini_httpd -p 8080
root@fb8f7dd1322d:/# mini_httpd -p 8090

I am then able to use curl from the host or other containers to fetch the home page of mini-httpd.

Further reading

Very detailed articles on the subject by Ivan Pepelnjak:

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?


The one-to-many table relationship looks as follows:


In a relational database system, a one-to-many table relationship links two tables based on a Foreign Key column in the child which references the Primary Key of the parent table row.

In the table diagram above, the post_id column in the post_comment table has a Foreign Key relationship with the post table id Primary Key column:



The one-to-one table relationship looks as follows:


In a relational database system, a one-to-one table relationship links two tables based on a Primary Key column in the child which is also a Foreign Key referencing the Primary Key of the parent table row.

Therefore, we can say that the child table shares the Primary Key with the parent table.

In the table diagram above, the id column in the post_details table has also a Foreign Key relationship with the post table id Primary Key column:



The many-to-many table relationship looks as follows:


In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key columns referencing the Primary Key columns of the two parent tables.

In the table diagram above, the post_id column in the post_tag table has also a Foreign Key relationship with the post table id Primary Key column:


And, the tag_id column in the post_tag table has a Foreign Key relationship with the tag table id Primary Key column:


Getting distance between two points based on latitude/longitude

Update: 04/2018: Note that Vincenty distance is deprecated since GeoPy version 1.13 - you should use geopy.distance.distance() instead!

The answers above are based on the Haversine formula, which assumes the earth is a sphere, which results in errors of up to about 0.5% (according to help(geopy.distance)). Vincenty distance uses more accurate ellipsoidal models such as WGS-84, and is implemented in geopy. For example,

import geopy.distance

coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)

print geopy.distance.vincenty(coords_1, coords_2).km

will print the distance of 279.352901604 kilometers using the default ellipsoid WGS-84. (You can also choose .miles or one of several other distance units).

vertical divider between two columns in bootstrap

Use this, 100% guaranteed:-

vr {
  margin-left: 20px;
  margin-right: 20px;
  height: 50px;
  border: 0;
  border-left: 1px solid #cccccc;
  display: inline-block;
  vertical-align: bottom;

Call apply-like function on each row of dataframe with multiple arguments from each row

data.table has a really intuitive way of doing this as well:


sample_fxn = function(x,y,z){

df = data.table(A = 1:5,B=seq(2,10,2),C = 6:10)
> df
   A  B  C
1: 1  2  6
2: 2  4  7
3: 3  6  8
4: 4  8  9
5: 5 10 10

The := operator can be called within brackets to add a new column using a function

df[,new_column := sample_fxn(A,B,C)]
> df
   A  B  C new_column
1: 1  2  6         18
2: 2  4  7         42
3: 3  6  8         72
4: 4  8  9        108
5: 5 10 10        150

It's also easy to accept constants as arguments as well using this method:

df[,new_column2 := sample_fxn(A,B,2)]

> df
   A  B  C new_column new_column2
1: 1  2  6         18           6
2: 2  4  7         42          12
3: 3  6  8         72          18
4: 4  8  9        108          24
5: 5 10 10        150          30

Programmatically trigger "select file" dialog box

Most answers here are lacking a useful information:

Yes, you can programmatically click the input element using jQuery/JavaScript, but only if you do it in an event handler belonging to an event THAT WAS STARTED BY THE USER!

So, for example, nothing will happen if you, the script, programmatically click the button in an ajax callback, but if you put the same line of code in an event handler that was raised by the user, it will work.

P.S. The debugger; keyword disrupts the browse window if it is before the programmatical click least in chrome 33...

Given two directory trees, how can I find out which files differ by content?

To find diff use this command:

diff -qr dir1/ dir2/

-r will diff all subdirectories too -q tells diff to report only when files differ.

diff  --brief dir1/ dir2/

--brief will show the files that dosent exist in directory.

Or else

we can use Meld which will show in graphical window its easy to find the difference.

meld  dir1/ dir2/

How to find the statistical mode?

This works pretty fine

> a<-c(1,1,2,2,3,3,4,4,5)
> names(table(a))[table(a)==max(table(a))]

Get full path of the files in PowerShell

If relative paths are what you want you can just use the -Name flag.

Get-ChildItem "C:\windows\System32" -Recurse -Filter *.txt -Name

Run all SQL files in a directory

@echo off
cd C:\Program Files (x86)\MySQL\MySQL Workbench 6.0 CE

for %%a in (D:\abc\*.sql) do (
echo %%a
mysql --host=ip --port=3306 --user=uid--password=ped < %%a

Step1: above lines copy into note pad save it as bat.

step2: In d drive abc folder in all Sql files in queries executed in sql server.

step3: Give your ip, user id and password.

Responsive width Facebook Page Plugin

Facebook's new "Page Plugin" width ranges from 180px to 500px as per the documentation.

  • If configured below 180px it would enforce a minimum width of 180px
  • If configured above 500px it would enforce a maximum width of 500px

With Adaptive Width checked, ex:

enter image description here

Unlike like-box, this plugin enforces its limits by sticking to the boundary values if mis-configured.

For small screens / Responsive behaviors

  • When rendering on smaller screens, enforce desiered width on the plugin container and plugin would try to fit in.

  • The plugin renders at a smaller width (to fit in smaller screens) automatically, if the container is of slimmer than the configured width.

  • You can scale down the container on mobile and the plugin will fit in as long as it gets the minimum of 180px to fit in.

Without Adaptive Width

enter image description here

  • The plugin will render at the width specified, irrespective of the container width

Javascript get object key name

An ES6 update... though both filter and map might need customization.

Object.entries(theObj) returns a [[key, value],] array representation of an object that can be worked on using Javascript's array methods, .each(), .any(), .forEach(), .filter(), .map(), .reduce(), etc.

Saves a ton of work on iterating over parts of an object Object.keys(theObj), or Object.values() separately.

const buttons = {_x000D_
    button1: {_x000D_
        text: 'Close',_x000D_
        onclick: function(){_x000D_
    button2: {_x000D_
        text: 'OK',_x000D_
        onclick: function(){_x000D_
    button3: {_x000D_
        text: 'Cancel',_x000D_
        onclick: function(){_x000D_
list = Object.entries(buttons)_x000D_
    .filter(([key, value]) => `${key}`[value] !== 'undefined' ) //has options_x000D_
    .map(([key, value], idx) => `{${idx} {${key}: ${value}}}`)_x000D_

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

How to reload/refresh jQuery dataTable?

Try destroy datatable first then setup it again, example

var table;
$(document).ready(function() {
    table = $("#my-datatable").datatable()
    $("#my-button").click(function() {
        table = $("#my-datatable").dataTable();

Format ints into string of hex

With python 2.X, you can do the following:

numbers = [0, 1, 2, 3, 127, 200, 255]
print "".join(chr(i).encode('hex') for i in numbers)



How to convert date to string and to date again?

Convert Date to String using this function

public String convertDateToString(Date date, String format) {
        String dateStr = null;
        DateFormat df = new SimpleDateFormat(format);
        try {
            dateStr = df.format(date);
        } catch (Exception ex) {
        return dateStr;

From Convert Date to String in Java . And convert string to date again

public Date convertStringToDate(String dateStr, String format) {
        Date date = null;
        DateFormat df = new SimpleDateFormat(format);
        try {
            date = df.parse(dateStr);
        } catch (Exception ex) {
        return date;

From Convert String to date in Java

How to determine if .NET Core is installed

One of the dummies ways to determine if .NET Core is installed on Windows is:

  • Press Windows + R
  • Type cmd
  • On the command prompt, type dotnet --version

dotnet --version

If the .NET Core is installed, we should not get any error in the above steps.

What does a question mark represent in SQL queries?

The ? is an unnamed parameter which can be filled in by a program running the query to avoid SQL injection.

Passing arguments forward to another javascript function

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.

Example without using the apply method:

function a(...args){_x000D_
  b(6, ...args, 8) // You can even add more elements_x000D_
function b(){_x000D_
a(1, 2, 3)

Note This snippet returns a syntax error if your browser still uses ES5.

Editor's note: Since the snippet uses console.log(), you must open your browser's JS console to see the result - there will be no in-page result.

It will display this result:

Image of Spread operator arguments example

In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters

How in node to split string by newline ('\n')?

The first one should work:

> "a\nb".split("\n");
[ 'a', 'b' ]
> var a = "test.js\nagain.js"
> a.split("\n");
[ 'test.js', 'again.js' ]

How to unpackage and repackage a WAR file

Non programmatically, you can just open the archive using the 7zip UI to add/remove or extract/replace files without the structure changing. I didn't know it was a problem using other things until now :)

unary operator expected in shell script when comparing null value with string

Since the value of $var is the empty string, this:

if [ $var == $var1 ]; then

expands to this:

if [ == abcd ]; then

which is a syntax error.

You need to quote the arguments:

if [ "$var" == "$var1" ]; then

You can also use = rather than ==; that's the original syntax, and it's a bit more portable.

If you're using bash, you can use the [[ syntax, which doesn't require the quotes:

if [[ $var = $var1 ]]; then

Even then, it doesn't hurt to quote the variable reference, and adding quotes:

if [[ "$var" = "$var1" ]]; then

might save a future reader a moment trying to remember whether [[ ... ]] requires them.

Python for and if on one line

Found this one:

[x for (i,x) in enumerate(my_list) if my_list[i] == "two"]

Will print:


Visual Studio 2010 - recommended extensions

CleanProject - Cleans Visual Studio Solutions

How many times have you wanted to send a project to a friend or upload it to a web site like MSDN Code Gallery only to find that your zip file has lots of stuff that you don't need to send in it making the file larger than it needs to be.

bin folder obj folder TestResults folder Resharper folders And then if you forget about removing Source Control bindings whoever gets your project will be prompted about that. As someone who does this process a great deal I decided to share with you my code for cleaning a project.

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])


int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:


  for (k=0; k<50;k++) {



  for (k=0; k<50;k++) {
  printf("\n");//at the end of every row, print a new line

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

How to break out of while loop in Python?

What I would do is run the loop until the ans is Q

while not ans=='Q':
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")

Shortcut for creating single item list in C#

You can also do

new List<string>() { "string here" };

Where is the Postgresql config file: 'postgresql.conf' on Windows?

postgresql.conf is located in PostgreSQL's data directory. The data directory is configured during the setup and the setting is saved as PGDATA entry in c:\Program Files\PostgreSQL\<version>\pg_env.bat, for example

REM The script sets environment variables helpful for PostgreSQL

@SET PATH="C:\Program Files\PostgreSQL\<version>\bin";%PATH%
@SET PGDATA=D:\PostgreSQL\<version>\data
@SET PGUSER=postgres
@SET PGLOCALEDIR=C:\Program Files\PostgreSQL\<version>\share\locale

Alternatively you can query your database with SHOW config_file; if you are a superuser.

Insert multiple values using INSERT INTO (SQL Server 2005)

In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.

 INSERT INTO TableName ( Column1, Column2 ) VALUES
    ( Value1, Value2 ), ( Value1, Value2 )

Another way

INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
SELECT Value1 ,Value2
SELECT Value1 ,Value2
SELECT Value1 ,Value2
SELECT Value1 ,Value2

Pure CSS scroll animation

You can do it with anchor tags using css3 :target pseudo-selector, this selector is going to be triggered when the element with the same id as the hash of the current URL get an match. Example

Knowing this, we can combine this technique with the use of proximity selectors like "+" and "~" to select any other element through the target element who id get match with the hash of the current url. An example of this would be something like what you are asking.

What is the best way to connect and use a sqlite database from C#

ADO.NET 2.0 Provider for SQLite has over 200 downloads every day, so I think you are safe using that one.

sql set variable using COUNT

You just need parentheses around your select:

SET @times = (SELECT COUNT(DidWin) FROM ...)

Or you can do it like this:

SELECT @times = COUNT(DidWin) FROM ...

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

How to enable ASP classic in IIS7.5

If you get the above problem on windows server 2008 you may need to enable ASP. To do so, follow these steps:

Add an 'Application Server' role:

  1. Click Start, point to Control Panel, click Programs, and then click Turn Windows features on or off.
  2. Right-click Server Manager, select Add Roles.
  3. On the Add Roles Wizard page, select Application Server, click Next three times, and then click Install. Windows Server installs the new role.

Then, add a 'Web Server' role:

  1. Web Server Role (IIS): in ServerManager, Roles, if the Web Server (IIS) role does not exist then add it.
  2. Under Web Server (IIS) role add role services for: ApplicationDevelopment:ASP, ApplicationDevelopment:ISAPI Exstensions, Security:Request Filtering.

More info:

git commit error: pathspec 'commit' did not match any file(s) known to git

The order line contentions are isolated by space. On the off chance that you need furnish a contention with a space in it, you should cite it. So use git commit - m "Initial commit". must follow this syntax.

SQL Server 2008: how do I grant privileges to a username?

If you want to give your user all read permissions, you could use:

EXEC sp_addrolemember N'db_datareader', N'your-user-name'

That adds the default db_datareader role (read permission on all tables) to that user.

There's also a db_datawriter role - which gives your user all WRITE permissions (INSERT, UPDATE, DELETE) on all tables:

EXEC sp_addrolemember N'db_datawriter', N'your-user-name'

If you need to be more granular, you can use the GRANT command:

GRANT SELECT, INSERT ON dbo.YourTable2 TO YourUserName
GRANT SELECT, DELETE ON dbo.YourTable3 TO YourUserName

and so forth - you can granularly give SELECT, INSERT, UPDATE, DELETE permission on specific tables.

This is all very well documented in the MSDN Books Online for SQL Server.

And yes, you can also do it graphically - in SSMS, go to your database, then Security > Users, right-click on that user you want to give permissions to, then Properties adn at the bottom you see "Database role memberships" where you can add the user to db roles.

alt text

Using HttpClient and HttpPost in Android with post parameters

public class GetUsers extends AsyncTask {

    protected void onPreExecute() {


    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
        } catch (IOException e) {
        } finally {
            try {
            } catch (IOException e) {

        return sb.toString();

    public String connect()
        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpPost htopost = new HttpPost("URL");
        htopost.setHeader(new BasicHeader("Authorization","Basic Og=="));

        try {

            JSONObject param = new JSONObject();

            htopost.setEntity(new StringEntity(param.toString()));

            // Execute the request
            HttpResponse response;

            response = httpclient.execute(htopost);
            // Examine the response status
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result = convertStreamToString(instream);

                // A Simple JSONObject Creation
                json = new JSONArray(result);

                // Closing the input stream will trigger connection release
                return ""+response.getStatusLine().getStatusCode();
        } catch (Exception e) {

        return null;

    protected String doInBackground(String... urls) {
        return connect();

    protected void onPostExecute(String status){
        try {



                    for (int i = 0; i < json.length(); i++) {
                        JSONObject ojb = json.getJSONObject(i);
                        UserMomentModel u = new UserMomentModel();


                            userAdapter = new UserAdapter(getActivity(), Global.defaultMoemntLsit);

        catch (Exception e)


Changing the highlight color when selecting text in an HTML text input

Try this code to use:

/* For Mozile Firefox Browser */

::-moz-selection { background-color: #4CAF50; }

/* For Other Browser*/
::selection { background-color: #4CAF50; }

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

The most common issue is misconfiguration of your JAVA_HOME variable which should point to the right Java Development Kit library, if you've multiple installed.

To find where SDK Java folder is located, run the following commands:

jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));'


To check which java (openjdk) you've installed, check via:

dpkg -l "openjdk*" | grep ^i


update-java-alternatives -l

To change it, use:

update-alternatives --config java

Prefix with sudo if required.

to select the alternative java version.

Or check which are available for install:

apt-cache search ^openjdk

Prefix with sudo if required.

Then you can install, for example:

apt-get install openjdk-7-jre

Prefix with sudo if required.

Fedora, Oracle Linux, Red Hat

Install/upgrade appropriate package via:

yum install java-1.7.0-openjdk java-1.7.0-openjdk-devel

The java-1.7.0-openjdk package contains just the Java Runtime Environment. If you want to develop Java programs then install the java-1.7.0-openjdk-devel package.


There is an OpenJDK 7 package in the FreeBSD Ports collection called openjdk7 which probably needs to be reconfigured.

See: OpenJDK wiki page.


Just install appropriate Java SE Development Kit library from the Oracle site or install


If you're experiencing this issue with Jenkins, see:

However selecting the right version of Java (newer) with update-alternatives should work.

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

Simple excel find and replace for formulas

It turns out that the solution was to switch to R1C1 Cell Reference. My worksheet was structured in such a way that every formula had the same structure just different references. Luck though, they were always positioned the same way








In R1C1 Reference, every formula was identical so the find and replace required no wildcards. Thank you to those who answered!

php execute a background process

PHP scripting is not like other desktop application developing language. In desktop application languages we can set daemon threads to run a background process but in PHP a process is occuring when user request for a page. However It is possible to set a background job using server's cron job functionality which php script runs.

Addressing localhost from a VirtualBox virtual machine

I solved by adding a port forwarding in Virtualbox settings under network. Host IP set port : 8080 Guest ip : Give any IP for the website ( say port : 8080 Now from guest machine access using IE

How to invoke the super constructor in Python?

super() returns a parent-like object in new-style classes:

class A(object):
    def __init__(self):

class B(A):
    def __init__(self):
        super(B, self).__init__()


ReCaptcha API v2 Styling

Just adding a hack-ish solution to make it responsive.

Wrap the recaptcha in an extra div:

<div class="recaptcha-wrap">                   
    <div id="g-recaptcha"></div>

Add styles. This assumes the dark theme.

// Recaptcha
.recaptcha-wrap {
    position: relative;
    height: 76px;
    padding:1px 0 0 1px;
    > div {
        position: absolute;
        bottom: 2px;

// Hides top border
.recaptcha-wrap:after {
    display: block;
    background-color: #222;
    height: 2px;
    width: 100%;
    top: -1px;
    left: 0px;
    position: absolute;

// Hides left border
.recaptcha-wrap:before {
    display: block;
    background-color: #222;
    height: 100%;
    width: 2px;
    top: 0;
    left: -1px;
    position: absolute;
    z-index: 1;

// Makes it responsive & hides cut-off elements
#g-recaptcha {
    overflow: hidden;
    height: 76px;
    border-right: 60px solid #222222;
    border-top: 1px solid #222222;
    border-bottom: 1px solid #222;
    position: relative;
    box-sizing: border-box;
    max-width: 294px;

This yields the following:


It will now resize horizontally, and doesn't have a border. The recaptcha logo would get cut off on the right, so I am hiding it with a border-right. It's also hiding the privacy and terms links, so you may want to add those back in.

I attempted to set a height on the wrapper element, and then vertically center the recaptcha to reduce the height. Unfortunately, any combo of overflow:hidden and a smaller height seems to kill the iframe.

How to get JSON from webpage into Python script

All that the call to urlopen() does (according to the docs) is return a file-like object. Once you have that, you need to call its read() method to actually pull the JSON data across the network.

Something like:

jsonurl = urlopen(url)

text = json.loads(
print text

How to get document height and width without using jquery

Get document size without jQuery


And use this if you need Screen size


Get Wordpress Category from Single Post

How about get_the_category?

You can then do

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

Mask for an Input to allow phone numbers?

Reactive Form

See at Stackblitz

Addition to the @Günter Zöchbauer's answer above, I tried as follows and it seems to be working but I'm not sure whether it is a efficient way.

I use valueChanges observable to listen for change events in the reactive form by subscribing to it. For special handling of backspace, I get the data from subscribe and check it with [formGroup]="userForm"). Because, at that moment, the data changes to the new value but the latter refers to the previous value because of not setting yet. If the data is less than previous value then the user should remove character from input. In this case, change pattern as follows:

from : newVal = newVal.replace(/^(\d{0,3})/, '($1)');

to : newVal = newVal.replace(/^(\d{0,3})/, '($1');

Otherwise, as Günter Zöchbauer mentioned above, deleting of non-numeric characters is not recognized because when we remove parentheses from input, digits still remain the same and added again parentheses from pattern match.


import { Component,OnInit } from '@angular/core';
import { FormGroup,FormBuilder,AbstractControl,Validators } from '@angular/forms';
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent implements OnInit{

  constructor(private fb:FormBuilder) { 

    this.userForm ={

  ngOnInit() {

    const phoneControl:AbstractControl = this.userForm.controls['phone'];

    phoneControl.valueChanges.subscribe(data => {
    /**the most of code from @Günter Zöchbauer's answer.*/

    /**we remove from input but: 
       @preInputValue still keep the previous value because of not setting.
    let preInputValue:string =;
    let lastChar:string = preInputValue.substr(preInputValue.length - 1);

    var newVal = data.replace(/\D/g, '');
    //when removed value from input
    if (data.length < preInputValue.length) {

      /**while removing if we encounter ) character,
         then remove the last digit too.*/
      if(lastChar == ')'){
         newVal = newVal.substr(0,newVal.length-1); 
      if (newVal.length == 0) {
        newVal = '';
      else if (newVal.length <= 3) {
        /**when removing, we change pattern match.
        "otherwise deleting of non-numeric characters is not recognized"*/
        newVal = newVal.replace(/^(\d{0,3})/, '($1');
      } else if (newVal.length <= 6) {
        newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
      } else {
        newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) $2-$3');
    //when typed value in input
    } else{

    if (newVal.length == 0) {
      newVal = '';
    else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '($1)');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
    } else {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) $2-$3');

    this.userForm.controls['phone'].setValue(newVal,{emitEvent: false});



<form [formGroup]="userForm"  novalidate>
  <div class="form-group">
    <label for="tel">Tel:</label>
    <input id="tel" formControlName="phone" maxlength="14">
  <button [disabled]="userForm.status == 'INVALID'" type="submit">Send</button>


Is there a way to preserve cursor position while backspacing in the middle of the string? Currently, it jumps back to the end.

Define an id <input id="tel" formControlName="phone" #phoneRef> and renderer2#selectRootElement to get the native element in the component.

So we can get the cursor position using:

let start = this.renderer.selectRootElement('#tel').selectionStart;
let end = this.renderer.selectRootElement('#tel').selectionEnd;

and then we can apply it after the input is updated to new value:

this.userForm.controls['phone'].setValue(newVal,{emitEvent: false});
//keep cursor the appropriate position after setting the input above.


It's probably better to put this sort of logic inside a directive rather than in the component

I also put the logic into a directive. This makes it easier to apply it to other elements.

See at Stackblitz

Note: It is specific to (123) 123-4567 pattern.

How to write a basic swap function in Java

Here is one trick:

public static int getItself(int itself, int dummy)
    return itself;

public static void main(String[] args)
    int a = 10;
    int b = 20;

    a = getItself(b, b = a);

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

CSS Vertical align does not work with float

Vertical alignment doesn't work with floated elements, indeed. That's because float lifts the element from the normal flow of the document. You might want to use other vertical aligning techniques, like the ones based on transform, display: table, absolute positioning, line-height, js (last resort maybe) or even the plain old html table (maybe the first choice if the content is actually tabular). You'll find that there's a heated debate on this issue.

However, this is how you can vertically align YOUR 3 divs:

    width: 500px;
    background: pink;

.left {
    width: 150px;       
    margin-right: 10px;
    background: yellow;  
    vertical-align: middle; 

.left2 {
    width: 150px;    
    margin-right: 10px;
    background: aqua; 
    vertical-align: middle; 

    width: 150px;
    background: orange;
    vertical-align: middle; 

Not sure why you needed both fixed width, display: inline-block and floating.

Prevent form submission on Enter key press

if(characterCode == 13)
    return false; // returning false will prevent the event from bubbling up.
    return true;

Ok, so imagine you have the following textbox in a form:

<input id="scriptBox" type="text" onkeypress="return runScript(event)" />

In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.

function runScript(e) {
    //See notes about 'which' and 'key'
    if (e.keyCode == 13) {
        var tb = document.getElementById("scriptBox");
        return false;

returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.


It's been pointed out that keyCode is now deprecated. The next best alternative which has also been deprecated.

Unfortunately the favored standard key, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.

Furthermore, while the deprecated warning is quite ominous about keyCode and which, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");

suitButton = new JCheckBox("Denim Jeans");

should maybe be,

suitButton = new JCheckBox("Suit");

denimjeansButton = new JCheckBox("Denim Jeans");

REST API - Use the "Accept: application/json" HTTP Header

Basically I use Fiddler or Postman for testing API's.

In fiddler, in request header you need to specify instead of xml, html you need to change it to json. Eg: Accept: application/json. That should do the job.

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

Assuming the file exists and you just need to update the timestamp.

type test.c > test.c.bkp && type test.c.bkp > test.c && del test.c.bkp

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

Probably very trivial, but I solved it by just converting the input to numpy array.

For the neural network architecture,

    model = Sequential()
    model.add(Conv2D(32, (5, 5), activation="relu", input_shape=(32, 32, 3)))

When the input was,

    n_train = len(train_y_raw)
    train_X = [train_X_raw[:,:,:,i] for i in range(n_train)]
    train_y = [train_y_raw[i][0] for i in range(n_train)]

I got the error,enter image description here

But when I changed it to,

   n_train = len(train_y_raw)
   train_X = np.asarray([train_X_raw[:,:,:,i] for i in range(n_train)])
   train_y = np.asarray([train_y_raw[i][0] for i in range(n_train)])

It fixed the issue.

AWS Lambda import module error in python

The issue here that the Python version used to build your Lambda function dependencies (on your own machine) is different than the selected Python version for your Lambda function. This case is common especially if the Numpy library part of your dependencies.

Example: Your machine's python version: 3.6 ---> Lambda python version 3.6

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(;

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

setContentView(new GraphTemperature(getApplicationContext()));

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

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

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


Throws that exception.

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

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

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

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

u should add a theme to ur all activities (u should add theme for all application in ur <application> in ur manifest) but if u have set different theme to ur activity u can use :


or each kind of AppCompat theme!

What does it mean if a Python object is "subscriptable" or not?

It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

Is there a CSS selector for elements containing certain text?

If you're using Chimp /, they support a lot more CSS selectors than the CSS spec.

This, for example, will click on the first anchor that contains the words "Bad bear":"a*=Bad Bear");

Listen to changes within a DIV and act accordingly

If possible you can change the div to an textarea and use .change().

Another solution could be use a hidden textarea and update the textarea same time as you update the div. Then use .change() on the hidden textarea.

You can also use to make the text area act more like a div.


<textarea class="hidden" rows="4" cols="50">


$("#hiddentextarea").change(function() {

alert('Textarea changed');


Update: It seems like textarea has to be defocused after updated, for more info: How do I set up a listener in jQuery/javascript to monitor a if a value in the textbox has changed?

Regular expression which matches a pattern, or is an empty string

I'm not sure why you'd want to validate an optional email address, but I'd suggest you use



^$        empty string
|         or
^         beginning of string
[^@\s]+   any character but @ or whitespace
$         end of string

You won't stop fake emails anyway, and this way you won't stop valid addresses.

Use of 'const' for function parameters

Sometimes (too often!) I have to untangle someone else's C++ code. And we all know that someone else's C++ code is a complete mess almost by definition :) So the first thing I do to decipher local data flow is put const in every variable definition until compiler starts barking. This means const-qualifying value arguments as well, because they are just fancy local variables initialized by caller.

Ah, I wish variables were const by default and mutable was required for non-const variables :)

Get properties and values from unknown object

Yes, Reflection would be the way to go. First, you would get the Type that represents the type (at runtime) of the instance in the list. You can do this by calling the GetType method on Object. Because it is on the Object class, it's callable by every object in .NET, as all types derive from Object (well, technically, not everything, but that's not important here).

Once you have the Type instance, you can call the GetProperties method to get the PropertyInfo instances which represent the run-time informationa about the properties on the Type.

Note, you can use the overloads of GetProperties to help classify which properties you retrieve.

From there, you would just write the information out to a file.

Your code above, translated, would be:

// The instance, it can be of any type.
object o = <some object>;

// Get the type.
Type type = o.GetType();

// Get all public instance properties.
// Use the override if you want to classify
// which properties to return.
foreach (PropertyInfo info in type.GetProperties())
    // Do something with the property info.

Note that if you want method information or field information, you would have to call the one of the overloads of the GetMethods or GetFields methods respectively.

Also note, it's one thing to list out the members to a file, but you shouldn't use this information to drive logic based on property sets.

Assuming you have control over the implementations of the types, you should derive from a common base class or implement a common interface and make the calls on those (you can use the as or is operator to help determine which base class/interface you are working with at runtime).

However, if you don't control these type definitions and have to drive logic based on pattern matching, then that's fine.

Do standard windows .ini files allow comments?

Windows INI API support for:

  • Line comments: yes, using semi-colon ;
  • Trailing comments: No

The authoritative source is the Windows API function that reads values out of INI files


Retrieves a string from the specified section in an initialization file.

The reason "full line comments" work is because the requested value does not exist. For example, when parsing the following ini file contents:

pepsi=diet   ;gag

Reading the values:

  • UseLiveData: 1
  • coke: not present
  • ;coke: not present
  • pepsi: diet ;gag
  • stackoverflow: not present
  • #stackoverflow: splotchy

Update: I used to think that the number sign (#) was a pseudo line-comment character. The reason using leading # works to hide stackoverflow is because the name stackoverflow no longer exists. And it turns out that semi-colon (;) is a line-comment.

But there is no support for trailing comments.

WPF TemplateBinding vs RelativeSource TemplatedParent

One more thing - TemplateBindings don't allow value converting. They don't allow you to pass a Converter and don't automatically convert int to string for example (which is normal for a Binding).

How to switch back to 'master' with git?

Will take you to the master branch.

git checkout master

To switch to other branches do (ignore the square brackets, it's just for emphasis purposes)

git checkout [the name of the branch you want to switch to]

To create a new branch use the -b like this (ignore the square brackets, it's just for emphasis purposes)

git checkout -b [the name of the branch you want to create]

Select N random elements from a List<T> in C#

why not something like this:

 Dim ar As New ArrayList
    Dim numToGet As Integer = 5
    'hard code just to test

    Dim randomListOfProductIds As New ArrayList

    Dim toAdd As String = ""
    For i = 0 To numToGet - 1
        toAdd = ar(CInt((ar.Count - 1) * Rnd()))

        'remove from id list

'sorry i'm lazy and have to write vb at work :( and didn't feel like converting to c#

argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args = p.parse_args(['-f'])

Angularjs autocomplete from $http

Use angular-ui-bootstrap's typehead.

It had great support for $http and promises. Also, it doesn't include any JQuery at all, pure AngularJS.

(I always prefer using existing libraries and if they are missing something to open an issue or pull request, much better then creating your own again)

Change language of Visual Studio 2017 RC

In RC2 (and most likely in the final release) you can switch language from inside Visual Studio and you can modify your setup to include other language packs.

You can now add and remove multiple user interface languages at any time using the Visual Studio installer on the Language Pack tab. You can select the current user interface language among those installed using Tools > Options > International Settings. Source :

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

You don't need to learn JPA. You can use my easy-criteria for JPA2 ( Here is the example

CriteriaComposer<Pet> petCriteria CriteriaComposer.from(Pet.class).
where(Pet_.type, EQUAL, "Cat").join(Pet_.owner).where(,EQUAL, "foo");

List<Pet> result = CriteriaProcessor.findAllEntiry(petCriteria);


List<Tuple> result =  CriteriaProcessor.findAllTuple(petCriteria);

git ignore vim temporary files

Quit vim before "git commit".

to make vim use other folders for backup files, (/tmp for example):

set bdir-=.
set bdir+=/tmp

to make vim stop using current folder for .swp files:

set dir-=.
set dir+=/tmp

Use -=, += would be generally good, because vim has other defaults for bdir, dir, we don't want to clear all. Check vim help for more about bdir, dir:

:h bdir
:h dir

"Unable to launch the IIS Express Web server" error

In Debug > Website Properties.

change port number in Project Url to any nearest value and save

enter image description here

How do I count unique values inside a list

How about:

import pandas as pd
#List with all words

#Code for adding words

#When Input equals blank:

It returns how many unique values are in a list

How to "git clone" including submodules?

Try this:

git clone --recurse-submodules

It automatically pulls in the submodule data assuming you have already added the submodules to the parent project.

How to download a file from a website in C#

Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.


    webClient.DownloadFileAsync(new Uri(""), "test.jpg");

For more information:

How to embed a PDF viewer in a page?

using bootstrap you can have a responsive and mobile first embeded file.

<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="address of your file" allowfullscreen></iframe>

Aspect ratios can be customized with modifier classes.
<!-- 21:9 aspect ratio -->
<div class="embed-responsive embed-responsive-21by9">
  <iframe class="embed-responsive-item" src="..."></iframe>

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="..."></iframe>

<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="..."></iframe>

<!-- 1:1 aspect ratio -->
<div class="embed-responsive embed-responsive-1by1">
  <iframe class="embed-responsive-item" src="..."></iframe>