Programs & Examples On #Ca

How to add Certificate Authority file in CentOS 7

Find *.pem file and place it to the anchors sub-directory or just simply link the *.pem file to there.

yum install -y ca-certificates
update-ca-trust force-enable
sudo ln -s /etc/ssl/your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem
update-ca-trust

accepting HTTPS connections with self-signed certificates

The first thing you need to do is to set the level of verification. Such levels is not so much:

  • ALLOW_ALL_HOSTNAME_VERIFIER
  • BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
  • STRICT_HOSTNAME_VERIFIER

Although the method setHostnameVerifier() is obsolete for new library apache, but for version in Android SDK is normal. And so we take ALLOW_ALL_HOSTNAME_VERIFIER and set it in the method factory SSLSocketFactory.setHostnameVerifier().

Next, You need set our factory for the protocol to https. To do this, simply call the SchemeRegistry.register() method.

Then you need to create a DefaultHttpClient with SingleClientConnManager. Also in the code below you can see that on default will also use our flag (ALLOW_ALL_HOSTNAME_VERIFIER) by the method HttpsURLConnection.setDefaultHostnameVerifier()

Below code works for me:

HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();

SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

// Set verifier     
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

// Example send http request
final String url = "https://encrypted.google.com/";
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

Sometimes if the application you try to contact has self signed certificates, the normal cacert.pem from http://curl.haxx.se/ca/cacert.pem does not solve the problem.

If you are sure about the service endpoint url, hit it through browser, save the certificate manually in "X 509 certificate with chain (PEM)" format. Point this certificate file with the

curl_setopt ($ch, CURLOPT_CAINFO, "pathto/{downloaded certificate chain file}");   

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

How to sort a Pandas DataFrame by index?

Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

Note:

notifyDataSetChange not working from custom adapter

Maybe try to refresh your ListView:

receiptsListView.invalidate().

EDIT: Another thought came into my mind. Just for the record, try to disable list view cache:

<ListView
    ...
    android:scrollingCache="false"
    android:cacheColorHint="@android:color/transparent"
    ... />

Mongoose: Get full list of users

There was the very easy way to list your data :

server.get('/userlist' , function (req , res) {
 User.find({}).then(function (users) {
 res.send(users);
 });
});

run a python script in terminal without the python command

You use a shebang line at the start of your script:

#!/usr/bin/env python

make the file executable:

chmod +x arbitraryname

and put it in a directory on your PATH (can be a symlink):

cd ~/bin/
ln -s ~/some/path/to/myscript/arbitraryname

Best way to encode text data for XML

In .net 3.5+

new XText("I <want> to & encode this for XML").ToString();

Gives you:

I &lt;want&gt; to &amp; encode this for XML

Turns out that this method doesn't encode some things that it should (like quotes).

SecurityElement.Escape (workmad3's answer) seems to do a better job with this and it's included in earlier versions of .net.

If you don't mind 3rd party code and want to ensure no illegal characters make it into your XML, I would recommend Michael Kropat's answer.

When do I use super()?

I just tried it, commenting super(); does the same thing without commenting it as @Mark Peters said

package javaapplication6;

/**
 *
 * @author sborusu
 */
public class Super_Test {
    Super_Test(){
        System.out.println("This is super class, no object is created");
    }
}
class Super_sub extends Super_Test{
    Super_sub(){
       super();
       System.out.println("This is sub class, object is created");
    }
    public static void main(String args[]){
        new Super_sub();
    }
}

Add one day to date in javascript

Note that Date.getDate only returns the day of the month. You can add a day by calling Date.setDate and appending 1.

// Create new Date instance
var date = new Date()

// Add a day
date.setDate(date.getDate() + 1)

JavaScript will automatically update the month and year for you.

EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.

Java - Find shortest path between 2 points in a distance weighted map

Maintain a list of nodes you can travel to, sorted by the distance from your start node. In the beginning only your start node will be in the list.

While you haven't reached your destination: Visit the node closest to the start node, this will be the first node in your sorted list. When you visit a node, add all its neighboring nodes to your list except the ones you have already visited. Repeat!

How to stick text to the bottom of the page?

Try this

 <head>
 <style type ="text/css" >
   .footer{ 
       position: fixed;     
       text-align: center;    
       bottom: 0px; 
       width: 100%;
   }  
</style>
</head>
<body>
    <div class="footer">All Rights Reserved</div>
</body>

Change HTML email body font type and size in VBA

FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :

strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"

Decimal to Hexadecimal Converter in Java

Code to convert DECIMAL -to-> BINARY, OCTAL, HEXADECIMAL

public class ConvertBase10ToBaseX {
    enum Base {
        /**
         * Integer is represented in 32 bit in 32/64 bit machine.
         * There we can split this integer no of bits into multiples of 1,2,4,8,16 bits
         */
        BASE2(1,1,32), BASE4(3,2,16), BASE8(7,3,11)/* OCTAL*/, /*BASE10(3,2),*/ 
        BASE16(15, 4, 8){       
            public String getFormattedValue(int val){
                switch(val) {
                case 10:
                    return "A";
                case 11:
                    return "B";
                case 12:
                    return "C";
                case 13:
                    return "D";
                case 14:
                    return "E";
                case 15:
                    return "F";
                default:
                    return "" + val;
                }

            }
        }, /*BASE32(31,5,1),*/ BASE256(255, 8, 4), /*BASE512(511,9),*/ Base65536(65535, 16, 2);

        private int LEVEL_0_MASK;
        private int LEVEL_1_ROTATION;
        private int MAX_ROTATION;

        Base(int levelZeroMask, int levelOneRotation, int maxPossibleRotation) {
            this.LEVEL_0_MASK = levelZeroMask;
            this.LEVEL_1_ROTATION = levelOneRotation;
            this.MAX_ROTATION = maxPossibleRotation;
        }

        int getLevelZeroMask(){
            return LEVEL_0_MASK;
        }
        int getLevelOneRotation(){
            return LEVEL_1_ROTATION;
        }
        int getMaxRotation(){
            return MAX_ROTATION;
        }
        String getFormattedValue(int val){
            return "" + val;
        }
    }

    public void getBaseXValueOn(Base base, int on) {
        forwardPrint(base, on);
    }

    private void forwardPrint(Base base, int on) {

        int rotation = base.getLevelOneRotation();
        int mask = base.getLevelZeroMask();
        int maxRotation = base.getMaxRotation();
        boolean valueFound = false;

        for(int level = maxRotation; level >= 2; level--) {
            int rotation1 = (level-1) * rotation;
            int mask1 = mask << rotation1 ;
            if((on & mask1) > 0 ) {
                valueFound = true;
            }
            if(valueFound)
            System.out.print(base.getFormattedValue((on & mask1) >>> rotation1));
        }
        System.out.println(base.getFormattedValue((on & mask)));
    }

    public int getBaseXValueOnAtLevel(Base base, int on, int level) {
        if(level > base.getMaxRotation() || level < 1) {
            return 0; //INVALID Input
        }
        int rotation = base.getLevelOneRotation();
        int mask = base.getLevelZeroMask();

        if(level > 1) {
            rotation = (level-1) * rotation;
            mask = mask << rotation;
        } else {
            rotation = 0;
        }


        return (on & mask) >>> rotation;
    }

    public static void main(String[] args) {
        ConvertBase10ToBaseX obj = new ConvertBase10ToBaseX();

        obj.getBaseXValueOn(Base.BASE16,12456); 
//      obj.getBaseXValueOn(Base.BASE16,300); 
//      obj.getBaseXValueOn(Base.BASE16,7); 
//      obj.getBaseXValueOn(Base.BASE16,7);

        obj.getBaseXValueOn(Base.BASE2,12456);
        obj.getBaseXValueOn(Base.BASE8,12456);
        obj.getBaseXValueOn(Base.BASE2,8);
        obj.getBaseXValueOn(Base.BASE2,9);
        obj.getBaseXValueOn(Base.BASE2,10);
        obj.getBaseXValueOn(Base.BASE2,11);
        obj.getBaseXValueOn(Base.BASE2,12);
        obj.getBaseXValueOn(Base.BASE2,13);
        obj.getBaseXValueOn(Base.BASE2,14);
        obj.getBaseXValueOn(Base.BASE2,15);
        obj.getBaseXValueOn(Base.BASE2,16);
        obj.getBaseXValueOn(Base.BASE2,17);


        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 1)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 2)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 3)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 4)); 

        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,15, 1)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,30, 2)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,7, 1)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,7, 2)); 

        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 511, 1)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 511, 2)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 512, 1));
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 512, 2)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 513, 2)); 


    }
}

Convert data.frame column format from character to factor

Unless you need to identify the columns automatically, I found this to be the simplest solution:

df$name <- as.factor(df$name)

This makes column name in dataframe df a factor.

Git Cherry-Pick and Conflicts

Do, I need to resolve all the conflicts before proceeding to next cherry -pick

Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.

Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.

That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.

Further, is it suggested to do cherry-pick or branch merge in this case?

Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.

Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.

$(document).ready shorthand

What about this?

(function($) { 
   $(function() {
     // more code using $ as alias to jQuery
     // will be fired when document is ready
   });
})(jQuery);

Change background color of iframe issue

just building on what Chetabahana wrote, I found that adding a short delay to the JS function helped on a site I was working on. It meant that the function kicked in after the iframe loaded. You can play around with the delay.

var delayInMilliseconds = 500; // half a second

setTimeout(function() { 

   var iframe = document.getElementsByTagName('iframe')[0];
   iframe.style.background = 'white';
   iframe.contentWindow.document.body.style.backgroundColor = 'white';

}, delayInMilliseconds);

I hope this helps!

How do I bind the enter key to a function in tkinter?

Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")
root.bind('<Return>', func)

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Then you just have tweak things a little when making both the button click and hitting Return call the same function--because the command function needs to be a function that takes no arguments, whereas the bind function needs to be a function that takes one argument(the event object):

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event=None):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Or, you can just forgo using the button's command argument and instead use bind() to attach the onclick function to the button, which means the function needs to take one argument--just like with Return:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()

root.mainloop()

Here it is in a class setting:

import tkinter as tk

class Application(tk.Frame):
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("300x200")

        tk.Frame.__init__(self, self.root)
        self.create_widgets()

    def create_widgets(self):
        self.root.bind('<Return>', self.parse)
        self.grid()

        self.submit = tk.Button(self, text="Submit")
        self.submit.bind('<Button-1>', self.parse)
        self.submit.grid()

    def parse(self, event):
        print("You clicked?")

    def start(self):
        self.root.mainloop()


Application().start()

405 method not allowed Web API

I'm late to this party but as nothing above was either viable or working in most cases, here is how this was finally resolved for me.

On the server the site/service was hosted on, a feature was required! HTTP ACTIVATION!!!

Server Manager > Manage > Add Roles and Features > next next next till you get to Features > Under .NET (each version) tick HTTP Activation. Also note there is one hidden under >net > WCF Services.

This then worked instantly! That was melting my brain

OpenCV - Saving images to a particular folder of choice

Answer given by Jeru Luke is working only on Windows systems, if we try on another operating system (Ubuntu) then it runs without error but the image is saved on target location or path.

Not working in Ubuntu and working in Windows

  import cv2
  img = cv2.imread('1.jpg', 1)
  path = '/tmp'
  cv2.imwrite(str(path) + 'waka.jpg',img)
  cv2.waitKey(0)

I run above code but the image does not save the image on target path. Then I found that the way of adding path is wrong for the general purpose we using OS module to add the path.

Example:

 import os
 final_path = os.path.join(path_1,path_2,path_3......)

working in Ubuntu and Windows

 import cv2
 import os
 img = cv2.imread('1.jpg', 1)
 path = 'D:/OpenCV/Scripts/Images'
 cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
 cv2.waitKey(0)

that code works fine on both Windows and Ubuntu :)

Detect when input has a 'readonly' attribute

You can just use the attribute selector and then test the length:

$('input[readonly]').length == 0 // --> ok
$('input[readonly]').length > 0  // --> not ok

Dynamically adding properties to an ExpandoObject

Here is a sample helper class which converts an Object and returns an Expando with all public properties of the given object.


    public static class dynamicHelper
        {
            public static ExpandoObject convertToExpando(object obj)
            {
                //Get Properties Using Reflections
                BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
                PropertyInfo[] properties = obj.GetType().GetProperties(flags);

                //Add Them to a new Expando
                ExpandoObject expando = new ExpandoObject();
                foreach (PropertyInfo property in properties)
                {
                    AddProperty(expando, property.Name, property.GetValue(obj));
                }

                return expando;
            }

            public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
            {
                //Take use of the IDictionary implementation
                var expandoDict = expando as IDictionary;
                if (expandoDict.ContainsKey(propertyName))
                    expandoDict[propertyName] = propertyValue;
                else
                    expandoDict.Add(propertyName, propertyValue);
            }
        }

Usage:

//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);

//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");

How to install XNA game studio on Visual Studio 2012?

I found another issue, for some reason if the extensions are cached in the local AppData folder, the XNA extensions never get loaded.

You need to remove the files extensionSdks.en-US.cache and extensions.en-US.cache from the %LocalAppData%\Microsoft\VisualStudio\11.0\Extensions folder. These files are rebuilt the next time you launch

If you need access to the Visual Studio startup log to debug what's happening, run devenv.exe /log command from the C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE directory (assuming you are on a 64 bit machine). The log file generated is located here:

%AppData%\Microsoft\VisualStudio\11.0\ActivityLog.xml

Git error: src refspec master does not match any error: failed to push some refs

One classic root cause for this message is:

  • when the repo has been initialized (git init lis4368/assignments),
  • but no commit has ever been made

Ie, if you don't have added and committed at least once, there won't be a local master branch to push to.

Try first to create a commit:

  • either by adding (git add .) then git commit -m "first commit"
    (assuming you have the right files in place to add to the index)
  • or by create a first empty commit: git commit --allow-empty -m "Initial empty commit"

And then try git push -u origin master again.

See "Why do I need to explicitly push a new branch?" for more.

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

Xcode couldn't find any provisioning profiles matching

I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:

  • Tried automatic signing again. No go, so reverted to manual.
  • After reverting, I had no Eligible Profiles, all were ineligible. Strange.
  • I created a new certificate and profile, imported both. This too was "ineligible".
  • Removed the iOS platform and re-added it. I had tried this previously without luck.
  • After doing this, Xcode on its own defaulted to automatic signing. And this worked! Success!

