Programs & Examples On #Boost build

Boost Build is designed as a multi-platform replacement for for build control systems like GNUMake. Unlike Make, it is currently limited to programs written in C++.

How to calculate a Mod b in Casio fx-991ES calculator

There is a switch a^b/c

If you want to calculate

491 mod 12

then enter 491 press a^b/c then enter 12. Then you will get 40, 11, 12. Here the middle one will be the answer that is 11.

Similarly if you want to calculate 41 mod 12 then find 41 a^b/c 12. You will get 3, 5, 12 and the answer is 5 (the middle one). The mod is always the middle value.

How to use a DataAdapter with stored procedure and parameter

 SqlConnection con = new SqlConnection(@"Some Connection String");
 SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123;
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

Jinja2 shorthand conditional

Yes, it's possible to use inline if-expressions:

{{ 'Update' if files else 'Continue' }}

Certificate has either expired or has been revoked

Sometimes the "Bundle Identifier" in Xcode is changing due to some things that you made. Make sure the Bundle Identifier you defined in your Apple Developer account is exactly the same as the one in Xcode.

Capturing Groups From a Grep RegEx

I prefer the one line python or perl command, both often included in major linux disdribution

echo $'
<a href="http://stackoverflow.com">
</a>
<a href="http://google.com">
</a>
' |  python -c $'
import re
import sys
for i in sys.stdin:
  g=re.match(r\'.*href="(.*)"\',i);
  if g is not None:
    print g.group(1)
'

and to handle files:

ls *.txt | python -c $'
import sys
import re
for i in sys.stdin:
  i=i.strip()
  f=open(i,"r")
  for j in f:
    g=re.match(r\'.*href="(.*)"\',j);
    if g is not None:
      print g.group(1)
  f.close()
'

Filtering lists using LINQ

This LINQ below will generate the SQL for a left outer join and then take all of the results that don't find a match in your exclusion list.

List<Person> filteredResults =from p in people
        join e in exclusions on p.compositeKey equals e.compositeKey into temp
        from t in temp.DefaultIfEmpty()
        where t.compositeKey == null
        select p

let me know if it works!

How do you share constants in NodeJS modules?

I ended up doing this by exporting a frozen object with anonymous getter functions, rather than the constants themselves. This reduces the risk of nasty bugs introduced due to a simple typo of the const name, as a runtime error will be thrown in case of a typo. Here's a full example that also uses ES6 Symbols for the constants, ensuring uniqueness, and ES6 arrow functions. Would appreciate feedback if anything in this approach seems problematic.

'use strict';
const DIRECTORY = Symbol('the directory of all sheets');
const SHEET = Symbol('an individual sheet');
const COMPOSER = Symbol('the sheet composer');

module.exports = Object.freeze({
  getDirectory: () => DIRECTORY,
  getSheet: () => SHEET,
  getComposer: () => COMPOSER
});

Get Android Device Name

You can see answers at here Get Android Phone Model Programmatically

public String getDeviceName() {
   String manufacturer = Build.MANUFACTURER;
   String model = Build.MODEL;
   if (model.startsWith(manufacturer)) {
      return capitalize(model);
   } else {
      return capitalize(manufacturer) + " " + model;
   }
}


private String capitalize(String s) {
    if (s == null || s.length() == 0) {
        return "";
    }
    char first = s.charAt(0);
    if (Character.isUpperCase(first)) {
        return s;
    } else {
        return Character.toUpperCase(first) + s.substring(1);
    }
}

Laravel Mail::send() sending to multiple to or bcc addresses

it works for me fine, if you a have string, then simply explode it first.

$emails = array();

Mail::send('emails.maintenance',$mail_params, function($message) use ($emails) {
    foreach ($emails as $email) {
        $message->to($email);
    }

    $message->subject('My Email');
});

Rendering React Components from Array of Objects

This is quite likely the simplest way to achieve what you are looking for.

In order to use this map function in this instance, we will have to pass a currentValue (always-required) parameter, as well an index (optional) parameter. In the below example, station is our currentValue, and x is our index.

station represents the current value of the object within the array as it is iterated over. x automatically increments; increasing by one each time a new object is mapped.

render () {
    return (
        <div>
            {stations.map((station, x) => (
                <div key={x}> {station} </div>
            ))}
        </div>
    );
}

What Thomas Valadez had answered, while it had provided the best/simplest method to render a component from an array of objects, it had failed to properly address the way in which you would assign a key during this process.

What is the best Java library to use for HTTP POST, GET etc.?

I want to mention the Ning Async Http Client Library. I've never used it but my colleague raves about it as compared to the Apache Http Client, which I've always used in the past. I was particularly interested to learn it is based on Netty, the high-performance asynchronous i/o framework, with which I am more familiar and hold in high esteem.

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

Is it possible to use an input value attribute as a CSS selector?

Following the currently top voted answer, I've found using a dataset / data attribute works well.

_x000D_
_x000D_
//Javascript

const input1 = document.querySelector("#input1");
input1.value = "0.00";
input1.dataset.value = input1.value;
//dataset.value will set "data-value" on the input1 HTML element
//and will be used by CSS targetting the dataset attribute

document.querySelectorAll("input").forEach((input) => {
  input.addEventListener("input", function() {
    this.dataset.value = this.value;
    console.log(this);
  })
})
_x000D_
/*CSS*/

input[data-value="0.00"] {
  color: red;
}
_x000D_
<!--HTML-->

<div>
  <p>Input1 is programmatically set by JavaScript:</p>
  <label for="input1">Input 1:</label>
  <input id="input1" value="undefined" data-value="undefined">
</div>
<br>
<div>
  <p>Try typing 0.00 inside input2:</p>
  <label for="input2">Input 2:</label>
  <input id="input2" value="undefined" data-value="undefined">
</div>
_x000D_
_x000D_
_x000D_

How to ssh connect through python Paramiko with ppk public key

@VonC's answer to a duplicate question:

If, as commented, Paraminko does not support PPK key, the official solution, as seen here, would be to use PuTTYgen.

But you can also use the Python library CkSshKey to make that same conversion directly in your program.

See "Convert PuTTY Private Key (ppk) to OpenSSH (pem)"

import sys
import chilkat

key = chilkat.CkSshKey()

#  Load an unencrypted or encrypted PuTTY private key.

#  If  your PuTTY private key is encrypted, set the Password
#  property before calling FromPuttyPrivateKey.
#  If your PuTTY private key is not encrypted, it makes no diffference
#  if Password is set or not set.
key.put_Password("secret")

#  First load the .ppk file into a string:

keyStr = key.loadText("putty_private_key.ppk")

#  Import into the SSH key object:
success = key.FromPuttyPrivateKey(keyStr)
if (success != True):
    print(key.lastErrorText())
    sys.exit()

#  Convert to an encrypted or unencrypted OpenSSH key.

#  First demonstrate converting to an unencrypted OpenSSH key

bEncrypt = False
unencryptedKeyStr = key.toOpenSshPrivateKey(bEncrypt)
success = key.SaveText(unencryptedKeyStr,"unencrypted_openssh.pem")
if (success != True):
    print(key.lastErrorText())
    sys.exit()

Play multiple CSS animations at the same time

TL;DR

With a comma, you can specify multiple animations each with their own properties as stated in the CriticalError answer below.

Example:

animation: rotate 1s, spin 3s;

Original answer

There are two issues here:

#1

-webkit-animation:spin 2s linear infinite;
-webkit-animation:scale 4s linear infinite;

The second line replaces the first one. So, has no effect.

#2

Both keyframes applies on the same property transform

As an alternative you could to wrap the image in a <div> and animate each one separately and at different speeds.

http://jsfiddle.net/rnrlabs/x9cu53hp/

_x000D_
_x000D_
.scaler {
    position: absolute;
    top: 100%;
    left: 50%;
    width: 120px;
    height: 120px;
    margin:-60px 0 0 -60px;
    animation: scale 4s infinite linear;    
}

.spinner {
    position: relative;
    top: 150px;
    animation: spin 2s infinite linear;
}


@keyframes spin { 
    100% { 
        transform: rotate(180deg);
    } 
}

@keyframes scale {
    100% {
         transform: scaleX(2) scaleY(2);
    }
}
_x000D_
<div class="spinner">
<img class="scaler" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
<div>
_x000D_
_x000D_
_x000D_

Python 2.7.10 error "from urllib.request import urlopen" no module named request

You are right the urllib and urllib2 packages have been split into urllib.request , urllib.parse and urllib.error packages in Python 3.x. The latter packages do not exist in Python 2.x

From documentation -

The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.

From urllib2 documentation -

The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error.

So I am pretty sure the code you downloaded has been written for Python 3.x , since they are using a library that is only present in Python 3.x .

There is a urllib package in python, but it does not have the request subpackage. Also, lets assume you do lots of work and somehow make request subpackage available in Python 2.x .

There is a very very high probability that you will run into more issues, there is lots of incompatibility between Python 2.x and Python 3.x , in the end you would most probably end up rewriting atleast half the code from github (and most probably reading and understanding the complete code from there).

Even then there may be other bugs arising from the fact that some of the implementation details changed between Python 2.x to Python 3.x (As an example - list comprehension got its own namespace in Python 3.x)

You are better off trying to download and use Python 3 , than trying to make code written for Python 3.x compatible with Python 2.x

Send string to stdin

Solution

You want to (1) create stdout output in one process (like echo '…') and (2) redirect that output to stdin input of another process but (3) without the use of the bash pipe mechanism. Here's a solution that matches all three conditions:

/my/bash/script < <(echo 'This string will be sent to stdin.')

The < is normal input redirection for stdin. The <(…) is bash process substitution. Roughly it creates a /dev/fd/… file with the output of the substituting command and passes that filename in place of the <(…), resulting here for example in script < /dev/fd/123. For details, see this answer.

Comparison with other solutions

  • A one-line heredoc sent to stdin script <<< 'string' only allows to send static strings, not the output of other commands.

  • Process substitution alone, such as in diff <(ls /bin) <(ls /usr/bin), does not send anything to stdin. Instead, the process output is saved into a file, and its path is passed as a command line argument. For the above example, this is equivalent to diff /dev/fd/10 /dev/fd/11, a command where diff receives no input from stdin.

Use cases

I like that, unlike the pipe mechanism, the < <(…) mechanism allows to put the command first and all input after it, as is the standard for input from command line options.

However, beyond commandline aesthetics, there are some cases where a pipe mechanism cannot be used. For example, when a certain command has to be provided as argument to another command, such as in this example with sshpass.

How to post a file from a form with Axios

How to post file using an object in memory (like a JSON object):

import axios from 'axios';
import * as FormData  from 'form-data'

async function sendData(jsonData){
    // const payload = JSON.stringify({ hello: 'world'});
    const payload = JSON.stringify(jsonData);
    const bufferObject = Buffer.from(payload, 'utf-8');
    const file = new FormData();

    file.append('upload_file', bufferObject, "b.json");

    const response = await axios.post(
        lovelyURL,
        file,
        headers: file.getHeaders()
    ).toPromise();


    console.log(response?.data);
}

Matplotlib legends in subplot

This does what you want and overcomes some of the problems in other answers:

import matplotlib.pyplot as plt

labels = ["HHZ 1", "HHN", "HHE"]
colors = ["r","g","b"]

f,axs = plt.subplots(3, sharex=True, sharey=True)

# ---- loop over axes ----
for i,ax in enumerate(axs):
  axs[i].plot([0,1],[1,0],color=colors[i],label=labels[i])
  axs[i].legend(loc="upper right")

plt.show()

... produces ... subplots

Python constructors and __init__

Classes are simply blueprints to create objects from. The constructor is some code that are run every time you create an object. Therefor it does'nt make sense to have two constructors. What happens is that the second over write the first.

What you typically use them for is create variables for that object like this:

>>> class testing:
...     def __init__(self, init_value):
...         self.some_value = init_value

So what you could do then is to create an object from this class like this:

>>> testobject = testing(5)

The testobject will then have an object called some_value that in this sample will be 5.

>>> testobject.some_value
5

But you don't need to set a value for each object like i did in my sample. You can also do like this:

>>> class testing:
...     def __init__(self):
...         self.some_value = 5

then the value of some_value will be 5 and you don't have to set it when you create the object.

>>> testobject = testing()
>>> testobject.some_value
5

the >>> and ... in my sample is not what you write. It's how it would look in pyshell...

Grep and Python

Concise and memory efficient:

#!/usr/bin/env python
# file: grep.py
import re, sys

map(sys.stdout.write,(l for l in sys.stdin if re.search(sys.argv[1],l)))

It works like egrep (without too much error handling), e.g.:

cat input-file | grep.py "RE"

And here is the one-liner:

cat input-file | python -c "import re,sys;map(sys.stdout.write,(l for l in sys.stdin if re.search(sys.argv[1],l)))" "RE"

How do I remove a specific element from a JSONArray?

i guess you are using Me version, i suggest to add this block of function manually, in your code (JSONArray.java) :

public Object remove(int index) {
    Object o = this.opt(index);
    this.myArrayList.removeElementAt(index);
    return o;
}

In java version they use ArrayList, in ME Version they use Vector.

System.Data.OracleClient requires Oracle client software version 8.1.7

Why not use this: dotConnect for Oracle (formerly known as OraDirect .NET)?

It can be configured to not require an Oracle Client at all.

We have been using this in both Windows Services and ASP.NET Web Services and it works like a charm.

Creating a byte array from a stream

You can simply use ToArray() method of MemoryStream class, for ex-

MemoryStream ms = (MemoryStream)dataInStream;
byte[] imageBytes = ms.ToArray();

Append a single character to a string or char array in java?

You'll want to use the static method Character.toString(char c) to convert the character into a string first. Then you can use the normal string concatenation functions.

UITableView, Separator color where to set?

Swift version:

override func viewDidLoad() {
    super.viewDidLoad()

    // Assign your color to this property, for example here we assign the red color.
    tableView.separatorColor = UIColor.redColor()
}

How do I skip an iteration of a `foreach` loop?

Another approach is to filter using LINQ before the loop executes:

foreach ( int number in numbers.Where(n => n >= 0) )
{
    // process number
}

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

On my Mac OS, Text Wrangler identified a CSV file created with Excel as having "Western" encoding.

After some googling I have made this small script (I am not sure about Windows availability, maybe with Cygwin?):

$ cat /usr/local/bin/utf8.sh

#!/bin/bash

INPUTFILE="$1"

iconv -f macroman -c -t UTF-8 $INPUTFILE |tr '\r' '\n' >/tmp/file.$$.csv

mv $INPUTFILE ms_trash
mv /tmp/file.$$.csv $INPUTFILE

SQL multiple column ordering

You can use multiple ordering on multiple condition,

ORDER BY 
     (CASE 
        WHEN @AlphabetBy = 2  THEN [Drug Name]
      END) ASC,
    CASE 
        WHEN @TopBy = 1  THEN [Rx Count]
        WHEN @TopBy = 2  THEN [Cost]
        WHEN @TopBy = 3  THEN [Revenue]
    END DESC 

Multiple glibc libraries on a single host

I am not sure that the question is still relevant, but there is another way of fixing the problem: Docker. One can install an almost empty container of the Source Distribution (The Distribution used for development) and copy the files into the Container. That way You do not need to create the filesystem needed for chroot.

Use grep to report back only line numbers

using only grep:

grep -n "text to find" file.ext | grep -Po '^[^:]+'

How can I build multiple submit buttons django form?

It's an old question now, nevertheless I had the same issue and found a solution that works for me: I wrote MultiRedirectMixin.

from django.http import HttpResponseRedirect

class MultiRedirectMixin(object):
    """
    A mixin that supports submit-specific success redirection.
     Either specify one success_url, or provide dict with names of 
     submit actions given in template as keys
     Example: 
       In template:
         <input type="submit" name="create_new" value="Create"/>
         <input type="submit" name="delete" value="Delete"/>
       View:
         MyMultiSubmitView(MultiRedirectMixin, forms.FormView):
             success_urls = {"create_new": reverse_lazy('create'),
                               "delete": reverse_lazy('delete')}
    """
    success_urls = {}  

    def form_valid(self, form):
        """ Form is valid: Pick the url and redirect.
        """

        for name in self.success_urls:
            if name in form.data:
                self.success_url = self.success_urls[name]
                break

        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        """
        Returns the supplied success URL.
        """
        if self.success_url:
            # Forcing possible reverse_lazy evaluation
            url = force_text(self.success_url)
        else:
            raise ImproperlyConfigured(
                _("No URL to redirect to. Provide a success_url."))
        return url

Get Return Value from Stored procedure in asp.net

Procedure never returns a value.You have to use a output parameter in store procedure.

ALTER PROC TESTLOGIN
@UserName   varchar(50),
@password   varchar(50)
@retvalue int output
 as
 Begin
    declare @return     int 
    set @return  = (Select COUNT(*) 
    FROM    CPUser  
    WHERE   UserName = @UserName AND Password = @password)

   set @retvalue=@return
  End

Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.

PHP Include for HTML?

Here is the step by step process to include php code in html file ( Tested )

If PHP is working there is only one step left to use PHP scripts in files with *.html or *.htm extensions as well. The magic word is ".htaccess". Please see the Wikipedia definition of .htaccess to learn more about it. According to Wikipedia it is "a directory-level configuration file that allows for decentralized management of web server configuration."

You can probably use such a .htaccess configuration file for your purpose. In our case you want the webserver to parse HTML files like PHP files.

First, create a blank text file and name it ".htaccess". You might ask yourself why the file name starts with a dot. On Unix-like systems this means it is a dot-file is a hidden file. (Note: If your operating system does not allow file names starting with a dot just name the file "xyz.htaccess" temporarily. As soon as you have uploaded it to your webserver in a later step you can rename the file online to ".htaccess") Next, open the file with a simple text editor like the "Editor" in MS Windows. Paste the following line into the file: AddType application/x-httpd-php .html .htm If this does not work, please remove the line above from your file and paste this alternative line into it, for PHP5: AddType application/x-httpd-php5 .html .htm Now upload the .htaccess file to the root directory of your webserver. Make sure that the name of the file is ".htaccess". Your webserver should now parse *.htm and *.html files like PHP files.

You can try if it works by creating a HTML-File like the following. Name it "php-in-html-test.htm", paste the following code into it and upload it to the root directory of your webserver:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
     <HTML>
 <HEAD>
 <TITLE>Use PHP in HTML files</TITLE>
 </HEAD>

   <BODY>
    <h1>
    <?php echo "It works!"; ?>
    </h1>
  </BODY>
 </HTML>

Try to open the file in your browser by typing in: http://www.your-domain.com/php-in-html-test.htm (once again, please replace your-domain.com by your own domain...) If your browser shows the phrase "It works!" everything works fine and you can use PHP in .*html and *.htm files from now on. However, if not, please try to use the alternative line in the .htaccess file as we showed above. If is still does not work please contact your hosting provider.

Why would one use nested classes in C++?

Nested classes are cool for hiding implementation details.

List:

class List
{
    public:
        List(): head(nullptr), tail(nullptr) {}
    private:
        class Node
        {
              public:
                  int   data;
                  Node* next;
                  Node* prev;
        };
    private:
        Node*     head;
        Node*     tail;
};

Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.

Look at std::list or std::map they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list.

How to convert char to integer in C?

The standard function atoi() will likely do what you want.

A simple example using "atoi":

#include <unistd.h>

int main(int argc, char *argv[])
{
    int useconds = atoi(argv[1]); 
    usleep(useconds);
}

Received an invalid column length from the bcp client for colid 6

Great piece of code, thanks for sharing!

I ended up using reflection to get the actual DataMemberName to throw back to a client on an error (I'm using bulk save in a WCF service). Hopefully someone else will find how I did it useful.

_x000D_
_x000D_
static string GetDataMemberName(string colName, object t) {_x000D_
  foreach(PropertyInfo propertyInfo in t.GetType().GetProperties()) {_x000D_
    if (propertyInfo.CanRead) {_x000D_
      if (propertyInfo.Name == colName) {_x000D_
        var attributes = propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault() as DataMemberAttribute;_x000D_
        if (attributes != null && !string.IsNullOrEmpty(attributes.Name))_x000D_
          return attributes.Name;_x000D_
        return colName;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return colName;_x000D_
}
_x000D_
_x000D_
_x000D_

php: how to get associative array key from numeric index?

Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,

    function get_key($array, $index){
      $idx=0;
      while($idx!=$index  && next($array)) $idx++;
      if($idx==$index) return key($array);
      else return '';
    }

Try catch statements in C

Redis use goto to simulate try/catch, IMHO it is very clean and elegant:

/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success. */
int rdbSave(char *filename) {
    char tmpfile[256];
    FILE *fp;
    rio rdb;
    int error = 0;

    snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
    fp = fopen(tmpfile,"w");
    if (!fp) {
        redisLog(REDIS_WARNING, "Failed opening .rdb for saving: %s",
            strerror(errno));
        return REDIS_ERR;
    }

    rioInitWithFile(&rdb,fp);
    if (rdbSaveRio(&rdb,&error) == REDIS_ERR) {
        errno = error;
        goto werr;
    }

    /* Make sure data will not remain on the OS's output buffers */
    if (fflush(fp) == EOF) goto werr;
    if (fsync(fileno(fp)) == -1) goto werr;
    if (fclose(fp) == EOF) goto werr;

    /* Use RENAME to make sure the DB file is changed atomically only
     * if the generate DB file is ok. */
    if (rename(tmpfile,filename) == -1) {
        redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
        unlink(tmpfile);
        return REDIS_ERR;
    }
    redisLog(REDIS_NOTICE,"DB saved on disk");
    server.dirty = 0;
    server.lastsave = time(NULL);
    server.lastbgsave_status = REDIS_OK;
    return REDIS_OK;

werr:
    fclose(fp);
    unlink(tmpfile);
    redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
    return REDIS_ERR;
}

How do I revert a Git repository to a previous commit?

I couldn't revert mine manually for some reason so here is how I ended up doing it.

  1. Checked out the branch I wanted to have, copied it.
  2. Checked out the latest branch.
  3. Copied the contents from the branch I wanted to the latest branch's directory overwriting the changes and committing that.

How can I clear the content of a file?

Use FileMode.Truncate everytime you create the file. Also place the File.Create inside a try catch.

Get the list of stored procedures created and / or modified on a particular date?

Here is the "newer school" version.

SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = N'PROCEDURE' and ROUTINE_SCHEMA = N'dbo' 
and CREATED = '20120927'

Twitter Bootstrap Responsive Background-Image inside Div

The way to do this is by using background-size so in your case:

background-size: 50% 50%;

or

You can set the width and the height of the elements to percentages as well

How to connect to a remote Git repository?

Now, if the repository is already existing on a remote machine, and you do not have anything locally, you do git clone instead.

The URL format is simple, it is PROTOCOL:/[user@]remoteMachineAddress/path/to/repository.git

For example, cloning a repository on a machine to which you have SSH access using the "dev" user, residing in /srv/repositories/awesomeproject.git and that machine has the ip 10.11.12.13 you do:

git clone ssh://[email protected]/srv/repositories/awesomeproject.git

Proxy with express.js

Ok, here's a ready-to-copy-paste answer using the require('request') npm module and an environment variable *instead of an hardcoded proxy):

coffeescript

app.use (req, res, next) ->                                                 
  r = false
  method = req.method.toLowerCase().replace(/delete/, 'del')
  switch method
    when 'get', 'post', 'del', 'put'
      r = request[method](
        uri: process.env.PROXY_URL + req.url
        json: req.body)
    else
      return res.send('invalid method')
  req.pipe(r).pipe res

javascript:

app.use(function(req, res, next) {
  var method, r;
  method = req.method.toLowerCase().replace(/delete/,"del");
  switch (method) {
    case "get":
    case "post":
    case "del":
    case "put":
      r = request[method]({
        uri: process.env.PROXY_URL + req.url,
        json: req.body
      });
      break;
    default:
      return res.send("invalid method");
  }
  return req.pipe(r).pipe(res);
});

How can I rollback a git repository to a specific commit?

Most suggestions are assuming that you need to somehow destroy the last 20 commits, which is why it means "rewriting history", but you don't have to.

Just create a new branch from the commit #80 and work on that branch going forward. The other 20 commits will stay on the old orphaned branch.

If you absolutely want your new branch to have the same name, remember that branch are basically just labels. Just rename your old branch to something else, then create the new branch at commit #80 with the name you want.

What does $(function() {} ); do?

Some Theory

$ is the name of a function like any other name you give to a function. Anyone can create a function in JavaScript and name it $ as shown below:

$ = function() { 
        alert('I am in the $ function');
    }

JQuery is a very famous JavaScript library and they have decided to put their entire framework inside a function named jQuery. To make it easier for people to use the framework and reduce typing the whole word jQuery every single time they want to call the function, they have also created an alias for it. That alias is $. Therefore $ is the name of a function. Within the jQuery source code, you can see this yourself:

window.jQuery = window.$ = jQuery;

Answer To Your Question

So what is $(function() { });?

Now that you know that $ is the name of the function, if you are using the jQuery library, then you are calling the function named $ and passing the argument function() {} into it. The jQuery library will call the function at the appropriate time. When is the appropriate time? According to jQuery documentation, the appropriate time is once all the DOM elements of the page are ready to be used.

The other way to accomplish this is like this:

$(document).ready(function() { });

As you can see this is more verbose so people prefer $(function() { })

So the reason why some functions cannot be called, as you have noticed, is because those functions do not exist yet. In other words the DOM has not loaded yet. But if you put them inside the function you pass to $ as an argument, the DOM is loaded by then. And thus the function has been created and ready to be used.

Another way to interpret $(function() { }) is like this:

Hey $ or jQuery, can you please call this function I am passing as an argument once the DOM has loaded?

Java, how to compare Strings with String Arrays

import java.util.Scanner;
import java.util.*;
public class Main
{
  public static void main (String[]args) throws Exception
  {
    Scanner in = new Scanner (System.in);
    /*Prints out the welcome message at the top of the screen */
      System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
      System.out.printf ("%55s", "=================================\n");

      String[] codes =
    {
    "G22", "K13", "I30", "S20"};

      System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
             codes[3]);
      System.out.printf ("Enter one of the above!\n");

    String usercode = in.nextLine ();
    for (int i = 0; i < codes.length; i++)
      {
    if (codes[i].equals (usercode))
      {
        System.out.printf ("What's the matter with you?\n");
      }
    else
      {
        System.out.printf ("Youda man!");
      }
      }

  }
}

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

window.open(url, '_blank'); not working on iMac/Safari

Taken from the accepted answers comment by Steve on Dec 20, 2013:

Actually, there's a very easy way to do it: just click off "Block popup windows" in the iMac/Safari browser and it does what I want.

To clarify, when running Safari on Mac OS X El Capitan:

  1. Safari -> Preferences
  2. Security -> Uncheck 'Block pop-up windows'

How to add a vertical Separator?

From http://social.msdn.microsoft.com/Forums/vstudio/en-US/12ead5d4-1d57-4dbb-ba81-bc13084ba370/how-can-i-add-a-line-as-a-visual-separator-to-the-content-control-like-grid?forum=wpf:

Try this example and see if it fits your needs, there are three main aspects to it.

  1. Line.Stretch is set to fill.

  2. For horizontal lines the VerticalAlignment of the line is set Bottom, and for VerticalLines the HorizontalAlignment is set to Right.

  3. We then need to tell the line how many rows or columns to span, this is done by binding to either RowDefinitions or ColumnDefintions count property.



        <Style x:Key="horizontalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">  
            <Setter Property="X2" Value="1" /> 
            <Setter Property="VerticalAlignment" Value="Bottom" /> 
            <Setter Property="Grid.ColumnSpan" 
                    Value="{Binding   
                                Path=ColumnDefinitions.Count,  
                                RelativeSource={RelativeSource AncestorType=Grid}}"/> 
        </Style> 
    
        <Style x:Key="verticalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">  
            <Setter Property="Y2" Value="1" /> 
            <Setter Property="HorizontalAlignment" Value="Right" /> 
            <Setter Property="Grid.RowSpan"   
                    Value="{Binding   
                                Path=RowDefinitions.Count,  
                                RelativeSource={RelativeSource AncestorType=Grid}}"/> 
        </Style> 
    </Grid.Resources>        
    
    <Grid.RowDefinitions> 
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
    </Grid.RowDefinitions> 
    
    <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
    </Grid.ColumnDefinitions> 
    
    <Line Grid.Column="0" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="1" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="2" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="3" Style="{StaticResource verticalLineStyle}"/>  
    
    <Line Grid.Row="0" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="1" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="2" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="3" Style="{StaticResource horizontalLineStyle}"/>  
    

How do I get the path of the current executed file in Python?

See my answer to the question Importing modules from parent folder for related information, including why my answer doesn't use the unreliable __file__ variable. This simple solution should be cross-compatible with different operating systems as the modules os and inspect come as part of Python.

First, you need to import parts of the inspect and os modules.

from inspect import getsourcefile
from os.path import abspath

Next, use the following line anywhere else it's needed in your Python code:

abspath(getsourcefile(lambda:0))

How it works:

From the built-in module os (description below), the abspath tool is imported.

OS routines for Mac, NT, or Posix depending on what system we're on.

Then getsourcefile (description below) is imported from the built-in module inspect.

Get useful information from live Python objects.

  • abspath(path) returns the absolute/full version of a file path
  • getsourcefile(lambda:0) somehow gets the internal source file of the lambda function object, so returns '<pyshell#nn>' in the Python shell or returns the file path of the Python code currently being executed.

Using abspath on the result of getsourcefile(lambda:0) should make sure that the file path generated is the full file path of the Python file.
This explained solution was originally based on code from the answer at How do I get the path of the current executed file in Python?.

How to set default value for form field in Symfony2?

You can set the default for related field in your model class (in mapping definition or set the value yourself).

Furthermore, FormBuilder gives you a chance to set initial values with setData() method. Form builder is passed to the createForm() method of your form class.

Also, check this link: http://symfony.com/doc/current/book/forms.html#using-a-form-without-a-class

Ignore 'Security Warning' running script from command line

I made this powershell script to unblock all files on a share on my server

Get-ChildItem "\\ServerName\e$\MyDirectory\" -Recurse -File | % {
       Unblock-File -Path $_.FullName
}

javascript find and remove object in array based on key value

here is a solution if you are not using jquery:

myArray = myArray.filter(function( obj ) {
  return obj.id !== id;
});

How to define dimens.xml for every different screen size in android?

You have to create Different values folder for different screens . Like

values-sw720dp          10.1” tablet 1280x800 mdpi

values-sw600dp          7.0”  tablet 1024x600 mdpi

values-sw480dp          5.4”  480x854 mdpi 
values-sw480dp          5.1”  480x800 mdpi 

values-xxhdpi           5.5"  1080x1920 xxhdpi
values-xxxhdpi           5.5" 1440x2560 xxxhdpi

values-xhdpi            4.7”   1280x720 xhdpi 
values-xhdpi            4.65”  720x1280 xhdpi 

values-hdpi             4.0” 480x800 hdpi
values-hdpi             3.7” 480x854 hdpi

values-mdpi             3.2” 320x480 mdpi

values-ldpi             3.4” 240x432 ldpi
values-ldpi             3.3” 240x400 ldpi
values-ldpi             2.7” 240x320 ldpi

enter image description here

For more information you may visit here

Different values folders in android

http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html

Edited By @humblerookie

You can make use of Android Studio plugin called Dimenify to auto generate dimension values for other pixel buckets based on custom scale factors. Its still in beta, be sure to notify any issues/suggestions you come across to the developer.

C# Test if user has write access to a folder

You can try following code block to check if the directory is having Write Access. It checks the FileSystemAccessRule.

string directoryPath = "C:\\XYZ"; //folderBrowserDialog.SelectedPath;
bool isWriteAccess = false;
try
{
    AuthorizationRuleCollection collection =
        Directory.GetAccessControl(directoryPath)
            .GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
    foreach (FileSystemAccessRule rule in collection)
    {
        if (rule.AccessControlType == AccessControlType.Allow)
        {
            isWriteAccess = true;
            break;
        }
    }
}
catch (UnauthorizedAccessException ex)
{
    isWriteAccess = false;
}
catch (Exception ex)
{
    isWriteAccess = false;
}
if (!isWriteAccess)
{
    //handle notifications 
}

How to group dataframe rows into list in pandas groupby

Use any of the following groupby and agg recipes.

# Setup
df = pd.DataFrame({
  'a': ['A', 'A', 'B', 'B', 'B', 'C'],
  'b': [1, 2, 5, 5, 4, 6],
  'c': ['x', 'y', 'z', 'x', 'y', 'z']
})
df

   a  b  c
0  A  1  x
1  A  2  y
2  B  5  z
3  B  5  x
4  B  4  y
5  C  6  z

To aggregate multiple columns as lists, use any of the following:

df.groupby('a').agg(list)
df.groupby('a').agg(pd.Series.tolist)

           b          c
a                      
A     [1, 2]     [x, y]
B  [5, 5, 4]  [z, x, y]
C        [6]        [z]

To group-listify a single column only, convert the groupby to a SeriesGroupBy object, then call SeriesGroupBy.agg. Use,

df.groupby('a').agg({'b': list})  # 4.42 ms 
df.groupby('a')['b'].agg(list)    # 2.76 ms - faster

a
A       [1, 2]
B    [5, 5, 4]
C          [6]
Name: b, dtype: object

How to make rounded percentages add up to 100%

The goal of rounding is to generate the least amount of error. When you're rounding a single value, that process is simple and straightforward and most people understand it easily. When you're rounding multiple numbers at the same time, the process gets trickier - you must define how the errors are going to combine, i.e. what must be minimized.

The well-voted answer by Varun Vohra minimizes the sum of the absolute errors, and it's very simple to implement. However there are edge cases it does not handle - what should be the result of rounding 24.25, 23.25, 27.25, 25.25? One of those needs to be rounded up instead of down. You would probably just arbitrarily pick the first or last one in the list.

Perhaps it's better to use the relative error instead of the absolute error. Rounding 23.25 up to 24 changes it by 3.2% while rounding 27.25 up to 28 only changes it by 2.8%. Now there's a clear winner.

It's possible to tweak this even further. One common technique is to square each error, so that large errors count disproportionately more than small ones. I'd also use a non-linear divisor to get the relative error - it doesn't seem right that an error at 1% is 99 times more important than an error at 99%. In the code below I've used the square root.

The complete algorithm is as follows:

  1. Sum the percentages after rounding them all down, and subtract from 100. This tells you how many of those percentages must be rounded up instead.
  2. Generate two error scores for each percentage, one when when rounded down and one when rounded up. Take the difference between the two.
  3. Sort the error differences produced above.
  4. For the number of percentages that need to be rounded up, take an item from the sorted list and increment the rounded down percentage by 1.

You may still have more than one combination with the same error sum, for example 33.3333333, 33.3333333, 33.3333333. This is unavoidable, and the result will be completely arbitrary. The code I give below prefers to round up the values on the left.

Putting it all together in Python looks like this.

def error_gen(actual, rounded):
    divisor = sqrt(1.0 if actual < 1.0 else actual)
    return abs(rounded - actual) ** 2 / divisor

def round_to_100(percents):
    if not isclose(sum(percents), 100):
        raise ValueError
    n = len(percents)
    rounded = [int(x) for x in percents]
    up_count = 100 - sum(rounded)
    errors = [(error_gen(percents[i], rounded[i] + 1) - error_gen(percents[i], rounded[i]), i) for i in range(n)]
    rank = sorted(errors)
    for i in range(up_count):
        rounded[rank[i][1]] += 1
    return rounded

>>> round_to_100([13.626332, 47.989636, 9.596008, 28.788024])
[14, 48, 9, 29]
>>> round_to_100([33.3333333, 33.3333333, 33.3333333])
[34, 33, 33]
>>> round_to_100([24.25, 23.25, 27.25, 25.25])
[24, 23, 28, 25]
>>> round_to_100([1.25, 2.25, 3.25, 4.25, 89.0])
[1, 2, 3, 4, 90]

As you can see with that last example, this algorithm is still capable of delivering non-intuitive results. Even though 89.0 needs no rounding whatsoever, one of the values in that list needed to be rounded up; the lowest relative error results from rounding up that large value rather than the much smaller alternatives.

This answer originally advocated going through every possible combination of round up/round down, but as pointed out in the comments a simpler method works better. The algorithm and code reflect that simplification.

Rails: update_attribute vs update_attributes

update_attribute simply updates only one attribute of a model, but we can pass multiple attributes in update_attributes method.

Example:

user = User.last

#update_attribute
user.update_attribute(:status, "active")

It pass the validation

#update_attributes
user.update_attributes(first_name: 'update name', status: "active")

it doesn't update if validation fails.

When to use .First and when to use .FirstOrDefault with LINQ?

First:

  • Returns the first element of a sequence
  • Throws exception: There are no elements in the result
  • Use when: When more than 1 element is expected and you want only the first

FirstOrDefault:

  • Returns the first element of a sequence, or a default value if no element is found
  • Throws exception: Only if the source is null
  • Use when: When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

From: http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/

How to pull remote branch from somebody else's repo

GitHub has a new option relative to the preceding answers, just copy/paste the command lines from the PR:

  1. Scroll to the bottom of the PR to see the Merge or Squash and merge button
  2. Click the link on the right: view command line instructions
  3. Press the Copy icon to the right of Step 1
  4. Paste the commands in your terminal

Entity Framework and Connection Pooling

According to Daniel Simmons:

Create a new ObjectContext instance in a Using statement for each service method so that it is disposed of before the method returns. This step is critical for scalability of your service. It makes sure that database connections are not kept open across service calls and that temporary state used by a particular operation is garbage collected when that operation is over. The Entity Framework automatically caches metadata and other information it needs in the app domain, and ADO.NET pools database connections, so re-creating the context each time is a quick operation.

This is from his comprehensive article here:

http://msdn.microsoft.com/en-us/magazine/ee335715.aspx

I believe this advice extends to HTTP requests, so would be valid for ASP.NET. A stateful, fat-client application such as a WPF application might be the only case for a "shared" context.

How to update the constant height constraint of a UIView programmatically?

Select the height constraint from the Interface builder and take an outlet of it. So, when you want to change the height of the view you can use the below code.

yourHeightConstraintOutlet.constant = someValue
yourView.layoutIfNeeded()

Method updateConstraints() is an instance method of UIView. It is helpful when you are setting the constraints programmatically. It updates constraints for the view. For more detail click here.

Argument list too long error for rm, cp, mv commands

The reason this occurs is because bash actually expands the asterisk to every matching file, producing a very long command line.

Try this:

find . -name "*.pdf" -print0 | xargs -0 rm

Warning: this is a recursive search and will find (and delete) files in subdirectories as well. Tack on -f to the rm command only if you are sure you don't want confirmation.

You can do the following to make the command non-recursive:

find . -maxdepth 1 -name "*.pdf" -print0 | xargs -0 rm

Another option is to use find's -delete flag:

find . -name "*.pdf" -delete

Sorting a vector of custom objects

You could use functor as third argument of std::sort, or you could define operator< in your class.

struct X {
    int x;
    bool operator<( const X& val ) const { 
        return x < val.x; 
    }
};

struct Xgreater
{
    bool operator()( const X& lx, const X& rx ) const {
        return lx.x < rx.x;
    }
};

int main () {
    std::vector<X> my_vec;

    // use X::operator< by default
    std::sort( my_vec.begin(), my_vec.end() );

    // use functor
    std::sort( my_vec.begin(), my_vec.end(), Xgreater() );
}

Java: JSON -> Protobuf & back conversion

Try JsonFormat.printer().print(MessageOrBuilder), it looks good for proto3. Yet, it is unclear how to convert the actual protobuf message (which is provided as the java package of my choice defined in the .proto file) to a com.google.protbuf.Message object.

How to Allow Remote Access to PostgreSQL database

A fast shortcut for restarting service on Windows:

1) Press Windows Key + R

2) Type "services.msc"

