Programs & Examples On #Ksoap

kSOAP is a SOAP web service client library for constrained Java environments such as Applets or J2ME applications.

How to call a .NET Webservice from Android using KSOAP2?

You can Use below code to call the web service and get response .Make sure that your Web Service return the response in Data Table Format..This code help you if you using data from SQL Server database .If you you using MYSQL you need to change one thing just replace word NewDataSet from sentence obj2=(SoapObject) obj1.getProperty("NewDataSet"); by DocumentElement

private static final String NAMESPACE = "";
private static final String URL = "http://localhost/Web_Service.asmx?"; // you can use   IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("parm_name", prm_value); // Parameter for Method
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try {, envelope); //call the eb service Method
} catch (Exception e) {
} //Next task is to get Response and format that response

SoapObject obj, obj1, obj2, obj3;
obj = (SoapObject) envelope.getResponse();
obj1 = (SoapObject) obj.getProperty("diffgram");
obj2 = (SoapObject) obj1.getProperty("NewDataSet");

for (int i = 0; i < obj2.getPropertyCount(); i++) //the method getPropertyCount() return the number of rows
    obj3 = (SoapObject) obj2.getProperty(i);
    obj3.getProperty(0).toString(); //value of column 1
    obj3.getProperty(1).toString(); //value of column 2
    //like that you will get value from each column

If you have any problem regarding this you can write me..

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

In my case I created a database and gave the collation 'utf8_general_ci' but the required collation was 'latin1'. After changing my collation type to latin1_bin the error was gone.

How do I concatenate two arrays in C#?

I settled on a more general-purpose solution that allows concatenating an arbitrary set of one-dimensional arrays of the same type. (I was concatenating 3+ at a time.)

My function:

    public static T[] ConcatArrays<T>(params T[][] list)
        var result = new T[list.Sum(a => a.Length)];
        int offset = 0;
        for (int x = 0; x < list.Length; x++)
            list[x].CopyTo(result, offset);
            offset += list[x].Length;
        return result;

And usage:

        int[] a = new int[] { 1, 2, 3 };
        int[] b = new int[] { 4, 5, 6 };
        int[] c = new int[] { 7, 8 };
        var y = ConcatArrays(a, b, c); //Results in int[] {1,2,3,4,5,6,7,8}

SQL Client for Mac OS X that works with MS SQL Server

For MySQL, there is Querious and Sequel Pro. The former costs US$25, and the latter is free. You can find a comparison of them here, and a list of some other Mac OS X MySQL clients here.


After installing SQL Server 2014 Express can't find local db

I downloaded a different installer "SQL Server 2014 Express with Advanced Services" and found Instance Features in it. Thanks for Alberto Solano's answer, it was really helpful.

My first installer was "SQL Server 2014 Express". It installed only SQL Management Studio and tools without Instance features. After installation "SQL Server 2014 Express with Advanced Services" my LocalDB is now alive!!!

How to set a parameter in a HttpServletRequest?