While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(

Thanks for help.

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

Detect If Browser Tab Has Focus

Yes, window.onfocus and window.onblur should work for your scenario:

http://www.thefutureoftheweb.com/blog/detect-browser-window-focus

Recursive search and replace in text files on Mac and Linux

Whenever I type this command I always seem to hose it up, or forget a flag. I created a Gist on github based off of TaylanUB's answer that does a global find replace from the current directory. This is Mac OSX specific.

https://gist.github.com/nateflink/9056302

It's nice because now I just pop open a terminal then copy in:

curl -s https://gist.github.com/nateflink/9056302/raw/findreplaceosx.sh | bash -s "find-a-url.com" "replace-a-url.com"

You can get some weird byte sequence errors, so here is the full code:

#!/bin/bash
#By Nate Flink

#Invoke on the terminal like this
#curl -s https://gist.github.com/nateflink/9056302/raw/findreplaceosx.sh | bash -s "find-a-url.com" "replace-a-url.com"

if [ -z "$1" ] || [ -z "$2" ]; then
  echo "Usage: ./$0 [find string] [replace string]"
  exit 1
fi

FIND=$1
REPLACE=$2

#needed for byte sequence error in ascii to utf conversion on OSX
export LC_CTYPE=C;
export LANG=C;

#sed -i "" is needed by the osx version of sed (instead of sed -i)
find . -type f -exec sed -i "" "s|${FIND}|${REPLACE}|g" {} +
exit 0

Android ListView headers

Here's how I do it, the keys are getItemViewType and getViewTypeCount in the Adapter class. getViewTypeCount returns how many types of items we have in the list, in this case we have a header item and an event item, so two. getItemViewType should return what type of View we have at the input position.

Android will then take care of passing you the right type of View in convertView automatically.

Here what the result of the code below looks like:

First we have an interface that our two list item types will implement

public interface Item {
    public int getViewType();
    public View getView(LayoutInflater inflater, View convertView);
}

Then we have an adapter that takes a list of Item

public class TwoTextArrayAdapter extends ArrayAdapter<Item> {
    private LayoutInflater mInflater;

    public enum RowType {
        LIST_ITEM, HEADER_ITEM
    }

    public TwoTextArrayAdapter(Context context, List<Item> items) {
        super(context, 0, items);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getViewTypeCount() {
        return RowType.values().length;

    }

    @Override
    public int getItemViewType(int position) {
        return getItem(position).getViewType();
    }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
   return getItem(position).getView(mInflater, convertView);
}

EDIT Better For Performance.. can be noticed when scrolling

private static final int TYPE_ITEM = 0; 
private static final int TYPE_SEPARATOR = 1; 

public View getView(int position, View convertView, ViewGroup parent)  {
    ViewHolder holder = null;
    int rowType = getItemViewType(position);
    View View;
    if (convertView == null) {
        holder = new ViewHolder();
        switch (rowType) {
            case TYPE_ITEM:
                convertView = mInflater.inflate(R.layout.task_details_row, null);
                holder.View=getItem(position).getView(mInflater, convertView);
                break;
            case TYPE_SEPARATOR:
                convertView = mInflater.inflate(R.layout.task_detail_header, null);
                holder.View=getItem(position).getView(mInflater, convertView);
                break;
        }
        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }
    return convertView; 
} 

public static class ViewHolder {
    public  View View; } 
}

Then we have classes the implement Item and inflate the correct layouts. In your case you'll have something like a Header class and a ListItem class.

   public class Header implements Item {
    private final String         name;

    public Header(String name) {
        this.name = name;
    }

    @Override
    public int getViewType() {
        return RowType.HEADER_ITEM.ordinal();
    }

    @Override
    public View getView(LayoutInflater inflater, View convertView) {
        View view;
        if (convertView == null) {
            view = (View) inflater.inflate(R.layout.header, null);
            // Do some initialization
        } else {
            view = convertView;
        }

        TextView text = (TextView) view.findViewById(R.id.separator);
        text.setText(name);

        return view;
    }

}

And then the ListItem class

    public class ListItem implements Item {
    private final String         str1;
    private final String         str2;

    public ListItem(String text1, String text2) {
        this.str1 = text1;
        this.str2 = text2;
    }

    @Override
    public int getViewType() {
        return RowType.LIST_ITEM.ordinal();
    }

    @Override
    public View getView(LayoutInflater inflater, View convertView) {
        View view;
        if (convertView == null) {
            view = (View) inflater.inflate(R.layout.my_list_item, null);
            // Do some initialization
        } else {
            view = convertView;
        }

        TextView text1 = (TextView) view.findViewById(R.id.list_content1);
        TextView text2 = (TextView) view.findViewById(R.id.list_content2);
        text1.setText(str1);
        text2.setText(str2);

        return view;
    }

}

And a simple Activity to display it

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<Item> items = new ArrayList<Item>();
        items.add(new Header("Header 1"));
        items.add(new ListItem("Text 1", "Rabble rabble"));
        items.add(new ListItem("Text 2", "Rabble rabble"));
        items.add(new ListItem("Text 3", "Rabble rabble"));
        items.add(new ListItem("Text 4", "Rabble rabble"));
        items.add(new Header("Header 2"));
        items.add(new ListItem("Text 5", "Rabble rabble"));
        items.add(new ListItem("Text 6", "Rabble rabble"));
        items.add(new ListItem("Text 7", "Rabble rabble"));
        items.add(new ListItem("Text 8", "Rabble rabble"));

        TwoTextArrayAdapter adapter = new TwoTextArrayAdapter(this, items);
        setListAdapter(adapter);
    }

}

Layout for R.layout.header

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

    <TextView
        style="?android:attr/listSeparatorTextViewStyle"
        android:id="@+id/separator"
        android:text="Header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#757678"
        android:textColor="#f5c227" />

</LinearLayout>

Layout for R.layout.my_list_item

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

    <TextView
        android:id="@+id/list_content1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_margin="5dip"
        android:clickable="false"
        android:gravity="center"
        android:longClickable="false"
        android:paddingBottom="1dip"
        android:paddingTop="1dip"
        android:text="sample"
        android:textColor="#ff7f1d"
        android:textSize="17dip"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/list_content2"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_margin="5dip"
        android:clickable="false"
        android:gravity="center"
        android:linksClickable="false"
        android:longClickable="false"
        android:paddingBottom="1dip"
        android:paddingTop="1dip"
        android:text="sample"
        android:textColor="#6d6d6d"
        android:textSize="17dip" />

</LinearLayout>

Layout for R.layout.activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

You can also get fancier and use ViewHolders, load stuff asynchronously, or whatever you like.

MySQL order by before group by

First, don't use * in select, affects their performance and hinder the use of the group by and order by. Try this query:

SELECT wp_posts.post_author, wp_posts.post_date as pdate FROM wp_posts
WHERE wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author           
ORDER BY pdate DESC

When you don't specifies the table in ORDER BY, just the alias, they will order the result of the select.

How to resize an image with OpenCV2.0 and Python2.6

Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio

# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    # Grab the image size and initialize dimensions
    dim = None
    (h, w) = image.shape[:2]

    # Return original image if no need to resize
    if width is None and height is None:
        return image

    # We are resizing height if width is none
    if width is None:
        # Calculate the ratio of the height and construct the dimensions
        r = height / float(h)
        dim = (int(w * r), height)
    # We are resizing width if height is none
    else:
        # Calculate the ratio of the width and construct the dimensions
        r = width / float(w)
        dim = (width, int(h * r))

    # Return the resized image
    return cv2.resize(image, dim, interpolation=inter)

Usage

import cv2

image = cv2.imread('1.png')
cv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))
cv2.imshow('width_300', maintain_aspect_ratio_resize(image, width=300))
cv2.waitKey()

Using this example image

enter image description here

Simply downscale to width=100 (left) or upscale to width=300 (right)

enter image description here enter image description here

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

What's the best way to calculate the size of a directory in .NET?

I try to change the sample (Alexandre Pepin and hao's Answer)

As is

    private long GetDirectorySize(string dirPath)
    {
        if (Directory.Exists(dirPath) == false)
        {
            return 0;
        }

        DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

        long size = 0;

        // Add file sizes.
        FileInfo[] fis = dirInfo.GetFiles();
        foreach (FileInfo fi in fis)
        {
            size += fi.Length;
        }

        // Add subdirectory sizes.
        DirectoryInfo[] dis = dirInfo.GetDirectories();
        foreach (DirectoryInfo di in dis)
        {
            size += GetDirectorySize(di.FullName);
        }

        return size;
    }

To be

    private long GetDirectorySize2(string dirPath)
    {
        if (Directory.Exists(dirPath) == false)
        {
            return 0;
        }

        DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

        long size = 0;

        // Add file sizes.
        IEnumerable<FileInfo> fis = dirInfo.EnumerateFiles("*.*", SearchOption.AllDirectories);
        foreach (FileInfo fi in fis)
        {
            size += fi.Length;
        }

        return size;
    }

finally you can check the result

        // ---------------------------------------------
        // size of directory
        using System.IO;

        string log1Path = @"D:\SampleDirPath1";
        string log2Path = @"D:\SampleDirPath2";
        string log1DirName = Path.GetDirectoryName(log1Path);
        string log2DirName = Path.GetDirectoryName(log2Path);
        long log1Size = GetDirectorySize(log1Path);
        long log2Size = GetDirectorySize(log2Path);
        long log1Size2 = GetDirectorySize2(log1Path);
        long log2Size2 = GetDirectorySize2(log2Path);

        Console.WriteLine($@"{log1DirName} Size: {SizeSuffix(log1Size)}, {SizeSuffix(log1Size2)}
        {log2DirName} Size: {SizeSuffix(log2Size)}, {SizeSuffix(log2Size2)}");

and this is the SizeSuffix function

    private static readonly string[] SizeSuffixes =
               { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

    /// <summary>
    /// Size Display
    /// </summary>
    /// <param name="value">bytes ??</param>
    /// <param name="decimalPlaces">????</param>
    /// <returns></returns>
    public static string SizeSuffix(Int64 value, int decimalPlaces = 2)
    {
        if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
        if (value < 0) { return "-" + SizeSuffix(-value); }
        if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

        // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
        int mag = (int)Math.Log(value, 1024);

        // 1L << (mag * 10) == 2 ^ (10 * mag) 
        // [i.e. the number of bytes in the unit corresponding to mag]
        decimal adjustedSize = (decimal)value / (1L << (mag * 10));

        // make adjustment when the value is large enough that
        // it would round up to 1000 or more
        if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
        {
            mag += 1;
            adjustedSize /= 1024;
        }

        return string.Format("{0:n" + decimalPlaces + "} {1}",
            adjustedSize,
            SizeSuffixes[mag]);
    }

What's default HTML/CSS link color?

Entirely depends on the website you are visiting, and in absence of an overwrite on the website, on the browser. There is no standard for that.

Setting an image for a UIButton in code

You can put the image in either of the way:

UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self 
           action:@selector(goToOne) 
 forControlEvents:UIControlEventTouchUpInside];


[btnTwo setImage:[UIImage imageNamed:@"name.png"] forState:UIControlStateNormal];

//OR setting as background image

[btnTwo setBackgroundImage:[UIImage imageNamed:@"name.png"] 
                  forState:UIControlStateNormal];

[self.view addSubview:btnTwo];

jQuery: get the file name selected from <input type="file" />

I had used following which worked correctly.

$('#fileAttached').attr('value', $('#attachment').val())

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

How to export data as CSV format from SQL Server using sqlcmd?

Alternate option with BCP:

exec master..xp_cmdshell 'BCP "sp_who" QUERYOUT C:\av\sp_who.txt -S MC0XENTC -T -c '

How to force a checkbox and text on the same line?

Try this. The following considers checkbox and label as a unique element:

<style>
  .item {white-space: nowrap;display:inline  }
</style>
<fieldset>
<div class="item">
    <input type="checkbox" id="a">
    <label for="a">aaaaaaaaaaaa aaaa a a a a a a aaaaaaaaaaaaa</label>
</div>
<div class="item">
   <input type="checkbox" id="b">
<!-- depending on width, a linebreak NEVER occurs here. -->
    <label for="b">bbbbbbbbbbbb bbbbbbbbbbbbbbbbb  b b b b  bb</label>
</div>
<div class="item">
    <input type="checkbox" id="c">
    <label for="c">ccccc c c c c ccccccccccccccc  cccc</label>
</div>
</fieldset>

What is the difference between "mvn deploy" to a local repo and "mvn install"?

Ken, good question. I should be more explicit in the The Definitive Guide about the difference. "install" and "deploy" serve two different purposes in a build. "install" refers to the process of installing an artifact in your local repository. "deploy" refers to the process of deploying an artifact to a remote repository.

Example:

  1. When I run a large multi-module project on a my machine, I'm going to usually run "mvn install". This is going to install all of the generated binary software artifacts (usually JARs) in my local repository. Then when I build individual modules in the build, Maven is going to retrieve the dependencies from the local repository.

  2. When it comes time to deploy snapshots or releases, I'm going to run "mvn deploy". Running this is going to attempt to deploy the files to a remote repository or server. Usually I'm going to be deploying to a repository manager such as Nexus

It is true that running "deploy" is going to require some extra configuration, you are going to have to supply a distributionManagement section in your POM.

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

Both attributes are needed and also recheck all the form elements has "name" attribute. if you are using form submit concept, other wise just use div tag instead of form element.

<input [(ngModel)]="firstname" name="something">

Scroll to the top of the page using JavaScript?

None of the answers above will work in SharePoint 2016.

It has to be done like this : https://sharepoint.stackexchange.com/questions/195870/

var w = document.getElementById("s4-workspace");
w.scrollTop = 0;

How to break out of jQuery each Loop

I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.

I would like to explain it with 2 simple examples:

1. Example: In this case, we have a simple iteration and we want to break with return true, if we can find the three.

function canFindThree() {
    for(var i = 0; i < 5; i++) {
        if(i === 3) {
           return true;
        }
    }
}

if we call this function, it will simply return the true.

2. Example In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.

function canFindThree() {

    var result = false;

    $.each([1, 2, 3, 4, 5], function(key, value) { 
        if(value === 3) {
            result = true;
            return false; //This will only exit the anonymous function and stop the iteration immediatelly.
        }
    });

    return result; //This will exit the function with return true;
}

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

Because on Unix, usually, the current directory is not in $PATH.

When you type a command the shell looks up a list of directories, as specified by the PATH variable. The current directory is not in that list.

The reason for not having the current directory on that list is security.

Let's say you're root and go into another user's directory and type sl instead of ls. If the current directory is in PATH, the shell will try to execute the sl program in that directory (since there is no other sl program). That sl program might be malicious.

It works with ./ because POSIX specifies that a command name that contain a / will be used as a filename directly, suppressing a search in $PATH. You could have used full path for the exact same effect, but ./ is shorter and easier to write.

EDIT

That sl part was just an example. The directories in PATH are searched sequentially and when a match is made that program is executed. So, depending on how PATH looks, typing a normal command may or may not be enough to run the program in the current directory.

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

So In my case, After trying all the above options, I realized it was VPN (company firewall).once connected and ran cmd: clean install spring-boot:run. Issue is resolved. Step 1: check maven is configured correctly or not. Step 2: check settings.xml is mapped correctly or not. Step 3: verify if you are behind any firewall then map your repo urls accordingly. Step 4:run clean install spring-boot:run step 5: issue is resolved.

python plot normal distribution

Use seaborn instead i am using distplot of seaborn with mean=5 std=3 of 1000 values

value = np.random.normal(loc=5,scale=3,size=1000)
sns.distplot(value)

You will get a normal distribution curve

Swift Alamofire: How to get the HTTP response status code

I needed to know how to get the actual error code number.

I inherited a project from someone else and I had to get the error codes from a .catch clause that they had previously setup for Alamofire:

} .catch { (error) in

    guard let error = error as? AFError else { return }
    guard let statusCode = error.responseCode else { return }

    print("Alamofire statusCode num is: ", statusCode)
}

Or if you need to get it from the response value follow @mbryzinski's answer

Alamofire ... { (response) in

    guard let error = response.result.error as? AFError else { return }
    guard let statusCode = error.responseCode else { return }

    print("Alamofire statusCode num is: ", statusCode)
})

What is logits, softmax and softmax_cross_entropy_with_logits?