enter image description here

3) Order by name

4) Find "PostgreSQL" service and restart it.

enter image description here

How do you find the sum of all the numbers in an array in Java?

In Java 8

Code:

   int[] array = new int[]{1,2,3,4,5};
   int sum = IntStream.of(array).reduce( 0,(a, b) -> a + b);
   System.out.println("The summation of array is " + sum);

  System.out.println("Another way to find summation :" + IntStream.of(array).sum());

Output:

The summation of array is 15
Another way to find summation :15

Explanation:

In Java 8, you can use reduction concept to do your addition.

Read all about Reduction

Integer division with remainder in JavaScript?

Here is a way to do this. (Personally I would not do it this way, but thought it was a fun way to do it for an example)

_x000D_
_x000D_
function intDivide(numerator, denominator) {
  return parseInt((numerator/denominator).toString().split(".")[0]);
}

let x = intDivide(4,5);
let y = intDivide(5,5);
let z = intDivide(6,5);
console.log(x);
console.log(y);
console.log(z);
_x000D_
_x000D_
_x000D_

Get filename from input [type='file'] using jQuery

Using Bootstrap

Remove form-control-file Class from input field to avoid unwanted horizontal scroll bar

Try this!!

_x000D_
_x000D_
$('#upload').change(function() {_x000D_
    var filename = $('#upload').val();_x000D_
    if (filename.substring(3,11) == 'fakepath') {_x000D_
        filename = filename.substring(12);_x000D_
    } // For Remove fakepath_x000D_
    $("label[for='file_name'] b").html(filename);_x000D_
    $("label[for='file_default']").text('Selected File: ');_x000D_
    if (filename == "") {_x000D_
        $("label[for='file_default']").text('No File Choosen');_x000D_
    }_x000D_
});
_x000D_
.custom_file {_x000D_
  margin: auto;_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
  z-index: -1;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="form-group">_x000D_
   <label for="upload" class="btn btn-sm btn-primary">Upload Image</label>_x000D_
    <input type="file" class="text-center form-control-file custom_file" id="upload" name="user_image">_x000D_
    <label for="file_default">No File Choosen </label>_x000D_
    <label for="file_name"><b></b></label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

how to realize countifs function (excel) in R

Easy peasy. Your data frame will look like this:

df <- data.frame(sex=c('M','F','M'),
                 occupation=c('Student','Analyst','Analyst'))

You can then do the equivalent of a COUNTIF by first specifying the IF part, like so:

df$sex == 'M'

This will give you a boolean vector, i.e. a vector of TRUE and FALSE. What you want is to count the observations for which the condition is TRUE. Since in R TRUE and FALSE double as 1 and 0 you can simply sum() over the boolean vector. The equivalent of COUNTIF(sex='M') is therefore

sum(df$sex == 'M')

Should there be rows in which the sex is not specified the above will give back NA. In that case, if you just want to ignore the missing observations use

sum(df$sex == 'M', na.rm=TRUE)

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

How to test multiple variables against a value?

The most pythonic way of representing your pseudo-code in Python would be:

x = 0
y = 1
z = 3
mylist = []

if any(v == 0 for v in (x, y, z)):
    mylist.append("c")
if any(v == 1 for v in (x, y, z)):
    mylist.append("d")
if any(v == 2 for v in (x, y, z)):
    mylist.append("e")
if any(v == 3 for v in (x, y, z)):
    mylist.append("f")

Best way to define private methods for a class in Objective-C

You could use blocks?

@implementation MyClass

id (^createTheObject)() = ^(){ return [[NSObject alloc] init];};

NSInteger (^addEm)(NSInteger, NSInteger) =
^(NSInteger a, NSInteger b)
{
    return a + b;
};

//public methods, etc.

- (NSObject) thePublicOne
{
    return createTheObject();
}

@end

I'm aware this is an old question, but it's one of the first I found when I was looking for an answer to this very question. I haven't seen this solution discussed anywhere else, so let me know if there's something foolish about doing this.

ASP MVC href to a controller/view

how about

<li>
<a href="@Url.Action("Index", "Users")" class="elements"><span>Clients</span></a>
</li>

How to stop the Timer in android?

I had a similar problem: every time I push a particular button, I create a new Timer.

my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}