The most upvoted solution generally works but for Spring and/or Spring Boot, the values will not wire to parameters in controller methods annotated with @RequestParam unless you specifically implemented getParameterValues(). I combined the solution(s) here and from this blog:

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MutableHttpRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> mutableParams = new HashMap<>();

    public MutableHttpRequest(final HttpServletRequest request) {

    public MutableHttpRequest addParameter(String name, String value) {
        if (value != null)
            mutableParams.put(name, new String[] { value });

        return this;

    public String getParameter(final String name) {
        String[] values = getParameterMap().get(name);


    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> allParameters = new HashMap<>();

        return Collections.unmodifiableMap(allParameters);

    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(getParameterMap().keySet());

    public String[] getParameterValues(final String name) {
        return getParameterMap().get(name);

note that this code is not super-optimized but it works.

How can I stop the browser back button using JavaScript?

This code was tested with the latest Chrome and Firefox browsers.

<script type="text/javascript">
    history.pushState(null, null, location.href);
    window.onpopstate = function () { history.go(1); };

How to create circular ProgressBar in android?

It's easy to create this yourself

In your layout include the following ProgressBar with a specific drawable (note you should get the width from dimensions instead). The max value is important here:

    android:progressDrawable="@drawable/circular" />

Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius instead of innerRadiusRatio) and thickness values.

circular (Pre Lollipop OR API Level < 21)

        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />

circular ( >= Lollipop OR API Level >= 21)

        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />

useLevel is "false" by default in API Level 21 (Lollipop) .

Start Animation

Next in your code use an ObjectAnimator to animate the progress field of the ProgessBar of your layout.

ProgressBar progressBar = (ProgressBar) view.findViewById(;
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());

Stop Animation


P.S. unlike examples above, it give smooth animation.

git add, commit and push commands in one?

Add in ~/.bash_profile for adding, committing and pushing with one command put:

function g() { git commit -a -m "$*"; git push; }


g your commit message
g your commit message 'message'

No quotes are needed although you can't use semicolons or parenthesis in your commit messages (single quotes are allowed). If you want to any of these just simply put double quotes in you message, e.g.:

g "your commit message; (message)"

To create a comment in your message do:

g "your commit message:
> your note"

There's also a function for adding and committing in a similar way:

function c() { git add --all; git commit -m "$*"; }

Works exactly the same way that g function and has the same constraints. Just put c instead. E.g.

c your commit message

You can also add an alias for pushing to the remote:

alias p='git push'



That amounts into 2 letters, c and p you use while working with your git repository. Or you can use g instead to do it all with only one letter.

Full list of aliases and functions:

Find files containing a given text

egrep -ir --include=*.{php,html,js} "(document.cookie|setcookie)" .

The r flag means to search recursively (search subdirectories). The i flag means case insensitive.

If you just want file names add the l (lowercase L) flag:

egrep -lir --include=*.{php,html,js} "(document.cookie|setcookie)" .

Creating a file name as a timestamp in a batch job

This worked for me and was a filename-safe solution (though it generates a MM-dd-YYYY format):

C:\ set SAVESTAMP=%DATE:/=-%@%TIME::=-%
C:\ echo %SAVESTAMP%
[email protected]

The first command takes a DATE and replaces / with -, takes the TIME and replaces : with -, and combines them into DATE@TIME format. The second set statement removes any spaces, and the third set replaces , with . and appends the .jpg extension.

The above code is used in a little script that pulls images from a security IP Camera for further processing:

set SAVESTAMP=%DATE:/=-%@%TIME::=-%
wget-1.10.2.exe --tries=0 -O %SAVESTAMP% http://admin:<password>@<ip address>:<port>/snapshot.cgi
timeout 1
GOTO while

Storing images in SQL Server?

I would prefer to store the image in a directory, then store a reference to the image file in the database.

However, if you do store the image in the database, you should partition your database so the image column resides in a separate file.

You can read more about using filegroups here

How to delete a record by id in Flask-SQLAlchemy

You can do this,



User.query.filter( == 123).delete()

Make sure to commit for delete() to take effect.

In Python, what happens when you import inside of a function?

It imports once when the function is called for the first time.

I could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...

How do I initialise all entries of a matrix with a specific value?

The ones method is much faster than using repmat:

>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds. 

And, in my opinion, makes for much more readable code.

How to replace plain URLs with links?

 * Convert URLs in a string to anchor buttons
 * @param {!string} string
 * @returns {!string}

function URLify(string){
  var urls = string.match(/(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)/g);
  if (urls) {
    urls.forEach(function (url) {
      string = string.replace(url, '<a target="_blank" href="' + url + '">' + url + "</a>");
  return string.replace("(", "<br/>(");

simple example

How to get Enum Value from index in Java?

Here's three ways to do it.

public enum Months {
    JAN(1), FEB(2), MAR(3), APR(4), MAY(5), JUN(6), JUL(7), AUG(8), SEP(9), OCT(10), NOV(11), DEC(12);

    int monthOrdinal = 0;

    Months(int ord) {
        this.monthOrdinal = ord;

    public static Months byOrdinal2ndWay(int ord) {
        return Months.values()[ord-1]; // less safe

    public static Months byOrdinal(int ord) {
        for (Months m : Months.values()) {
            if (m.monthOrdinal == ord) {
                return m;
        return null;
    public static Months[] MONTHS_INDEXED = new Months[] { null, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };


import static junit.framework.Assert.assertEquals;

import org.junit.Test;

public class MonthsTest {

public void test_indexed_access() {
    assertEquals(Months.MONTHS_INDEXED[1], Months.JAN);
    assertEquals(Months.MONTHS_INDEXED[2], Months.FEB);

    assertEquals(Months.byOrdinal(1), Months.JAN);
    assertEquals(Months.byOrdinal(2), Months.FEB);

    assertEquals(Months.byOrdinal2ndWay(1), Months.JAN);
    assertEquals(Months.byOrdinal2ndWay(2), Months.FEB);


Working with select using AngularJS's ng-options

If you need a custom title for each option, ng-options is not applicable. Instead use ng-repeat with options:

<select ng-model="myVariable">
  <option ng-repeat="item in items"
          title="Custom title: {{item.Title}} [{{item.ID}}]">

Add leading zeroes to number in Java?

In case of your jdk version less than 1.5, following option can be used.

    int iTest = 2;
    StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
    System.out.println(sTest.substring(sTest.length()-6, sTest.length()));

How to access nested elements of json object using getJSONArray method

I suggest you to use Gson library. It allows to parse JSON string into object data model. Please, see my example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class GsonProgram {

    public static void main(String... args) {
        String response = "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}";

        Gson gson = new GsonBuilder().serializeNulls().create();
        Response res = gson.fromJson(response, Response.class);

        System.out.println("Entries: " + res.getResult().getMap().getEntry());

class Response {

    private Result result;

    public Result getResult() {
        return result;

    public void setResult(Result result) {
        this.result = result;

    public String toString() {
        return result.toString();

class Result {

    private MapNode map;

    public MapNode getMap() {
        return map;

    public void setMap(MapNode map) { = map;

    public String toString() {
        return map.toString();

class MapNode {

    List<Entry> entry = new ArrayList<Entry>();

    public List<Entry> getEntry() {
        return entry;

    public void setEntry(List<Entry> entry) {
        this.entry = entry;

    public String toString() {
        return Arrays.toString(entry.toArray());

class Entry {

    private Key key;
    private String value;

    public String getValue() {
        return value;

    public void setValue(String value) {
        this.value = value;

    public Key getKey() {
        return key;

    public void setKey(Key key) {
        this.key = key;

    public String toString() {
        return "[key=" + key + ", value=" + value + "]";

class Key {

    private String value;

    private String type;

    public String getValue() {
        return value;

    public void setValue(String value) {
        this.value = value;

    public String getType() {
        return type;

    public void setType(String type) {
        this.type = type;

    public String toString() {
        return "[value=" + value + ", type=" + type + "]";

Program output:

Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]

If you not familiar with this library, then you can find a lot of informations in "Gson User Guide".

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

Make sure your AndroidManifest file contains a package name in the manifest node. Setting a package name fixed this problem for me.

Datatable select with multiple conditions

    protected void FindCsv()
        string strToFind = "2";

        importFolder = @"C:\Documents and Settings\gmendez\Desktop\";

        fileName = "CSVFile.csv";

        connectionString= @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+importFolder+";Extended Properties=Text;HDR=No;FMT=Delimited";
        conn = new OdbcConnection(connectionString);

        System.Data.Odbc.OdbcDataAdapter  da = new OdbcDataAdapter("select * from [" + fileName + "]", conn);
        DataTable dt = new DataTable();

        dt.Columns[0].ColumnName = "id";

        DataRow[] dr = dt.Select("id=" + strToFind);

        Response.Write(dr[0][0].ToString() + dr[0][1].ToString() + dr[0][2].ToString() + dr[0][3].ToString() + dr[0][4].ToString() + dr[0][5].ToString());

getResources().getColor() is deprecated

well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor function. You can get current theme with getTheme().

This will do the trick in fragment, you can replace getActivity() with getBaseContext(), yourContext, etc which hold your current context

    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {

*p.s : color is deprecated in M, but drawable is deprecated in L

Making a Bootstrap table column fit to content

Tested on Bootstrap 4.5 and 5.0

None of the solution works for me. The td last column still takes the full width. So here's the solution works.

Add table-fit to your table

table.table-fit {
    width: auto !important;
    table-layout: auto !important;
table.table-fit thead th, table.table-fit tfoot th {
    width: auto !important;
table.table-fit tbody td, table.table-fit tfoot td {
    width: auto !important;

Here's the one for sass uses.

@mixin width {
    width: auto !important;

table {
    &.table-fit {
        @include width;
        table-layout: auto !important;
        thead th, tfoot th  {
            @include width;
        tbody td, tfoot td {
            @include width;

How can I uninstall Ruby on ubuntu?

Run the following command on the terminal:

sudo apt-get autoremove ruby

Using Mockito, how do I verify a method was a called with a certain argument?

This is the better solution:

verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));

Find all files in a folder

A lot of these answers won't actually work, having tried them myself. Give this a go:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);

It will move all .txt files on the desktop to the folder TextFiles.

How to include another XHTML in XHTML using JSF 2.0 Facelets?


Most basic way is <ui:include>. The included content must be placed inside <ui:composition>.

Kickoff example of the master page /page.xhtml:

<!DOCTYPE html>
<html lang="en"
        <title>Include demo</title>
        <h1>Master page</h1>
        <p>Master page blah blah lorem ipsum</p>
        <ui:include src="/WEB-INF/include.xhtml" />

The include page /WEB-INF/include.xhtml (yes, this is the file in its entirety, any tags outside <ui:composition> are unnecessary as they are ignored by Facelets anyway):

    <h2>Include page</h2>
    <p>Include page blah blah lorem ipsum</p>

This needs to be opened by /page.xhtml. Do note that you don't need to repeat <html>, <h:head> and <h:body> inside the include file as that would otherwise result in invalid HTML.

You can use a dynamic EL expression in <ui:include src>. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).


A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert> to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define> to define the template content which is to be inserted.

Master template page /WEB-INF/template.xhtml (as a design hint: the header, menu and footer can in turn even be <ui:include> files):

<!DOCTYPE html>
<html lang="en"
        <title><ui:insert name="title">Default title</ui:insert></title>
        <div id="header">Header</div>
        <div id="menu">Menu</div>
        <div id="content"><ui:insert name="content">Default content</ui:insert></div>
        <div id="footer">Footer</div>

Template client page /page.xhtml (note the template attribute; also here, this is the file in its entirety):

<ui:composition template="/WEB-INF/template.xhtml"

    <ui:define name="title">
        New page title here

    <ui:define name="content">
        <h1>New content here</h1>
        <p>Blah blah</p>

This needs to be opened by /page.xhtml. If there is no <ui:define>, then the default content inside <ui:insert> will be displayed instead, if any.


You can pass parameters to <ui:include> or <ui:composition template> by <ui:param>.

<ui:include ...>
    <ui:param name="foo" value="#{}" />
<ui:composition template="...">
    <ui:param name="foo" value="#{}" />
</ui:composition >

Inside the include/template file, it'll be available as #{foo}. In case you need to pass "many" parameters to <ui:include>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{}">. See also When to use <ui:include>, tag files, composite components and/or custom components?

You can even pass whole beans, methods and parameters via <ui:param>. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?

Design hints

The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?

There doesn't need to be any markup (HTML code) outside <ui:composition> and <ui:define>. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?

The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.

CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?

You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.

For real world examples of advanced Facelets templating, check the src/main/webapp folder of Java EE Kickoff App source code and OmniFaces showcase site source code.

How to copy selected lines to clipboard in vim

Install "xclip" if you haven't...

sudo apt-get install xclip

Xclip puts the data into the "selection/highlighted" clipboard that you middle-click to paste as opposed to "ctrl+v"

While in vim use ex commands:

7w !xclip


1,7w !xclip


%w !xclip

Then just middle-click to paste into any other application...

What is the proper way to URL encode Unicode characters?

The general rule seems to be that browsers encode form responses according to the content-type of the page the form was served from. This is a guess that if the server sends us "text/xml; charset=iso-8859-1", then they expect responses back in the same format.

If you're just entering a URL in the URL bar, then the browser doesn't have a base page to work on and therefore just has to guess. So in this case it seems to be doing utf-8 all the time (since both your inputs produced three-octet form values).

The sad truth is that AFAIK there's no standard for what character set the values in a query string, or indeed any characters in the URL, should be interpreted as. At least in the case of values in the query string, there's no reason to suppose that they necessarily do correspond to characters.

It's a known problem that you have to tell your server framework which character set you expect the query string to be encoded as--- for instance, in Tomcat, you have to call request.setEncoding() (or some similar method) before you call any of the request.getParameter() methods. The dearth of documentation on this subject probably reflects the lack of awareness of the problem amongst many developers. (I regularly ask Java interviewees what the difference between a Reader and an InputStream is, and regularly get blank looks)

Can we have multiple "WITH AS" in single sql - Oracle SQL

the correct syntax is -

with t1
(select * from tab1
where conditions...
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
select * from t1, t2
where t1.col1=t2.col2;

How do I verify that an Android apk is signed with a release certificate?

    1. unzip apk
    1. keytool -printcert -file ANDROID_.RSA or keytool -list -printcert -jarfile app.apk to obtain the hash md5
  • keytool -list -v -keystore clave-release.jks
  • compare the md5

How to retrieve Jenkins build parameters using the Groovy API?

The following can be used to retreive an environment parameter:

println System.getenv("MY_PARAM") 

Function to convert column number to letter?

This is a function based on @DamienFennelly's answer above. If you give me a thumbs up, give him a thumbs up too! :P

Function outColLetterFromNumber(iCol as Integer) as String
    sAddr = Cells(1, iCol).Address
    aSplit = Split(sAddr, "$")
    outColLetterFromNumber = aSplit(1)
End Function

Generate a unique id

Why not just use ToString?

public string generateID()
    return Guid.NewGuid().ToString("N");

If you would like it to be based on a URL, you could simply do the following:

public string generateID(string sourceUrl)
    return string.Format("{0}_{1:N}", sourceUrl, Guid.NewGuid());

If you want to hide the URL, you could use some form of SHA1 on the sourceURL, but I'm not sure what that might achieve.

How can I search Git branches for a file or directory?

git log + git branch will find it for you:

% git log --all -- somefile

commit 55d2069a092e07c56a6b4d321509ba7620664c63
Author: Dustin Sallings <[email protected]>
Date:   Tue Dec 16 14:16:22 2008 -0800

    added somefile

% git branch -a --contains 55d2069

Supports globbing, too:

% git log --all -- '**/my_file.png'

The single quotes are necessary (at least if using the Bash shell) so the shell passes the glob pattern to git unchanged, instead of expanding it (just like with Unix find).

how to get last insert id after insert query in codeigniter active record

Just to complete this topic: If you set up your table with primary key and auto increment you can omit the process of manually incrementing the id.

Check out this example

if (!$CI->db->table_exists(db_prefix() . 'my_table_name')) {
    $CI->db->query('CREATE TABLE `' . db_prefix() . "my_table_name` (
  `name` varchar(64) NOT NULL,
  `hash` varchar(32) NOT NULL,
  `url` varchar(120) NOT NULL,
  `datecreated` datetime NOT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=" . $CI->db->char_set . ';');

Now you can insert rows

$this->db->insert(db_prefix(). 'my_table_name', [
            'name'         => $data['name'],
            'hash'            => app_generate_hash(),
            'url'     => $data['url'],
            'datecreated'     => date('Y-m-d H:i:s'),
            'active'          => $data['active']

Populating spinner directly in the layout xml

I'm not sure about this, but give it a shot.

In your strings.xml define:

<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>

In your layout:


I've heard this doesn't always work on the designer, but it compiles fine.

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

You can directly use the equality operator

    var firstName;
    var lastName = null;
    /* Since null == undefined is true, the following statements will catch both null and undefined */
        if(firstName == null){
            alert('Variable "firstName" is undefined.');
        if(lastName == null){
           alert('Variable "lastName" is null.');

demo @ How to determine if variable is undefined or null using JavaScript

Java constructor/method with optional parameters?

Java doesn't support default parameters. You will need to have two constructors to do what you want.

An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.


   public class Foo {
     private final String param1;
     private final String param2;

     private Foo(Builder builder) {
       this.param1 = builder.param1;
       this.param2 = builder.param2;
     public static class Builder {
       private String param1 = "defaultForParam1";
       private String param2 = "defaultForParam2";

       public Builder param1(String param1) {
         this.param1 = param1;
         return this;
       public Builder param2(String param1) {
         this.param2 = param2;
         return this;
       public Foo build() {
         return new Foo(this);

which allows you to say:

Foo myFoo = new Foo.Builder().param1("myvalue").build();

which will have a default value for param2.

How to add \newpage in Rmarkdown in a smart way?

Simply \newpage or \pagebreak will work, e.g.

hello world
```{r, echo=FALSE}
```{r, echo=FALSE}

This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.

How to make a .NET Windows Service start right after the installation?

To add to ScottTx's answer, here's the actual code to start the service if you're doing it the Microsoft way (ie. using a Setup project etc...)

(excuse the code, but this is what I'm stuck with)

Private Sub ServiceInstaller1_AfterInstall(ByVal sender As System.Object, ByVal e As System.Configuration.Install.InstallEventArgs) Handles ServiceInstaller1.AfterInstall
    Dim sc As New ServiceController()
    sc.ServiceName = ServiceInstaller1.ServiceName

    If sc.Status = ServiceControllerStatus.Stopped Then
            ' Start the service, and wait until its status is "Running".

            ' TODO: log status of service here: sc.Status
        Catch ex As Exception
            ' TODO: log an error here: "Could not start service: ex.Message"
        End Try
    End If
End Sub

To create the above event handler, go to the ProjectInstaller designer where the 2 controlls are. Click on the ServiceInstaller1 control. Go to the properties window under events and there you'll find the AfterInstall event.

Note: Don't put the above code under the AfterInstall event for ServiceProcessInstaller1. It won't work, coming from experience. :)

How can I make my flexbox layout take 100% vertical space?

You should set height of html, body, .wrapper to 100% (in order to inherit full height) and then just set a flex value greater than 1 to .row3 and not on the others.

.wrapper, html, body {
    height: 100%;
    margin: 0;
.wrapper {
    display: flex;
    flex-direction: column;
#row1 {
    background-color: red;
#row2 {
    background-color: blue;
#row3 {
    background-color: green;
    display: flex;
#col1 {
    background-color: yellow;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
#col2 {
    background-color: orange;
    flex: 1 1;
    min-height: 100%;/* chrome needed it a question time , not anymore */
#col3 {
    background-color: purple;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
<div class="wrapper">
    <div id="row1">this is the header</div>
    <div id="row2">this is the second line</div>
    <div id="row3">
        <div id="col1">col1</div>
        <div id="col2">col2</div>
        <div id="col3">col3</div>


Resize UIImage by keeping Aspect ratio and width


imageView.contentMode = UIViewContentModeScaleAspectFit;


enter image description here

How to install sklearn?

You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do

pip install -U scikit-learn

If you are on windows you might want to check out these pages.

Find files in created between a date range

If you use GNU find, since version 4.3.3 you can do:

find -newerct "1 Aug 2013" ! -newerct "1 Sep 2013" -ls

It will accept any date string accepted by GNU date -d.

You can change the c in -newerct to any of a, B, c, or m for looking at atime/birth/ctime/mtime.

Another example - list files modified between 17:30 and 22:00 on Nov 6 2017:

find -newermt "2017-11-06 17:30:00" ! -newermt "2017-11-06 22:00:00" -ls

Full details from man find:

   -newerXY reference
          Compares the timestamp of the current file with reference.  The reference argument is normally the name of a file (and one of its timestamps  is  used
          for  the  comparison)  but  it may also be a string describing an absolute time.  X and Y are placeholders for other letters, and these letters select
          which time belonging to how reference is used for the comparison.

          a   The access time of the file reference
          B   The birth time of the file reference
          c   The inode status change time of reference
          m   The modification time of the file reference
          t   reference is interpreted directly as a time

          Some combinations are invalid; for example, it is invalid for X to be t.  Some combinations are not implemented on all systems; for example B  is  not
          supported on all systems.  If an invalid or unsupported combination of XY is specified, a fatal error results.  Time specifications are interpreted as
          for the argument to the -d option of GNU date.  If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal
          error  message  results.   If  you  specify a test which refers to the birth time of files being examined, this test will fail for any files where the
          birth time is unknown.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:


 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")


mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

C char* to int conversion

Use atoi() from <stdlib.h>

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
  int sign=1;
  if(*s == '-'){
    sign = -1;
  int num=0;
  return num*sign;

Force sidebar height 100% using CSS (with a sticky bottom image)?

This worked for me

.container { 
  overflow: hidden; 

#sidebar { 
  margin-bottom: -5000px; /* any large number will do */
  padding-bottom: 5000px; 

Can I call an overloaded constructor from another constructor of the same class in C#?

EDIT: According to the comments on the original post this is a C# question.

Short answer: yes, using the this keyword.

Long answer: yes, using the this keyword, and here's an example.

class MyClass
   private object someData;

   public MyClass(object data)
      this.someData = data;

   public MyClass() : this(new object())
      // Calls the previous constructor with a new object, 
      // setting someData to that object

Delete keychain items when an app is uninstalled

Files will be deleted from your app's document directory when the user uninstalls the app. Knowing this, all you have to do is check whether a file exists as the first thing that happens in application:didFinishLaunchingWithOptions:. Afterwards, unconditionally create the file (even if it's just a dummy file).

If the file did not exist at time of check, you know this is the first run since the latest install. If you need to know later in the app, save the boolean result to your app delegate member.

How do I output text without a newline in PowerShell?

I cheated, but I believe this is the only answer that addresses every requirement. Namely, this avoids the trailing CRLF, provides a place for the other operation to complete in the meantime, and properly redirects to stdout as necessary.

$c_sharp_source = @"
using System;
namespace StackOverflow
   public class ConsoleOut
      public static void Main(string[] args)
$compiler_parameters = New-Object System.CodeDom.Compiler.CompilerParameters
$compiler_parameters.GenerateExecutable = $true
$compiler_parameters.OutputAssembly = "consoleout.exe"
Add-Type -TypeDefinition $c_sharp_source -Language CSharp -CompilerParameters $compiler_parameters

.\consoleout.exe "Enabling feature XYZ......."
Write-Output 'Done.'

Listing contents of a bucket with boto3

This is similar to an 'ls' but it does not take into account the prefix folder convention and will list the objects in the bucket. It's left up to the reader to filter out prefixes which are part of the Key name.

In Python 2:

from boto.s3.connection import S3Connection

conn = S3Connection() # assumes boto.cfg setup
bucket = conn.get_bucket('bucket_name')
for obj in bucket.get_all_keys():

In Python 3:

from boto3 import client

conn = client('s3')  # again assumes boto.cfg setup, assume AWS S3
for key in conn.list_objects(Bucket='bucket_name')['Contents']:

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

Even I had same problem

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/]

I have added respective dependency at very begenining it had worked for me.


Importing CSV File to Google Maps

GPS Visualizer has an interface by which you can cut and paste a CSV file and convert it to kml:

Then use Google Earth. If you don't have Google Earth and want to display it online I found another nifty service that will plot kml files online:

Show diff between commits

Accepted answer is good.

Just putting it again here, so its easy to understand & try in future

git diff c1...c2 > mypatch_1.patch  
git diff c1..c2  > mypatch_2.patch  
git diff c1^..c2 > mypatch_3.patch  

I got the same diff for all the above commands.

Above helps in
1. seeing difference of between commit c1 & another commit c2
2. also making a patch file that shows diff and can be used to apply changes to another branch

If it not showing difference correctly
then c1 & c2 may be taken wrong
so adjust them to a before commit like c1 to c0, or to one after like c2 to c3

Use gitk to see the commits SHAs, 1st 8 characters are enough to use them as c0, c1, c2 or c3. You can also see the commits ids from Gitlab > Repository > Commits, etc.

Hope that helps.

Div Scrollbar - Any way to style it?

This one does well its scrolling job. It's very easy to understand, just really few lines of code, well written and totally readable.

How can I make a div stick to the top of the screen once it's been scrolled to?

This is how i did it with jquery. This was all cobbled together from various answers on stack overflow. This solution caches the selectors for faster performance and also solves the "jumping" issue when the sticky div becomes sticky.

Check it out on jsfiddle:


.stick {
    position: fixed;
    top: 0;


$(document).ready(function() {
    // Cache selectors for faster performance.
    var $window = $(window),
        $mainMenuBar = $('#mainMenuBar'),
        $mainMenuBarAnchor = $('#mainMenuBarAnchor');

    // Run this on scroll events.
    $window.scroll(function() {
        var window_top = $window.scrollTop();
        var div_top = $mainMenuBarAnchor.offset().top;
        if (window_top > div_top) {
            // Make the div sticky.
        else {
            // Unstick the div.

Returning JSON object from an ASP.NET page

In your Page_Load you will want to clear out the normal output and write your own, for example:

string json = "{\"name\":\"Joe\"}";
Response.ContentType = "application/json; charset=utf-8";

To convert a C# object to JSON you can use a library such as Json.NET.

Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.

Remove First and Last Character C++

My BASIC interpreter chops beginning and ending quotes with


Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert if not:

assert(str->front() == '"' && str->back() == '"');

Just my two cents.

Javascript to convert UTC to local time

This should work

var date = new Date('2012-11-29 17:00:34 UTC');

iPhone 6 and 6 Plus Media Queries

This is what is working for me right now:

iPhone 6

@media only screen and (max-device-width: 667px) 
    and (-webkit-device-pixel-ratio: 2) {

iPhone 6+

@media screen and (min-device-width : 414px) 
    and (-webkit-device-pixel-ratio: 3)

Threading Example in Android

One of Androids powerful feature is the AsyncTask class.

To work with it, you have to first extend it and override doInBackground(...). doInBackground automatically executes on a worker thread, and you can add some listeners on the UI Thread to get notified about status update, those functions are called: onPreExecute(), onPostExecute() and onProgressUpdate()

You can find a example here.

Refer to below post for other alternatives:

Handler vs AsyncTask vs Thread

Parsing ISO 8601 date in Javascript

datejs could parse following, you might want to try out.

Date.parse('1997-07-16T19:20:15')           // ISO 8601 Formats
Date.parse('1997-07-16T19:20:30+01:00')     // ISO 8601 with Timezone offset

Edit: Regex version

x = "2011-01-28T19:30:00EST"

MM = ["January", "February","March","April","May","June","July","August","September","October","November", "December"]

xx = x.replace(
        return MM[$2-1]+" "+$3+", "+$1+" - "+$4%12+":"+$5+(+$4>12?"PM":"AM")+" "+$6


January 28, 2011 - 7:30PM EST

Edit2: I changed my timezone to EST and now I got following

x = "2011-01-28T19:30:00-05:00"

MM = {Jan:"January", Feb:"February", Mar:"March", Apr:"April", May:"May", Jun:"June", Jul:"July", Aug:"August", Sep:"September", Oct:"October", Nov:"November", Dec:"December"}

xx = String(new Date(x)).replace(
    /\w{3} (\w{3}) (\d{2}) (\d{4}) (\d{2}):(\d{2}):[^(]+\(([A-Z]{3})\)/,
        return MM[$1]+" "+$2+", "+$3+" - "+$4%12+":"+$5+(+$4>12?"PM":"AM")+" "+$6 


January 28, 2011 - 7:30PM EST


String(new Date(x))


Fri Jan 28 2011 19:30:00 GMT-0500 (EST)

regex parts just converting above string to your required format.

January 28, 2011 - 7:30PM EST

ng-if check if array is empty

In my experience, doing this on the HTML template proved difficult so I decided to use an event to call a function on TS and then check the condition. If true make condition equals to true and then use that variable on the ngIf on HTML

    emptyClause(array:any) {

        if (array.length === 0) {
            // array empty or does not exist





        <div class="row">

            <div class="col-md-1 col-sm-1 col-xs-1"></div>
            <div class="col-md-10 col-sm-10 col-xs-10">
        <div [hidden]="emptyMessage" class="alert alert-danger">

            No Clauses Have Been Identified For the Search Criteria

            <div class="col-md-1 col-sm-1 col-xs-1"></div>

Concatenate two NumPy arrays vertically

Because both a and b have only one axis, as their shape is (3), and the axis parameter specifically refers to the axis of the elements to concatenate.

this example should clarify what concatenate is doing with axis. Take two vectors with two axis, with shape (2,3):

a = np.array([[1,5,9], [2,6,10]])
b = np.array([[3,7,11], [4,8,12]])

concatenates along the 1st axis (rows of the 1st, then rows of the 2nd):

np.concatenate((a,b), axis=0)
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd):

np.concatenate((a, b), axis=1)
array([[ 1,  5,  9,  3,  7, 11],
       [ 2,  6, 10,  4,  8, 12]])

to obtain the output you presented, you can use vstack

a = np.array([1,2,3])
b = np.array([4,5,6])
np.vstack((a, b))
array([[1, 2, 3],
       [4, 5, 6]])

You can still do it with concatenate, but you need to reshape them first:

np.concatenate((a.reshape(1,3), b.reshape(1,3)))
array([[1, 2, 3],
       [4, 5, 6]])

Finally, as proposed in the comments, one way to reshape them is to use newaxis:

np.concatenate((a[np.newaxis,:], b[np.newaxis,:]))

ASP.NET email validator regex

For regex, I first look at this web site:

Convert a list of characters into a string

This may be the fastest way:

>> from array import array
>> a = ['a','b','c','d']
>> array('B', map(ord,a)).tostring()

ReferenceError: document is not defined (in plain JavaScript)

This happened with me because I was using Next JS which has server side rendering. When you are using server side rendering there is no browser. Hence, there will not be any variable window or document. Hence this error shows up.

Work around :

If you are using Next JS you can use the dynamic rendering to prevent server side rendering for the component.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false

export default () => <DynamicComponentWithNoSSR />

If you are using any other server side rendering library. Then add the code that you want to run at the client side in componentDidMount. If you are using React Hooks then use useEffects in the place of componentsDidMount.

import React, {useState, useEffects} from 'react';

const DynamicComponentWithNoSSR = <>Some JSX</>

export default function App(){

[a,setA] = useState();
useEffect(() => {

return (<>{a}<>)

References :


Redis connection to failed - connect ECONNREFUSED

You have to install redis server first;

You can install redis server on mac by following step -

  $ curl -O
  $ tar xzvf redis-stable.tar.gz
  $ cd redis-stable
  $ make
  $ make test
  $ sudo make install
  $ redis-server

Good luck.

Command-line Git on Windows

These instructions worked for a Windows 8 with a msysgit/TortoiseGit installation, but should be applicable for other types of git installations on Windows.

  • Go to Control Panel\System and Security\System
  • Click on Advanced System Settings on the left which opens System Properties.
  • Click on the Advanced Tab
  • Click on the Environment Variables button at the bottom of the dialog box.
  • Edit the System Variable called PATH.
  • Append these two paths to the list of existing paths already present in the system variable. The tricky part was two paths were required. These paths may vary for your PC. ;C:\msysgit\bin\;C:\msysgit\mingw\bin\
  • Close the CMD prompt window if it is open already. CMD needs to restart to get the updated Path variable.
  • Try typing git in the command line, you should see a list of the git commands scroll down the screen.

How can I get name of element with jQuery?

If anyone is also looking for how to get the name of the HTML tag, you can use "tagName": $(this)[0].tagName

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

I think this should work.

UPDATE QuestionTrackings
SET QuestionID = (SELECT QuestionID
                  FROM AnswerTrackings
                  WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID)

Get commit list between tags in git

Consider also this:

git range-diff tagA...tagB


Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

How can I do division with variables in a Linux shell?

To get the numbers after decimal point, you can do this:-

read num1 num2
div=`echo $num1 / $num2 | bc -l`
echo $div

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Don't pass db models directly to your views. You're lucky enough to be using MVC, so encapsulate using view models.

Create a view model class like this:

public class EmployeeAddViewModel
    public Employee employee { get; set; }
    public Dictionary<int, string> staffTypes { get; set; }
    // really? a 1-to-many for genders
    public Dictionary<int, string> genderTypes { get; set; }

    public EmployeeAddViewModel() { }
    public EmployeeAddViewModel(int id)
        employee = someEntityContext.Employees
            .Where(e => e.ID == id).SingleOrDefault();

        // instantiate your dictionaries

        foreach(var staffType in someEntityContext.StaffTypes)
            staffTypes.Add(staffType.ID, staffType.Type);

        // repeat similar loop for gender types


public ActionResult Add()
    return View(new EmployeeAddViewModel());

public ActionResult Add(EmployeeAddViewModel vm)
        return View("Index"); // or wherever you go after successful add

    return View(vm);

Then, finally in your view (which you can use Visual Studio to scaffold it first), change the inherited type to ShadowVenue.Models.EmployeeAddViewModel. Also, where the drop down lists go, use:

@Html.DropDownListFor(model => model.employee.staffTypeID,
    new SelectList(model.staffTypes, "ID", "Type"))

and similarly for the gender dropdown

@Html.DropDownListFor(model => model.employee.genderID,
    new SelectList(model.genderTypes, "ID", "Gender"))

Update per comments

For gender, you could also do this if you can be without the genderTypes in the above suggested view model (though, on second thought, maybe I'd generate this server side in the view model as IEnumerable). So, in place of new SelectList... below, you would use your IEnumerable.

@Html.DropDownListFor(model => model.employee.genderID,
    new SelectList(new SelectList()
        new { ID = 1, Gender = "Male" },
        new { ID = 2, Gender = "Female" }
    }, "ID", "Gender"))

Finally, another option is a Lookup table. Basically, you keep key-value pairs associated with a Lookup type. One example of a type may be gender, while another may be State, etc. I like to structure mine like this:

ID | LookupType | LookupKey | LookupValue | LookupDescription | Active
1  | Gender     | 1         | Male        | male gender       | 1
2  | State      | 50        | Hawaii      | 50th state        | 1
3  | Gender     | 2         | Female      | female gender     | 1
4  | State      | 49        | Alaska      | 49th state        | 1
5  | OrderType  | 1         | Web         | online order      | 1

I like to use these tables when a set of data doesn't change very often, but still needs to be enumerated from time to time.

Hope this helps!

What is an Android PendingIntent?

Why PendingIntent is required ? I was thinking like

  1. Why the receiving application itself cannot create the Intent or
  2. Why we cannot use a simple Intent for the same purpose.

E.g.Intent bluetoothIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

If I send bluetoothIntent to another application, which doesn't have permission android.permission.BLUETOOTH_ADMIN, that receiving application cannot enable Bluetooth with startActivity(bluetoothIntent).

The limitation is overcome using PendingIntent. With PendingIntent the receiving application, doesn't need to have android.permission.BLUETOOTH_ADMIN for enabling Bluetooth. Source.

PHP Warning: PHP Startup: ????????: Unable to initialize module

This is just describing why I had this issue in case someone finds it helpful.

My problem was that I had upgraded php with homebrew and had forced at some point the variable PHP_INI_SCAN_DIR in my profile or bashrc file so it was pointing to the old php version. Removed that line and fixed.

How to read file with space separated values in pandas

add delim_whitespace=True argument, it's faster than regex.

How to declare empty list and then add string in scala?

Maybe you can use ListBuffers in scala to create empty list and add strings later because ListBuffers are mutable. Also all the List functions are available for the ListBuffers in scala.

import scala.collection.mutable.ListBuffer 

val dm = ListBuffer[String]()
dm: scala.collection.mutable.ListBuffer[String] = ListBuffer()
dm += "text1"
dm += "text2"
dm = ListBuffer(text1, text2)

if you want you can convert this to a list by using .toList

Reading a string with scanf

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)

Marker in leaflet, click event

A little late to the party, found this while looking for an example of the marker click event. The undefined error the original poster got is because the onClick function is referred to before it's defined. Swap line 2 and 3 and it should work.

JavaScript property access: dot notation vs. brackets?

Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object. Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.

Java: JSON -> Protobuf & back conversion

Here is my utility class, you may use:

package <removed>;
 * Author @espresso stackoverflow.
 * Sample use:
 *      Model.Person reqObj = ProtoUtil.toProto(reqJson, Model.Person.getDefaultInstance());
        Model.Person res = personSvc.update(reqObj);
        final String resJson = ProtoUtil.toJson(res);
public class ProtoUtil {
    public static <T extends Message> String toJson(T obj){
            return JsonFormat.printer().print(obj);
        }catch(Exception e){
            throw new RuntimeException("Error converting Proto to json", e);
   public static <T extends MessageOrBuilder> T toProto(String protoJsonStr, T message){
            Message.Builder builder = message.getDefaultInstanceForType().toBuilder();
            T out = (T);
            return out;
        }catch(Exception e){
            throw new RuntimeException(("Error converting Json to proto", e);

Spring's overriding bean

Since Spring 3.0 you can use @Primary annotation. As per documentation:

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the element's primary attribute in Spring XML.

You should use it on Bean definition like this:

public ExampleBean exampleBean(@Autowired EntityManager em) {
    return new ExampleBeanImpl(em);

or like this:

public class ExampleService implements BaseServive {

How to set top position using jquery

And with Prototype:

$('yourDivId').setStyle({top: '100px', left:'80px'});

tr:hover not working

tr:hover doesn't work in old browsers.

You can use jQuery for this:

$('.list1 tr').hover(function()

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

Auto code completion on Eclipse

Since you asked about other Java IDE, I suggest IntelliJ by JetBrains. Just look at it: not only does it support auto completion as you type, but also it support import package once you select the auto completion.


Before someone said "Eclipse is free", note that IntelliJ has free community edition as well:

How many significant digits do floats and doubles have in java?

Look at Float.intBitsToFloat and Double.longBitsToDouble, which sort of explain how bits correspond to floating-point numbers. In particular, the bits of a normal float look something like


where A...W are 23 bits -- 0s and 1s -- representing a fraction in binary -- s is +/- 1, represented by a 0 or a 1 respectively, and exp is a signed 8-bit integer.

Disable beep of Linux Bash on Windows 10

its not specific to bash windows 10. but if you want remove the bell terminal for zsh, just use the right option in zshrc. (for vim, answer already posted)

unsetopt beep

i have find this option quickly, but would find it even faster if its was on this post ^^


How to pass multiple values through command argument in

CommandArgument='<%#Eval("ScrapId").Tostring()+ Eval("UserId")%>
//added the comment function

batch to copy files with xcopy

If the requirement is to copy all files in "\Publish\Appfolder" into the parent "\Publish\" folder (inclusive of any subfolders, following works for me) The switch '/s' allows copying of all subfolders, recursively.

xcopy src\main\Publish\Appfolder\*.* /s src\main\Publish\

What does \d+ mean in regular expression terms?

\d is a digit (a character in the range 0-9), and + means 1 or more times. So, \d+ is 1 or more digits.

This is about as simple as regular expressions get. You should try reading up on regular expressions a little bit more. Google has a lot of results for regular expression tutorial, for instance. Or you could try using a tool like the free Regex Coach that will let you enter a regular expression and sample text, then indicate what (if anything) matches the regex.

Is there any way to install Composer globally on Windows?

Start > Computer : Properties > Change Settings > Advanced > Environment Variables > PATH : Edit [add this string (without "") at the end of line ";C:\<path to php folder>\php5.5.3"].. open cmd and type composer thats it :-)

What is the function of FormulaR1C1?

Here's some info from my blog on how I like to use formular1c1 outside of vba:

You’ve just finished writing a formula, copied it to the whole spreadsheet, formatted everything and you realize that you forgot to make a reference absolute: every formula needed to reference Cell B2 but now, they all reference different cells.

How are you going to do a Find/Replace on the cells, considering that one has B5, the other C12, the third D25, etc., etc.?

The easy way is to update your Reference Style to R1C1. The R1C1 reference works with relative positioning: R marks the Row, C the Column and the numbers that follow R and C are either relative positions (between [ ]) or absolute positions (no [ ]).


  • R[2]C refers to the cell two rows below the cell in which the formula’s in
  • RC[-1] refers to the cell one column to the left
  • R1C1 refers the cell in the first row and first cell ($A$1)

What does it matter? Well, When you wrote your first formula back in the beginning of this post, B2 was the cell 4 rows above the cell you wrote it in, i.e. R[-4]C. When you copy it across and down, while the A1 reference changes, the R1C1 reference doesn’t. Throughout the whole spreadsheet, it’s R[-4]C. If you switch to R1C1 Reference Style, you can replace R[-4]C by R2C2 ($B$2) with a simple Find / Replace and be done in one fell swoop.

How can I resize an image dynamically with CSS as the browser width/height changes?

window.onresize = function(){
    var img = document.getElementById('fullsize'); = "100%";

In IE onresize event gets fired on every pixel change (width or height) so there could be performance issue. Delay image resizing for few milliseconds by using javascript's window.setTimeout().

What is the exact meaning of Git Bash?

At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.

What is Git Bash?

Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.

source :

What's the best way to parse command line arguments?

Pretty much everybody is using getopt

Here is the example code for the doc :

import getopt, sys

def main():
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError:
        # print help information and exit:
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        if o in ("-h", "--help"):
        if o in ("-o", "--output"):
            output = a

So in a word, here is how it works.

You've got two types of options. Those who are receiving arguments, and those who are just like switches.

sys.argv is pretty much your char** argv in C. Like in C you skip the first element which is the name of your program and parse only the arguments : sys.argv[1:]

Getopt.getopt will parse it according to the rule you give in argument.

"ho:v" here describes the short arguments : -ONELETTER. The : means that -o accepts one argument.

Finally ["help", "output="] describes long arguments ( --MORETHANONELETTER ). The = after output once again means that output accepts one arguments.

The result is a list of couple (option,argument)

If an option doesn't accept any argument (like --help here) the arg part is an empty string. You then usually want to loop on this list and test the option name as in the example.

I hope this helped you.

How can I pass a file argument to my bash script using a Terminal command in Linux?

you can use getopt to handle parameters in your bash script. there are not many explanations for getopt out there. here is an example:


OPTIONS=$(getopt -o hf:gb -l help,file:,foo,bar -- "$@")

if [ $? -ne 0 ]; then
  echo "getopt error"
  exit 1

eval set -- $OPTIONS

while true; do
  case "$1" in
    -h|--help) HELP=1 ;;
    -f|--file) FILE="$2" ; shift ;;
    -g|--foo)  FOO=1 ;;
    -b|--bar)  BAR=1 ;;
    --)        shift ; break ;;
    *)         echo "unknown option: $1" ; exit 1 ;;

if [ $# -ne 0 ]; then
  echo "unknown option(s): $@"
  exit 1

echo "help: $HELP"
echo "file: $FILE"
echo "foo: $FOO"
echo "bar: $BAR"

see also:

Splitting strings in PHP and get last part

$string = 'abc-123-xyz-789';
$exploded = explode('-', $string);
echo end($exploded);

EDIT::Finally got around to removing the E_STRICT issue

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

//This works ONLY if the server returns 401 first
//The client DOES NOT send credentials on first request
//ONLY after a 401
client.Credentials = new NetworkCredential(userName, passWord); //doesnt work

//So use THIS instead to send credentials RIGHT AWAY
string credentials = Convert.ToBase64String(
    Encoding.ASCII.GetBytes(userName + ":" + password));
client.Headers[HttpRequestHeader.Authorization] = string.Format(
    "Basic {0}", credentials);

Windows equivalent of $export

There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

How to select an item in a ListView programmatically?

Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application.

  1. The simple solution is to set the focus to the ListView first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load event, or immediately after you set the Selected property:


    The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button).

  2. To fix that, you will need to set the HideSelection property of the ListView control to False. That will cause the selected item to remain highlighted, even when the control loses the focus.

    When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text.

    You can set this property either at design time, or through code:

    myListView.HideSelection = false;

Stop MySQL service windows

For Windows there's a couple of tricks to take care of...

(Assuming you've installed MySQL from Oracle's site but maybe have chosen not to run the service at startup)...

  1. To use "mysqld stop" from the command line for WinVista/Win7 you must right click on Start -> All Programs -> Accessories -> Command Prompt -> Run As Administrator

  2. Now that you have local OS admin access you can use "mysqld stop" (which will simply return)


121228 11:54:50 [Warning] Can't create test file c:\Program Files\MySQL\MySQL Server 5.5\data\hpdv7.lower-test
121228 11:54:50 [Warning] Can't create test file c:\Program Files\MySQL\MySQL Server 5.5\data\hpdv7.lower-test
121228 11:54:50 [Note] Plugin 'FEDERATED' is disabled.
121228 11:54:50 InnoDB: The InnoDB memory heap is disabled
121228 11:54:50 InnoDB: Mutexes and rw_locks use Windows interlocked functions
121228 11:54:50 InnoDB: Compressed tables use zlib 1.2.3
121228 11:54:50 InnoDB: Initializing buffer pool, size = 128.0M
121228 11:54:50 InnoDB: Completed initialization of buffer pool
121228 11:54:50  InnoDB: Operating system error number 5 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory. It may also be you have created a subdirectory
InnoDB: of the same name as a data file.
InnoDB: File name .\ibdata1
InnoDB: File operation call: 'create'.
InnoDB: Cannot continue operation.

If mysqld does not appear as a known system command, try adding it to your class path

  1. Right click on My Computer
  2. Advanced System Settings
  3. Environment Variables
  4. System variables
  5. look for and left click select the variable named path
  6. click on "Edit" and copy out the string to notepad and append at the end the full path to your MySQL bin directory , e.g.

    %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;c:\Program Files\MySQL\MySQL Server 5.5\bin

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

This thread is a bit older but here something I just came across:

Try this code:

$date = new DateTime();
$arr = ['date' => $date];

echo $date->format('Ymd') . '<br>';
echo $date->format('Ymd') . '<br>';

function mytest($params = []) {
    if (isset($params['date'])) {
        $params['date']->add(new DateInterval('P1D'));

Note there is no amp for the $params parameter and still it changes the value of $arr['date']. This doesn't really match with all the other explanations here and what I thought until now.

If I clone the $params['date'] object, the 2nd outputted date stays the same. If I just set it to a string it doesn't effect the output either.

Could not open input file: artisan

If it is your first install of laravel then create another directory/folder inside the laravel directory and then move to that empty folder and create another project using the command below:

composer create-project --prefer-dist laravel/laravel blog

This will create a new project named "blog", then go back to parent laravel directory and now you can run this command:

php artisan serve

You will receive the return such as:

laravel deployment server started: http://localhost:8000

See attached image enter image description here

syntaxerror: "unexpected character after line continuation character in python" math

Well, what do you try to do? If you want to use division, use "/" not "\". If it is something else, explain it in a bit more detail, please.

Difference between "as $key => $value" and "as $value" in PHP foreach

A very important place where it is REQUIRED to use the key => value pair in foreach loop is to be mentioned. Suppose you would want to add a new/sub-element to an existing item (in another key) in the $features array. You should do the following:

foreach($features as $key => $feature) {
    $features[$key]['new_key'] = 'new value';  

Instead of this:

foreach($features as $feature) {
    $feature['new_key'] = 'new value';  

The big difference here is that, in the first case you are accessing the array's sub-value via the main array itself with a key to the element which is currently being pointed to by the array pointer.

While in the second (which doesn't work for this purpose) you are assigning the sub-value in the array to a temporary variable $feature which is unset after each loop iteration.

Error Code: 2013. Lost connection to MySQL server during query

Start the DB server with the comandline option net_read_timeout / wait_timeout and a suitable value (in seconds) - for example: --net_read_timeout=100.

For reference see here and here.

You seem to not be depending on "@angular/core". This is an error

I had the same issue and along with removing the node_modules and reinstalling I needed to remove package-lock.json first.

In a unix shell, how to get yesterday's date into a variable?

You have atleast 2 options

  1. Use perl:

    perl -e '@T=localtime(time-86400);printf("%02d/%02d/%02d",$T[4]+1,$T[3],$T[5]+1900)'
  2. Install GNU date (it's in the sh_utils package if I remember correctly)

    date --date yesterday "+%a %d/%m/%Y" | read dt
    echo ${dt}
  3. Not sure if this works, but you might be able to use a negative timezone. If you use a timezone that's 24 hours before your current timezone than you can simply use date.

How do search engines deal with AngularJS applications?

Let's get definitive about AngularJS and SEO

Google, Yahoo, Bing, and other search engines crawl the web in traditional ways using traditional crawlers. They run robots that crawl the HTML on web pages, collecting information along the way. They keep interesting words and look for other links to other pages (these links, the amount of them and the number of them come into play with SEO).

So why don't search engines deal with javascript sites?

The answer has to do with the fact that the search engine robots work through headless browsers and they most often do not have a javascript rendering engine to render the javascript of a page. This works for most pages as most static pages don't care about JavaScript rendering their page, as their content is already available.

What can be done about it?

Luckily, crawlers of the larger sites have started to implement a mechanism that allows us to make our JavaScript sites crawlable, but it requires us to implement a change to our site.

If we change our hashPrefix to be #! instead of simply #, then modern search engines will change the request to use _escaped_fragment_ instead of #!. (With HTML5 mode, i.e. where we have links without the hash prefix, we can implement this same feature by looking at the User Agent header in our backend).

That is to say, instead of a request from a normal browser that looks like:!/signup/page

A search engine will search the page with:

We can set the hash prefix of our Angular apps using a built-in method from ngRoute:

angular.module('myApp', [])
.config(['$location', function($location) {

And, if we're using html5Mode, we will need to implement this using the meta tag:

<meta name="fragment" content="!">

Reminder, we can set the html5Mode() with the $location service:

angular.module('myApp', [])
function($location) {

Handling the search engine

We have a lot of opportunities to determine how we'll deal with actually delivering content to search engines as static HTML. We can host a backend ourselves, we can use a service to host a back-end for us, we can use a proxy to deliver the content, etc. Let's look at a few options:


We can write a service to handle dealing with crawling our own site using a headless browser, like phantomjs or zombiejs, taking a snapshot of the page with rendered data and storing it as HTML. Whenever we see the query string ?_escaped_fragment_ in a search request, we can deliver the static HTML snapshot we took of the page instead of the pre-rendered page through only JS. This requires us to have a backend that delivers our pages with conditional logic in the middle. We can use something like's backend as a starting point to run this ourselves. Of course, we still need to handle the proxying and the snippet handling, but it's a good start.

With a paid service

The easiest and the fastest way to get content into search engine is to use a service Brombone, seo.js, seo4ajax, and are good examples of these that will host the above content rendering for you. This is a good option for the times when we don't want to deal with running a server/proxy. Also, it's usually super quick.

For more information about Angular and SEO, we wrote an extensive tutorial on it at and we detailed it even more in our book ng-book: The Complete Book on AngularJS. Check it out at

How to shift a block of code left/right by one space in VSCode?

Have a look at File > Preferences > Keyboard Shortcuts (or Ctrl+K Ctrl+S)

Search for cursorColumnSelectDown or cursorColumnSelectUp which will give you the relevent keyboard shortcut. For me it is Shift+Alt+Down/Up Arrow

How to right-align form input boxes?

You can use floating to the right and clear them.

form {_x000D_
  overflow: hidden;_x000D_
input {_x000D_
  float: right;_x000D_
  clear: both;_x000D_
  <input name="declared_first" value="above" />_x000D_
  <input name="declared_second" value="below" />_x000D_

You can also set a right-to-left direction to the parent and restore the default left-to-right on the inputs. With display: block you can force them to be on different lines.

form {_x000D_
  direction: rtl;_x000D_
input {_x000D_
  display: block;_x000D_
  direction: ltr;_x000D_
  <input name="declared_first" value="above" />_x000D_
  <input name="declared_second" value="below" />_x000D_

Or the modern way, flexbox layout

form {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  align-items: flex-end;_x000D_
  <input name="declared_first" value="above" />_x000D_
  <input name="declared_second" value="below" />_x000D_

How to check if a given directory exists in Ruby

All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:

File.exists? '~/exists'
=> false '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

It's not good to keep changing the gulp & npm versions in-order to fix the errors. I was getting several exceptions last days after reinstall my working machine. And wasted tons of minutes to re-install & fixing those.

So, I decided to upgrade all to latest versions:

npm -v : v12.13.0 
node -v : 6.13.0
gulp -v : CLI version: 2.2.0 Local version: 4.0.2

This error is getting because of the how it has coded in you gulpfile but not the version mismatch. So, Here you have to change 2 things in the gulpfile to aligned with Gulp version 4. Gulp 4 has changed how initiate the task than Version 3.

  1. In version 4, you have to defined the task as a function, before call it as a gulp task by it's string name. In V3:

gulp.task('serve', ['sass'], function() {..});

But in V4 it should be like:

function serve() {
gulp.task('serve', gulp.series(sass));
  1. As @Arthur has mentioned, you need to change the way of passing arguments to the task function. It was like this in V3:

gulp.task('serve', ['sass'], function() { ... });

But in V4, it should be:

gulp.task('serve', gulp.series(sass));

How to use if-else option in JSTL

In addition with skaffman answer, simple if-else you can use ternary operator like this

<c:set value="34" var="num"/>
<c:out value="${num % 2 eq 0 ? 'even': 'odd'}"/>

Find size of an array in Perl

From perldoc perldata, which should be safe to quote:

The following is always true:

scalar(@whatever) == $#whatever + 1;

Just so long as you don't $#whatever++ and mysteriously increase the size or your array.

The array indices start with 0.


You can truncate an array down to nothing by assigning the null list () to it. The following are equivalent:

    @whatever = ();
    $#whatever = -1;

Which brings me to what I was looking for which is how to detect the array is empty. I found it if $#empty == -1;

Javascript counting number of objects in object

Try Demo Here

var list ={}; var count= Object.keys(list).length;

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

use this code solve the problem:

string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + "Uploadfile\\" + fileName;
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, (int)fs.Length);
Response.ContentType = "application/x-unknown/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName;+ "\"");
    if (bt != null)
        System.IO.MemoryStream stream1 = new System.IO.MemoryStream(bt, true);
        stream1.Write(bt, 0, bt.Length);
        //Response.OutputStream.Write(bt, 0, (int)stream1.Length);
        // Response.End();
catch (Exception ex)
    throw ex;

Cycles in family tree software

The most important thing is to avoid creating a problem, so I believe that you should use a direct relation to avoid having a cycle.

As @markmywords said, #include "fritzl.h".

Finally I have to say recheck your data structure. Maybe something is going wrong over there (maybe a bidirectional linked list solves your problem).

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
    public Global()
        // TODO: Add constructor logic here

    void Application_Start(object sender, EventArgs e)
        // Code that runs on application startup

    /// Many other events like begin request...e.t.c, e.t.c

How to change the default background color white to something else in twitter bootstrap

The colors changed due to the order of CSS files.

Place the custom CSS under the bootstrap CSS.

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

You can use zIndex for placing a view on top of another. It works like the CSS z-index property - components with a larger zIndex will render on top.

You can refer: Layout Props


          <StatusBar backgroundColor="black" barStyle="light-content" />
          <Image style={styles.headerImage} source={{ uri: "" }}>
            <View style={styles.back}>
                <Icons name="arrow-back" size={25} color="#ffffff" />
            <Image style={styles.subHeaderImage} borderRadius={55} source={{ uri: "" }} />

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: "white"
    headerImage: {
        height: height(150),
        width: deviceWidth
    subHeaderImage: {
        height: 110,
        width: 110,
        marginTop: height(35),
        marginLeft: width(25),
        borderColor: "white",
        borderWidth: 2,
        zIndex: 5

How to add a footer to the UITableView?

If you don't prefer the sticky bottom effect i would put it in viewDidLoad()

Replace single quotes in SQL Server

select replace ( colname, '''', '') AS colname FROM .[dbo].[Db Name]

How to make MySQL table primary key auto increment with some prefix

If you really need this you can achieve your goal with help of separate table for sequencing (if you don't mind) and a trigger.


CREATE TABLE table1_seq

Now the trigger

CREATE TRIGGER tg_table1_insert

Then you just insert rows to table1

INSERT INTO Table1 (name) 
VALUES ('Jhon'), ('Mark');

And you'll have

|      ID | NAME |
| LHPL001 | Jhon |
| LHPL002 | Mark |

Here is SQLFiddle demo

How to install easy_install in Python 2.7.1 on Windows 7

I usually just run IIRC, that works fine, at least with UAC off.

It also creates an easy_install executable in your Python\scripts subdirectory, which should be in your PATH.

UPDATE: I highly recommend not to bother with easy_install anymore! Jump right to pip, it's better in every regard!
Installation is just as simple: from the installation instructions page, you can download and run it. Works just like the mentioned above.

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

You might try having that delete job operate by first inserting the key of each row to be deleted into a temp table like this pseudocode

create temporary table deletetemp (userid int);

insert into deletetemp (userid)
  select userid from onlineusers where datetime <= now - interval 900 second;

delete from onlineusers where userid in (select userid from deletetemp);

Breaking it up like this is less efficient but it avoids the need to hold a key-range lock during the delete.

Also, modify your select queries to add a where clause excluding rows older than 900 seconds. This avoids the dependency on the cron job and allows you to reschedule it to run less often.

Theory about the deadlocks: I don't have a lot of background in MySQL but here goes... The delete is going to hold a key-range lock for datetime, to prevent rows matching its where clause from being added in the middle of the transaction, and as it finds rows to delete it will attempt to acquire a lock on each page it is modifying. The insert is going to acquire a lock on the page it is inserting into, and then attempt to acquire the key lock. Normally the insert will wait patiently for that key lock to open up but this will deadlock if the delete tries to lock the same page the insert is using because thedelete needs that page lock and the insert needs that key lock. This doesn't seem right for inserts though, the delete and insert are using datetime ranges that don't overlap so maybe something else is going on.

Styling an anchor tag to look like a submit button

I Suggest you to use both Input Submit / Button instead of anchor and put this line of code onClick="javascript:location.href = '';" in that Input Submit / Button which you want to work as link.

Submit Example

<input type="submit" value="Submit" onClick="javascript:location.href = 'some_url';" />

Button Example

<button type="button" onClick="javascript:location.href = 'some_url';" />Submit</button>

Opacity of div's background without affecting contained element in IE 8?

Try setting the z-index higher on the contained element.

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.


LaTeX output

Angular.js: set element height on page load

To avoid check on every digest cycle, we can change the height of the div when the window height gets changed.

<div ng-app="miniapp" resize>


var app = angular.module('miniapp', []);

app.directive('resize', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        var changeHeight = function() {element.css('height', (w.height() -20) + 'px' );};  
            w.bind('resize', function () {        
              changeHeight();   // when window size gets changed             
        changeHeight(); // when page loads          

How to remove jar file from local maven repository which was added with install:install-file?

  1. cd ~/.m2
  2. git init
  3. git commit -am "some comments"
  4. cd /path/to/your/project
  5. mvn install
  6. cd ~/.m2
  7. git reset --hard

drag drop files into standard html file input

This is the "DTHML" HTML5 way to do it. Normal form input (which IS read only as Ricardo Tomasi pointed out). Then if a file is dragged in, it is attached to the form. This WILL require modification to the action page to accept the file uploaded this way.

function readfiles(files) {_x000D_
  for (var i = 0; i < files.length; i++) {_x000D_
    document.getElementById('fileDragName').value = files[i].name_x000D_
    document.getElementById('fileDragSize').value = files[i].size_x000D_
    document.getElementById('fileDragType').value = files[i].type_x000D_
    reader = new FileReader();_x000D_
    reader.onload = function(event) {_x000D_
      document.getElementById('fileDragData').value =;}_x000D_
var holder = document.getElementById('holder');_x000D_
holder.ondragover = function () { this.className = 'hover'; return false; };_x000D_
holder.ondragend = function () { this.className = ''; return false; };_x000D_
holder.ondrop = function (e) {_x000D_
  this.className = '';_x000D_
#holder.hover { border: 10px dashed #0c0 !important; }
<form method="post" action="">_x000D_
  <input type="file"><input id="fileDragName"><input id="fileDragSize"><input id="fileDragType"><input id="fileDragData">_x000D_
  <div id="holder" style="width:200px; height:200px; border: 10px dashed #ccc"></div>_x000D_

It is even more boss if you can make the whole window a drop zone, see How do I detect a HTML5 drag event entering and leaving the window, like Gmail does?

How can I create a simple index.html file which lists all files/directories?

Did you try to allow it for this directory via .htaccess?

Options +Indexes

I use this for some of my directories where directory listing is disabled by my provider

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).

To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.

Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How to get exact browser name and version?

  • There is a conflict between (Safari) and (Opera) and (Chrome) !!!

  • The above codes couldn't work properly

This is my code, and it works very well without any conflict:

function ExactBrowserName()


if (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")) {
    // OPERA
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "chrome/")) {
    // CHROME
} elseIf (strpos(strtolower($ExactBrowserNameUA), "msie")) {
    $ExactBrowserNameBR="Internet Explorer";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "firefox/")) {
    // FIREFOX
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")==false and strpos(strtolower($ExactBrowserNameUA), "chrome/")==false) {
    // SAFARI
} else {
    // OUT OF DATA
    $ExactBrowserNameBR="OUT OF DATA";

return $ExactBrowserNameBR;

The absolute uri: cannot be resolved in either web.xml or the jar files deployed with this application

Make sure you didn't skip all jars in


in Tomcat

In Python, how do I read the exif data for an image?

You can use the _getexif() protected method of a PIL Image.

import PIL.Image
img ='img.jpg')
exif_data = img._getexif()

This should give you a dictionary indexed by EXIF numeric tags. If you want the dictionary indexed by the actual EXIF tag name strings, try something like:

import PIL.ExifTags
exif = {
    PIL.ExifTags.TAGS[k]: v
    for k, v in img._getexif().items()
    if k in PIL.ExifTags.TAGS

Group query results by month and year in postgresql

to_char actually lets you pull out the Year and month in one fell swoop!

select to_char(date('2014-05-10'),'Mon-YY') as year_month; --'May-14'
select to_char(date('2014-05-10'),'YYYY-MM') as year_month; --'2014-05'

or in the case of the user's example above:

select to_char(date,'YY-Mon') as year_month
       sum("Sales") as "Sales"
from some_table
group by 1;

Declaring variables in Excel Cells

I also just found out how to do this with the Excel Name Manager (Formulas > Defined Names Section > Name Manager).

You can define a variable that doesn't have to "live" within a cell and then you can use it in formulas.

Excel Name Manager

Querying data by joining two tables in two database on different servers

If a linked server is not allowed by your dba, you can use OPENROWSET. Books Online will provide the syntax you need.

SQL Server - Create a copy of a database table and place it in the same database?

1st option

select *
  into ABC_1
  from ABC;

2nd option: use SSIS, that is right click on database in object explorer > all tasks > export data

  • source and target: your DB
  • source table: ABC
  • target table: ABC_1 (table will be created)

How can I check if a scrollbar is visible?

(scrollWidth/Height - clientWidth/Height) is a good indicator for the presence of a scrollbar, but it will give you a "false positive" answer on many occasions. if you need to be accurate i would suggest using the following function. instead of trying to guess if the element is scrollable - you can scroll it...

function isScrollable( el ){_x000D_
  var y1 = el.scrollTop;_x000D_
  el.scrollTop  += 1;_x000D_
  var y2 = el.scrollTop;_x000D_
  el.scrollTop  -= 1;_x000D_
  var y3 = el.scrollTop;_x000D_
  el.scrollTop   = y1;_x000D_
  var x1 = el.scrollLeft;_x000D_
  el.scrollLeft += 1;_x000D_
  var x2 = el.scrollLeft;_x000D_
  el.scrollLeft -= 1;_x000D_
  var x3 = el.scrollLeft;_x000D_
  el.scrollLeft  = x1;_x000D_
  return {_x000D_
    horizontallyScrollable: x1 !== x2 || x2 !== x3,_x000D_
    verticallyScrollable: y1 !== y2 || y2 !== y3_x000D_
function check( id ){_x000D_
  alert( JSON.stringify( isScrollable( document.getElementById( id ))));_x000D_
#outer1, #outer2, #outer3 {_x000D_
  background-color: pink;_x000D_
  overflow: auto;_x000D_
  float: left;_x000D_
#inner {_x000D_
  width:  150px;_x000D_
  height: 150px;_x000D_
button {  margin: 2em 0 0 1em; }
<div id="outer1" style="width: 100px; height: 100px;">_x000D_
  <div id="inner">_x000D_
    <button onclick="check('outer1')">check if<br>scrollable</button>_x000D_
<div id="outer2" style="width: 200px; height: 100px;">_x000D_
  <div id="inner">_x000D_
    <button onclick="check('outer2')">check if<br>scrollable</button>_x000D_
<div id="outer3" style="width: 100px; height: 180px;">_x000D_
  <div id="inner">_x000D_
    <button onclick="check('outer3')">check if<br>scrollable</button>_x000D_

MongoDB: How to query for records where field is null or not set?


db.emails.count({sent_at: null})

Which counts all emails whose sent_at property is null or is not set. The above query is same as below.

db.emails.count($or: [
  {sent_at: {$exists: false}},
  {sent_at: null}

How to import load a .sql or .csv file into SQLite?

Try doing it from the command like:

cat dump.sql | sqlite3 database.db

This will obviously only work with SQL statements in dump.sql. I'm not sure how to import a CSV.

What Process is using all of my disk IO

You're looking for iotop (assuming you've got kernel >2.6.20 and Python 2.5). Failing that, you're looking into hooking into the filesystem. I recommend the former.

Command not found after npm install in zsh

FOR MAC: I tried some of the above but to no avail, could not get anything to work.

I did have BREW INSTALLED, so although this not be the best approach, with zsh, I did:

  1. sudo chown -R $(whoami) /usr/local/share/man/man8 (for brew access)
  2. brew update && brew install npm (I had had node installed)
  3. npm -v (to confirm install)
  4. nano ~/.zshrc (to empty file changes and save)

This worked for me. Hope this helps someone. #1 bothers me, but I will live with for now.

"document.getElementByClass is not a function"

Before jumping into any further error checking please first check whether its

document.getElementsByClassName() itself.

double check its getElements and not getElement

Java generating non-repeating random numbers

Integer[] arr = {...};

For example:

public static void main(String[] args) {
    Integer[] arr = new Integer[1000];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = i;


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

Thanks Riddhi M. Following worked for me.

Remove Temporary Files C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files Close VSTS and Open Again Remove and Add the same DLLs (Note: you add the same matching versions)

Creating a comma separated list from IList<string> or IEnumerable<string>

My answer is like above Aggregate solution but should be less call-stack heavy since there are no explicit delegate calls:

public static string ToCommaDelimitedString<T>(this IEnumerable<T> items)
    StringBuilder sb = new StringBuilder();
    foreach (var item in items)
    if (sb.Length >= 1) sb.Length--;
    return sb.ToString();

Of course, one can extend the signature to be delimiter-independent. I'm really not a fan of the sb.Remove() call and I'd like to refactor it to be a straight-up while-loop over an IEnumerable and use MoveNext() to determine whether or not to write a comma. I'll fiddle around and post that solution if I come upon it.

Here's what I wanted initially:

public static string ToDelimitedString<T>(this IEnumerable<T> source, string delimiter, Func<T, string> converter)
    StringBuilder sb = new StringBuilder();
    var en = source.GetEnumerator();
    bool notdone = en.MoveNext();
    while (notdone)
        notdone = en.MoveNext();
        if (notdone) sb.Append(delimiter);
    return sb.ToString();

No temporary array or list storage required and no StringBuilder Remove() or Length-- hack required.

In my framework library I made a few variations on this method signature, every combination of including the delimiter and the converter parameters with usage of "," and x.ToString() as defaults, respectively.

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

When you're using foreign key, your order of columns should be same for insertion.

For example, if you're adding (userid, password) in table1 from table2 then from table2 order should be same (userid, password) and not like (password,userid) where userid is foreign key in table2 of table1.

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

use the "onmouseup" property with each option element. it's verbose, but should work. also, depending on what your function is actually doing, you could arrange things a little differently, assuming the number is important in the handler:

<option onmouseup="handler()" value="1">1</option>  //get selected element in handler
<option onmouseup="handler(2)" value="2">2</option>  //explicitly send the value as argument
<option onmouseup="handler(this.value)" value="3">3</option> //same as above, but using the element's value property and allowing for dynamic option value. you could also send "this.innerHTML" or "this.textContent" to the handler, making option value unnecessary

CSS: fixed to bottom and centered

There are 2 potential issues that I see:

1 - IE has had trouble with position:fixed in the past. If you are using IE7+ with a valid doctype or a non-IE browser this isn't part of the problem

2 - You need to specify a width for the footer if you want the footer object to be centered. Otherwise it defaults to the full width of the page and the auto margin for the left and right get set to 0. If you want the footer bar to take up the width (like the StackOverflow notice bar) and center the text, then you need to add "text-align: center" to your definition.

How to remove the first character of string in PHP?

$str = substr($str, 1);

See PHP manual example 3

echo substr('abcdef', 1);     // bcdef



will not work as you cannot unset part of a string:-

Fatal error: Cannot unset string offsets

Postgresql -bash: psql: command not found

If you are using the Postgres Mac app (by Heroku) and Bundler, you can add the pg_config directly inside the app, to your bundle.

bundle config --with-pg-config=/Applications/

...then run bundle again.

Note: check the version first using the following.

ls /Applications/

Rendering partial view on button click in ASP.NET MVC

So here is the controller code.

public IActionResult AddURLTest()
    return ViewComponent("AddURL");

You can load it using JQuery load method.

$(document).ready (function(){

source code link

Public free web services for testing soap client

There is a bunch on here:

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

grep for special characters in Unix

grep -n "\*\^\%\Q\&\$\&\^\@\$\&\!\^\@\$\&\^\&\^\&\^\&" test.log

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

Changed my application.conf file as below. It solved the problem.

Before Change:

slick {
  dbs {
    default {
      profile = "slick.jdbc.MySQLProfile$"
      db {
        driver = "com.mysql.jdbc.Driver"
        url = "jdbc:mysql://localhost:3306/test"
        user = "root"
        password = "root"

After Change:

slick {
  dbs {
    default {
      profile = "slick.jdbc.MySQLProfile$"
      db {
        driver = "com.mysql.cj.jdbc.Driver"
        url = "jdbc:mysql://localhost:3306/test"
        user = "root"
        password = "root"

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

How to get element value in jQuery

$("#list li").click(function() {
        var selected = $(this).html();

Max value of Xmx and Xms in Eclipse?

I am guessing you are using a 32 bit eclipse with 32 bit JVM. It wont allow heapsize above what you have specified.

Using a 64-bit Eclipse with a 64-bit JVM helps you to start up eclipse with much larger memory. (I am starting with -Xms1024m -Xmx4000m)

Multiple Buttons' OnClickListener() android

You can use this

    TextView output = (TextView) findViewById(;
    // set the onclicklistener for other buttons also

    public void onClick(View v) {
      int id = v.getId();
    switch(id) {

 private void append(String s,TextView t){

you can identify the views in your activity in a separate method.

How to analyze disk usage of a Docker container

(this answer is not useful, but leaving it here since some of the comments may be)

docker images will show the 'virtual size', i.e. how much in total including all the lower layers. So some double-counting if you have containers that share the same base image.


Git: "Corrupt loose object"

I solved this way: I decided to simply copy the uncorrupted object file from the backup's clone to my original repository. This worked just as well. (By the way: If you can't find the object in .git/objects/ by its name, it probably has been [packed][pack] to conserve space.)

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

As far as I am aware, the MSVCRxxx.dlls are in %SystemRoot%\System32 (usually C:\Windows\System32).

The xxx refers to the version of the MS Visual C Runtime (hence MSVCR...)

However, the complication seems to be that the xxx version is not the same as the two digits of the year "version".

For example, Visual C Runtime 2013 yields MSVCR120.dll and "...Runtime 2012" yields MSVCR110.dll. And then Microsoft packages these as vcredist_x86.exe or vcredist_x64.exe, seemingly irrespective of the xxx version or the Visual Studio version number (2012, 2013 etc) - confused? You have every right to be!

So, firstly, you need to determine whether you need 32 bit, 64 bit or even both (some PHP distributions apparently do need both), then download the relevant vcredist... for the bits AND for the Visual Studio version. As far as I can tell, the only way to tell which vcredist... you have is to start to install it. Recent versions give an intro screen that quotes the Visual Studio version and the xxx version. I have renamed by vcredists to something like vcredist_x64_2012_V11.exe.

[EDIT] Forgot to add earlier that if you are simply looking to "install" the missing DLL (as opposed to resolve some bigger set of issues), then you probably won't do any harm by simply installing the relevant vcredist for your architecture (32 bit, 64 bit) and "missing" version.

How to delete last character from a string using jQuery?

@skajfes and @GolezTrol provided the best methods to use. Personally, I prefer using "slice()". It's less code, and you don't have to know how long a string is. Just use:

// @param begin  Required. The index where 
//               to begin the extraction. 
//               1st character is at index 0
// @param end    Optional. Where to end the
//               extraction. If omitted, 
//               slice() selects all 
//               characters from the begin 
//               position to the end of 
//               the string.
var str = '123-4';
alert(str.slice(0, -1));

jQuery how to find an element based on a data-attribute value?

in case you don't want to type all that, here's a shorter way to query by data attribute:

$("ul[data-slide='" + current +"']");


How to check if object has been disposed in C#

If you're not sure whether the object has been disposed or not, you should call the Dispose method itself rather than methods such as Close. While the framework doesn't guarantee that the Dispose method must run without exceptions even if the object had previously been disposed, it's a common pattern and to my knowledge implemented on all disposable objects in the framework.

The typical pattern for Dispose, as per Microsoft:

public void Dispose() 

    // Use SupressFinalize in case a subclass
    // of this type implements a finalizer.

protected virtual void Dispose(bool disposing)
    // If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    if (!_disposed)
        if (disposing) {
            if (_resource != null)
                Console.WriteLine("Object disposed.");

        // Indicate that the instance has been disposed.
        _resource = null;
        _disposed = true;   

Notice the check on _disposed. If you were to call a Dispose method implementing this pattern, you could call Dispose as many times as you wanted without hitting exceptions.

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

A couple of suggestions

The ACE driver isn't installed by default. It's also a 64 bit driver, so it might be worth disabling 32bit in your app pool. I've known 64 bit drivers not work when 32 bit is enabled.(eg the ISAPI filter which connects IIS to Tomcat).

The older JET driver is 32bit. It is included by default. If you could save a copy of your database as a .mdb file then using the JET driver might be a workaround

Java Desktop application: SWT vs. Swing

One thing to consider: Screenreaders

For some reasons, some Swing components do not work well when using a screenreader (and the Java AccessBridge for Windows). Know that different screenreaders result in different behaviour. And in my experience the SWT-Tree performs a lot better than the Swing-Tree in combination with a screenreader. Thus our application ended up in using both SWT and Swing components.

For distributing and loading the proper SWT-library, you might find this link usefull:

Pivoting rows into columns dynamically in Oracle

Oracle 11g provides a PIVOT operation that does what you want.

Oracle 11g solution

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)

I obtained this solution from:

EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)

Edit2: Changed v in the pivot and pivot xml statements to max(v) since it is supposed to be aggregated as mentioned in one of the comments. I also added the in clause which is not optional for pivot. Of course, having to specify the values in the in clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.

Can I use an image from my local file system as background in HTML?

background: url(../images/backgroundImage.jpg) no-repeat center center fixed;

this should help

iOS - UIImageView - how to handle UIImage image orientation

If I understand, what you want to do is disregard the orientation of the UIImage? If so then you could do this:

UIImage *originalImage = [... whatever ...];

UIImage *imageToDisplay =
     [UIImage imageWithCGImage:[originalImage CGImage]
              scale:[originalImage scale]
              orientation: UIImageOrientationUp];

So you're creating a new UIImage with the same pixel data as the original (referenced via its CGImage property) but you're specifying an orientation that doesn't rotate the data.


You should be able to do this by checking the value of $_SERVER['HTTPS'] (it should only be set when using https).


How do I run msbuild from the command line using Windows SDK 7.1?

The SetEnv.cmd script that the "SDK command prompt" shortcut runs checks for cl.exe in various places before setting up entries to add to PATH. So it fails to add anything if a native C compiler is not installed.

To fix that, apply the following patch to <SDK install dir>\Bin\SetEnv.cmd. This will also fix missing paths to other tools located in <SDK install dir>\Bin and subfolders. Of course, you can install the C compiler instead to work around this bug.

--- SetEnv.Cmd_ 2010-04-27 19:52:00.000000000 +0400
+++ SetEnv.Cmd  2013-12-02 15:05:30.834400000 +0400
@@ -228,10 +228,10 @@

 IF "%CURRENT_CPU%" =="x64" (
   IF "%TARGET_CPU%" == "x64" (
+    SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\amd64\cl.exe" (
       SET "VCTools=%VCTools%\amd64;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The x64 compilers are not currently installed.
@@ -239,10 +239,10 @@
       ECHO .
   ) ELSE IF "%TARGET_CPU%" == "IA64" (
+    SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\x86_ia64\cl.exe" (
       SET "VCTools=%VCTools%\x86_ia64;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The IA64 compilers are not currently installed.
@@ -250,10 +250,10 @@
       ECHO .
   ) ELSE IF "%TARGET_CPU%" == "x86" (
+    SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\cl.exe" (
       SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The x86 compilers are not currently installed.
@@ -263,10 +263,10 @@
 ) ELSE IF "%CURRENT_CPU%" =="IA64" (
   IF "%TARGET_CPU%" == "IA64" (
+    SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\IA64\cl.exe" (
       SET "VCTools=%VCTools%\IA64;%VCTools%;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The IA64 compilers are not currently installed.
@@ -274,10 +274,10 @@
       ECHO .
   ) ELSE IF "%TARGET_CPU%" == "x64" (
+    SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\x86_amd64\cl.exe" (
       SET "VCTools=%VCTools%\x86_amd64;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The VC compilers are not currently installed.
@@ -285,10 +285,10 @@
       ECHO .
   ) ELSE IF "%TARGET_CPU%" == "x86" (
+    SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\cl.exe" (
       SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The x86 compilers are not currently installed.
@@ -298,10 +298,10 @@
 ) ELSE IF "%CURRENT_CPU%"=="x86" (
   IF "%TARGET_CPU%" == "x64" (
+    SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\x86_amd64\cl.exe" (
       SET "VCTools=%VCTools%\x86_amd64;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The x64 cross compilers are not currently installed.
@@ -309,10 +309,10 @@
       ECHO .
   ) ELSE IF "%TARGET_CPU%" == "IA64" (
+    SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\x86_IA64\cl.exe" (
       SET "VCTools=%VCTools%\x86_IA64;%VCTools%;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The IA64 compilers are not currently installed.
@@ -320,10 +320,10 @@
       ECHO .
   ) ELSE IF "%TARGET_CPU%" == "x86" (
+    SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\cl.exe" (
       SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The x86 compilers are not currently installed. x86-x86
@@ -331,15 +331,17 @@
       ECHO .
-) ELSE IF EXIST "%VCTools%\cl.exe" (
-  SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
-  SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-  SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
 ) ELSE (
-  SET VCTools=
-  ECHO The x86 compilers are not currently installed. default
-  ECHO Please go to Add/Remove Programs to update your installation.
-  ECHO .
+  SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+  SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
+  IF EXIST "%VCTools%\cl.exe" (
+    SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
+  ) ELSE (
+    SET VCTools=
+    ECHO The x86 compilers are not currently installed. default
+    ECHO Please go to Add/Remove Programs to update your installation.
+    ECHO .
+  )

 :: --------------------------------------------------------------------------------------------

Sort tuples based on second parameter

And if you are using python 3.X, you may apply the sorted function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.

# using *sort method*
mylist.sort(lambda x: x[1]) 

# using *sorted function*
sorted(mylist, key = lambda x: x[1]) 

How to include clean target in Makefile?

The best thing is probably to create a variable that holds your binaries:

binaries=code1 code2

Then use that in the all-target, to avoid repeating:

all: clean $(binaries)

Now, you can use this with the clean-target, too, and just add some globs to catch object files and stuff:

.PHONY: clean

    rm -f $(binaries) *.o

Note use of the .PHONY to make clean a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.

image processing to improve tesseract OCR accuracy

Java version for Sathyaraj's code above:

// Resize
public Bitmap resize(Bitmap img, int newWidth, int newHeight) {
    Bitmap bmap = img.copy(img.getConfig(), true);

    double nWidthFactor = (double) img.getWidth() / (double) newWidth;
    double nHeightFactor = (double) img.getHeight() / (double) newHeight;

    double fx, fy, nx, ny;
    int cx, cy, fr_x, fr_y;
    int color1;
    int color2;
    int color3;
    int color4;
    byte nRed, nGreen, nBlue;

    byte bp1, bp2;

    for (int x = 0; x < bmap.getWidth(); ++x) {
        for (int y = 0; y < bmap.getHeight(); ++y) {

            fr_x = (int) Math.floor(x * nWidthFactor);
            fr_y = (int) Math.floor(y * nHeightFactor);
            cx = fr_x + 1;
            if (cx >= img.getWidth())
                cx = fr_x;
            cy = fr_y + 1;
            if (cy >= img.getHeight())
                cy = fr_y;
            fx = x * nWidthFactor - fr_x;
            fy = y * nHeightFactor - fr_y;
            nx = 1.0 - fx;
            ny = 1.0 - fy;

            color1 = img.getPixel(fr_x, fr_y);
            color2 = img.getPixel(cx, fr_y);
            color3 = img.getPixel(fr_x, cy);
            color4 = img.getPixel(cx, cy);

            // Blue
            bp1 = (byte) (nx * + fx *;
            bp2 = (byte) (nx * + fx *;
            nBlue = (byte) (ny * (double) (bp1) + fy * (double) (bp2));

            // Green
            bp1 = (byte) (nx * + fx *;
            bp2 = (byte) (nx * + fx *;
            nGreen = (byte) (ny * (double) (bp1) + fy * (double) (bp2));

            // Red
            bp1 = (byte) (nx * + fx *;
            bp2 = (byte) (nx * + fx *;
            nRed = (byte) (ny * (double) (bp1) + fy * (double) (bp2));

            bmap.setPixel(x, y, Color.argb(255, nRed, nGreen, nBlue));

    bmap = setGrayscale(bmap);
    bmap = removeNoise(bmap);

    return bmap;

// SetGrayscale
private Bitmap setGrayscale(Bitmap img) {
    Bitmap bmap = img.copy(img.getConfig(), true);
    int c;
    for (int i = 0; i < bmap.getWidth(); i++) {
        for (int j = 0; j < bmap.getHeight(); j++) {
            c = bmap.getPixel(i, j);
            byte gray = (byte) (.299 * + .587 *
                    + .114 *;

            bmap.setPixel(i, j, Color.argb(255, gray, gray, gray));
    return bmap;

// RemoveNoise
private Bitmap removeNoise(Bitmap bmap) {
    for (int x = 0; x < bmap.getWidth(); x++) {
        for (int y = 0; y < bmap.getHeight(); y++) {
            int pixel = bmap.getPixel(x, y);
            if ( < 162 && < 162 && < 162) {
                bmap.setPixel(x, y, Color.BLACK);
    for (int x = 0; x < bmap.getWidth(); x++) {
        for (int y = 0; y < bmap.getHeight(); y++) {
            int pixel = bmap.getPixel(x, y);
            if ( > 162 && > 162 && > 162) {
                bmap.setPixel(x, y, Color.WHITE);
    return bmap;

Convert varchar to float IF ISNUMERIC

I found this very annoying bug while converting EmployeeID values with ISNUMERIC:

ISNUMERIC(ISNULL([EmployeeID], '')) AS [IsNumericResult],

CASE WHEN COALESCE(NULLIF(tmpImport.[EmployeeID], ''), 'Z')
    LIKE '%[^0-9]%' THEN 'NonNumeric' ELSE 'Numeric'
END AS [IsDigitsResult]
FROM [MyTable]

This returns:

EmployeeID IsNumericResult MyCustomResult
---------- --------------- --------------
           0               NonNumeric
00000000c  0               NonNumeric
00D026858  1               NonNumeric

(3 row(s) affected)

Hope this helps!

how to always round up to the next integer

Math.Ceiling((double)list.Count() / 10);

How to know if an object has an attribute in Python

Depending on the situation you can check with isinstance what kind of object you have, and then use the corresponding attributes. With the introduction of abstract base classes in Python 2.6/3.0 this approach has also become much more powerful (basically ABCs allow for a more sophisticated way of duck typing).

One situation were this is useful would be if two different objects have an attribute with the same name, but with different meaning. Using only hasattr might then lead to strange errors.

One nice example is the distinction between iterators and iterables (see this question). The __iter__ methods in an iterator and an iterable have the same name but are semantically quite different! So hasattr is useless, but isinstance together with ABC's provides a clean solution.

However, I agree that in most situations the hasattr approach (described in other answers) is the most appropriate solution.

How to instantiate a File object in JavaScript?

The idea ...To create a File object (api) in javaScript for images already present in the DOM :

<img src="../img/Products/fijRKjhudDjiokDhg1524164151.jpg">

var file = new File(['fijRKjhudDjiokDhg1524164151'],

// created object file

Don't do that ! ... (but I did it anyway)

-> the console give a result similar as an Object File :

File(0) {name: "fijRKjokDhgfsKtG1527053050.jpg", lastModified: 1527053530715, lastModifiedDate: Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)), webkitRelativePath: "", size: 0, …}
lastModifiedDate:Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)) {}

But the size of the object is wrong ...

Why i need to do that ?

For example to retransmit an image form already uploaded, during a product update, along with additional images added during the update

How can I set Image source with base64

Your problem are the cr (carriage return)

you can use:

document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

But if i take the piece of sql and run it from sql management studio, it will run without issue.

If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.

The real crux of the issue is:

I use the following to convert -> date.Value.ToString("MM/dd/yyyy HH:mm:ss")

Please start using parameterized queries so that you won't encounter these issues in the future. It is also more robust, predictable and best practice.

Postgresql, update if row with some unique value exists, else insert

Firstly It tries insert. If there is a conflict on url column then it updates content and last_analyzed fields. If updates are rare this might be better option.

INSERT INTO URLs (url, content, last_analyzed)
SET content=%(content)s, last_analyzed = NOW();

How to build and run Maven projects after importing into Eclipse IDE

1.Update project

Right Click on your project maven > update project

2.Build project

Right Click on your project again. run as > Maven build

If you have not created a “Run configuration” yet, it will open a new configuration with some auto filled values.

You can change the name. "Base directory" will be a auto filled value for you. Keep it as it is. Give maven command to ”Goals” fields.

i.e, “clean install” for building purpose

Click apply

Click run.

3.Run project on tomcat

Right Click on your project again. run as > Run-Configuration. It will open Run-Configuration window for you.

Right Click on “Maven Build” from the right side column and Select “New”. It will open a blank configuration for you.

Change the name as you want. For the base directory field you can choose values using 3 buttons(workspace,FileSystem,Variables). You can also copy and paste the auto generated value from previously created Run-configuration. Give the Goals as “tomcat:run”. Click apply. Click run.

If you want to get more clear idea with snapshots use the following link.

Build and Run Maven project in Eclipse

(I hope this answer will help someone come after the topic of the question)

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

How to validate a credit card number

I hope the following two links help to solve your problem.

FYI, various credit cards are available in the world. So, your thought is wrong. Credit cards have some format. See the following links. The first one is pure JavaScript and the second one is using jQuery.


function testCreditCard() {_x000D_
  myCardNo = document.getElementById('CardNumber').value;_x000D_
  myCardType = document.getElementById('CardType').value;_x000D_
  if (checkCreditCard(myCardNo, myCardType)) {_x000D_
    alert("Credit card has a valid format")_x000D_
  } else {_x000D_
<script src=""></script>_x000D_
      <td style="padding-right: 30px;">American Express</td>_x000D_
      <td>3400 0000 0000 009</td>_x000D_
      <td>Carte Blanche</td>_x000D_
      <td>3000 0000 0000 04</td>_x000D_
      <td>6011 0000 0000 0004</td>_x000D_
      <td>Diners Club</td>_x000D_
      <td>3852 0000 0232 37</td>_x000D_
      <td>2014 0000 0000 009</td>_x000D_
      <td>3530 111333300000</td>_x000D_
      <td>5500 0000 0000 0004</td>_x000D_
      <td>6334 0000 0000 0004</td>_x000D_
      <td>4903 0100 0000 0009</td>_x000D_
      <td>4111 1111 1111 1111</td>_x000D_
      <td>6304 1000 0000 0008</td>_x000D_
<hr /> Card Number:_x000D_
<select tabindex="11" id="CardType" style="margin-left: 10px;">_x000D_
  <option value="AmEx">American Express</option>_x000D_
  <option value="CarteBlanche">Carte Blanche</option>_x000D_
  <option value="DinersClub">Diners Club</option>_x000D_
  <option value="Discover">Discover</option>_x000D_
  <option value="EnRoute">enRoute</option>_x000D_
  <option value="JCB">JCB</option>_x000D_
  <option value="Maestro">Maestro</option>_x000D_
  <option value="MasterCard">MasterCard</option>_x000D_
  <option value="Solo">Solo</option>_x000D_
  <option value="Switch">Switch</option>_x000D_
  <option value="Visa">Visa</option>_x000D_
  <option value="VisaElectron">Visa Electron</option>_x000D_
  <option value="LaserCard">Laser</option>_x000D_
</select> <input type="text" id="CardNumber" maxlength="24" size="24" style="margin-left: 10px;"> <button id="mybutton" type="button" onclick="testCreditCard();" style="margin-left: 10px; color: #f00;">Check</button>_x000D_
<p style="color: red; font-size: 10px;"> COPIED THE DEMO CODE FROM TEH SOURCE WEBSITE ( </p>

Reading file using fscanf() in C

In your code:

while(fscanf(fp,"%s %c",item,&status) == 1)  

why 1 and not 2? The scanf functions return the number of objects read.

Easy way to build Android UI?

Droiddraw is good. I have been using it since long and haven't faced any issues yet (though it crashes sometimes, but thats ok)

pythonic way to do something N times without an index variable?

A slightly faster approach than looping on xrange(N) is:

import itertools

for _ in itertools.repeat(None, N):

In android how to set navigation drawer header image and name programmatically in class file?

As mentioned in the bug 190226, Since version 23.1.0 getting header layout view with: navigationView.findViewById( no longer works.

A workaround is to inflate the headerview programatically and find view by ID from the inflated header view.

For example:

View headerView = navigationView.inflateHeaderView(R.layout.navigation_header);

Ideally there should be a method getHeaderView() but it has already been proposed, let's see and wait for it to be released in the feature release of design support library.

AngularJS/javascript converting a date String to date object

I know this is in the above answers, but my point is that I think all you need is

new Date(collectionDate);

if your goal is to convert a date string into a date (as per the OP "How do I convert it to a date object?").

Retrieve specific commit from a remote Git repository

This works best:

git fetch origin specific_commit
git checkout -b temp FETCH_HEAD

name "temp" whatever you want...this branch might be orphaned though