Logits simply means that the function operates on the unscaled output of earlier layers and that the relative scale to understand the units is linear. It means, in particular, the sum of the inputs may not equal 1, that the values are not probabilities (you might have an input of 5).

tf.nn.softmax produces just the result of applying the softmax function to an input tensor. The softmax "squishes" the inputs so that sum(input) = 1: it's a way of normalizing. The shape of output of a softmax is the same as the input: it just normalizes the values. The outputs of softmax can be interpreted as probabilities.

a = tf.constant(np.array([[.1, .3, .5, .9]]))
print s.run(tf.nn.softmax(a))
[[ 0.16838508  0.205666    0.25120102  0.37474789]]

In contrast, tf.nn.softmax_cross_entropy_with_logits computes the cross entropy of the result after applying the softmax function (but it does it all together in a more mathematically careful way). It's similar to the result of:

sm = tf.nn.softmax(x)
ce = cross_entropy(sm)

The cross entropy is a summary metric: it sums across the elements. The output of tf.nn.softmax_cross_entropy_with_logits on a shape [2,5] tensor is of shape [2,1] (the first dimension is treated as the batch).

If you want to do optimization to minimize the cross entropy AND you're softmaxing after your last layer, you should use tf.nn.softmax_cross_entropy_with_logits instead of doing it yourself, because it covers numerically unstable corner cases in the mathematically right way. Otherwise, you'll end up hacking it by adding little epsilons here and there.

Edited 2016-02-07: If you have single-class labels, where an object can only belong to one class, you might now consider using tf.nn.sparse_softmax_cross_entropy_with_logits so that you don't have to convert your labels to a dense one-hot array. This function was added after release 0.6.0.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Getter and Setter?

Why use getters and setters?

  1. Scalability: It's easier refactor a getter than search all the var assignments in a project code.
  2. Debugging: You can put breakpoints at setters and getters.
  3. Cleaner: Magic functions are not good solution for writting less, your IDE will not suggest the code. Better use templates for fast-writting getters.

direct assignment and getters/setters

How to find sitemap.xml path on websites?

I don't think there's a standard as to the location of the sitemap. That's the reason why you should specify an arbitrary URL to your sitemap when you're adding one using Google's Webmaster Tools.

Entity Framework. Delete all rows in table

This works for me... EF v3.1.5

context.ModelName.RemoveRange(context.ModelName.ToList());
context.SaveChanges();

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Copied from the stacktrace:

BeanInstantiationException: Could not instantiate bean class [com.gestEtu.project.model.dao.CompteDAOHib]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.gestEtu.project.model.dao.CompteDAOHib.<init>()

By default, Spring will try to instantiate beans by calling a default (no-arg) constructor. The problem in your case is that the implementation of the CompteDAOHib has a constructor with a SessionFactory argument. By adding the @Autowired annotation to a constructor, Spring will attempt to find a bean of matching type, SessionFactory in your case, and provide it as a constructor argument, e.g.

@Autowired
public CompteDAOHib(SessionFactory sessionFactory) {
    // ...
}

Delete a database in phpMyAdmin

select database on the left side. Then on the right-central top you can find Operations. In that go for remove database (DROP). That's all.

Show whitespace characters in Visual Studio Code

It can also be done via the main menu View -> Render Whitespace

What is SYSNAME data type in SQL Server?

Just as an FYI....

select * from sys.types where system_type_id = 231 gives you two rows.