Exiting from that activity I deleted the timer:

if(my_timer!=null){
my_timer.cancel();
my_timer = null;
}

But it was not enough because the cancel() method only canceled the latest Timer. The older ones were ignored an didn't stop running. The purge() method was not useful for me. I solved the problem just checking the Timer instantiation:

if(my_timer == null){
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
}

Recursively list all files in a directory including files in symlink directories

How about tree? tree -l will follow symlinks.

Disclaimer: I wrote this package.

make iframe height dynamic based on content inside- JQUERY/Javascript

just make iframe container position:absolute and iframe will automatically change its height according to its content

<style>
   .iframe-container {
       display: block;
       position: absolute;
       /*change position as you need*/
       bottom: 0;
       left: 0;
       right: 0;
       top: 0;
   }
   iframe {
       margin: 0;
       padding: 0;
       border: 0;
       width: 100%;
       background-color: #fff;
   }
 </style>
 <div class="iframe-container">
     <iframe src="http://iframesourcepage"></iframe>
 </div>

Convert a 1D array to a 2D array in numpy

There is a simple way as well, we can use the reshape function in a different way:

A_reshape = A.reshape(No_of_rows, No_of_columns)

dyld: Library not loaded: @rpath/libswiftCore.dylib

For me building a MacOS command line Swift app that depended on 3rd party Swift libs (e.g. SQLite) none of the above solutions seemed to work. What did work was directly adding the following path to my Runpath Search Paths in the Build Settings:

/Applications/Xcode.app/Contents//Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/

Doing that did give a warning at runtime saying that Xcode had found 2 versions of libswiftCore - which makes sense. Except that not including that line resulted in Xcode not finding any versions of libswiftCore.

Anyway, that'll do for me even if it doesn't seem right - my app is just a utility that I'm not intending to distribute and at least it runs now!

PHP, Get tomorrows date from date

By strange it can seem it works perfectly fine: date_create( '2016-02-01 + 1 day' );

echo date_create( $your_date . ' + 1 day' )->format( 'Y-m-d' );

Should do it

C# equivalent to Java's charAt()?

Simply use String.ElementAt(). It's quite similar to java's String.charAt(). Have fun coding!

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

SQL comment header examples

-- [why did we write this?]
-- [auto-generated change control info]

ReflectionException: Class ClassName does not exist - Laravel

Check your capitalization!

Your host system (Windows or Mac) is case insensitive by default, and Homestead inherits this behavior. Your production server on the other hand is case sensitive.

Whenever you get a ClassNotFound Exception check the following:

  1. Spelling
  2. Namespaces
  3. Capitalization

Coarse-grained vs fine-grained

Coarse-grained: A few ojects hold a lot of related data that's why services have broader scope in functionality. Example: A single "Account" object holds the customer name, address, account balance, opening date, last change date, etc. Thus: Increased design complexity, smaller number of cells to various operations