(i'm not sure what this means yet but i'm 100% sure it's messing up my code right now)

edit: i guess what it means is that you should join by the user_type_id in this situation (my situation) or possibly both the user_type_id and the system_type_id

name        system_type_id   user_type_id   schema_id   principal_id    max_length  precision   scale   collation_name                  is_nullable     is_user_defined     is_assembly_type    default_object_id   rule_object_id
nvarchar    231              231            4           NULL            8000        0           0       SQL_Latin1_General_CP1_CI_AS    1               0                   0                   0                   0
sysname     231              256            4           NULL            256         0           0       SQL_Latin1_General_CP1_CI_AS    0               0                   0                   0                   0

create procedure dbo.yyy_test (
    @col_one    nvarchar(max),
    @col_two    nvarchar(max)  = 'default',
    @col_three  nvarchar(1),
    @col_four   nvarchar(1)    = 'default',
    @col_five   nvarchar(128),
    @col_six    nvarchar(128)  = 'default',
    @col_seven  sysname  
)
as begin 

    select 1
end 

This query:

select  parm.name AS Parameter,    
        parm.max_length, 
        parm.parameter_id 
         
from    sys.procedures sp

        join sys.parameters parm ON sp.object_id = parm.object_id 
        
where   sp.name = 'yyy_test'

order   by parm.parameter_id

Yields:

parameter           max_length  parameter_id
@col_one            -1          1
@col_two            -1          2
@col_three           2          3
@col_four            2          4
@col_five            256        5
@col_six             256        6
@col_seven           256        7

And This:

select  parm.name as parameter,    
        parm.max_length, 
        parm.parameter_id,
        typ.name as data_type, 
        typ.system_type_id, 
        typ.user_type_id,
        typ.collation_name,
        typ.is_nullable 
from    sys.procedures sp

        join sys.parameters parm ON sp.object_id = parm.object_id
        
        join sys.types typ ON parm.system_type_id = typ.system_type_id
        
where   sp.name = 'yyy_test'

order   by parm.parameter_id

Gives You This:

parameter   max_length  parameter_id    data_type   system_type_id  user_type_id    collation_name                  is_nullable
@col_one    -1          1               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_one    -1          1               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_two    -1          2               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_two    -1          2               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_three   2          3               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_three   2          3               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_four    2          4               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_four    2          4               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_five    256        5               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_five    256        5               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_six     256        6               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_six     256        6               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_seven   256        7               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_seven   256        7               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0

MVC ajax post to controller action method

It's due to you sending one object, and you're expecting two parameters.

Try this and you'll see:

public class UserDetails
{
   public string username { get; set; }
   public string password { get; set; }
}

public JsonResult Login(UserDetails data)
{
   string error = "";
   //the rest of your code
}

Why I got " cannot be resolved to a type" error?

I had my own instance of this error, and in my case none of the above solutions resolved the "cannot be resolved to a type" error by themselves, although they were necessary steps toward doing so. I found something silly that did though.

This seemed to be due a bug in Eclipse (Luna Service Release 1a (4.4.1) in my case). In the file where you're seeing the error, try saving after making and then undoing a trivial change (e.g. deleting one character and then typing it back in). For some reason this caused all my class references to resolve.

Detect all Firefox versions in JS

This script detects all versions of Firefox, for Desktop, from version 1 to 46.

It's the third time I've tried to answer this question on StackOverflow because I kept finding new ways to break my script. However, I think it's working now. It's a great exercise to learn about Firefox features and interesting to see how things have evolved. The script can be rewritten with different features, I chose ones I thought would be most useful, I would love for someone else to rewrite with other more useful features and post here, and compare results.

I placed the script in a try statement in case the user has any disabled settings in about.config. Otherwise I tested on every version of Firefox and it detects each one. I gave a brief description of what each feature is used for in the comments. I would like to do this for Webkit too but find the documentation not as good. Mozilla has easy to download previous versions and detailed releases.

_x000D_
_x000D_
// Element to display version_x000D_
var outputVersion = document.getElementById("displayFoxVersion");_x000D_
_x000D_
try {_x000D_
    // Match UserAgent string with Firefox Desktop_x000D_
    // Detect hybrid Gecko browsers and mobile_x000D_
    if (navigator.userAgent.match(/firefox/i) &&_x000D_
        !navigator.userAgent.match(/mobi|tablet|fennec|android|netscape|seamonkey|iceweasel|iceape|icecat|waterfox|gnuzilla|shadowfox|swiftfox/i)) {_x000D_
_x000D_
        // Create Element and Array to test availability  _x000D_
        var createdElement = document.createElement('div'),_x000D_
            createdArray = [],_x000D_
            firefoxVersion = "0";_x000D_
_x000D_
        // Firefox 1.0 released November 9, 2004 _x000D_
        // Check a current feature as being true, or NOT undefined _x000D_
        // AND check future features as EQUAL undefined_x000D_
        if (typeof window.alert !== "undefined" &&_x000D_
            typeof window.XPCNativeWrapper === "undefined" &&_x000D_
            typeof window.URL === "undefined") {_x000D_
            firefoxVersion = "1";_x000D_
        }_x000D_
_x000D_
        // Firefox 1.5 released October 15, 2003 _x000D_
        // XPCNativeWrapper used to create security wrapper_x000D_
        else if (typeof window.XPCNativeWrapper !== "undefined" &&_x000D_
            typeof window.globalStorage === "undefined" &&_x000D_
            typeof window.devicePixelRatio === "undefined" &&_x000D_
            typeof createdElement.style.animation === "undefined" &&_x000D_
            typeof document.querySelector === "undefined") {_x000D_
            firefoxVersion = "1.5";_x000D_
        }_x000D_
_x000D_
        // Firefox 2 released October 24, 2006_x000D_
        // globalStorage later deprecated in favor of localstorage_x000D_
        else if (typeof window.globalStorage !== "undefined" &&_x000D_
            typeof window.postMessage === "undefined") {_x000D_
            firefoxVersion = "2";_x000D_
        }_x000D_
_x000D_
        // Firefox 3 released June 17, 2008_x000D_
        // postMessage for cross window messaging_x000D_
        else if (typeof window.postMessage !== "undefined" &&_x000D_
            typeof document.querySelector === "undefined") {_x000D_
            firefoxVersion = "3";_x000D_
        }_x000D_
_x000D_
        // Firefox 3.5 released June 30, 2009_x000D_
        // querySelector returns list of the elements from document_x000D_
        else if (typeof document.querySelector !== "undefined" &&_x000D_
            typeof window.mozRequestAnimationFrame === "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "3.5";_x000D_
        }_x000D_
_x000D_
        // Firefox 4 released March 22, 2011_x000D_
        // window.URL is Gecko, Webkit is window.webkitURL, manages object URLs_x000D_
        else if (typeof window.URL !== "undefined" &&_x000D_
            typeof createdElement.style.MozAnimation === "undefined") {_x000D_
            firefoxVersion = "4";_x000D_
        }_x000D_
_x000D_
        // After April 2011 releases every six weeks on Tuesday_x000D_
_x000D_
        // Firefox 5 released June 21, 2011_x000D_
        // style.MozAnimation for CSS animation, renamed to style.animation_x000D_
        else if (typeof createdElement.style.MozAnimation !== "undefined" &&_x000D_
            typeof WeakMap === "undefined") {_x000D_
            firefoxVersion = "5";_x000D_
        }_x000D_
_x000D_
        // Firefox 6 released August 16, 2011_x000D_
        // WeakMap collects key value pairs weakly referenced_x000D_
        else if (typeof WeakMap !== "undefined" &&_x000D_
            typeof createdElement.style.textOverflow === "undefined") {_x000D_
            firefoxVersion = "6";_x000D_
        }_x000D_
_x000D_
        // Firefox 7 released September 27, 2011_x000D_
        // textOverflow manages overflowed non displayed content_x000D_
        else if (typeof createdElement.style.textOverflow !== "undefined" &&_x000D_
            typeof createdElement.insertAdjacentHTML === "undefined") {_x000D_
            firefoxVersion = "7";_x000D_
        }_x000D_
_x000D_
        // Firefox 8 released November 8, 2011_x000D_
        // insertAdjacentHTML parses as HTML and inserts into specified position_x000D_
        // faster than direct innerHTML manipulation and_x000D_
        // appends without affecting other elements under the same parent_x000D_
        else if (typeof createdElement.insertAdjacentHTML !== "undefined" &&_x000D_
            typeof navigator.doNotTrack === "undefined") {_x000D_
            firefoxVersion = "8";_x000D_
        }_x000D_
_x000D_
        // Firefox 9 released December 20, 2011_x000D_
        // mozIndexedDB dropped ver 16, renamed window.indexedDB _x000D_
        // IndexDB improved functionality than localstorage_x000D_
        else if (typeof window.mozIndexedDB !== "undefined" &&_x000D_
            typeof document.mozFullScreenEnabled === "undefined") {_x000D_
            firefoxVersion = "9";_x000D_
        }_x000D_
_x000D_
        // Firefox 10 released January 31, 2012_x000D_
        // mozFullScreenEnabled reports if full-screen mode is available_x000D_
        else if (typeof document.mozFullScreenEnabled !== "undefined" &&_x000D_
            typeof window.mozCancelAnimationFrame === "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "10";_x000D_
        }_x000D_
_x000D_
        // Firefox 11 released March 13, 2012_x000D_
        // mozCancelAnimationFrame prior to Firefox 23 prefixed with moz_x000D_
        // Cancels an animation frame request_x000D_
        else if (typeof window.mozCancelAnimationFrame !== "undefined" &&_x000D_
            typeof createdElement.style.MozTextAlignLast === "undefined") {_x000D_
            firefoxVersion = "11";_x000D_
        }_x000D_
_x000D_
        // Firefox 12 released April 24, 2012_x000D_
        // MozTextAlignLast how the last line is aligned_x000D_
        else if (typeof createdElement.style.MozTextAlignLast !== "undefined" &&_x000D_
            typeof createdElement.style.MozOpacity !== "undefined") {_x000D_
            firefoxVersion = "12";_x000D_
        }_x000D_
_x000D_
        // Firefox 13 released June 5, 2012_x000D_
        // MozOpacity dropped from this version_x000D_
        else if (typeof createdElement.style.MozOpacity === "undefined" &&_x000D_
            typeof window.globalStorage !== "undefined") {_x000D_
            firefoxVersion = "13";_x000D_
        }_x000D_
_x000D_
        // Firefox 14 released June 26, 2012_x000D_
        // globalStorage dropped from this version_x000D_
        else if (typeof window.globalStorage === "undefined" &&_x000D_
            typeof createdElement.style.borderImage === "undefined" &&_x000D_
            typeof document.querySelector !== "undefined") {_x000D_
            firefoxVersion = "14";_x000D_
        }_x000D_
_x000D_
        // Firefox 15 released August 28, 2012_x000D_
        // borderImage allows drawing an image on the borders of elements_x000D_
        else if (typeof createdElement.style.borderImage !== "undefined" &&_x000D_
            typeof createdElement.style.animation === "undefined") {_x000D_
            firefoxVersion = "15";_x000D_
        }_x000D_
_x000D_
        // Firefox 16 released October 9, 2012_x000D_
        // animation was MozAnimation_x000D_
        else if (typeof createdElement.style.animation !== "undefined" &&_x000D_
            typeof createdElement.style.iterator === "undefined" &&_x000D_
            typeof Math.hypot === "undefined") {_x000D_
            firefoxVersion = "16";_x000D_
        }_x000D_
_x000D_
        // Firefox 17 released November 20, 2012_x000D_
        // version 27 drops iterator and renames italic_x000D_
        // Used to iterate over enumerable properties of an object_x000D_
        else if (typeof createdElement.style.iterator !== "undefined" &&_x000D_
            typeof window.devicePixelRatio === "undefined") {_x000D_
            firefoxVersion = "17";_x000D_
        }_x000D_
_x000D_
        // Firefox 18 released January 8, 2013_x000D_
        // devicePixelRatio returns ratio of one vertical pixel between devices_x000D_
        else if (typeof window.devicePixelRatio !== "undefined" &&_x000D_
            typeof window.getInterface === "undefined" &&_x000D_
            typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
            firefoxVersion = "18";_x000D_
        }_x000D_
_x000D_
        // Firefox 19 released February 19, 2013_x000D_
        // getInterface dropped and renamed in version 32_x000D_
        // Retrieves specified interface pointers_x000D_
        else if (typeof window.getInterface !== "undefined" &&_x000D_
            typeof Math.imul === "undefined") {_x000D_
            firefoxVersion = "19";_x000D_
        }_x000D_
_x000D_
        // Firefox 20 released April 2, 2013_x000D_
        // Math.imul provides fast 32 bit integer multiplication_x000D_
        else if (typeof Math.imul !== "undefined" &&_x000D_
            typeof window.crypto.getRandomValues === "undefined") {_x000D_
            firefoxVersion = "20";_x000D_
        }_x000D_
_x000D_
        // Firefox 21 released May 14, 2013_x000D_
        // getRandomValues lets you get cryptographically random values_x000D_
        else if (typeof window.crypto.getRandomValues !== "undefined" &&_x000D_
            typeof createdElement.style.flex === "undefined") {_x000D_
            firefoxVersion = "21";_x000D_
        }_x000D_
_x000D_
        // Firefox 22 released June 25, 2013_x000D_
        // flex can alter dimensions to fill available space_x000D_
        else if (typeof createdElement.style.flex !== "undefined" &&_x000D_
            typeof window.cancelAnimationFrame === "undefined") {_x000D_
            firefoxVersion = "22";_x000D_
        }_x000D_
_x000D_
        // Firefox 23 released August 6, 2013_x000D_
        // cancelAnimationFrame was mozCancelAnimationFrame_x000D_
        else if (typeof window.cancelAnimationFrame !== "undefined" &&_x000D_
            typeof document.loadBindingDocument !== "undefined" &&_x000D_
            typeof Math.trunc === "undefined") {_x000D_
            firefoxVersion = "23";_x000D_
        }_x000D_
_x000D_
        // Firefox 24 released September 17, 2013_x000D_
        // loadBindingDocument dropped_x000D_
        // loadBindingDocument reintroduced in 25 then dropped again in 26 _x000D_
        else if (typeof document.loadBindingDocument === "undefined" &&_x000D_
            typeof Math.trunc === "undefined") {_x000D_
            firefoxVersion = "24";_x000D_
        }_x000D_
_x000D_
        // Firefox 25 released October 29, 2013_x000D_
        // Math.trunc returns number removing fractional digits_x000D_
        else if (typeof Math.trunc !== "undefined" &&_x000D_
            typeof document.loadBindingDocument !== "undefined") {_x000D_
            firefoxVersion = "25";_x000D_
        }_x000D_
_x000D_
        // Firefox 26 released December 10, 2013_x000D_
        // loadBindingDocument dropped_x000D_
        else if (typeof Math.trunc !== "undefined" &&_x000D_
            typeof Math.hypot === "undefined") {_x000D_
            firefoxVersion = "26";_x000D_
        }_x000D_
_x000D_
        // Firefox 27 released February 4, 2014_x000D_
        // Math.hypot returns square root of the sum of squares_x000D_
        else if (typeof Math.hypot !== "undefined" &&_x000D_
            typeof createdArray.entries === "undefined") {_x000D_
            firefoxVersion = "27";_x000D_
        }_x000D_
_x000D_
        // Firefox 28 released March 18, 2014_x000D_
        // entries returns key value pairs for arrays_x000D_
        else if (typeof createdArray.entries !== "undefined" &&_x000D_
            typeof createdElement.style.boxSizing === "undefined") {_x000D_
            firefoxVersion = "28";_x000D_
        }_x000D_
_x000D_
        // Firefox 29 released April 29, 2014_x000D_
        // boxSizing alters CSS box model, calculates width and height of elements_x000D_
        else if (typeof createdElement.style.boxSizing != "undefined" &&_x000D_
            typeof createdElement.style.backgroundBlendMode === "undefined") {_x000D_
            firefoxVersion = "29";_x000D_
        }_x000D_
_x000D_
        // Firefox 30 released June 10, 2014_x000D_
        // backgroundBlendMode blends elements background images_x000D_
        else if (typeof createdElement.style.backgroundBlendMode !== "undefined" &&_x000D_
            typeof createdElement.style.paintOrder === "undefined") {_x000D_
            firefoxVersion = "30";_x000D_
        }_x000D_
_x000D_
        // Firefox 31 released July 22, 2014_x000D_
        // paintOrder specifies the order fill, stroke, markers of shape or element_x000D_
        else if (typeof createdElement.style.paintOrder !== "undefined" &&_x000D_
            typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
            firefoxVersion = "31";_x000D_
        }_x000D_
_x000D_
        // Firefox 32 released September 2, 2014_x000D_
        // mixBlendMode how an element should blend _x000D_
        else if (typeof createdElement.style.mixBlendMode !== "undefined" &&_x000D_
            typeof Number.toInteger !== "undefined") {_x000D_
            firefoxVersion = "32";_x000D_
        }_x000D_
_x000D_
        // Firefox 33 released October 14, 2014_x000D_
        // numberToIntger dropped, used to convert values to integer_x000D_
        else if (typeof Number.toInteger === "undefined" &&_x000D_
            typeof createdElement.style.fontFeatureSettings === "undefined") {_x000D_
            firefoxVersion = "33";_x000D_
        }_x000D_
_x000D_
        // Firefox 34 released December 1, 2014_x000D_
        // fontFeatureSettings control over advanced typographic features_x000D_
        else if (typeof createdElement.style.fontFeatureSettings !== "undefined" &&_x000D_
            typeof navigator.mozIsLocallyAvailable !== "undefined") {_x000D_
            firefoxVersion = "34";_x000D_
        }_x000D_
_x000D_
        // Firefox 35 released January 13, 2015_x000D_
        // mozIsLocallyAvailable dropped_x000D_
        else if (typeof navigator.mozIsLocallyAvailable === "undefined" &&_x000D_
            typeof createdElement.style.MozWindowDragging === "undefined") {_x000D_
            firefoxVersion = "35";_x000D_
        }_x000D_
_x000D_
        // Firefox 36 released February 24, 2015_x000D_
        // quote returns a copy of the string_x000D_
        else if (typeof String.quote !== "undefined" &&_x000D_
            typeof createdElement.style.MozWindowDragging !== "undefined") {_x000D_
            firefoxVersion = "36";_x000D_
        }_x000D_
_x000D_
        // Firefox 37 released March 31, 2015_x000D_
        // quote quickly dropped_x000D_
        else if (typeof String.quote === "undefined" &&_x000D_
            typeof createdElement.style.rubyPosition === "undefined") {_x000D_
            firefoxVersion = "37";_x000D_
        }_x000D_
_x000D_
        // Firefox 38 released May 12, 2015_x000D_
        // rubyPosition defines position of a ruby element relative to its base element_x000D_
        else if (typeof createdElement.style.rubyPosition !== "undefined" &&_x000D_
            typeof window.Headers === "undefined") {_x000D_
            firefoxVersion = "38";_x000D_
        }_x000D_
_x000D_
        // Firefox 39 released July 2, 2015_x000D_
        // Headers allows us to create our own headers objects _x000D_
        else if (typeof window.Headers !== "undefined" &&_x000D_
            typeof Symbol.match === "undefined") {_x000D_
            firefoxVersion = "39";_x000D_
        }_x000D_
_x000D_
        // Firefox 40 released August 11, 2015_x000D_
        // match matches a regular expression against a string_x000D_
        else if (typeof Symbol.match !== "undefined" &&_x000D_
            typeof Symbol.species === "undefined") {_x000D_
            firefoxVersion = "40";_x000D_
        }_x000D_
_x000D_
        // Firefox 41 released September 22, 2015_x000D_
        // species allows subclasses to over ride the default constructor_x000D_
        else if (typeof Symbol.species !== "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "41";_x000D_
        }_x000D_
_x000D_
        // Firefox 42 released November 3, 2015_x000D_
        // mozRequestAnimationFrame and mozFullScreenEnabled dropped_x000D_
        // Reflect offers methods for interceptable JavaScript operations_x000D_
        else if (typeof Reflect !== "undefined" &&_x000D_
            typeof window.screen.orientation === "undefined") {_x000D_
            firefoxVersion = "42";_x000D_
        }_x000D_
_x000D_
        // Firefox 43 released December 15, 2015_x000D_
        // orientation is mozOrientation in B2G and Android_x000D_
        else if (typeof window.screen.orientation !== "undefined" &&_x000D_
            typeof document.charset === "undefined") {_x000D_
            firefoxVersion = "43";_x000D_
        }_x000D_
_x000D_
        // Firefox 44 released January 26, 2016_x000D_
        // charset is for legacy, use document.characterSet_x000D_
        else if (typeof document.charset !== "undefined" &&_x000D_
            typeof window.onstorage === "undefined") {_x000D_
            firefoxVersion = "44";_x000D_
        }_x000D_
_x000D_
        // Firefox 45 released March 8, 2016_x000D_
        // onstorage contains an event handler that runs when the storage event fires_x000D_
        else if (typeof window.onstorage !== "undefined" &&_x000D_
            typeof window.onabsolutedeviceorientation === "undefined") {_x000D_
            firefoxVersion = "45";_x000D_
        }_x000D_
_x000D_
        // Firefox 46 - beta_x000D_
        // onabsolutedeviceorientation_x000D_
        else if (typeof window.onabsolutedeviceorientation !== "undefined") {_x000D_
            firefoxVersion = "46 or above";_x000D_
        }_x000D_
_x000D_
        // Else could not verify_x000D_
        else {_x000D_
            outputVersion.innerHTML = "Could not verify Mozilla Firefox";_x000D_
        }_x000D_
_x000D_
        // Display Firefox version_x000D_
        outputVersion.innerHTML = "Verified as Mozilla Firefox " + firefoxVersion;_x000D_
_x000D_
        // Else not detected_x000D_
    } else {_x000D_
        outputVersion.innerHTML = "Mozilla Firefox not detected";_x000D_
    }_x000D_
} catch (e) {_x000D_
    // Statement to handle exceptions_x000D_
    outputVersion.innerHTML = "An error occured. This could be because the default settings in Firefox have changed. Check about.config ";_x000D_
}
_x000D_
<div id="displayFoxVersion"></div>
_x000D_
_x000D_
_x000D_

How to add 20 minutes to a current date?

Add it in milliseconds:

var currentDate = new Date();
var twentyMinutesLater = new Date(currentDate.getTime() + (20 * 60 * 1000));

How to check the version of scipy

From the python command prompt:

import scipy
print scipy.__version__

In python 3 you'll need to change it to:

print (scipy.__version__)

How to repeat last command in python interpreter shell?

You didn't specify which environment. Assuming you are using IDLE.

From IDLE documentation: Command history:

Alt-p retrieves previous command matching what you have typed.
Alt-n retrieves next.
      (These are Control-p, Control-n on the Mac)
Return while cursor is on a previous command retrieves that command.
Expand word is also useful to reduce typing.

CSS horizontal scroll

try using table structure, it's more back compatible. Check this outHorizontal Scrolling using Tables

Getting the Username from the HKEY_USERS values

  1. Open Reg HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\

  2. make a loop to get all subkeys

  3. the subkeys you are interested with are those started with [S-1-5-21-] which means user (see key name [ProfileImagePath] they are always started with a path c:\Users)

  4. Those starting with [S-1-5-21-12] are all local users

  5. Those starting with [S-1-5-21-13] are all network users [if joined to Domained network] that are previously logged on the machine.

How can I view the source code for a function?

You can also try to use print.function(), which is S3 generic, to get the function write in the console.

Resize iframe height according to content height in it

To directly answer your two subquestions: No, you cannot do this with Ajax, nor can you calculate it with PHP.

What I have done in the past is use a trigger from the iframe'd page in window.onload (NOT domready, as it can take a while for images to load) to pass the page's body height to the parent.

<body onload='parent.resizeIframe(document.body.scrollHeight)'>

Then the parent.resizeIframe looks like this:

function resizeIframe(newHeight)
{
    document.getElementById('blogIframe').style.height = parseInt(newHeight,10) + 10 + 'px';
}

Et voila, you have a robust resizer that triggers once the page is fully rendered with no nasty contentdocument vs contentWindow fiddling :)

Sure, now people will see your iframe at default height first, but this can be easily handled by hiding your iframe at first and just showing a 'loading' image. Then, when the resizeIframe function kicks in, put two extra lines in there that will hide the loading image, and show the iframe for that faux Ajax look.

Of course, this only works from the same domain, so you may want to have a proxy PHP script to embed this stuff, and once you go there, you might as well just embed your blog's RSS feed directly into your site with PHP.

Android webview slow

I think the following works best:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

Android 19 has Chromium engine for WebView. I guess it works better with hardware acceleration.

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly mscorlib

Yes, this technically can go wrong when you execute code on .NET 4.0 instead of .NET 4.5. The attribute was moved from System.Core.dll to mscorlib.dll in .NET 4.5. While that sounds like a rather nasty breaking change in a framework version that is supposed to be 100% compatible, a [TypeForwardedTo] attribute is supposed to make this difference unobservable.

As Murphy would have it, every well intended change like this has at least one failure mode that nobody thought of. This appears to go wrong when ILMerge was used to merge several assemblies into one and that tool was used incorrectly. A good feedback article that describes this breakage is here. It links to a blog post that describes the mistake. It is rather a long article, but if I interpret it correctly then the wrong ILMerge command line option causes this problem:

  /targetplatform:"v4,c:\windows\Microsoft.NET\Framework\v4.0.30319"

Which is incorrect. When you install 4.5 on the machine that builds the program then the assemblies in that directory are updated from 4.0 to 4.5 and are no longer suitable to target 4.0. Those assemblies really shouldn't be there anymore but were kept for compat reasons. The proper reference assemblies are the 4.0 reference assemblies, stored elsewhere:

  /targetplatform:"v4,C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"

So possible workarounds are to fall back to 4.0 on the build machine, install .NET 4.5 on the target machine and the real fix, to rebuild the project from the provided source code, fixing the ILMerge command.


Do note that this failure mode isn't exclusive to ILMerge, it is just a very common case. Any other scenario where these 4.5 assemblies are used as reference assemblies in a project that targets 4.0 is liable to fail the same way. Judging from other questions, another common failure mode is in build servers that were setup without using a valid VS license. And overlooking that the multi-targeting packs are a free download.

Using the reference assemblies in the c:\program files (x86) subdirectory is a rock hard requirement. Starting at .NET 4.0, already important to avoid accidentally taking a dependency on a class or method that was added in the 4.01, 4.02 and 4.03 releases. But absolutely essential now that 4.5 is released.

Converting milliseconds to a date (jQuery/JavaScript)

use datejs

new Date().toString('yyyy-MM-d-h-mm-ss');

Is it possible to change the radio button icon in an android radio button group

Here's probably a quick approach,

enter image description here

With two icons shown above, you shall have a RadioGroup something like this

enter image description here

  • change the RadioGroup's orientation to horizontal
  • for each RadioButton's Properties, try giving the icon for Button under CompoundButton,
  • adjust the Padding and size,
  • and set the Background attribute when checked.

how to download file using AngularJS and calling MVC API?

This is how I solved this problem

$scope.downloadPDF = function () {
    var link = document.createElement("a");
    link.setAttribute("href",  "path_to_pdf_file/pdf_filename.pdf");
    link.setAttribute("download", "download_name.pdf");
    document.body.appendChild(link); // Required for FF
    link.click(); // This will download the data file named "download_name.pdf"
}

How to send 500 Internal Server Error error from a PHP script

Your code should look like:

<?php
if ( that_happened ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

if ( something_else_happened ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

// Your function should return FALSE if something goes wrong
if ( !update_database() ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

// the script can also fail on the above line
// e.g. a mysql error occurred


header('HTTP/1.1 200 OK');
?>

I assume you stop execution if something goes wrong.

Android: Share plain text using intent (to all messaging apps)

This code is for sharing through sms

     String smsBody="Sms Body";
     Intent sendIntent = new Intent(Intent.ACTION_VIEW);
     sendIntent.putExtra("sms_body", smsBody);
     sendIntent.setType("vnd.android-dir/mms-sms");
     startActivity(sendIntent);

How to send JSON instead of a query string with $.ajax?

You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    complete: callback
});

Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.

Deny direct access to all .php files except index.php

An oblique answer to the question is to write all the code as classes, apart from the index.php files, which are then the only points of entry. PHP files that contain classes will not cause anything to happen, even if they are invoked directly through Apache.

A direct answer is to include the following in .htaccess:

<FilesMatch "\.php$">
    Order Allow,Deny
    Deny from all
</FilesMatch>
<FilesMatch "index[0-9]?\.php$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

This will allow any file like index.php, index2.php etc to be accessed, but will refuse access of any kind to other .php files. It will not affect other file types.

How can I generate random alphanumeric strings?

UPDATED based on comments. The original implementation generated a-h ~1.95% of the time and the remaining characters ~1.56% of the time. The update generates all characters ~1.61% of the time.

FRAMEWORK SUPPORT - .NET Core 3 (and future platforms that support .NET Standard 2.1 or above) provides a cryptographically sound method RandomNumberGenerator.GetInt32() to generate a random integer within a desired range.

Unlike some of the alternatives presented, this one is cryptographically sound.

using System;
using System.Security.Cryptography;
using System.Text;

namespace UniqueKey
{
    public class KeyGenerator
    {
        internal static readonly char[] chars =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray(); 

        public static string GetUniqueKey(int size)
        {            
            byte[] data = new byte[4*size];
            using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetBytes(data);
            }
            StringBuilder result = new StringBuilder(size);
            for (int i = 0; i < size; i++)
            {
                var rnd = BitConverter.ToUInt32(data, i * 4);
                var idx = rnd % chars.Length;

                result.Append(chars[idx]);
            }

            return result.ToString();
        }

        public static string GetUniqueKeyOriginal_BIASED(int size)
        {
            char[] chars =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            byte[] data = new byte[size];
            using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetBytes(data);
            }
            StringBuilder result = new StringBuilder(size);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }
    }
}

Based on a discussion of alternatives here and updated/modified based on the comments below.

Here's a small test harness that demonstrates the distribution of characters in the old and updated output. For a deep discussion of the analysis of randomness, check out random.org.

using System;
using System.Collections.Generic;
using System.Linq;
using UniqueKey;

namespace CryptoRNGDemo
{
    class Program
    {

        const int REPETITIONS = 1000000;
        const int KEY_SIZE = 32;

        static void Main(string[] args)
        {
            Console.WriteLine("Original BIASED implementation");
            PerformTest(REPETITIONS, KEY_SIZE, KeyGenerator.GetUniqueKeyOriginal_BIASED);

            Console.WriteLine("Updated implementation");
            PerformTest(REPETITIONS, KEY_SIZE, KeyGenerator.GetUniqueKey);
            Console.ReadKey();
        }

        static void PerformTest(int repetitions, int keySize, Func<int, string> generator)
        {
            Dictionary<char, int> counts = new Dictionary<char, int>();
            foreach (var ch in UniqueKey.KeyGenerator.chars) counts.Add(ch, 0);

            for (int i = 0; i < REPETITIONS; i++)
            {
                var key = generator(KEY_SIZE); 
                foreach (var ch in key) counts[ch]++;
            }

            int totalChars = counts.Values.Sum();
            foreach (var ch in UniqueKey.KeyGenerator.chars)
            {
                Console.WriteLine($"{ch}: {(100.0 * counts[ch] / totalChars).ToString("#.000")}%");
            }
        }
    }
}

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

Headers and client library minor version mismatch

I have this problems when use Percona/MySQL 5.6 and the php driver was compiled with 5.5 and php5-mysql is required for some apps, so I write a script to rebuild the drivers.

https://github.com/falcacibar/php5-mysql-rebuild

CronJob not running

For me, the solution was that the file cron was trying to run was in an encrypted directory, more specifcically a user diretory on /home/. Although the crontab was configured as root, because the script being run exisited in an encrypted user directory in /home/ cron could only read this directory when the user was actually logged in. To see if the directory is encrypted check if this directory exists:

/home/.ecryptfs/<yourusername>

if so then you have an encrypted home directory.

The fix for me was to move the script in to a non=encrypted directory and everythig worked fine.

How to add and get Header values in WebApi

For .NET Core:

string Token = Request.Headers["Custom"];

Or

var re = Request;
var headers = re.Headers;
string token = string.Empty;
StringValues x = default(StringValues);
if (headers.ContainsKey("Custom"))
{
   var m = headers.TryGetValue("Custom", out x);
}

Getting the error "Missing $ inserted" in LaTeX

I had the same problem - and I have read all these answers, but unfortunately none of them worked for me. Eventually I tried removing this line

%\usepackage[latin1]{inputenc}

and all errors disappeared.

Executing a shell script from a PHP script

I was struggling with this exact issue for three days. I had set permissions on the script to 755. I had been calling my script as follows.

<?php
   $outcome = shell_exec('/tmp/clearUp.sh');
   echo $outcome;
?>

My script was as follows.

#!bin/bash
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;

I was getting no output or feedback. The change I made to get the script to run was to add a cd to tmp inside the script:

#!bin/bash
cd /tmp;
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;

This was more by luck than judgement but it is now working perfectly. I hope this helps.

Initialize class fields in constructor or at declaration?

My rules:

  1. Don't initialize with the default values in declaration (null, false, 0, 0.0…).
  2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
  3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
  4. Be consistent in your practice (the most important rule).

How to push a single file in a subdirectory to Github (not master)

git status #then file which you need to push git add example.FileExtension

git commit "message is example"

git push -u origin(or whatever name you used) master(or name of some branch where you want to push it)

Fastest way to Remove Duplicate Value from a list<> by lambda

The easiest way to get a new list would be:

List<long> unique = longs.Distinct().ToList();

Is that good enough for you, or do you need to mutate the existing list? The latter is significantly more long-winded.

Note that Distinct() isn't guaranteed to preserve the original order, but in the current implementation it will - and that's the most natural implementation. See my Edulinq blog post about Distinct() for more information.

If you don't need it to be a List<long>, you could just keep it as:

IEnumerable<long> unique = longs.Distinct();

At this point it will go through the de-duping each time you iterate over unique though. Whether that's good or not will depend on your requirements.

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

Maybe not very elegant, but it does the job:

exec(open("script.py").read())

PHP, MySQL error: Column count doesn't match value count at row 1

You have 9 fields listed, but only 8 values. Try adding the method.

Find duplicate lines in a file and count how many time each line was duplicated?

Assuming there is one number per line:

sort <file> | uniq -c

You can use the more verbose --count flag too with the GNU version, e.g., on Linux:

sort <file> | uniq --count

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

How to convert AAR to JAR

As many other people have pointed out, just extracting the .jar from the .aar file doesn't quite cut it as resources may be missing.

Here are the steps that worked for me (context of Android, your mileage may vary if you have other purposes):

  1. Rename the .aar file to .zip and extract.
  2. The extracted folder is an ADT project that you can import in Eclipse with some minor modifications (see below)!
  3. In the extracted folder rename the contained file classes.jar to whatever you like (in this example myProjectLib.jar) and move it to the lib folder within the extracted folder.
  4. Now in order for Eclipse to accept it you need to put two files into the extracted folder root:
    • .project
    • .classpath
  5. To do that, create a new Android dummy project in Eclipse and copy over the files, or copy over from an existing Android project.
  6. Open the .project file and look for the XML name tag and replace the contents of it with myProjectLib (or whatever you called your jar file above) and save.
  7. Now in Eclipse you can File -> New -> Project -> Android Project from existing source.. and point to the extracted folder content.
  8. After import right click on the newly created project, select Properties -> Android, and check Is Library.
  9. In your main project that you want to use the library for, also go to Properties -> Android and add the newly added myProjectLib to the list of dependencies.

Mysql 1050 Error "Table already exists" when in fact, it does not

In my case the problem was that there was a view with the same name as my table, so I had to drop the view to allow the import to continue.

drop view `my-view-that-has-same-name-as-table`;

An automated solution that worked for me is to replace the normal drop table with this sed during the dump to also drop any views that might exist:

mysqldump my-db \
| sed -E 's/^DROP TABLE IF EXISTS(.+)$/\0 DROP VIEW IF EXISTS\1/g' \
| mysql my-other-db

Or if you would rather print to a file for backup

mysqldump my-db \
| sed -E 's/^DROP TABLE IF EXISTS(.+)$/\0 DROP VIEW IF EXISTS\1/g' \
> my-db.dump.sql

Or if you received the dumped file and you are importing it to your db

cat my-db.dump.sql \
| sed -E 's/^DROP TABLE IF EXISTS(.+)$/\0 DROP VIEW IF EXISTS\1/g' \
| mysql my-other-db

You get the idea

Note: it is important that you add the ^ at the beginning of the replacement regex, because there are other types of DROP TABLE IF EXISTS commands in dumps that you don't want to touch.

You go from having something like this:

--
-- Table structure for table `my_table`
--

DROP TABLE IF EXISTS `my_table`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `my_table` (
...

To having something like this:

--
-- Table structure for table `my_table`
--

DROP TABLE IF EXISTS `my_table`; DROP VIEW IF EXISTS `my_table`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `my_table` (
...

Visual Studio Code: format is not using indent settings

I sometimes have this same problem. VSCode will just suddenly lose it's mind and completely ignore any indentation setting I tell it, even though it's been indenting the same file just fine all day.

I have editor.tabSize set to 2 (as well as editor.formatOnSave set to true). When VSCode messes up a file, I use the options at the bottom of the editor to change indentation type and size, hoping something will work, but VSCode insists on actually using an indent size of 4.

The fix? Restart VSCode. It should come back with the indent status showing something wrong (in my case, 4). For me, I had to change the setting and then save for it to actually make the change, but that's probably because of my editor.formatOnSave setting.

I haven't figured out why it happens, but for me it's usually when I'm editing a nested object in a JS file. It will suddenly do very strange indentation within the object, even though I've been working in that file for a while and it's been indenting just fine.

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

Link to add to Google calendar

For the next person Googling this topic, I've written a small NPM package to make it simple to generate Google Calendar URLs. It includes TypeScript type definitions, for those who need that. Hope it helps!

https://www.npmjs.com/package/google-calendar-url

JBoss vs Tomcat again

First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.

Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.

How to decide whether to use Tomcat or a full stack Java EE application server:

When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:

  1. JMS messaging for asynchronous integration
  2. Web Services engine (JAX-WS and/or JAX-RS)
  3. Management capabilities like JMX and a scripted administration interface
  4. Advanced security, e.g. out-of-the-box integration with 3rd party directories
  5. EAR file instead of "only" WAR file support
  6. all the other "great" Java EE features I can't remember :-)

In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.

Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.

my 2 cent

Converting float to char*

char* str=NULL;
int len = asprintf(&str, "%g", float_var);
if (len == -1)
  fprintf(stderr, "Error converting float: %m\n");
else
  printf("float is %s\n", str);
free(str);

What is the 'override' keyword in C++ used for?

The override keyword serves two purposes:

  1. It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class."
  2. The compiler also knows that it's an override, so it can "check" that you are not altering/adding new methods that you think are overrides.

To explain the latter:

class base
{
  public:
    virtual int foo(float x) = 0; 
};


class derived: public base
{
   public:
     int foo(float x) override { ... } // OK
}

class derived2: public base
{
   public:
     int foo(int x) override { ... } // ERROR
};

In derived2 the compiler will issue an error for "changing the type". Without override, at most the compiler would give a warning for "you are hiding virtual method by same name".

Visual c++ can't open include file 'iostream'

    // first.cpp -- displays a message


#include <iostream>   // a PREPROCESSOR directive
using namesapce std;
int main()        // function header
{             // start of a function body
  ///using namespace std;
  cout << "Come up and C++ me sometime.\n";  // message
  // start a new line
  cout << "Here is the total: 1000.00\n";
  cout << "Here we go!\n";
  return 0;
}

Truncate to three decimals in Python

Maybe this way:

def myTrunc(theNumber, theDigits):

    myDigits = 10 ** theDigits
    return (int(theNumber * myDigits) / myDigits)

What is the IntelliJ shortcut key to create a javadoc comment?

Typing /** + then pressing Enter above a method signature will create Javadoc stubs for you.

onclick event function in JavaScript

One possible cause for an item not responding to an event is when the item is overlapped by another. In that case, you may have to set a higher z-index for the item you wish to click on.

How to check if a specified key exists in a given S3 bucket using Java

I also faced this problem when I used

String BaseFolder = "3patti_Logs"; 
S3Object object = s3client.getObject(bucketName, BaseFolder);
 

I got error key not found

When I hit and try

String BaseFolder = "3patti_Logs"; 
S3Object object = s3client.getObject(bucketName, BaseFolder+"/");

it worked , this code is working with 1.9 jar otherwise update to 1.11 and use doesObjectExist as said above

When & why to use delegates?

I've just go my head around these, and so I'll share an example as you already have descriptions but at the moment one advantage I see is to get around the Circular Reference style warnings where you can't have 2 projects referencing each other.

Let's assume an application downloads an XML, and then saves the XML to a database.

I have 2 projects here which build my solution: FTP and a SaveDatabase.

So, our application starts by looking for any downloads and downloading the file(s) then it calls the SaveDatabase project.

Now, our application needs to notify the FTP site when a file is saved to the database by uploading a file with Meta data (ignore why, it's a request from the owner of the FTP site). The issue is at what point and how? We need a new method called NotifyFtpComplete() but in which of our projects should it be saved too - FTP or SaveDatabase? Logically, the code should live in our FTP project. But, this would mean our NotifyFtpComplete will have to be triggered or, it will have to wait until the save is complete, and then query the database to ensure it is in there. What we need to do is tell our SaveDatabase project to call the NotifyFtpComplete() method direct but we can't; we'd get a ciruclar reference and the NotifyFtpComplete() is a private method. What a shame, this would have worked. Well, it can.

During our application's code, we would have passed parameters between methods, but what if one of those parameters was the NotifyFtpComplete method. Yup, we pass the method, with all of the code inside as well. This would mean we could execute the method at any point, from any project. Well, this is what the delegate is. This means, we can pass the NotifyFtpComplete() method as a parameter to our SaveDatabase() class. At the point it saves, it simply executes the delegate.

See if this crude example helps (pseudo code). We will also assume that the application starts with the Begin() method of the FTP class.

class FTP
{
    public void Begin()
    {
        string filePath = DownloadFileFromFtpAndReturnPathName();

        SaveDatabase sd = new SaveDatabase();
        sd.Begin(filePath, NotifyFtpComplete());
    }

    private void NotifyFtpComplete()
    {
        //Code to send file to FTP site
    }
}


class SaveDatabase
{
    private void Begin(string filePath, delegateType NotifyJobComplete())
    {
        SaveToTheDatabase(filePath);

        /* InvokeTheDelegate - 
         * here we can execute the NotifyJobComplete
         * method at our preferred moment in the application,
         * despite the method being private and belonging
         * to a different class.
         */
        NotifyJobComplete.Invoke();
    }
}

So, with that explained, we can do it for real now with this Console Application using C#

using System;

namespace ConsoleApplication1
{
    /* I've made this class private to demonstrate that 
    * the SaveToDatabase cannot have any knowledge of this Program class.
    */
    class Program
    {
        static void Main(string[] args)
        {
            //Note, this NotifyDelegate type is defined in the SaveToDatabase project
            NotifyDelegate nofityDelegate = new NotifyDelegate(NotifyIfComplete);

            SaveToDatabase sd = new SaveToDatabase();            
            sd.Start(nofityDelegate);
            Console.ReadKey();
        }