Fine-grained: More objects each holding less data that's why services have more narrow scope in functionality. Example: An Account object holds balance, a Customer object holds name and address, a AccountOpenings object holds opening date, etc. Thus: Decreased design complexity , higher number of cells to various service operations. These are relationships defined between these objects.

JFrame Exit on close Java

If you don't extend JFrame and use JFrame itself in variable, you can use:

frame.dispose();
System.exit(0);

How does autowiring work in Spring?

Spring dependency inject help you to remove coupling from your classes. Instead of creating object like this:

UserService userService = new UserServiceImpl();

You will be using this after introducing DI:

@Autowired
private UserService userService;

For achieving this you need to create a bean of your service in your ServiceConfiguration file. After that you need to import that ServiceConfiguration class to your WebApplicationConfiguration class so that you can autowire that bean into your Controller like this:

public class AccController {

    @Autowired
    private UserService userService;
} 

You can find a java configuration based POC here example.

How to edit an Android app?

First you have to download file x-plore and installed it.. After that open it and find the thoes you want to edit.. After that just rename the file Xyz.apk to xyz.zip After that open that file and you can see some folders.. then just go and edit the app..

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

Run php function on button click

No Problem You can use onClick() function easily without using any other interference of language,

<?php
echo '<br><Button onclick="document.getElementById(';?>'modal-wrapper2'<?php echo ').style.display=';?>'block'<?php echo '" name="comment" style="width:100px; color: white;background-color: black;border-radius: 10px; padding: 4px;">Show</button>';
?>

Difference between ProcessBuilder and Runtime.exec()

Look at how Runtime.getRuntime().exec() passes the String command to the ProcessBuilder. It uses a tokenizer and explodes the command into individual tokens, then invokes exec(String[] cmdarray, ......) which constructs a ProcessBuilder.

If you construct the ProcessBuilder with an array of strings instead of a single one, you'll get to the same result.

The ProcessBuilder constructor takes a String... vararg, so passing the whole command as a single String has the same effect as invoking that command in quotes in a terminal:

shell$ "command with args"

Global Angular CLI version greater than local version

Just do these things

npm install --save-dev @angular/cli@latest
npm audit fix
npm audit fix --force

How to implement endless list with RecyclerView?

There is an easy to use library for this named paginate . Supports both ListView and RecyclerView ( LinearLayout , GridLayout and StaggeredGridLayout).

Here is the link to the project on Github

setting system property

You need the path of the plugins directory of your local GATE install. So if Gate is installed in "/home/user/GATE_Developer_8.1", the code looks like this:

System.setProperty("gate.home", "/home/user/GATE_Developer_8.1/plugins");

You don't have to set gate.home from the command line. You can set it in your application, as long as you set it BEFORE you call Gate.init().

How do I select a sibling element using jQuery?

Try -

   $(this).siblings(".bidbutton").addClass("disabled").attr("disabled", "");

Python POST binary data

Basically what you do is correct. Looking at redmine docs you linked to, it seems that suffix after the dot in the url denotes type of posted data (.json for JSON, .xml for XML), which agrees with the response you get - Processing by AttachmentsController#upload as XML. I guess maybe there's a bug in docs and to post binary data you should try using http://redmine/uploads url instead of http://redmine/uploads.xml.

Btw, I highly recommend very good and very popular Requests library for http in Python. It's much better than what's in the standard lib (urllib2). It supports authentication as well but I skipped it for brevity here.

import requests
with open('./x.png', 'rb') as f:
    data = f.read()
res = requests.post(url='http://httpbin.org/post',
                    data=data,
                    headers={'Content-Type': 'application/octet-stream'})

# let's check if what we sent is what we intended to send...
import json
import base64

assert base64.b64decode(res.json()['data'][len('data:application/octet-stream;base64,'):]) == data

UPDATE

To find out why this works with Requests but not with urllib2 we have to examine the difference in what's being sent. To see this I'm sending traffic to http proxy (Fiddler) running on port 8888:

Using Requests

import requests

data = 'test data'
res = requests.post(url='http://localhost:8888',
                    data=data,
                    headers={'Content-Type': 'application/octet-stream'})

we see

POST http://localhost:8888/ HTTP/1.1
Host: localhost:8888
Content-Length: 9
Content-Type: application/octet-stream
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/1.0.4 CPython/2.7.3 Windows/Vista

test data

and using urllib2

import urllib2

data = 'test data'    
req = urllib2.Request('http://localhost:8888', data)
req.add_header('Content-Length', '%d' % len(data))
req.add_header('Content-Type', 'application/octet-stream')
res = urllib2.urlopen(req)

we get

POST http://localhost:8888/ HTTP/1.1
Accept-Encoding: identity
Content-Length: 9
Host: localhost:8888
Content-Type: application/octet-stream
Connection: close
User-Agent: Python-urllib/2.7

test data

I don't see any differences which would warrant different behavior you observe. Having said that it's not uncommon for http servers to inspect User-Agent header and vary behavior based on its value. Try to change headers sent by Requests one by one making them the same as those being sent by urllib2 and see when it stops working.

Append data to a POST NSURLRequest

If you don't wish to use 3rd party classes then the following is how you set the post body...

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                             delegate:self];

Simply append your key/value pair to the post string

How to get a web page's source code from Java

URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();

SQL - How to find the highest number in a column?

If you are using AUTOINCREMENT, use:

SELECT LAST\_INSERT\_ID();

Assumming that you are using Mysql: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Postgres handles this similarly via the currval(sequence_name) function.

Note that using MAX(ID) is not safe, unless you lock the table, since it's possible (in a simplified case) to have another insert that occurs before you call MAX(ID) and you lose the id of the first insert. The functions above are session based so if another session inserts you still get the ID that you inserted.

How to send file contents as body entity using cURL

I believe you're looking for the @filename syntax, e.g.:

strip new lines

curl --data "@/path/to/filename" http://...

keep new lines

curl --data-binary "@/path/to/filename" http://...

curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary in place of --data

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

If you are using WAMP/XAMP server turn it off. This resolved my problem.

SQL: set existing column as Primary Key in MySQL

ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);

Why don't self-closing script elements work?

To add to what Brad and squadette have said, the self-closing XML syntax <script /> actually is correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like application/xhtml+xml in the HTTP Content-Type header (and not as text/html).

However, sending an XML mimetype will cause your pages not to be parsed by IE7, which only likes text/html.

From w3:

In summary, 'application/xhtml+xml' SHOULD be used for XHTML Family documents, and the use of 'text/html' SHOULD be limited to HTML-compatible XHTML 1.0 documents. 'application/xml' and 'text/xml' MAY also be used, but whenever appropriate, 'application/xhtml+xml' SHOULD be used rather than those generic XML media types.

I puzzled over this a few months ago, and the only workable (compatible with FF3+ and IE7) solution was to use the old <script></script> syntax with text/html (HTML syntax + HTML mimetype).

If your server sends the text/html type in its HTTP headers, even with otherwise properly formed XHTML documents, FF3+ will use its HTML rendering mode which means that <script /> will not work (this is a change, Firefox was previously less strict).

This will happen regardless of any fiddling with http-equiv meta elements, the XML prolog or doctype inside your document -- Firefox branches once it gets the text/html header, that determines whether the HTML or XML parser looks inside the document, and the HTML parser does not understand <script />.

Oracle: How to filter by date and time in a where clause

Try:

To_Date (SESSION_START_DATE_TIME, 'MM/DD/YYYY hh24:mi') > 
To_Date ('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi' )

Can I delete data from the iOS DeviceSupport directory?

The ~/Library/Developer/Xcode/iOS DeviceSupport folder is basically only needed to symbolicate crash logs.

You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.

I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.

How to retrieve Jenkins build parameters using the Groovy API?

To get the parameterized build params from the current build from your GroovyScript (using Pipeline), all you need to do is: Say you had a variable called VARNAME.

def myVariable = env.VARNAME

How do you create optional arguments in php?

The date function would be defined something like this:

function date($format, $timestamp = null)
{
    if ($timestamp === null) {
        $timestamp = time();
    }

    // Format the timestamp according to $format
}

Usually, you would put the default value like this:

function foo($required, $optional = 42)
{
    // This function can be passed one or more arguments
}

However, only literals are valid default arguments, which is why I used null as default argument in the first example, not $timestamp = time(), and combined it with a null check. Literals include arrays (array() or []), booleans, numbers, strings, and null.

ERROR 1064 (42000): You have an error in your SQL syntax;

Use varchar instead of VAR_CHAR and omit the comma in the last line i.e.phone INT NOT NULL );. The last line during creating table is kept "comma free". Ex:- CREATE TABLE COMPUTER ( Model varchar(50) ); Here, since we have only one column ,that's why there is no comma used during entire code.

MySQL : transaction within a stored procedure

This is just an explanation not addressed in other answers

At least in recent versions of Mysql, your first query is not committed.

If you query it under the same session you will see the changes, but if you query it from a different session, the changes are not there, they are not committed.

What's going on?

When you open a transaction, and a query inside it fails, the transaction keeps open, it does not commit nor rollback the changes.

So BE CAREFUL, any table/row that was locked with a previous query likeSELECT ... FOR SHARE/UPDATE, UPDATE, INSERT or any other locking-query, keeps locked until that session is killed (and executes a rollback), or until a subsequent query commits it explicitly (COMMIT) or implicitly, thus making the partial changes permanent (which might happen hours later, while the transaction was in a waiting state).

That's why the solution involves declaring handlers to immediately ROLLBACK when an error happens.

Extra

Inside the handler you can also re-raise the error using RESIGNAL, otherwise the stored procedure executes "Successfully"

BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
        BEGIN
            ROLLBACK;
            RESIGNAL;
        END;

    START TRANSACTION;
        #.. Query 1 ..
        #.. Query 2 ..
        #.. Query 3 ..
    COMMIT;
END

How to URL encode a string in Ruby

Code:

str = "http://localhost/with spaces and spaces"
encoded = URI::encode(str)
puts encoded

Result:

http://localhost/with%20spaces%20and%20spaces

How to display custom view in ActionBar?

There is an example in the launcher app of Android (that I've made a library out of it, here), inside the class that handles wallpapers-picking ("WallpaperPickerActivity") .

The example shows that you need to set a customized theme for this to work. Sadly, this worked for me only using the normal framework, and not the one of the support library.

Here're the themes:

styles.xml

 <style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowShowWallpaper">true</item>
  </style>

  <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
  </style>

  <style name="WallpaperCropperActionBar" parent="@android:style/Widget.DeviceDefault.ActionBar">
    <item name="android:displayOptions">showCustom</item>
    <item name="android:background">#88000000</item>
  </style>

value-v19/styles.xml

 <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

  <style name="Theme" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

EDIT: there is a better way to do it, which works on the support library too. Just add this line of code instead of what I've written above:

getSupportActionBar().setDisplayShowCustomEnabled(true);

Go Back to Previous Page

Depends what it is that you're trying to do it with. You could use something like this:

echo "<a href=\"javascript:history.go(-1)\">GO BACK</a>";

That's the simplest option. The other poster is right about having a proper flow of history but this is an example for you.

Just edited, orig version wasn't indented and looked like nothing. ;)

Boolean checking in the 'if' condition

The former. The latter merely adds verbosity.

Getting reference to the top-most view/window in iOS application

I'm sticking to the question as the title states and not the discussion. Which view is top visible on any given point?

@implementation UIView (Extra)

- (UIView *)findTopMostViewForPoint:(CGPoint)point
{
    for(int i = self.subviews.count - 1; i >= 0; i--)
    {
        UIView *subview = [self.subviews objectAtIndex:i];
        if(!subview.hidden && CGRectContainsPoint(subview.frame, point))
        {
            CGPoint pointConverted = [self convertPoint:point toView:subview];
            return [subview findTopMostViewForPoint:pointConverted];
        }
    }

    return self;
}

- (UIWindow *)topmostWindow
{
    UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
        return win1.windowLevel - win2.windowLevel;
    }] lastObject];
    return topWindow;
}

@end

Can be used directly with any UIWindow as receiver or any UIView as receiver.

How to get longitude and latitude of any address?

I came up with the following which takes account of rubbish passed in and file_get_contents failing....

function get_lonlat(  $addr  ) {
    try {
            $coordinates = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($addr) . '&sensor=true');
            $e=json_decode($coordinates);
            // call to google api failed so has ZERO_RESULTS -- i.e. rubbish address...
            if ( isset($e->status)) { if ( $e->status == 'ZERO_RESULTS' ) {echo '1:'; $err_res=true; } else {echo '2:'; $err_res=false; } } else { echo '3:'; $err_res=false; }
            // $coordinates is false if file_get_contents has failed so create a blank array with Longitude/Latitude.
            if ( $coordinates == false   ||  $err_res ==  true  ) {
                $a = array( 'lat'=>0,'lng'=>0);
                $coordinates  = new stdClass();
                foreach (  $a  as $key => $value)
                {
                    $coordinates->$key = $value;
                }
            } else {
                // call to google ok so just return longitude/latitude.
                $coordinates = $e;

                $coordinates  =  $coordinates->results[0]->geometry->location;
            }

            return $coordinates;
    }
    catch (Exception $e) {
    }

then to get the cords: where $pc is the postcode or address.... $address = get_lonlat( $pc ); $l1 = $address->lat; $l2 = $address->lng;

nodeJS - How to create and read session with express

It is cumbersome to interoperate socket.io and connect sessions support. The problem is not because socket.io "hijacks" request somehow, but because certain socket.io transports (I think flashsockets) don't support cookies. I could be wrong with cookies, but my approach is the following:

  1. Implement a separate session store for socket.io that stores data in the same format as connect-redis
  2. Make connect session cookie not http-only so it's accessible from client JS
  3. Upon a socket.io connection, send session cookie over socket.io from browser to server
  4. Store the session id in a socket.io connection, and use it to access session data from redis.

How do I install a plugin for vim?

Update (as 2019):

cd ~/.vim
git clone git://github.com/tpope/vim-haml.git pack/bundle/start/haml

Explanation (from :h pack ad :h packages):

  1. All the directories found are added to runtimepath. They must be in ~/.vim/pack/whatever/start [you can only change whatever].
  2. the plugins found in the plugins dir in runtimepath are sourced.

So this load the plugin on start (hence the name start).

You can also get optional plugin (loaded with :packadd) if you put them in ~/.vim/pack/bundle/opt

Why does Eclipse complain about @Override on interface methods?

You could change the compiler settings to accept Java 6 syntax but generate Java 5 output (as I remember). And set the "Generated class files compatibility" a bit lower if needed by your runtime. Update: I checked Eclipse, but it complains if I set source compatibility to 1.6 and class compatibility to 1.5. If 1.6 is not allowed I usually manually comment out the offending @Override annotations in the source (which doesn't help your case).

Update2: If you do only manual build, you could write a small program which copies the original project into a new one, strips @Override annotations from the java sources and you just hit Clean project in Eclipse.

CSS transition fade in

CSS Keyframes support is pretty good these days:

_x000D_
_x000D_
.fade-in {_x000D_
 opacity: 1;_x000D_
 animation-name: fadeInOpacity;_x000D_
 animation-iteration-count: 1;_x000D_
 animation-timing-function: ease-in;_x000D_
 animation-duration: 2s;_x000D_
}_x000D_
_x000D_
@keyframes fadeInOpacity {_x000D_
 0% {_x000D_
  opacity: 0;_x000D_
 }_x000D_
 100% {_x000D_
  opacity: 1;_x000D_
 }_x000D_
}
_x000D_
<h1 class="fade-in">Fade Me Down Scotty</h1>
_x000D_
_x000D_
_x000D_

Getters \ setters for dummies

What's so confusing about it... getters are functions that are called when you get a property, setters, when you set it. example, if you do

obj.prop = "abc";

You're setting the property prop, if you're using getters/setters, then the setter function will be called, with "abc" as an argument. The setter function definition inside the object would ideally look something like this:

set prop(var) {
   // do stuff with var...
}

I'm not sure how well that is implemented across browsers. It seems Firefox also has an alternative syntax, with double-underscored special ("magic") methods. As usual Internet Explorer does not support any of this.

How to measure time in milliseconds using ANSI C?

#include <time.h>
clock_t uptime = clock() / (CLOCKS_PER_SEC / 1000);

Illegal mix of collations error in MySql

Was getting Illegal mix of collations while creating a category in Bagisto. Running these commands (thank you @Quy Le) solved the issue for me:

--set utf8 for connection

SET collation_connection = 'utf8_general_ci'

--change CHARACTER SET of DB to utf8

ALTER DATABASE dbName CHARACTER SET utf8 COLLATE utf8_general_ci

--change category tables

ALTER TABLE categories CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci

ALTER TABLE category_translations CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci

How to Toggle a div's visibility by using a button click

with JQuery .toggle() you can accomplish it easily

$( ".target" ).toggle();

Check if an element is present in an array

ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the problem, and so is now the preferred method.

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false (second parameter is the index position in this array at which to begin searching)

As of JULY 2018, this has been implemented in almost all major browsers, if you need to support an older browser a polyfill is available.

Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

Reading Excel files from C#

I recommend the FileHelpers Library which is a free and easy to use .NET library to import/export data from EXCEL, fixed length or delimited records in files, strings or streams + More.

The Excel Data Link Documentation Section http://filehelpers.sourceforge.net/example_exceldatalink.html

jQuery event for images loaded

Waiting for all images to load...
I found the anwser to my problem with jfriend00 here jquery: how to listen to the image loaded event of one container div? .. and "if (this.complete)"
Waiting for the all thing to load and some possibly in cache !.. and i have added the "error" event... it's robust across all browsers

$(function() { // Wait dom ready
    var $img = $('img'), // images collection
        totalImg = $img.length,
        waitImgDone = function() {
            totalImg--;
            if (!totalImg) {
                console.log($img.length+" image(s) chargée(s) !");
            }
        };
    $img.each(function() {
        if (this.complete) waitImgDone(); // already here..
        else $(this).load(waitImgDone).error(waitImgDone); // completed...
    });
});

Demo : http://jsfiddle.net/molokoloco/NWjDb/

how to configure lombok in eclipse luna

if you're on windows, make sure you 'unblock' the lombok.jar before you install it. if you don't do this, it will install but it wont work.

How can I create a marquee effect?

The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.

Also, the accepted answers demo fiddle has a lot of unnecessary styles.

So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.

http://jsfiddle.net/e8ws12pt/

_x000D_
_x000D_
.marquee {_x000D_
    margin: 0 auto;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    box-sizing: border-box;_x000D_
    padding: 0;_x000D_
    height: 16px;_x000D_
    display: block;_x000D_
}_x000D_
.marquee span {_x000D_
    display: inline-block;_x000D_
    text-indent: 0;_x000D_
    overflow: hidden;_x000D_
    -webkit-transition: 15s;_x000D_
    transition: 15s;_x000D_
    -webkit-animation: marquee 15s linear infinite;_x000D_
    animation: marquee 15s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
    0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }_x000D_
    100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }_x000D_
}
_x000D_
<p class="marquee"><span>Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.</span></p>
_x000D_
_x000D_
_x000D_

Limiting number of displayed results when using ngRepeat

A little late to the party, but this worked for me. Hopefully someone else finds it useful.

<div ng-repeat="video in videos" ng-if="$index < 3">
    ...
</div>

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

How do you create a toggle button?

The good semantic way would be to use a checkbox, and then style it in different ways if it is checked or not. But there are no good ways do to it. You have to add extra span, extra div, and, for a really nice look, add some javascript.

So the best solution is to use a small jQuery function and two background images for styling the two different statuses of the button. Example with an up/down effect given by borders:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('a#button').click(function() {_x000D_
    $(this).toggleClass("down");_x000D_
  });_x000D_
});
_x000D_
a {_x000D_
  background: #ccc;_x000D_
  cursor: pointer;_x000D_
  border-top: solid 2px #eaeaea;_x000D_
  border-left: solid 2px #eaeaea;_x000D_
  border-bottom: solid 2px #777;_x000D_
  border-right: solid 2px #777;_x000D_
  padding: 5px 5px;_x000D_
}_x000D_
_x000D_
a.down {_x000D_
  background: #bbb;_x000D_
  border-top: solid 2px #777;_x000D_
  border-left: solid 2px #777;_x000D_
  border-bottom: solid 2px #eaeaea;_x000D_
  border-right: solid 2px #eaeaea;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a id="button" title="button">Press Me</a>
_x000D_
_x000D_
_x000D_

Obviously, you can add background images that represent button up and button down, and make the background color transparent.

How to force R to use a specified factor level as reference in a regression?

See the relevel() function. Here is an example:

set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
                 y = 4 + (1.5*x) + rnorm(100, sd = 2),
                 b = gl(5, 20))
head(DF)
str(DF)

m1 <- lm(y ~ x + b, data = DF)
summary(m1)

Now alter the factor b in DF by use of the relevel() function:

DF <- within(DF, b <- relevel(b, ref = 3))
m2 <- lm(y ~ x + b, data = DF)
summary(m2)

The models have estimated different reference levels.

> coef(m1)
(Intercept)           x          b2          b3          b4          b5 
  3.2903239   1.4358520   0.6296896   0.3698343   1.0357633   0.4666219 
> coef(m2)
(Intercept)           x          b1          b2          b4          b5 
 3.66015826  1.43585196 -0.36983433  0.25985529  0.66592898  0.09678759

error: use of deleted function

You are using a function, which is marked as deleted.
Eg:

int doSomething( int ) = delete;

The =delete is a new feature of C++0x. It means the compiler should immediately stop compiling and complain "this function is deleted" once the user use such function.

If you see this error, you should check the function declaration for =delete.

To know more about this new feature introduced in C++0x, check this out.

Creating SVG graphics using Javascript?

Have a look at this list on Wikipedia about which browsers support SVG. It also provides links to more details in the footnotes. Firefox for example supports basic SVG, but at the moment lacks most animation features.

A tutorial about how to create SVG objects using Javascript can be found here:

var svgns = "http://www.w3.org/2000/svg";
var svgDocument = evt.target.ownerDocument;
var shape = svgDocument.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r",  20);
shape.setAttributeNS(null, "fill", "green"); 

Is it possible to modify a string of char in C?

All are good answers explaining why you cannot modify string literals because they are placed in read-only memory. However, when push comes to shove, there is a way to do this. Check out this example:

#include <sys/mman.h>
#include <unistd.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int take_me_back_to_DOS_times(const void *ptr, size_t len);

int main()
{
    const *data = "Bender is always sober.";
    printf("Before: %s\n", data);
    if (take_me_back_to_DOS_times(data, sizeof(data)) != 0)
        perror("Time machine appears to be broken!");
    memcpy((char *)data + 17, "drunk!", 6);
    printf("After: %s\n", data);

    return 0;
}