        /* this is the method which will be delegated -
         * the only thing it has in common with the NofityDelegate
         * is that it takes 0 parameters and that it returns void.
         * However, it is these 2 which are essential.
         * It is really important to notice that it writes
         * a variable which, due to no constructor,
         * has not yet been called (so _notice is not initialized yet).
         */ 
    private static void NotifyIfComplete()
    {
        Console.WriteLine(_notice);
    }

    private static string _notice = "Notified";
    }


    public class SaveToDatabase
    {
        public void Start(NotifyDelegate nd)
        {
            /* I shouldn't write to the console from here, 
             * just for demonstration purposes
             */
            Console.WriteLine("SaveToDatabase Complete");
            Console.WriteLine(" ");
            nd.Invoke();
        }
    }
    public delegate void NotifyDelegate();
}

I suggest you step through the code and see when _notice is called and when the method (delegate) is called as this, I hope, will make things very clear.

However, lastly, we can make it more useful by changing the delegate type to include a parameter.

using System.Text;

namespace ConsoleApplication1
{
    /* I've made this class private to demonstrate that the SaveToDatabase
     * cannot have any knowledge of this Program class.
     */
    class Program
    {
        static void Main(string[] args)
        {
            SaveToDatabase sd = new SaveToDatabase();
            /* Please note, that although NotifyIfComplete()
         * takes a string parameter, we do not declare it,
         * all we want to do is tell C# where the method is
         * so it can be referenced later,
         * we will pass the parameter later.
         */
            var notifyDelegateWithMessage = new NotifyDelegateWithMessage(NotifyIfComplete);

            sd.Start(notifyDelegateWithMessage );

            Console.ReadKey();
        }

        private static void NotifyIfComplete(string message)
        {
            Console.WriteLine(message);
        }
    }


    public class SaveToDatabase
    {
        public void Start(NotifyDelegateWithMessage nd)
        {
                        /* To simulate a saving fail or success, I'm just going
         * to check the current time (well, the seconds) and
         * store the value as variable.
         */
            string message = string.Empty;
            if (DateTime.Now.Second > 30)
                message = "Saved";
            else
                message = "Failed";

            //It is at this point we pass the parameter to our method.
            nd.Invoke(message);
        }
    }

    public delegate void NotifyDelegateWithMessage(string message);
}

What is the best way to merge mp3 files?

Personally I would use something like mplayer with the audio pass though option eg -oac copy

delete all from table

This should be faster:

DELETE * FROM table_name;

because RDBMS don't have to look where is what.

You should be fine with truncate though:

truncate table table_name

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

The difference between creating an array with the implicit array and the array constructor is subtle but important.

When you create an array using

var a = [];

You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.

If you use:

var a = new Array();

You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.

Take the following example:

function Array() {
    this.is = 'SPARTA';
}

var a = new Array();
var b = [];

alert(a.is);  // => 'SPARTA'
alert(b.is);  // => undefined
a.push('Woa'); // => TypeError: a.push is not a function
b.push('Woa'); // => 1 (OK)

In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as push, where the other does not.

While you may expect this to happen, it just illustrates the fact that [] is not the same as new Array().

It's probably best to just use [] if you know you just want an array. I also do not suggest going around and redefining Array...

Count number of times a date occurs and make a graph out of it

If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1) next to it and copy the formula down. This assumes you have your values in range A1:A100 and the de-duplicated values are in column B.

Transpose a data frame

Take advantage of as.matrix:

# keep the first column 
names <-  df.aree[,1]

# Transpose everything other than the first column
df.aree.T <- as.data.frame(as.matrix(t(df.aree[,-1])))

# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names

What is the parameter "next" used for in Express?

Before understanding next, you need to have a little idea of Request-Response cycle in node though not much in detail. It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World’);

let’s have a look at a very simple example.

app.get('/hello', function (req, res, next) {
  res.send('USER')
})

Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.

Now let’s take a look at another example.