int take_me_back_to_DOS_times(const void *ptr, size_t len)
{
    int pagesize;
    unsigned long long pg_off;
    void *page;

    pagesize = sysconf(_SC_PAGE_SIZE);
    if (pagesize < 0)
        return -1;
    pg_off = (unsigned long long)ptr % (unsigned long long)pagesize;
    page = ((char *)ptr - pg_off);
    if (mprotect(page, len + pg_off, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
        return -1;
    return 0;
}

I have written this as part of my somewhat deeper thoughts on const-correctness, which you might find interesting (I hope :)).

Hope it helps. Good Luck!

Java Replacing multiple different substring in a string at once (or in the most efficient way)

If the string you are operating on is very long, or you are operating on many strings, then it could be worthwhile using a java.util.regex.Matcher (this requires time up-front to compile, so it won't be efficient if your input is very small or your search pattern changes frequently).

Below is a full example, based on a list of tokens taken from a map. (Uses StringUtils from Apache Commons Lang).

Map<String,String> tokens = new HashMap<String,String>();
tokens.put("cat", "Garfield");
tokens.put("beverage", "coffee");

String template = "%cat% really needs some %beverage%.";

// Create pattern of the format "%(cat|beverage)%"
String patternString = "%(" + StringUtils.join(tokens.keySet(), "|") + ")%";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(template);

StringBuffer sb = new StringBuffer();
while(matcher.find()) {
    matcher.appendReplacement(sb, tokens.get(matcher.group(1)));
}
matcher.appendTail(sb);

System.out.println(sb.toString());

Once the regular expression is compiled, scanning the input string is generally very quick (although if your regular expression is complex or involves backtracking then you would still need to benchmark in order to confirm this!)

How to cast a double to an int in Java by rounding it down?

In this question:

1.Casting double to integer is very easy task.

2.But it's not rounding double value to the nearest decimal. Therefore casting can be done like this:

double d=99.99999999;
int i=(int)d;
System.out.println(i);

and it will print 99, but rounding hasn't been done.

Thus for rounding we can use,

double d=99.99999999;
System.out.println( Math.round(d));

This will print the output of 100.

How to get the browser to navigate to URL in JavaScript

Try these:

  1. window.location.href = 'http://www.google.com';
  2. window.location.assign("http://www.w3schools.com");
  3. window.location = 'http://www.google.com';

For more see this link: other ways to reload the page with JavaScript

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Capturing mobile phone traffic on Wireshark

For Android, I previously used tPacketCapture but it didn't work well for an app streaming some video. I'm now using Shark. You need to be root to use it though.

It uses TCPDump (check the arguments you can pass) and creates a pcap file that can be read by Wireshark. The default arguments are usually good enough for me.

C read file line by line

Provide a portable and generic getdelim function, test passed via msvc, clang, gcc.

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

ssize_t
portabl_getdelim(char ** restrict linep,
                 size_t * restrict linecapp,
                 int delimiter,
                 FILE * restrict stream) {
    if (0 == *linep) {
        *linecapp = 8;
        *linep = malloc(*linecapp);
        if (0 == *linep) {
            return EOF;
        }
    }

    ssize_t linelen = 0;
    int c = 0;
    char *p = *linep;

    while (EOF != (c = fgetc(stream))) {
        if (linelen == (ssize_t) *linecapp - 1) {
            *linecapp <<= 1;
            char *p1 = realloc(*linep, *linecapp);
            if (0 == *p1) {
                return EOF;
            }
            p = p1 + linelen;
        }
        *p++ = c;
        linelen++;

        if (delimiter == c) {
            *p = 0;
            return linelen;
        }
    }
    return EOF == c ? EOF : linelen;
}


int
main(int argc, char **argv) {
    const char *filename = "/a/b/c.c";
    FILE *file = fopen(filename, "r");
    if (!file) {
        perror(filename);
        return 1;
    }

    char *line = 0;
    size_t linecap = 0;
    ssize_t linelen;

    while (0 < (linelen = portabl_getdelim(&line, &linecap, '\n', file))) {
        fwrite(line, linelen, 1, stdout);
    }
    if (line) {
        free(line);
    }
    fclose(file);   

    return 0;
}

How do I get the height of a div's full content with jQuery?

If you can possibly help it, DO NOT USE .scrollHeight.

.scrollHeight does not yield the same kind of results in different browsers in certain circumstances (most prominently while scrolling).

For example:

<div id='outer' style='width:100px; height:350px; overflow-y:hidden;'>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
</div>

If you do

console.log($('#outer').scrollHeight);

you'll get 900px in Chrome, FireFox and Opera. That's great.

But, if you attach a wheelevent / wheel event to #outer, when you scroll it, Chrome will give you a constant value of 900px (correct) but FireFox and Opera will change their values as you scroll down (incorrect).

A very simple way to do this is like so (a bit of a cheat, really). (This example works while dynamically adding content to #outer as well):

$('#outer').css("height", "auto");
var outerContentsHeight = $('#outer').height();
$('#outer').css("height", "350px");

console.log(outerContentsHeight); //Should get 900px in these 3 browsers

The reason I pick these three browsers is because all three can disagree on the value of .scrollHeight in certain circumstances. I ran into this issue making my own scrollpanes. Hope this helps someone.

How to re import an updated package while in Python Interpreter?

Update for Python3: (quoted from the already-answered answer, since the last edit/comment here suggested a deprecated method)

In Python 3, reload was moved to the imp module. In 3.4, imp was deprecated in favor of importlib, and reload was added to the latter. When targeting 3 or later, either reference the appropriate module when calling reload or import it.

Takeaway:

  • Python3 >= 3.4: importlib.reload(packagename)
  • Python3 < 3.4: imp.reload(packagename)
  • Python2: continue below

Use the reload builtin function:

https://docs.python.org/2/library/functions.html#reload

When reload(module) is executed:

  • Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time.
  • As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.
  • The names in the module namespace are updated to point to any new or changed objects.
  • Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.

Example:

# Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py

# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1

# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py

# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2

How to change the locale in chrome browser

[on hold: broken in Chrome 72; reported to work in Chrome 71]

The "Quick Language Switcher" extension may help too: https://chrome.google.com/webstore/detail/quick-language-switcher/pmjbhfmaphnpbehdanbjphdcniaelfie

The Quick Language Switcher extension allows the user to supersede the locale the browser is currently using in favor of the value chosen through the extension.

Why does range(start, end) not include end?

The length of the range is the top value minus the bottom value.

It's very similar to something like:

for (var i = 1; i < 11; i++) {
    //i goes from 1 to 10 in here
}

in a C-style language.

Also like Ruby's range:

1...11 #this is a range from 1 to 10

However, Ruby recognises that many times you'll want to include the terminal value and offers the alternative syntax:

1..10 #this is also a range from 1 to 10

Remove white space above and below large text in an inline-block element

span::before,
span::after {
    content: '';
    display: block;
    height: 0;
    width: 0;
}

span::before{
    margin-top:-6px;
}

span::after{
    margin-bottom:-8px;
}

Find out the margin-top and margin-bottom negative margins with this tool: http://text-crop.eightshapes.com/

The tool also gives you SCSS, LESS and Stylus examples. You can read more about it here: https://medium.com/eightshapes-llc/cropping-away-negative-impacts-of-line-height-84d744e016ce

Getting Integer value from a String using javascript/jquery

just do this , you need to remove char other than "numeric" and "." form your string will do work for you

yourString = yourString.replace ( /[^\d.]/g, '' );

your final code will be

  str1 = "test123.00".replace ( /[^\d.]/g, '' );
  str2 = "yes50.00".replace ( /[^\d.]/g, '' );
  total = parseInt(str1, 10) + parseInt(str2, 10);
  alert(total);

Demo

How do I exit from the text window in Git?

On windows, simply pressing 'q' on the keyboard quits this screen. I got it when I was reading help using '!help' or simply 'help' and 'enter', from the DOS prompt.

Happy Coding :-)

Can I use multiple versions of jQuery on the same page?

Taken from http://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page:

  • Original page loads his "jquery.versionX.js" -- $ and jQuery belong to versionX.
  • You call your "jquery.versionY.js" -- now $ and jQuery belong to versionY, plus _$ and _jQuery belong to versionX.
  • my_jQuery = jQuery.noConflict(true); -- now $ and jQuery belong to versionX, _$ and _jQuery are probably null, and my_jQuery is versionY.

Facebook Like-Button - hide count?

Most of the suggestions are now, no longer valid.

The correct fix as of today, is to use the 'button' layout.

eg. <div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button" data-action="like" data-show-faces="true" data-share="false"></div>

Image of button on FB Docs

The FB Docs, seem not to be fully updated yet... if you scroll down you'll see they state only 3 layouts are available, yet the dropdown suggests 4.

enter image description here

This means you can now use a less hacky solution!

Determine if a String is an Integer in Java

The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.

public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length(); i++) {
        if(i == 0 && s.charAt(i) == '-') {
            if(s.length() == 1) return false;
            else continue;
        }
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}

Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.

public static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if(!sc.hasNextInt(radix)) return false;
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt(radix);
    return !sc.hasNext();
}

If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    } catch(NullPointerException e) {
        return false;
    }
    // only got here if we didn't return false
    return true;
}

How to add SHA-1 to android application

On Windows, open the Command Prompt program. You can do this by going to the Start menu

  keytool -exportcert -list -v -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore

On Mac/Linux, open the Terminal and paste

   keytool -exportcert -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore

Simple line plots using seaborn

Since seaborn also uses matplotlib to do its plotting you can easily combine the two. If you only want to adopt the styling of seaborn the set_style function should get you started:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

sns.set_style("darkgrid")
plt.plot(np.cumsum(np.random.randn(1000,1)))
plt.show()

Result:

enter image description here

Persist javascript variables across pages?

You could use the window’s name window.name to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.

Get difference between 2 dates in JavaScript?

I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....

So here's my answer and can be run out of the box.

<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">

<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>

a Fiddle can be seen here DEMO

Detecting locked tables (locked by LOCK TABLE)

This article describes how to get information about locked MySQL resources. mysqladmin debug might also be of some use.

Using grep and sed to find and replace a string

If you are to replace a fixed string or some pattern, I would also like to add the bash builtin pattern string replacement variable substitution construct. Instead of describing it myself, I am quoting the section from the bash manual:

${parameter/pattern/string}

The pattern is expanded to produce a pattern just as in pathname expansion. parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is @ or *, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

In my case, I am using a tiny .exe that reloads the referenced DLLs via Reflection. So I just do these steps which saves my day:

From project properties on solution explorer, at build tab, I choose target platfrom x86

Autocompletion in Vim

You can use a plugin like AutoComplPop to get automatic code completion as you type.

2015 Edit: I personally use YouCompleteMe now.

Python unittest passing arguments

This is my solution:

# your test class
class TestingClass(unittest.TestCase):
    
    # This will only run once for all the tests within this class
    @classmethod
    def setUpClass(cls) -> None:
       if len(sys.argv) > 1:
          cls.email = sys.argv[1]

    def testEmails(self):
        assertEqual(self.email, "[email protected]")


if __name__ == "__main__":
    unittest.main()

you could have a runner.py file with something like this:

# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests


with the above code, you should be to run your tests with runner.py [email protected]

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

How do I modify the URL without reloading the page?

This code works for me. I used it into my application in ajax.

history.pushState({ foo: 'bar' }, '', '/bank');

Once a page load into an ID using ajax, It does change the browser url automatically without reloading the page.

This is ajax function bellow.

function showData(){
    $.ajax({
      type: "POST",
      url: "Bank.php", 
      data: {}, 
      success: function(html){          
        $("#viewpage").html(html).show();
        $("#viewpage").css("margin-left","0px");
      }
    });
  }

Example: From any page or controller like "Dashboard", When I click on the bank, it loads bank list using the ajax code without reloading the page. At this time, browser URL will not be changed.

history.pushState({ foo: 'bar' }, '', '/bank');

But when I use this code into the ajax, it change the browser url without reloading the page. This is the full ajax code here in the bellow.

function showData(){
        $.ajax({
          type: "POST",
          url: "Bank.php", 
          data: {}, 
          success: function(html){          
            $("#viewpage").html(html).show();
            $("#viewpage").css("margin-left","0px");
            history.pushState({ foo: 'bar' }, '', '/bank');
          }
        });
      }

Remove warning messages in PHP

For ignoring all warnings use this sample, on the top of your code :

error_reporting(0);

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

Default SQL Server Port

The default port of SQL server is 1433.

How to create new folder?

You probably want os.makedirs as it will create intermediate directories as well, if needed.

import os

#dir is not keyword
def makemydir(whatever):
  try:
    os.makedirs(whatever)
  except OSError:
    pass
  # let exception propagate if we just can't
  # cd into the specified directory
  os.chdir(whatever)

How do I add the contents of an iterable to a set?

You can add elements of a list to a set like this:

>>> foo = set(range(0, 4))
>>> foo
set([0, 1, 2, 3])
>>> foo.update(range(2, 6))
>>> foo
set([0, 1, 2, 3, 4, 5])

Errors in pom.xml with dependencies (Missing artifact...)

It seemed that a lot of dependencies were incorrect.

enter image description here

Download the whole POM here

A good place to look for the correct dependencies is the Maven Repository website.

When to use Spring Security`s antMatcher()?

I'm updating my answer...

antMatcher() is a method of HttpSecurity, it doesn't have anything to do with authorizeRequests(). Basically, http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

The authorizeRequests().antMatchers() is then used to apply authorization to one or more paths you specify in antMatchers(). Such as permitAll() or hasRole('USER3'). These only get applied if the first http.antMatcher() is matched.

Uncaught ReferenceError: jQuery is not defined

you need to put it after wp_head(); Because that loads your jQuery and you need to load jQuery first and then your js

iPhone Safari Web App opens links in new window

I created a bower installable package out of @rmarscher's answer which can be found here:

http://github.com/stylr/iosweblinks

You can easily install the snippet with bower using bower install --save iosweblinks

Setting TIME_WAIT TCP

Usually, only the endpoint that issues an 'active close' should go into TIME_WAIT state. So, if possible, have your clients issue the active close which will leave the TIME_WAIT on the client and NOT on the server.

See here: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html and http://www.isi.edu/touch/pubs/infocomm99/infocomm99-web/ for details (the later also explains why it's not always possible due to protocol design that doesn't take TIME_WAIT into consideration).

How do I set/unset a cookie with jQuery?

Try (doc here, SO snippet not works so run this one)

document.cookie = "test=1"             // set
document.cookie = "test=1;max-age=0"   // unset

UIScrollView not scrolling

adding the following code in viewDidLayoutSubviews worked for me with Autolayout. After trying all the answers:

- (void)viewDidLayoutSubviews
{
    self.activationScrollView.contentSize = CGSizeMake(IPHONE_SCREEN_WIDTH, 620);

}

//set the height of content size as required

Count the number of all words in a string

require(stringr)

Define a very simple function

str_words <- function(sentence) {

  str_count(sentence, " ") + 1

}

Check

str_words(This is a sentence with six words)

Open new popup window without address bars in firefox & IE

In internet explorer, if the new url is from the same domain as the current url, the window will be open without an address bar. Otherwise, it will cause an address bar to appear. One workaround is to open a page from the same domain and then redirect from that page.

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

JavaScript check if value is only undefined, null or false

Well, you can always "give up" :)

function b(val){
    return (val==null || val===false);
}

403 - Forbidden: Access is denied. ASP.Net MVC

Are you hosting the site on iis? if so make sure the account your website runs under has access to local file system?

Straight from msdn .....

The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.

To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.

To grant read, write, and modify permissions to a specific file

  • In Windows Explorer, locate and select the required file.
  • Right-click the file, and then click Properties.
  • In the Properties dialog box, click the Security tab.
  • On the Security tab, examine the list of users. If the Network Service
  • account is not listed, add it.
  • In the Properties dialog box, click the Network Service user name, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
  • Click Apply, and then click OK.

Click here for more

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Is your server configured for client authentication? If so you need to pass the client certificate while connecting with the server.

How to change color in circular progress bar?

styles.xml

<style name="CircularProgress" parent="Theme.AppCompat.Light">
    <item name="colorAccent">@color/yellow</item>
</style>

  <ProgressBar
        android:layout_width="@dimen/d_40"
        android:layout_height="@dimen/d_40"
        android:indeterminate="true"
        style="@style/Widget.AppCompat.ProgressBar"
        android:theme="@style/CircularProgress"/>

How to get selected value of a html select with asp.net

You need to add a name to your <select> element:

<select id="testSelect" name="testSelect">

It will be posted to the server, and you can see it using:

Request.Form["testSelect"]

Adding 'serial' to existing column in Postgres

TL;DR

Here's a version where you don't need a human to read a value and type it out themselves.

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Another option would be to employ the reusable Function shared at the end of this answer.


A non-interactive solution

Just adding to the other two answers, for those of us who need to have these Sequences created by a non-interactive script, while patching a live-ish DB for instance.

That is, when you don't wanna SELECT the value manually and type it yourself into a subsequent CREATE statement.

In short, you can not do:

CREATE SEQUENCE foo_a_seq
    START WITH ( SELECT max(a) + 1 FROM foo );

... since the START [WITH] clause in CREATE SEQUENCE expects a value, not a subquery.

Note: As a rule of thumb, that applies to all non-CRUD (i.e.: anything other than INSERT, SELECT, UPDATE, DELETE) statements in pgSQL AFAIK.

However, setval() does! Thus, the following is absolutely fine:

SELECT setval('foo_a_seq', max(a)) FROM foo;

If there's no data and you don't (want to) know about it, use coalesce() to set the default value:

SELECT setval('foo_a_seq', coalesce(max(a), 0)) FROM foo;
--                         ^      ^         ^
--                       defaults to:       0

However, having the current sequence value set to 0 is clumsy, if not illegal.
Using the three-parameter form of setval would be more appropriate:

--                                             vvv
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
--                                                  ^   ^
--                                                is_called

Setting the optional third parameter of setval to false will prevent the next nextval from advancing the sequence before returning a value, and thus:

the next nextval will return exactly the specified value, and sequence advancement commences with the following nextval.

— from this entry in the documentation

On an unrelated note, you also can specify the column owning the Sequence directly with CREATE, you don't have to alter it later:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;

In summary:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Using a Function

Alternatively, if you're planning on doing this for multiple columns, you could opt for using an actual Function.

CREATE OR REPLACE FUNCTION make_into_serial(table_name TEXT, column_name TEXT) RETURNS INTEGER AS $$
DECLARE
    start_with INTEGER;
    sequence_name TEXT;
BEGIN
    sequence_name := table_name || '_' || column_name || '_seq';
    EXECUTE 'SELECT coalesce(max(' || column_name || '), 0) + 1 FROM ' || table_name
            INTO start_with;
    EXECUTE 'CREATE SEQUENCE ' || sequence_name ||
            ' START WITH ' || start_with ||
            ' OWNED BY ' || table_name || '.' || column_name;
    EXECUTE 'ALTER TABLE ' || table_name || ' ALTER COLUMN ' || column_name ||
            ' SET DEFAULT nextVal(''' || sequence_name || ''')';
    RETURN start_with;
END;
$$ LANGUAGE plpgsql VOLATILE;

Use it like so:

INSERT INTO foo (data) VALUES ('asdf');
-- ERROR: null value in column "a" violates not-null constraint

SELECT make_into_serial('foo', 'a');
INSERT INTO foo (data) VALUES ('asdf');
-- OK: 1 row(s) affected

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

angular ng-repeat in reverse

Im adding one answer that no one mentioned. I would try to make the server do it if you have one. Clientside filtering can be dangerous if the server returns a lot of records. Because you might be forced to add paging. If you have paging from the server then the client filter on order, would be in the current page. Which would confuse the end user. So if you have a server, then send the orderby with the call and let the server return it.

Can Twitter Bootstrap alerts fade in as well as out?

The thing I use is this:

In your template an alert area

<div id="alert-area"></div>

Then an jQuery function for showing an alert

function newAlert (type, message) {
    $("#alert-area").append($("<div class='alert-message " + type + " fade in' data-alert><p> " + message + " </p></div>"));
    $(".alert-message").delay(2000).fadeOut("slow", function () { $(this).remove(); });
}
newAlert('success', 'Oh yeah!');

Global Events in Angular

DO Not Use EventEmitter for your service communication.

You should use one of the Observable types. I personally like BehaviorSubject.

Simple example:

You can pass initial state, here I passing null

let subject = new BehaviorSubject(null);

When you want to update the subject

subject.next(myObject)

Observe from any service or component and act when it gets new updates.

subject.subscribe(this.YOURMETHOD);

Here is more information..

How do I convert hex to decimal in Python?

If by "hex data" you mean a string of the form

s = "6a48f82d8e828ce82b82"

you can use

i = int(s, 16)

to convert it to an integer and

str(i)

to convert it to a decimal string.

How to check if a variable is equal to one string or another string?

This does not do what you expect:

if var is 'stringone' or 'stringtwo':
    dosomething()

It is the same as:

if (var is 'stringone') or 'stringtwo':
    dosomething()

Which is always true, since 'stringtwo' is considered a "true" value.

There are two alternatives:

if var in ('stringone', 'stringtwo'):
    dosomething()

Or you can write separate equality tests,

if var == 'stringone' or var == 'stringtwo':
    dosomething()

Don't use is, because is compares object identity. You might get away with it sometimes because Python interns a lot of strings, just like you might get away with it in Java because Java interns a lot of strings. But don't use is unless you really want object identity.

>>> 'a' + 'b' == 'ab'
True
>>> 'a' + 'b' is 'abc'[:2]
False # but could be True
>>> 'a' + 'b' is 'ab'
True  # but could be False

How to center links in HTML

The <p> will show up on a new line. Try wrapping all of your links in one single <p> tag:

<p style="text-align:center;"><a href="http//www.google.com">Search</a><a href="Contact Us">Contact Us</a></p>

Eclipse projects not showing up after placing project files in workspace/projects

Yeah.... i kinda see what you need. I just came across same problem.

Here is exactly what i did. Now, bear in mind, this some low level knowledge, since i'm just starting. I made my life complicated, so i needed solution. I kinda found it on my own, using different directions from above answers.

I switched from win 10 on HDD to linux on SSD, so i needed my few of .class and .java imported into new workspace.

First i made a mistake, not using export option on windows and i just simply copied all of files from src and bin folders on win 10 to src and bin folders on linux. Of course workspace did not see those files.

Solution was found in IMPORT tool (which i should have used right away).

  1. I put all of files in src folder into zipp file, and moved this file to some arbitrary folder (Home folder in my case).

  2. Go back to src folder and delete all of .java files (you won't be needing them anymore).

  3. Then i opened my empty project and selected import from File menu in Eclipse. In import window, under option General (first one) select Import Archive.

  4. Now simply find your zip file, and Voila! All is where it should be.

Get current time in hours and minutes

you can use command

date | awk '{print $4}'| cut -d ':' -f3

as you mentioned using only the date|awk '{print $4}' pipeline gives you something like this

20:18:19

so as we can see if we want to extract some part of this string then we need a delimiter , for our case it is :, so we decide to chop on the basis of :. Now this delimiter will chop the string into three parts i.e. 20 ,18 and 19 , as we want the second one we use -f2 in our command. to sum up ,

cut : chops some string based on delimeter.

-d : delimeter (here :)

-f2 : the chopped off token that we want.

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.