app.get('/hello', function (req, res, next) {
  res.send("Hello World !!!!");
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.

But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let’s modify the above code and see what happens.

app.get('/hello', function (req, res, next) {
  if(some condition){
    next();
    return;
  }
  res.send("Hello World !!!!");  
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

What’s the next doing here. And yes you might have gusses. It’s gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!" response.

So, next pass the control to the next function in the middleware stack.

What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.

Something like below:-

app.get('/hello', function (req, res, next) {
  // Your piece of logic
  next();
});

app.get('/hello', function (req, res, next) {
  res.send("Hello !!!!");
});

In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();

What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.

Usage of MySQL's "IF EXISTS"

I found the example RichardTheKiwi quite informative.

Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...

-- what I might write in MSSQL

IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
    SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
    INSERT INTO TABLE(FieldValue) VALUES('')
    SELECT SCOPE_IDENTITY() AS TableID
END

-- rewritten for MySQL

IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
    SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
    INSERT INTO Table (FieldValue) VALUES('');
    SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;

Can you use if/else conditions in CSS?

Not in the traditional sense, but you can use classes for this, if you have access to the HTML. Consider this:

<p class="normal">Text</p>

<p class="active">Text</p>

and in your CSS file:

p.normal {
  background-position : 150px 8px;
}
p.active {
  background-position : 4px 8px;
}

That's the CSS way to do it.


Then there are CSS preprocessors like Sass. You can use conditionals there, which'd look like this:

$type: monster;
p {
  @if $type == ocean {
    color: blue;
  } @else if $type == matador {
    color: red;
  } @else if $type == monster {
    color: green;
  } @else {
    color: black;
  }
}

Disadvantages are, that you're bound to pre-process your stylesheets, and that the condition is evaluated at compile time, not run time.


A newer feature of CSS proper are custom properties (a.k.a. CSS variables). They are evaluated at run time (in browsers supporting them).

With them you could do something along the line:

:root {
  --main-bg-color: brown;
}

.one {
  background-color: var(--main-bg-color);
}

.two {
  background-color: black;
}

Finally, you can preprocess your stylesheet with your favourite server-side language. If you're using PHP, serve a style.css.php file, that looks something like this:

p {
  background-position: <?php echo (@$_GET['foo'] == 'bar')? "150" : "4"; ?>px 8px;
}

In this case, you will however have a performance impact, since caching such a stylesheet will be difficult.

Convert a python dict to a string and back

I use json:

import json

# convert to string
input = json.dumps({'id': id })

# load to dict
my_dict = json.loads(input) 

Use of 'const' for function parameters

When I coded C++ for a living I consted everything I possibly could. Using const is a great way to help the compiler help you. For instance, const-ing your method return values can save you from typos such as:

foo() = 42

when you meant:

foo() == 42

If foo() is defined to return a non-const reference:

int& foo() { /* ... */ }

The compiler will happily let you assign a value to the anonymous temporary returned by the function call. Making it const:

const int& foo() { /* ... */ }

Eliminates this possibility.

I need to round a float to two decimal places in Java

1.2975118E7 is scientific notation.

1.2975118E7 = 1.2975118 * 10^7 = 12975118

Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.

You could use String.format.

String s = String.format("%.2f", 1.2975118);
// 1.30

What is Python Whitespace and how does it work?

It acts as curly bracket. We have to keep the number of white spaces consistent through out the program.

Example 1:

def main():
     print "we are in main function"
     print "print 2nd line"

main()

Result:

We are in main function
print 2nd line

Example 2:

def main():
    print "we are in main function"
print "print 2nd line"

main()

Result:

print 2nd line
We are in main function

Here, in the 1st program, both the statement comes under the main function since both have equal number of white spaces while in the 2nd program, the 1st line is printed later because the main function is called after the 2nd line Note - The 2nd line has no white space, so it is independent of the main function.

move a virtual machine from one vCenter to another vCenter

Yes, you can do this.

  1. Copy all of the cloned VM's files from its directory, and place it on its destination datastore.
  2. In the VI client connected to the destination vCenter, go to the Inventory->Datastores view.
  3. Open the datastore browser for the datastore where you placed the VM's files.
  4. Find the .vmx file that you copied over and right-click it.
  5. Choose 'Register Virtual Machine', and follow whatever prompts ensue. (Depending on your version of vCenter, this may be 'Add to Inventory' or some other variant)

The VM registration process should finish with the cloned VM usable in the new vCenter!

Good luck!

Using Apache httpclient for https

When I used Apache HTTP Client 4.3, I was using the Pooled or Basic Connection Managers to the HTTP Client. I noticed, from using java SSL debugging, that these classes loaded the cacerts trust store and not the one I had specified programmatically.

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
builder.setConnectionManager( cm );

I wanted to use them but ended up removing them and creating an HTTP Client without them. Note that builder is an HttpClientBuilder.

I confirmed when running my program with the Java SSL debug flags, and stopped in the debugger. I used -Djavax.net.debug=ssl as a VM argument. I stopped my code in the debugger and when either of the above *ClientConnectionManager were constructed, the cacerts file would be loaded.

HTML Input Type Date, Open Calendar by default

This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.

<input type="date" data-date-inline-picker="true" />

Here is a small demo

Regex - how to match everything except a particular pattern

If you want to match a word A in a string and not to match a word B. For example: If you have a text:

1. I have a two pets - dog and a cat
2. I have a pet - dog

If you want to search for lines of text that HAVE a dog for a pet and DOESN'T have cat you can use this regular expression:

^(?=.*?\bdog\b)((?!cat).)*$

It will find only second line:

2. I have a pet - dog

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

Printing Lists as Tabular Data

When I do this, I like to have some control over the details of how the table is formatted. In particular, I want header cells to have a different format than body cells, and the table column widths to only be as wide as each one needs to be. Here's my solution:

def format_matrix(header, matrix,
                  top_format, left_format, cell_format, row_delim, col_delim):
    table = [[''] + header] + [[name] + row for name, row in zip(header, matrix)]
    table_format = [['{:^{}}'] + len(header) * [top_format]] \
                 + len(matrix) * [[left_format] + len(header) * [cell_format]]
    col_widths = [max(
                      len(format.format(cell, 0))
                      for format, cell in zip(col_format, col))
                  for col_format, col in zip(zip(*table_format), zip(*table))]
    return row_delim.join(
               col_delim.join(
                   format.format(cell, width)
                   for format, cell, width in zip(row_format, row, col_widths))
               for row_format, row in zip(table_format, table))

print format_matrix(['Man Utd', 'Man City', 'T Hotspur', 'Really Long Column'],
                    [[1, 2, 1, -1], [0, 1, 0, 5], [2, 4, 2, 2], [0, 1, 0, 6]],
                    '{:^{}}', '{:<{}}', '{:>{}.3f}', '\n', ' | ')

Here's the output:

                   | Man Utd | Man City | T Hotspur | Really Long Column
Man Utd            |   1.000 |    2.000 |     1.000 |             -1.000
Man City           |   0.000 |    1.000 |     0.000 |              5.000
T Hotspur          |   2.000 |    4.000 |     2.000 |              2.000
Really Long Column |   0.000 |    1.000 |     0.000 |              6.000

AngularJS ng-style with a conditional expression

also this syntax for ternary operator will work:

  ng-style="<$scope.var><condition> ? {
        '<css-prop-1>':((<value>) / (<value2>)*100)+'%',
        '<css-prop-2>':'<string>'
      } : {
        '<css-prop-1>':'<string>',
        '<css-prop-2>':'<string>'
      }"

where <value> are $scope property values. In example:

ng-style="column.histograms.value=>0 ? 
  {
    'width':((column.histograms.value) / (column.histograms.limit)*100)+'%',
    'background':'#F03040'
  } : {
    'width':'1px',
    'background':'#2E92FA'
  }"

```

this allows for some calculaton into the css property values.

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

There is not a single reason for this error.

  1. settings.gradle may be missing or the content in it may be wrong.
  2. local.properties may be missing or the sdk path may be wrongly written.

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

Find out the history of SQL queries

For recent SQL:

select * from v$sql

For history:

select * from dba_hist_sqltext

How print out the contents of a HashMap<String, String> in ascending order based on its values?

  1. Create a TreeMap<String,String>
  2. Add each of the HashMap entries with the value as the key.
  3. iterate the TreeMap

If the values are nonunique, you would need a list in the second position.

How to generate JAXB classes from XSD?

In intellij click .xsd file -> WebServices ->Generate Java code from Xml Schema JAXB then give package path and package name ->ok

exception in initializer error in java when using Netbeans

@Christian Ullenboom' explanation is correct.

I'm surmising that the OBD2nerForm code you posted is a static initializer block and that it is all generated. Based on that and on the stack trace, it seems likely that generated code is tripping up because it has found some component of your form that doesn't have the type that it is expecting.

I'd do the following to try and diagnose this:

  • Google for reports of similar problems with NetBeans generated forms.
  • If you are running an old version of NetBeans, scan through the "bugs fixed" pages for more recent releases. Or just upgrade try a newer release anyway to see if that fixes the problem.
  • Try cutting bits out of the form design until the problem "goes away" ... and try to figure out what the real cause is that way.
  • Run the application under a debugger to figure out what is being (incorrectly) type cast as what. Just knowing the class names may help. And looking at the instance variables of the objects may reveal more; e.g. which specific form component is causing the problem.

My suspicion is that the root cause is a combination of something a bit unusual (or incorrect) with your form design, and bugs in the NetBeans form generator that is not coping with your form. If you can figure it out, a workaround may reveal itself.

Bootstrap 3 modal responsive

From the docs:

Modals have two optional sizes, available via modifier classes to be placed on a .modal-dialog: modal-lg and modal-sm (as of 3.1).

Also the modal dialogue will scale itself on small screens (as of 3.1.1).

Turn off display errors using file "php.ini"

In file php.ini you should try this for all errors:

error_reporting = off

Ansible - Save registered variable to file

More readable way of achieving this (not a fan of single line ansible tasks)

- local_action: 
    module: copy 
    content: "{{ foo_result }}"
    dest: /path/to/destination/file

How to add a search box with icon to the navbar in Bootstrap 3?

This one I implemented for my website , If some one got more no's of menu item and longer search bar can use this

enter image description here

enter image description here

Here is the code

       <style>
        .navbar-inverse .navbar-nav > li > a {
            color: white !important;
        }

            .navbar-inverse .navbar-nav > li > a:hover {
                text-decoration: underline;
            }

        .navbar-collapse ul li {
            padding-top: 0px;
            padding-bottom: 0px;
        }

            .navbar-collapse ul li a {
                padding-top: 0px;
                padding-bottom: 0px;
            }

        .navbar-brand img {
            width: 200px;
            height: 40px;
        }

        .navbar-inverse {
            background-color: #3A1B37;
        }
    </style>
   <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" runat="server" href="~/">
                    <img src="http://placehold.it/200x40/3A1B37/ffffff/?text=Apllicatin"></a>
                <div class="col-md-6 col-sm-8 col-xs-11 navbar-left">
                    <div class="navbar-form " role="search">
                        <div class="input-group">
                            <input type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term" style="max-width: 100%; width: 100%;">
                            <div class="input-group-btn">
                                <button class="btn btn-default" style="background: rgb(72, 166, 72);" type="submit"><i class="glyphicon glyphicon-search"></i></button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li class="navbar-brand  visible-md visible-lg visible-sm" style="visibility: hidden;" runat="server">
                        <img src="http://placehold.it/200x40/3A1B37/ffffff/?text=Apllicatin" />
                    </li>
                    <li><a runat="server" href="~/">Home</a></li>
                    <li><a runat="server" href="~/About">About</a></li>
                    <li><a runat="server" href="~/Contact">Contact</a></li>
                    <li><a runat="server" href="~/">Somthing</a></li>
                    <li><a runat="server" href="~/">Somthing</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                    <li><a runat="server" href="~/Account/Register">Register</a></li>
                    <li><a runat="server" href="~/Account/Login">Log in</a></li>
                </ul> </div>

        </div>
    </div>

Good Patterns For VBA Error Handling

The code below shows an alternative that ensures there is only one exit point for the sub/function.

sub something()
    on error goto errHandler

    ' start of code
    ....
    ....
    'end of code

    ' 1. not needed but signals to any other developer that looks at this
    ' code that you are skipping over the error handler...
    ' see point 1...
    err.clear

errHandler:
    if err.number <> 0 then
        ' error handling code
    end if
end sub

Angular ui-grid dynamically calculate height of the grid

UPDATE:

The HTML was requested so I've pasted it below.

<div ui-grid="gridOptions" class="my-grid"></div>

ORIGINAL:

We were able to adequately solve this problem by using responsive CSS (@media) that sets the height and width based on screen real estate. Something like (and clearly you can add more based on your needs):

@media (min-width: 1024px) {
  .my-grid {
    width: 772px;
  }
}

@media (min-width: 1280px) {
  .my-grid {
    width: 972px;
  }
}

@media (min-height: 768px) {
  .my-grid {
    height: 480px;
  }
}

@media (min-height: 900px) {
  .my-grid {
    height: 615px;
  }
}

The best part about this solution is that we need no resize event handling to monitor for grid size changes. It just works.

How do I clear the content of a div using JavaScript?

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
    div.removeChild(div.firstChild);
}

Difference between Divide and Conquer Algo and Dynamic Programming

I think of Divide & Conquer as an recursive approach and Dynamic Programming as table filling.

For example, Merge Sort is a Divide & Conquer algorithm, as in each step, you split the array into two halves, recursively call Merge Sort upon the two halves and then merge them.

Knapsack is a Dynamic Programming algorithm as you are filling a table representing optimal solutions to subproblems of the overall knapsack. Each entry in the table corresponds to the maximum value you can carry in a bag of weight w given items 1-j.

Is it possible to program iPhone in C++

I use Objective-C to slap the UI together.
But the hard guts of the code is still written in C++.

That is the main purpose of Objective-C the UI interface and handling the events.
And it works great for that purpose.

I still like C++ as the backend for the code though (but that's mainly becuase I like C++) you could quite easily use Objective-C for the backend of the application as well.

What is InputStream & Output Stream? Why and when do we use them?

The goal of InputStream and OutputStream is to abstract different ways to input and output: whether the stream is a file, a web page, or the screen shouldn't matter. All that matters is that you receive information from the stream (or send information into that stream.)

InputStream is used for many things that you read from.

OutputStream is used for many things that you write to.

Here's some sample code. It assumes the InputStream instr and OutputStream osstr have already been created:

int i;

while ((i = instr.read()) != -1) {
    osstr.write(i);
}

instr.close();
osstr.close();

Scraping data from website using vba

There are several ways of doing this. This is an answer that I write hoping that all the basics of Internet Explorer automation will be found when browsing for the keywords "scraping data from website", but remember that nothing's worth as your own research (if you don't want to stick to pre-written codes that you're not able to customize).

Please note that this is one way, that I don't prefer in terms of performance (since it depends on the browser speed) but that is good to understand the rationale behind Internet automation.

1) If I need to browse the web, I need a browser! So I create an Internet Explorer browser:

Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")

2) I ask the browser to browse the target webpage. Through the use of the property ".Visible", I decide if I want to see the browser doing its job or not. When building the code is nice to have Visible = True, but when the code is working for scraping data is nice not to see it everytime so Visible = False.

With appIE
    .Navigate "http://uk.investing.com/rates-bonds/financial-futures"
    .Visible = True
End With

3) The webpage will need some time to load. So, I will wait meanwhile it's busy...

Do While appIE.Busy
    DoEvents
Loop

4) Well, now the page is loaded. Let's say that I want to scrape the change of the US30Y T-Bond: What I will do is just clicking F12 on Internet Explorer to see the webpage's code, and hence using the pointer (in red circle) I will click on the element that I want to scrape to see how can I reach my purpose.

enter image description here

5) What I should do is straight-forward. First of all, I will get by the ID property the tr element which is containing the value:

Set allRowOfData = appIE.document.getElementById("pair_8907")

Here I will get a collection of td elements (specifically, tr is a row of data, and the td are its cells. We are looking for the 8th, so I will write:

Dim myValue As String: myValue = allRowOfData.Cells(7).innerHTML

Why did I write 7 instead of 8? Because the collections of cells starts from 0, so the index of the 8th element is 7 (8-1). Shortly analysing this line of code:

  • .Cells() makes me access the td elements;
  • innerHTML is the property of the cell containing the value we look for.

Once we have our value, which is now stored into the myValue variable, we can just close the IE browser and releasing the memory by setting it to Nothing:

appIE.Quit
Set appIE = Nothing

Well, now you have your value and you can do whatever you want with it: put it into a cell (Range("A1").Value = myValue), or into a label of a form (Me.label1.Text = myValue).

I'd just like to point you out that this is not how StackOverflow works: here you post questions about specific coding problems, but you should make your own search first. The reason why I'm answering a question which is not showing too much research effort is just that I see it asked several times and, back to the time when I learned how to do this, I remember that I would have liked having some better support to get started with. So I hope that this answer, which is just a "study input" and not at all the best/most complete solution, can be a support for next user having your same problem. Because I have learned how to program thanks to this community, and I like to think that you and other beginners might use my input to discover the beautiful world of programming.

Enjoy your practice ;)

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

Just import tensortflow and use keras, it's that easy.

import tensorflow as tf
# your code here
with tf.device('/gpu:0'):
    model.fit(X, y, epochs=20, batch_size=128, callbacks=callbacks_list)

Reverse engineering from an APK file to a project

There are two useful tools which will generate Java code (rough but good enough) from an unknown APK file.

  1. Download dex2jar tool from dex2jar.
  2. Use the tool to convert the APK file to JAR:

    $ d2j-dex2jar.bat demo.apk
    dex2jar demo.apk -> ./demo-dex2jar.jar
    
  3. Once the JAR file is generated, use JD-GUI to open the JAR file. You will see the Java files.

The output will be similar to:

JD GUI

Display date in dd/mm/yyyy format in vb.net

Dim formattedDate As String = Date.Today.ToString("dd/MM/yyyy")

Check link below

Force index use in Oracle

You can use:

WITH index = ...

more info

Print out the values of a (Mat) matrix in OpenCV C++

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
    Mat src = Mat(1, 4, CV_64F, &data);
    for(int i=0; i<4; i++)
        cout << setprecision(3) << src.at<double>(0,i) << endl;

    return 0;
}

Javascript: How to pass a function with string parameters as a parameter to another function

Try this:

onclick="myfunction(
    '/myController/myAction',
    function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
    function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"

Then you just need to call these two functions passed to myfunction:

function myfunction(url, f1, f2) {
    // …
    f1();
    f2();
}

batch file - counting number of files in folder and storing in a variable

I'm going to assume you do not want to count hidden or system files.

There are many ways to do this. All of the methods that I will show involve some form of the FOR command. There are many variations of the FOR command that look almost the same, but they behave very differently. It can be confusing for a beginner.

You can get help by typing HELP FOR or FOR /? from the command line. But that help is a bit cryptic if you are not used to reading it.

1) The DIR command lists the number of files in the directory. You can pipe the results of DIR to FIND to get the relevant line and then use FOR /F to parse the desired value from the line. The problem with this technique is the string you search for has to change depending on the language used by the operating system.

@echo off
for /f %%A in ('dir ^| find "File(s)"') do set cnt=%%A
echo File count = %cnt%

2) You can use DIR /B /A-D-H-S to list the non-hidden/non-system files without other info, pipe the result to FIND to count the number of files, and use FOR /F to read the result.

@echo off
for /f %%A in ('dir /a-d-s-h /b ^| find /v /c ""') do set cnt=%%A
echo File count = %cnt%

3) You can use a simple FOR to enumerate all the files and SET /A to increment a counter for each file found.

@echo off
set cnt=0
for %%A in (*) do set /a cnt+=1
echo File count = %cnt%

TypeError: 'str' object is not callable (Python)

It is important to note (in case you came here by Google) that "TypeError: 'str' object is not callable" means only that a variable that was declared as String-type earlier is attempted to be used as a function (e.g. by adding parantheses in the end.)

You can get the exact same error message also, if you use any other built-in method as variable name.

How to open a website when a Button is clicked in Android application?

Import import android.net.Uri;

Intent openURL = new Intent(android.content.Intent.ACTION_VIEW);
openURL.setData(Uri.parse("http://www.example.com"));
startActivity(openURL);

or it can be done using,

TextView textView = (TextView)findViewById(R.id.yourID);

textView.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse("http://www.typeyourURL.com"));
        startActivity(intent);
    } });

Java Look and Feel (L&F)

You can try L&F which i am developing - WebLaF
It combines three parts required for successful UI development:

  • Cross-platform re-stylable L&F for Swing applications
  • Large set of extended Swing components
  • Various utilities and managers

Binaries: https://github.com/mgarin/weblaf/releases
Source: https://github.com/mgarin/weblaf
Licenses: GPLv3 and Commercial

A few examples showing how some of WebLaF components look like: Some of WebLaF components

Main reason why i have started with a totally new L&F is that most of existing L&F lack flexibility - you cannot re-style them in most cases (you can only change a few colors and turn on/off some UI elements in best case) and/or there are only inconvenient ways to do that. Its even worse when it comes to custom/3rd party components styling - they doesn't look similar to other components styled by some specific L&F or even totally different - that makes your application look unprofessional and unpleasant.

My goal is to provide a fully customizable L&F with a pack of additional widely-known and useful components (for example: date chooser, tree table, dockable and document panes and lots of other) and additional helpful managers and utilities, which will reduce the amount of code required to quickly integrate WebLaF into your application and help creating awesome UIs using Swing.

jQuery - select the associated label element of a input field

There are two ways to specify label for element:

  1. Setting label's "for" attribute to element's id
  2. Placing element inside label

So, the proper way to find element's label is

   var $element = $( ... )

   var $label = $("label[for='"+$element.attr('id')+"']")
   if ($label.length == 0) {
     $label = $element.closest('label')
   }

   if ($label.length == 0) {
     // label wasn't found
   } else {
     // label was found
   }

for or while loop to do something n times

The fundamental difference in most programming languages is that unless the unexpected happens a for loop will always repeat n times or until a break statement, (which may be conditional), is met then finish with a while loop it may repeat 0 times, 1, more or even forever, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while loop, (or repeat until), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).

It is worth noting that in Python a for or while statement can have break, continue and else statements where:

  • break - terminates the loop
  • continue - moves on to the next time around the loop without executing following code this time around
  • else - is executed if the loop completed without any break statements being executed.

N.B. In the now unsupported Python 2 range produced a list of integers but you could use xrange to use an iterator. In Python 3 range returns an iterator.

So the answer to your question is 'it all depends on what you are trying to do'!

How to measure elapsed time in Python?

on python3:

from time import sleep, perf_counter as pc
t0 = pc()
sleep(1)
print(pc()-t0)

elegant and short.

How can I check if an element exists in the visible DOM?

this condition chick all cases.

_x000D_
_x000D_
function del() {_x000D_
//chick if dom has this element _x000D_
//if not true condition means null or undifind or false ._x000D_
_x000D_
if (!document.querySelector("#ul_list ")===true){_x000D_
_x000D_
// msg to user_x000D_
    alert("click btn load ");_x000D_
_x000D_
// if console chick for you and show null clear console._x000D_
    console.clear();_x000D_
_x000D_
// the function will stop._x000D_
    return false;_x000D_
}_x000D_
_x000D_
// if its true function will log delet ._x000D_
console.log("delet");_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

How can I mock an ES6 module import using Jest?

To mock an ES6 dependency module default export using Jest:

import myModule from '../myModule';
import dependency from '../dependency';

jest.mock('../dependency');

// If necessary, you can place a mock implementation like this:
dependency.mockImplementation(() => 42);

describe('myModule', () => {
  it('calls the dependency once with double the input', () => {
    myModule(2);

    expect(dependency).toHaveBeenCalledTimes(1);
    expect(dependency).toHaveBeenCalledWith(4);
  });
});

The other options didn't work for my case.

how to declare global variable in SQL Server..?

My first question is which version of SQL Server are you using (i.e 2005, 2008, 2008 R2, 2012)?

Assuming you are using 2008 or later SQL uses scope for variable determination. I believe 2005 still had global variables that would use @@variablename instead of @variable name which would define the difference between global and local variables. Starting in 2008 I believe this was changed to a scope defined variable designation structure. For example to create a global variable the @variable has to be defined at the start of a procedure, function, view, etc. In 2008 and later @@defined system variables for system functions I do believe. I could explain further if you explained the version and also where the variable is being defined, and the error that you are getting.

SSRS the definition of the report is invalid

The report definition is not valid or supported by this version of Reporting Services. This could be the result of publishing a report definition of a later version of Reporting Services, or that the report definition contains XML that is not well-formed or the XML is not valid based on the Report Definition schema.

I got this error when I used ReportSync to upload some .rdl files to SQL Server Report Services. In my case, the issue was that these .rdl files had some Text Box containing characters like ©, (Em dash), (En dash) characters, etc. When uploading .rdl files using ReportSync, I had to encode these characters (&copy;, &mdash;, &ndash;, etc.) and use Placeholder Properties to set the Markup type to HTML in order to get rid of this error.

I wouldn't get this error If I manually uploaded each of the .rdl files one-by-one using SQL Server Reporting Services. But I have a lot of .rdl files and uploading each one individually would be time-consuming, which is why I use ReportSync to mass upload all .rdl files.

Sorry, if my answer doesn't seem relevant, but I hope this helps anyone else getting this error message when dealing with SSRS .rdl files.

Does Index of Array Exist

// I'd modify this slightly to be more resilient to a bad parameter
// it will handle your case and better handle other cases given to it:

int index = 25;

if (index >= 0 && index < array.Length)
{
    // Array element found
}

Finding the index of elements based on a condition using python list comprehension

Maybe another question is, "what are you going to do with those indices once you get them?" If you are going to use them to create another list, then in Python, they are an unnecessary middle step. If you want all the values that match a given condition, just use the builtin filter:

matchingVals = filter(lambda x : x>2, a)

Or write your own list comprhension:

matchingVals = [x for x in a if x > 2]

If you want to remove them from the list, then the Pythonic way is not to necessarily remove from the list, but write a list comprehension as if you were creating a new list, and assigning back in-place using the listvar[:] on the left-hand-side:

a[:] = [x for x in a if x <= 2]

Matlab supplies find because its array-centric model works by selecting items using their array indices. You can do this in Python, certainly, but the more Pythonic way is using iterators and generators, as already mentioned by @EliBendersky.

How do I negate a condition in PowerShell?

if you don't like the double brackets or you don't want to write a function, you can just use a variable.

$path = Test-Path C:\Code
if (!$path) {
    write "it doesn't exist!"
}

Is there a command line command for verifying what version of .NET is installed

REM Search for the CONFIG file, if this doesn't exit then the user doesn't have the .Net framework 2.0 `

SET FileName=%windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG
IF EXIST %FileName% GOTO INSTALL_DIALER
ECHO.You currently do not have the Microsoft(c) .NET Framework 2.0 installed.

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

MySQL JDBC Driver 5.1.33 - Time Zone Issue

I also got the same running java JDBC in NetBeans. This is how it fixed

I use Xampp. In conf button of Apache I opened httpd.conf file and on first line I typed

# Set timezone to Europe/Athens UTC+02:00 
SetEnv TZ Europe/Athens.

In conf button of MySQL I opened my.ini file and on last line I typed "Europe/Athens"

Stopped and started both Apache and MySQL

Problem fixed.

*(Local mechine time zone is different, but no problem.)

org.hibernate.MappingException: Could not determine type for: java.util.Set

You may just need to add @Transient annotations on roles to not serialize the set.

Why does Java have transient fields?

Find the item with maximum occurrences in a list

Simple and best code:

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

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

Output: 4 occurs 6 times

Using context in a fragment

getActivity() is a child of Context so that should work for you

Array vs ArrayList in performance

I agree with somebody's recently deleted post that the differences in performance are so small that, with very very few exceptions, (he got dinged for saying never) you should not make your design decision based upon that.

In your example, where the elements are Objects, the performance difference should be minimal.

If you are dealing with a large number of primitives, an array will offer significantly better performance, both in memory and time.

Resizing SVG in html?

Use the following code:

<g transform="scale(0.1)">
...
</g>

Running an outside program (executable) in Python?

Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/') followed by relative paths for os.system, subprocess methods, or whatever...

If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial .exe file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?

Is there a limit to the length of a GET request?

This article sums it up pretty well

Summary: It's implementation dependent, as there is no specified limit in the RFC. It'd be safe to use up to 2000 characters (IE's limit.) If you are anywhere near this length, you should make sure you really need URIs that long, maybe an alternative design could get around that.

URIs should be readable, even when used to send data.

How to pass multiple parameters in json format to a web service using jquery?

Found the solution:

It should be:

"{'Id1':'2','Id2':'2'}"

and not

"{'Id1':'2'},{'Id2':'2'}"

Handling very large numbers in Python

python supports arbitrarily large integers naturally:

In [1]: 59**3*61**4*2*3*5*7*3*5*7
Out[1]: 62702371781194950
In [2]: _ % 61**4
Out[2]: 0

Structs data type in php?

I recommend 2 things. First is associative array.

$person = Array();
$person['name'] = "Joe";
$person['age'] = 22;

Second is classes.

Detailed documentation here: http://php.net/manual/en/language.oop5.php

Getting request payload from POST request in Java servlet

String payloadRequest = getBody(request);

Using this method

public static String getBody(HttpServletRequest request) throws IOException {

    String body = null;
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;

    try {
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } else {
            stringBuilder.append("");
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw ex;
            }
        }
    }

    body = stringBuilder.toString();
    return body;
}

Is it possible to read the value of a annotation in java?

I've never done it, but it looks like Reflection provides this. Field is an AnnotatedElement and so it has getAnnotation. This page has an example (copied below); quite straightforward if you know the class of the annotation and if the annotation policy retains the annotation at runtime. Naturally if the retention policy doesn't keep the annotation at runtime, you won't be able to query it at runtime.

An answer that's since been deleted (?) provided a useful link to an annotations tutorial that you may find helpful; I've copied the link here so people can use it.

Example from this page:

import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

class Meta {
  @MyAnno(str = "Two Parameters", val = 19)
  public static void myMeth(String str, int i) {
    Meta ob = new Meta();

    try {
      Class c = ob.getClass();

      Method m = c.getMethod("myMeth", String.class, int.class);

      MyAnno anno = m.getAnnotation(MyAnno.class);

      System.out.println(anno.str() + " " + anno.val());
    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }

  public static void main(String args[]) {
    myMeth("test", 10);
  }
}

How to revert a "git rm -r ."?

undo git rm

git rm file             # delete file & update index
git checkout HEAD file  # restore file & index from HEAD

undo git rm -r

git rm -r dir          # delete tracked files in dir & update index
git checkout HEAD dir  # restore file & index from HEAD

undo git rm -rf

git rm -r dir          # delete tracked files & delete uncommitted changes
not possible           # `uncommitted changes` can not be restored.

Uncommitted changes includes not staged changes, staged changes but not committed.

Python-equivalent of short-form "if" in C++

My cryptic version...

a = ['123', '456'][b == True]

When to catch java.lang.Error?

An Error usually shouldn't be caught, as it indicates an abnormal condition that should never occur.

From the Java API Specification for the Error class:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. [...]

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

As the specification mentions, an Error is only thrown in circumstances that are Chances are, when an Error occurs, there is very little the application can do, and in some circumstances, the Java Virtual Machine itself may be in an unstable state (such as VirtualMachineError)

Although an Error is a subclass of Throwable which means that it can be caught by a try-catch clause, but it probably isn't really needed, as the application will be in an abnormal state when an Error is thrown by the JVM.

There's also a short section on this topic in Section 11.5 The Exception Hierarchy of the Java Language Specification, 2nd Edition.

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

How to compile the finished C# project and then run outside Visual Studio?

Compile the Release version as .exe file, then just copy onto a machine with a suitable version of .NET Framework installed and run it there. The .exe file is located in the bin\Release subfolder of the project folder.

Format a JavaScript string using placeholders and an object of substitutions?

As a quick example:

var name = 'jack';
var age = 40;
console.log('%s is %d yrs old',name,age);

The output is:

jack is 40 yrs old

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

Why is an OPTIONS request sent and can I disable it?

After spending a whole day and a half trying to work through a similar problem I found it had to do with IIS.

My Web API project was set up as follows:

// WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);
    //...
}

I did not have CORS specific config options in the web.config > system.webServer node like I have seen in so many posts

No CORS specific code in the global.asax or in the controller as a decorator

The problem was the app pool settings.

The managed pipeline mode was set to classic (changed it to integrated) and the Identity was set to Network Service (changed it to ApplicationPoolIdentity)

Changing those settings (and refreshing the app pool) fixed it for me.

Android - Pulling SQlite database android device

For Ubuntu (not only?):

see Sergeis Answer but instead of openssl use zlib-flate:

cat appbackup.ab | (dd bs=24 count=0 skip=1; cat) | zlib-flate -uncompress > appbackup.tar

Otherwise openssl will probably throw:

openssl:Error: 'zlib' is an invalid command.

because openssl is not compiled with zlib support in Ubuntu

Angular File Upload

Here is a working example for file upload to api:

Step 1: HTML Template (file-upload.component.html)

Define simple input tag of type file. Add a function to (change)-event for handling choosing files.

<div class="form-group">
    <label for="file">Choose File</label>
    <input type="file"
           id="file"
           (change)="handleFileInput($event.target.files)">
</div>

Step 2: Upload Handling in TypeScript (file-upload.component.ts)

Define a default variable for selected file.

fileToUpload: File = null;

Create function which you use in (change)-event of your file input tag:

handleFileInput(files: FileList) {
    this.fileToUpload = files.item(0);
}

If you want to handle multifile selection, than you can iterate through this files array.

Now create file upload function by calling you file-upload.service:

uploadFileToActivity() {
    this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
      // do something, if upload success
      }, error => {
        console.log(error);
      });
  }

Step 3: File-Upload Service (file-upload.service.ts)

By uploading a file via POST-method you should use FormData, because so you can add file to http request.

postFile(fileToUpload: File): Observable<boolean> {
    const endpoint = 'your-destination-url';
    const formData: FormData = new FormData();
    formData.append('fileKey', fileToUpload, fileToUpload.name);
    return this.httpClient
      .post(endpoint, formData, { headers: yourHeadersConfig })
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

So, This is very simple working example, which I use everyday in my work.

Gradle to execute Java class (without modifying build.gradle)

There is no direct equivalent to mvn exec:java in gradle, you need to either apply the application plugin or have a JavaExec task.

application plugin

Activate the plugin:

plugins {
    id 'application'
    ...
}

Configure it as follows:

application {
    mainClassName = project.hasProperty("mainClass") ? getProperty("mainClass") : "NULL"
}

On the command line, write

$ gradle -PmainClass=Boo run

JavaExec task

Define a task, let's say execute:

task execute(type:JavaExec) {
   main = project.hasProperty("mainClass") ? getProperty("mainClass") : "NULL"
   classpath = sourceSets.main.runtimeClasspath
}

To run, write gradle -PmainClass=Boo execute. You get

$ gradle -PmainClass=Boo execute
:compileJava
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes
:execute
I am BOO!

mainClass is a property passed in dynamically at command line. classpath is set to pickup the latest classes.


If you do not pass in the mainClass property, both of the approaches fail as expected.

$ gradle execute

FAILURE: Build failed with an exception.

* Where:
Build file 'xxxx/build.gradle' line: 4

* What went wrong:
A problem occurred evaluating root project 'Foo'.
> Could not find property 'mainClass' on task ':execute'.

std::cin input with spaces?

I rather use the following method to get the input:

#include <iostream>
#include <string>

using namespace std;

int main(void) {
    string name;

    cout << "Hello, Input your name please: ";
    getline(cin, name);

    return 0;
}

It's actually super easy to use rather than defining the total length of array for a string which contains a space character.

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

_x000D_
_x000D_
<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
_x000D_
_x000D_

UIScrollView Scrollable Content Size Ambiguity

I think it is a 10 second work from now. I observed it in XCode 7.3 and made a video on it. Check here:

https://www.youtube.com/watch?v=yETZKqdaPiI

All you have to do, add a subview to UIScrollView with same width and height. Then select ViewController and press Reset to suggested constraint. Please check video for clear understanding.

Thanks

What are the differences between "=" and "<-" assignment operators in R?

The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:

median(x = 1:10)
x   
## Error: object 'x' not found

In this case, x is declared within the scope of the function, so it does not exist in the user workspace.

median(x <- 1:10)
x    
## [1]  1  2  3  4  5  6  7  8  9 10

In this case, x is declared in the user workspace, so you can use it after the function call has been completed.


There is a general preference among the R community for using <- for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like

x<-3
# Does this mean assignment?
x <- 3
# Or less than?
x < -3

Most R IDEs have keyboard shortcuts to make <- easier to type. Ctrl + = in Architect, Alt + - in RStudio (Option + - under macOS), Shift + - (underscore) in emacs+ESS.


If you prefer writing = to <- but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_* functions in the formatR package to automatically replace = with <-.

library(formatR)
tidy_source(text = "x=1:5", arrow = TRUE)
## x <- 1:5

The answer to the question "Why does x <- y = 5 throw an error but not x <- y <- 5?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether = or <- was used.

To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3).

Secondly, it's clearer if we use prefix notation for assignment. So

x <- 5
`<-`(x, 5)  #same thing

y = 5
`=`(y, 5)   #also the same thing

The parser interprets x <- y <- 5 as

`<-`(x, `<-`(y, 5))

We might expect that x <- y = 5 would then be

`<-`(x, `=`(y, 5))

but actually it gets interpreted as

`=`(`<-`(x, y), 5)

This is because = is lower precedence than <-, as shown on the ?Syntax help page.

Turn off warnings and errors on PHP and MySQL

Prepend functions with the '@' symbol to suppress certain errors, as opposed to turning off all error reporting.

More information: http://php.net/manual/en/language.operators.errorcontrol.php

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

@fsockopen();

app-release-unsigned.apk is not signed

If anyone wants to debug and release separate build variant using Android Studio 3.5, follow the below steps: 1. Set build variant to release mode.

Build Variant

  1. Go to File >> Project Structure
  2. Select Modules, then Signing Config
  3. Click in the Plus icon under Signing Config

Signing Config

  1. Select release section and Provide your release App Information then Apply and OK.

signin

  1. Go to your app level build.gradle and change your buildTypes > "release" section like below Screenshot.

final

Then Run your Project. Happy Coding.

Get the current time in C

You can use this function to get current local time. if you want gmt then use the gmtime function instead of localtime. cheers

time_t my_time;
struct tm * timeinfo; 
time (&my_time);
timeinfo = localtime (&my_time);
CCLog("year->%d",timeinfo->tm_year+1900);
CCLog("month->%d",timeinfo->tm_mon+1);
CCLog("date->%d",timeinfo->tm_mday);
CCLog("hour->%d",timeinfo->tm_hour);
CCLog("minutes->%d",timeinfo->tm_min);
CCLog("seconds->%d",timeinfo->tm_sec);

Listing all permutations of a string/integer

Here is the function which will print all permutaion. This function implements logic Explained by peter.

public class Permutation
{
    //http://www.java2s.com/Tutorial/Java/0100__Class-Definition/RecursivemethodtofindallpermutationsofaString.htm

    public static void permuteString(String beginningString, String endingString)
    {           

        if (endingString.Length <= 1)
            Console.WriteLine(beginningString + endingString);
        else
            for (int i = 0; i < endingString.Length; i++)
            {

                String newString = endingString.Substring(0, i) + endingString.Substring(i + 1);

                permuteString(beginningString + endingString.ElementAt(i), newString);

            }
    }
}

    static void Main(string[] args)
    {

        Permutation.permuteString(String.Empty, "abc");
        Console.ReadLine();

    }

How can I replace a newline (\n) using sed?

A solution I particularly like is to append all the file in the hold space and replace all newlines at the end of file:

$ (echo foo; echo bar) | sed -n 'H;${x;s/\n//g;p;}'
foobar

However, someone said me the hold space can be finite in some sed implementations.

How to cd into a directory with space in the name?

SOLUTION:

cd "Documents and Photos"

problem solved.

The reason I'm submitting this answer is you'll find that StackOverflow is being used by every day users (not just web devs, programmers or power users) and this was the number one result for a simple Windows user question on Google.

People are becoming more tech-savvy, but aren't necessarily familiar with command line in the cases above.

Can I do Model->where('id', ARRAY) multiple where conditions?

You can use whereIn which accepts an array as second paramter.

DB:table('table')
   ->whereIn('column', [value, value, value])
   ->get()

You can chain where multiple times.

DB:table('table')->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->get();

This will use AND operator. if you need OR you can use orWhere method.

For advanced where statements

DB::table('table')
    ->where('column', 'operator', 'value')
    ->orWhere(function($query)
    {
        $query->where('column', 'operator', 'value')
            ->where('column', 'operator', 'value');
    })
    ->get();

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}