Programs & Examples On #Jinternalframe

JInternalFrame is a lightweight Java Swing component that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar.

Creating a JavaScript cookie on a domain and reading it across sub domains

You want:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

Python 3 sort a dict by its values

itemgetter (see other answers) is (as I know) more efficient for large dictionaries but for the common case, I believe that d.get wins. And it does not require an extra import.

>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
>>> for k in sorted(d, key=d.get, reverse=True):
...     k, d[k]
...
('bb', 4)
('aa', 3)
('cc', 2)
('dd', 1)

Note that alternatively you can set d.__getitem__ as key function which may provide a small performance boost over d.get.

How to use LDFLAGS in makefile

In more complicated build scenarios, it is common to break compilation into stages, with compilation and assembly happening first (output to object files), and linking object files into a final executable or library afterward--this prevents having to recompile all object files when their source files haven't changed. That's why including the linking flag -lm isn't working when you put it in CFLAGS (CFLAGS is used in the compilation stage).

The convention for libraries to be linked is to place them in either LOADLIBES or LDLIBS (GNU make includes both, but your mileage may vary):

LDLIBS=-lm

This should allow you to continue using the built-in rules rather than having to write your own linking rule. For other makes, there should be a flag to output built-in rules (for GNU make, this is -p). If your version of make does not have a built-in rule for linking (or if it does not have a placeholder for -l directives), you'll need to write your own:

client.o: client.c
    $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ $<

client: client.o
    $(CC) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $@

How to set .net Framework 4.5 version in IIS 7 application pool

There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:

appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5

Appcmd is located in %windir%\System32\inetsrv. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.

MS article on setting .Net version for App Pool

Using stored procedure output parameters in C#

In your C# code, you are using transaction for the command. Just commit the transaction and after that access your parameter value, you will get the value. Worked for me. :)

How to set specific window (frame) size in java swing?

Well, you are using both frame.setSize() and frame.pack().

You should use one of them at one time.

Using setSize() you can give the size of frame you want but if you use pack(), it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.

Try removing frame.pack() from your code or putting it before setting size and then run it.

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

Note: This answer is somewhat intended to be a joke, but it actually does work...

#!/bin/bash
outfile="/tmp/$RANDOM"
cfile="$outfile.c"
echo '#include <stdio.h>
int main(void){int e=1;char c;while((c=getc(stdin))!=-1){if(c==10)e=1;if(c==32)e=0;if(e)putc(c,stdout);}}' >> "$cfile"
gcc -o "$outfile" "$cfile"
rm "$cfile"
cat somedata.txt | "$outfile"
rm "$outfile"

You can replace cat somedata.txt with a different command.

Why do I get an error instantiating an interface?

The error message seems self-explanatory. You can't instantiate an instance of an interface, and you've declared IUser as an interface. (The same rule applies to abstract classes.) The whole point of an interface is that it doesn't do anything—there is no implementation provided for its methods.

However, you can instantiate an instance of a class that implements that interface (provides an implementation for its methods), which in your case is the User class.

Thus, your code needs to look like this:

IUser user = new User();

This instantiates an instance of the User class (which provides the implementation), and assigns it to an object variable for the interface type (IUser, which provides the interface, the way in which you as the programmer can interact with the object).

Of course, you could also write:

User user = new User();

which creates an instance of the User class and assigns it to an object variable of the same type, but that sort of defeats the purpose of a defining a separate interface in the first place.

Input text dialog Android

How about this EXAMPLE? It seems straightforward.

final EditText txtUrl = new EditText(this);

// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");

new AlertDialog.Builder(this)
  .setTitle("Moustachify Link")
  .setMessage("Paste in the link of an image to moustachify!")
  .setView(txtUrl)
  .setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      String url = txtUrl.getText().toString();
      moustachify(null, url);
    }
  })
  .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    }
  })
  .show(); 

Using a dictionary to select function to execute

Simplify, simplify, simplify + DRY:

tasks = {}
task = lambda f: tasks.setdefault(f.__name__, f)

@task
def p1():
    whatever

@task
def p2():
    whatever

def my_main(key):
    tasks[key]()

HttpClient - A task was cancelled?

var clientHttp = new HttpClient();
clientHttp.Timeout = TimeSpan.FromMinutes(30);

The above is the best approach for waiting on a large request. You are confused about 30 minutes; it's random time and you can give any time that you want.

In other words, request will not wait for 30 minutes if they get results before 30 minutes. 30 min means request processing time is 30 min. When we occurred error "Task was cancelled", or large data request requirements.

Get attribute name value of <input>

Give your input an ID and use the attr method:

var name = $("#id").attr("name");

Write Array to Excel Range

This is an excerpt from method of mine, which converts a DataTable (the dt variable) into an array and then writes the array into a Range on a worksheet (wsh var). You can also change the topRow variable to whatever row you want the array of strings to be placed at.

object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
for (int r = 0; r < dt.Rows.Count; r++)
{
    DataRow dr = dt.Rows[r];
    for (int c = 0; c < dt.Columns.Count; c++)
    {
        arr[r, c] = dr[c];
    }
}
Excel.Range c1 = (Excel.Range)wsh.Cells[topRow, 1];
Excel.Range c2 = (Excel.Range)wsh.Cells[topRow + dt.Rows.Count - 1, dt.Columns.Count];
Excel.Range range = wsh.get_Range(c1, c2);
range.Value = arr;

Of course you do not need to use an intermediate DataTable like I did, the code excerpt is just to demonstrate how an array can be written to worksheet in single call.

Difference between style = "position:absolute" and style = "position:relative"

With CSS positioning, you can place an element exactly where you want it on your page.

When you are going to use CSS positioning, the first thing you need to do is use the CSS property position to tell the browser if you're going to use absolute or relative positioning.

Both Positions are having different features. In CSS Once you set Position then you can able to use top, right, bottom, left attributes.

Absolute Position

An absolute position element is positioned relative to the first parent element that has a position other than static.

Relative Position

A relative positioned element is positioned relative to its normal position.

To position an element relatively, the property position is set as relative. The difference between absolute and relative positioning is how the position is being calculated.

More :Postion Relative vs Absolute

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

This is possible with a bit of format conversion.

To extract the private key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa

To convert the private key to a public key:

openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8

To extract the public key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8

SQL Stored Procedure set variables using SELECT

One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.

SELECT @currentTerm = currentterm,
       @termID = termid,
       @endDate = enddate
FROM   table1
WHERE  iscurrent = 1

IF( @@ROWCOUNT <> 1 )
  BEGIN
      RAISERROR ('Unexpected number of matching rows',
                 16,
                 1)

      RETURN
  END  

Bootstrap with jQuery Validation Plugin

Try using this sample code. Using the Jquery validation plugin and additional methods. This is the working code for my project. Hope this helps you

_x000D_
_x000D_
//jquery validation booking page_x000D_
 _x000D_
 // Wait for the DOM to be ready_x000D_
$(function() {_x000D_
  // Initialize form validation on the registration form._x000D_
  // It has the name attribute "registration"_x000D_
  $("form[name='book']").validate({_x000D_
   //on key up validation_x000D_
   onkeyup: function(element) {_x000D_
      $(element).valid(); _x000D_
    },  _x000D_
    // Specify validation rules_x000D_
    rules: {_x000D_
      // The key name on the left side is the name attribute_x000D_
      // of an input field. Validation rules are defined_x000D_
      // on the right side_x000D_
      fname: {_x000D_
        required: true,_x000D_
        lettersonly: true_x000D_
        },_x000D_
      lname:{_x000D_
        required: true,_x000D_
        lettersonly: true_x000D_
        },_x000D_
      email: {_x000D_
        required: true,_x000D_
        // Specify that email should be validated_x000D_
        // by the built-in "email" rule_x000D_
        email: true_x000D_
      },_x000D_
      password: {_x000D_
        required: true,_x000D_
        minlength: 5_x000D_
      }_x000D_
    },_x000D_
    // Specify validation error messages_x000D_
    messages: {_x000D_
      fname: {_x000D_
      required:"Please enter your firstname",_x000D_
      lettersonly:"Letters allowed only"_x000D_
      },_x000D_
      lname: {_x000D_
      required:"Please enter your lastname",_x000D_
      lettersonly:"Letters allowed only"_x000D_
      },_x000D_
      email: "Please enter a valid email address"_x000D_
    },_x000D_
    // Make sure the form is submitted to the destination defined_x000D_
    // in the "action" attribute of the form when valid_x000D_
    submitHandler: function(form) {_x000D_
      form.submit();_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
.error {_x000D_
  color: red;_x000D_
  margin-left: 5px;_x000D_
  font-size:15px;_x000D_
}
_x000D_
<script src="design/bootstrap-3.3.7-dist/js/jquery.validate.js"></script>_x000D_
<script src="design/bootstrap-3.3.7-dist/js/additional-methods.js"></script>_x000D_
_x000D_
<form name="book" id="book" action="" method="post">_x000D_
_x000D_
    <div class="row form-group">_x000D_
        <div class="col-md-6 ">_x000D_
            <label class="" for="fname">First Name</label>_x000D_
            <input type="text" name="fname" id="fname" class="form-control" placeholder="First Name">_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
            <label class="" for="lname">Last Name</label>_x000D_
            <input type="text" name="lname" id="lname" class="form-control" placeholder="Last Name">_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="row form-group">_x000D_
        <div class="col-md-6 ">_x000D_
            <label class="" for="date">Date</label>_x000D_
            <input type="text" id="date" class="form-control datepicker px-2" placeholder="Date of visit">_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
            <label class="" for="email">Email</label>_x000D_
            <input type="email" name="email" id="email" class="form-control" placeholder="Email">_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="row form-group">_x000D_
        <div class="col-md-12">_x000D_
            <label class="" for="treatment">Service You Want</label>_x000D_
            <select name="treatment" id="treatment" class="form-control">_x000D_
                <option value="">Hair Cut</option>_x000D_
                <option value="">Hair Coloring</option>_x000D_
                <option value="">Perms and Curls</option>_x000D_
                <option value="">Hair Conditioning</option>_x000D_
                <option value="">Manicure</option>_x000D_
                <option value="">Pedicure</option>_x000D_
                <option value="">Nails Extension</option>_x000D_
                <option value="">Nail Design</option>_x000D_
                <option value="">Waxing Eyebrows</option>_x000D_
                <option value="">Waxing Hands/Legs</option>_x000D_
                <option value="">Full Face Waxing</option>_x000D_
                <option value="">Full Body/Body Parts Wax</option>_x000D_
            </select>_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="row form-group">_x000D_
        <div class="col-md-12">_x000D_
            <label class="" for="note">Notes</label>_x000D_
            <textarea name="note" id="note" cols="30" rows="5" class="form-control" placeholder="Write your notes or questions here..."></textarea>_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="row form-group">_x000D_
        <div class="col-md-12">_x000D_
            <center><input type="submit" value="Book Now" class="btn btn-primary btn-lg"></center>_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
</form>
_x000D_
_x000D_
_x000D_

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Download large file in python with requests

Not exactly what OP was asking, but... it's ridiculously easy to do that with urllib:

from urllib.request import urlretrieve
url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
dst = 'ubuntu-16.04.2-desktop-amd64.iso'
urlretrieve(url, dst)

Or this way, if you want to save it to a temporary file:

from urllib.request import urlopen
from shutil import copyfileobj
from tempfile import NamedTemporaryFile
url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
with urlopen(url) as fsrc, NamedTemporaryFile(delete=False) as fdst:
    copyfileobj(fsrc, fdst)

I watched the process:

watch 'ps -p 18647 -o pid,ppid,pmem,rsz,vsz,comm,args; ls -al *.iso'

And I saw the file growing, but memory usage stayed at 17 MB. Am I missing something?

How to get current CPU and RAM usage in Python?

Based on the cpu usage code by @Hrabal, this is what I use:

from subprocess import Popen, PIPE

def get_cpu_usage():
    ''' Get CPU usage on Linux by reading /proc/stat '''

    sub = Popen(('grep', 'cpu', '/proc/stat'), stdout=PIPE, stderr=PIPE)
    top_vals = [int(val) for val in sub.communicate()[0].split('\n')[0].split[1:5]]

    return (top_vals[0] + top_vals[2]) * 100. /(top_vals[0] + top_vals[2] + top_vals[3])

Git says remote ref does not exist when I delete remote branch

git branch -a will list the branches in your local and not the branches in your remote.

And the error error: unable to delete 'remotes/origin/test': remote ref does not exist means you don't have a branch in that name in your remote but the branch exists in your local.

Notice: Undefined offset: 0 in

If you leave out the brackets then PHP will assign the keys by default.

Try this:

$votes = $row['votes_up']; 
$votes = $row['votes_down']; 

Are string.Equals() and == operator really same?

An object is defined by an OBJECT_ID, which is unique. If A and B are objects and A == B is true, then they are the very same object, they have the same data and methods, but, this is also true:

A.OBJECT_ID == B.OBJECT_ID

if A.Equals(B) is true, that means that the two objects are in the same state, but this doesn't mean that A is the very same as B.

Strings are objects.

Note that the == and Equals operators are reflexive, simetric, tranzitive, so they are equivalentic relations (to use relational algebraic terms)

What this means: If A, B and C are objects, then:

(1) A == A is always true; A.Equals(A) is always true (reflexivity)

(2) if A == B then B == A; If A.Equals(B) then B.Equals(A) (simetry)

(3) if A == B and B == C, then A == C; if A.Equals(B) and B.Equals(C) then A.Equals(C) (tranzitivity)

Also, you can note that this is also true:

(A == B) => (A.Equals(B)), but the inverse is not true.

A B =>
0 0 1
0 1 1
1 0 0
1 1 1

Example of real life: Two Hamburgers of the same type have the same properties: they are objects of the Hamburger class, their properties are exactly the same, but they are different entities. If you buy these two Hamburgers and eat one, the other one won't be eaten. So, the difference between Equals and ==: You have hamburger1 and hamburger2. They are exactly in the same state (the same weight, the same temperature, the same taste), so hamburger1.Equals(hamburger2) is true. But hamburger1 == hamburger2 is false, because if the state of hamburger1 changes, the state of hamburger2 not necessarily change and vice versa.

If you and a friend get a Hamburger, which is yours and his in the same time, then you must decide to split the Hamburger into two parts, because you.getHamburger() == friend.getHamburger() is true and if this happens: friend.eatHamburger(), then your Hamburger will be eaten too.

I could write other nuances about Equals and ==, but I'm getting hungry, so I have to go.

Best regards, Lajos Arpad.

How to restart a node.js server

At first open terminal/command line then go to your project directory, now install nodemon by using command npm install nodemon --save-dev this command will make sure it saved as developer dependency. If you are working with expressjs then in your package file it will look like

{
  "name": "expressjs-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "^2.0.4"
  },
  "devDependencies": {
    "nodemon": "^2.0.3"
  }
}

now modify the "start" value in your package.json file, for production we will use the exsiting value but for development will use nodemon to track the changes in source file without restarting server. There for new value for start is "start": "if [[$NODE_ENV=='production']]; then node ./bin/www; else nodemon ./bin/www; fi"

final package.json file will look like

{
  "name": "expressjs-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "if [[$NODE_ENV=='production']]; then node ./bin/www; else nodemon ./bin/www; fi"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "^2.0.4"
  },
  "devDependencies": {
    "nodemon": "^2.0.3"
  }
}

to uninstall nodemon jusy simply run the command npm uninstall nodemon

What does `void 0` mean?

void is a reserved JavaScript keyword. It evaluates the expression and always returns undefined.

UITableView - scroll to the top

Swift 3

tableView.setContentOffset(CGPoint.zero, animated: true)

if tableView.setContentOffset don't work.

Use:

tableView.beginUpdates()
tableView.setContentOffset(CGPoint.zero, animated: true)
tableView.endUpdates()

Authenticate with GitHub using a token

Your curl command is entirely wrong. You should be using the following

curl -H 'Authorization: token <MYTOKEN>' ...

That aside, that doesn't authorize your computer to clone the repository if in fact it is private. (Taking a look, however, indicates that it is not.) What you would normally do is the following:

git clone https://scuzzlebuzzle:<MYTOKEN>@github.com/scuzzlebuzzle/ol3-1.git --branch=gh-pages gh-pages

That will add your credentials to the remote created when cloning the repository. Unfortunately, however, you have no control over how Travis clones your repository, so you have to edit the remote like so.

# After cloning
cd gh-pages
git remote set-url origin https://scuzzlebuzzle:<MYTOKEN>@github.com/scuzzlebuzzle/ol3-1.git

That will fix your project to use a remote with credentials built in.

Warning: Tokens have read/write access and should be treated like passwords. If you enter your token into the clone URL when cloning or adding a remote, Git writes it to your .git/config file in plain text, which is a security risk.

Swift UIView background color opacity

You can set background color of view to the UIColor with alpha, and not affect view.alpha:

view.backgroundColor = UIColor(white: 1, alpha: 0.5)

or

view.backgroundColor = UIColor.red.withAlphaComponent(0.5)

is there any alternative for ng-disabled in angular2?

Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable

For radio button:

<md-radio-button disabled>Select color</md-radio-button>

For dropdown:

<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>

Fastest method to replace all instances of a character in a string

Use Regex object like this

var regex = new RegExp('"', 'g'); str = str.replace(regex, '\'');

It will replace all occurrence of " into '.

Pointers in Python?

I wrote the following simple class as, effectively, a way to emulate a pointer in python:

class Parameter:
    """Syntactic sugar for getter/setter pair
    Usage:

    p = Parameter(getter, setter)

    Set parameter value:
    p(value)
    p.val = value
    p.set(value)

    Retrieve parameter value:
    p()
    p.val
    p.get()
    """
    def __init__(self, getter, setter):
        """Create parameter

        Required positional parameters:
        getter: called with no arguments, retrieves the parameter value.
        setter: called with value, sets the parameter.
        """
        self._get = getter
        self._set = setter

    def __call__(self, val=None):
        if val is not None:
            self._set(val)
        return self._get()

    def get(self):
        return self._get()

    def set(self, val):
        self._set(val)

    @property
    def val(self):
        return self._get()

    @val.setter
    def val(self, val):
        self._set(val)

Here's an example of use (from a jupyter notebook page):

l1 = list(range(10))
def l1_5_getter(lst=l1, number=5):
    return lst[number]

def l1_5_setter(val, lst=l1, number=5):
    lst[number] = val

[
    l1_5_getter(),
    l1_5_setter(12),
    l1,
    l1_5_getter()
]

Out = [5, None, [0, 1, 2, 3, 4, 12, 6, 7, 8, 9], 12]

p = Parameter(l1_5_getter, l1_5_setter)

print([
    p(),
    p.get(),
    p.val,
    p(13),
    p(),
    p.set(14),
    p.get()
])
p.val = 15
print(p.val, l1)

[12, 12, 12, 13, 13, None, 14]
15 [0, 1, 2, 3, 4, 15, 6, 7, 8, 9]

Of course, it is also easy to make this work for dict items or attributes of an object. There is even a way to do what the OP asked for, using globals():

def setter(val, dict=globals(), key='a'):
    dict[key] = val

def getter(dict=globals(), key='a'):
    return dict[key]

pa = Parameter(getter, setter)
pa(2)
print(a)
pa(3)
print(a)

This will print out 2, followed by 3.

Messing with the global namespace in this way is kind of transparently a terrible idea, but it shows that it is possible (if inadvisable) to do what the OP asked for.

The example is, of course, fairly pointless. But I have found this class to be useful in the application for which I developed it: a mathematical model whose behavior is governed by numerous user-settable mathematical parameters, of diverse types (which, because they depend on command line arguments, are not known at compile time). And once access to something has been encapsulated in a Parameter object, all such objects can be manipulated in a uniform way.

Although it doesn't look much like a C or C++ pointer, this is solving a problem that I would have solved with pointers if I were writing in C++.

How to use git merge --squash?

Suppose you worked in feature/task1 with multiple commits.

  1. Go to your project branch (project/my_project)

    git checkout project/my_project
    
  2. Create a new branch (feature/task1_bugfix)

    git checkout -b feature/task1_bugfix
    
  3. Marge with the --squash option

    git merge --squash feature/task1
    
  4. Create a single commit

    git commit -am "add single comments"
    
  5. Push your branch

    git push --set-upstream origin feature/task1_bugfix
    

Force overwrite of local file with what's in origin repo?

I believe what you are looking for is "git restore".

The easiest way is to remove the file locally, and then execute the git restore command for that file:

$ rm file.txt
$ git restore file.txt 

Switching to landscape mode in Android Emulator

On iMac with long keyboard (keyboard with numeric keypad at the right):

(1) Cmd + 7 (on numeric part of keyboard)
(2) Cmd + 9 (on numeric part of keyboard)

Node.js get file extension

A simple solution without need for require which solves the multiple period extension problem:

var filename = 'file.with.long.extension';
var ext = filename.substring(filename.indexOf('.')); 
//ext = '.with.long.extension'

Or if you don't want the leading dot:

var filename = 'file.with.long.extension';
var ext = filename.substring(filename.indexOf('.')+1); 
//ext = 'with.long.extension'

Make sure to test that the file has an extension too.

PostgreSQL unnest() with element number

Try:

select v.*, row_number() over (partition by id order by elem) rn from
(select
    id,
    unnest(string_to_array(elements, ',')) AS elem
 from myTable) v

If condition inside of map() React

You are using both ternary operator and if condition, use any one.

By ternary operator:

.map(id => {
    return this.props.schema.collectionName.length < 0 ?
        <Expandable>
            <ObjectDisplay
                key={id}
                parentDocumentId={id}
                schema={schema[this.props.schema.collectionName]}
                value={this.props.collection.documents[id]}
            />
        </Expandable>
    :
        <h1>hejsan</h1>
}

By if condition:

.map(id => {
    if(this.props.schema.collectionName.length < 0)
        return <Expandable>
                  <ObjectDisplay
                      key={id}
                      parentDocumentId={id}
                      schema={schema[this.props.schema.collectionName]}
                      value={this.props.collection.documents[id]}
                  />
              </Expandable>
    return <h1>hejsan</h1>
}

How do I run Selenium in Xvfb?

The easiest way is probably to use xvfb-run:

DISPLAY=:1 xvfb-run java -jar selenium-server-standalone-2.0b3.jar

xvfb-run does the whole X authority dance for you, give it a try!

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

Upping the directive in the virtualhost for KeepAliveTimeout to 60 solved this for me.

How can I format a list to print each element on a separate line in python?

Use str.join:

In [27]: mylist = ['10', '12', '14']

In [28]: print '\n'.join(mylist)
10
12
14

Using Pipes within ngModel on INPUT Elements in Angular

<input [ngModel]="item.value | useMyPipeToFormatThatValue" 
      (ngModelChange)="item.value=$event" name="inputField" type="text" />

The solution here is to split the binding into a one-way binding and an event binding - which the syntax [(ngModel)] actually encompasses. [] is one-way binding syntax and () is event binding syntax. When used together - [()] Angular recognizes this as shorthand and wires up a two-way binding in the form of a one-way binding and an event binding to a component object value.

The reason you cannot use [()] with a pipe is that pipes work only with one-way bindings. Therefore you must split out the pipe to only operate on the one-way binding and handle the event separately.

See Angular Template Syntax for more info.

Is there a Java API that can create rich Word documents?

It was mentioned only briefly once, so I'd like to call out the docx4j library, as I've had more success with docx4j than anything else. Apache POI's support for Word documents isn't very good. Also, unlike Aspose.Words, docx4j is an open source library.

The only drawback is with docx4j you have to create Office Open XML (docx) format documents rather than OLE2-based (doc) format documents. This is the default format for Word 2007, but Word 2003 and earlier users will need to install a compatibility pack.

Using HTML5/JavaScript to generate and save a file

You can use localStorage. This is the Html5 equivalent of cookies. It appears to work on Chrome and Firefox BUT on Firefox, I needed to upload it to a server. That is, testing directly on my home computer didn't work.

I'm working up HTML5 examples. Go to http://faculty.purchase.edu/jeanine.meyer/html5/html5explain.html and scroll to the maze one. The information to re-build the maze is stored using localStorage.

I came to this article looking for HTML5 JavaScript for loading and working with xml files. Is it the same as older html and JavaScript????

How do I pass JavaScript variables to PHP?

We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

So it's better to use the AJAX to parse the JavaScript value into the php Code.

Or alternatively we can make this done with the help of COOKIES in our code.

Thanks & Cheers.

Angular.js: set element height on page load

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

http://jsfiddle.net/zbjLh/709/

<div ng-app="miniapp" resize>
  Testing
</div>

.

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

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

How to define a two-dimensional array?

rows = int(input())
cols = int(input())

matrix = []
for i in range(rows):
  row = []
  for j in range(cols):
    row.append(0)
  matrix.append(row)

print(matrix)

Why such a long code, that too in Python you ask?

Long back when I was not comfortable with Python, I saw the single line answers for writing 2D matrix and told myself I am not going to use 2-D matrix in Python again. (Those single lines were pretty scary and It didn't give me any information on what Python was doing. Also note that I am not aware of these shorthands.)

Anyways, here's the code for a beginner whose coming from C, CPP and Java background

Note to Python Lovers and Experts: Please do not down vote just because I wrote a detailed code.

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

Extract Month and Year From Date in R

The zoo package has the function of as.yearmon can help to convert.

require(zoo)

df$ym<-as.yearmon(df$date, "%Y %m")

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Plotting power spectrum in python

From the numpy fft page http://docs.scipy.org/doc/numpy/reference/routines.fft.html:

When the input a is a time-domain signal and A = fft(a), np.abs(A) is its amplitude spectrum and np.abs(A)**2 is its power spectrum. The phase spectrum is obtained by np.angle(A).

How to read Data from Excel sheet in selenium webdriver

i have used following method to use input data from excel sheet: Need to import following as well

import jxl.Workbook;

then

Workbook wBook = Workbook.getWorkbook(new File("E:\\Testdata\\ShellData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0); 
//Now in application i have given my Username and Password input in following way
driver.findElement(By.xpath("//input[@id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[@name='Login']")).click();

it will Work

How do I count unique visitors to my site?

Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.

In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.

Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!


Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).

Facebook api: (#4) Application request limit reached

now Application-Level Rate Limiting 200 calls per hour !

you can look this image.enter image description here

twitter bootstrap navbar fixed top overlapping site

use this class inside nav tag

class="navbar navbar-expand-lg navbar-light bg-light sticky-top"

For bootstrap 4

How can I convert a date into an integer?

var dates = dates_as_int.map(function(dateStr) {
    return new Date(dateStr).getTime();
});

=>

[1468959781804, 1469029434776, 1469199218634, 1469457574527]

Update: ES6 version:

const dates = dates_as_int.map(date => new Date(date).getTime())

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

Calling virtual functions inside constructors

Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. All C++ implementations should call the version of the function defined at the level of the hierarchy in the current constructor and no further.

The C++ FAQ Lite covers this in section 23.7 in pretty good detail. I suggest reading that (and the rest of the FAQ) for a followup.

Excerpt:

[...] In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn’t yet happened. Objects are constructed from the base up, “base before derived”.

[...]

Destruction is done “derived class before base class”, so virtual functions behave as in constructors: Only the local definitions are used – and no calls are made to overriding functions to avoid touching the (now destroyed) derived class part of the object.

EDIT Corrected Most to All (thanks litb)

excel delete row if column contains value from to-remove-list

Given sheet 2:

ColumnA
-------
apple
orange

You can flag the rows in sheet 1 where a value exists in sheet 2:

ColumnA  ColumnB
-------  --------------
pear     =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple    =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry   =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange   =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum     =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")

The resulting data looks like this:

ColumnA  ColumnB
-------  --------------
pear     Keep
apple    Delete
cherry   Keep
orange   Delete
plum     Keep

You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.

What is w3wp.exe?

w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.

You can get more information on w3wp.exe here

http://www.processlibrary.com/en/directory/files/w3wp/25761/

SQL Server: Get table primary key using sql query

This should list all the constraints and at the end you can put your filters

/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH   ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME) 
AS
(
SELECT  CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
        PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE=  oParentColDtl.DATA_TYPE,        
        REFERENCE_TABLE_NAME='' ,
        REFERENCE_COL_NAME='' 

FROM sys.key_constraints as PKnUKEY
    INNER JOIN sys.tables as PKnUTable
            ON PKnUTable.object_id = PKnUKEY.parent_object_id
    INNER JOIN sys.index_columns as PKnUColIdx
            ON PKnUColIdx.object_id = PKnUTable.object_id
            AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
    INNER JOIN sys.columns as PKnUKEYCol
            ON PKnUKEYCol.object_id = PKnUTable.object_id
            AND PKnUKEYCol.column_id = PKnUColIdx.column_id
     INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=PKnUTable.name
            AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT  CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE='FK',
        PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,     
        REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
        REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30)) 
FROM sys.foreign_key_columns FKC
    INNER JOIN sys.sysobjects oConstraint
            ON FKC.constraint_object_id=oConstraint.id 
    INNER JOIN sys.sysobjects oParent
            ON FKC.parent_object_id=oParent.id
    INNER JOIN sys.all_columns oParentCol
            ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
    INNER JOIN sys.sysobjects oReference
            ON FKC.referenced_object_id=oReference.id
    INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=oParent.name
            AND oParentColDtl.COLUMN_NAME=oParentCol.name
    INNER JOIN sys.all_columns oReferenceCol
            ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/

)

select * from   ALL_KEYS_IN_TABLE
where   
    PARENT_TABLE_NAME  in ('YOUR_TABLE_NAME') 
    or REFERENCE_TABLE_NAME  in ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;

For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx

Regex to get the words after matching string

Here's a quick Perl script to get what you need. It needs some whitespace chomping.

#!/bin/perl

$sample = <<END;
Subject:
  Security ID:        S-1-5-21-3368353891-1012177287-890106238-22451
  Account Name:       ChamaraKer
  Account Domain:     JIC
  Logon ID:       0x1fffb

Object:
  Object Server:  Security
  Object Type:    File
  Object Name:    D:\\ApacheTomcat\\apache-tomcat-6.0.36\\logs\\localhost.2013- 07-01.log
  Handle ID:  0x11dc
END

my @sample_lines = split /\n/, $sample;
my $path;

foreach my $line (@sample_lines) {
  ($path) = $line =~ m/Object Name:([^s]+)/g;
  if($path) {
    print $path . "\n";
  }
}

Oracle SQL Query for listing all Schemas in a DB

Most likely, you want

SELECT username
  FROM dba_users

That will show you all the users in the system (and thus all the potential schemas). If your definition of "schema" allows for a schema to be empty, that's what you want. However, there can be a semantic distinction where people only want to call something a schema if it actually owns at least one object so that the hundreds of user accounts that will never own any objects are excluded. In that case

SELECT username
  FROM dba_users u
 WHERE EXISTS (
    SELECT 1
      FROM dba_objects o
     WHERE o.owner = u.username )

Assuming that whoever created the schemas was sensible about assigning default tablespaces and assuming that you are not interested in schemas that Oracle has delivered, you can filter out those schemas by adding predicates on the default_tablespace, i.e.

SELECT username
  FROM dba_users
 WHERE default_tablespace not in ('SYSTEM','SYSAUX')

or

SELECT username
  FROM dba_users u
 WHERE EXISTS (
    SELECT 1
      FROM dba_objects o
     WHERE o.owner = u.username )
   AND default_tablespace not in ('SYSTEM','SYSAUX')

It is not terribly uncommon to come across a system where someone has incorrectly given a non-system user a default_tablespace of SYSTEM, though, so be certain that the assumptions hold before trying to filter out the Oracle-delivered schemas this way.

Why are interface variables static and final by default?

(This is not a philosophical answer but more of a practical one). The requirement for static modifier is obvious which has been answered by others. Basically, since the interfaces cannot be instantiated, the only way to access its fields are to make them a class field -- static.

The reason behind the interface fields automatically becoming final (constant) is to prevent different implementations accidentally changing the value of interface variable which can inadvertently affect the behavior of the other implementations. Imagine the scenario below where an interface property did not explicitly become final by Java:

public interface Actionable {
    public static boolean isActionable = false;

    public void performAction();
}

public NuclearAction implements Actionable {

    public void performAction() {
        // Code that depends on isActionable variable
        if (isActionable) {
            // Launch nuclear weapon!!!
        }
    }
}

Now, just think what would happen if another class that implements Actionable alters the state of the interface variable:

public CleanAction implements Actionable  {

    public void performAction() {
        // Code that can alter isActionable state since it is not constant
        isActionable = true;
    }
}

If these classes are loaded within a single JVM by a classloader, then the behavior of NuclearAction can be affected by another class, CleanAction, when its performAction() is invoke after CleanAction's is executed (in the same thread or otherwise), which in this case can be disastrous (semantically that is).

Since we do not know how each implementation of an interface is going to use these variables, they must implicitly be final.

OPENSSL file_get_contents(): Failed to enable crypto

Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html

For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432

Here is the example:

    $url = 'https://www.example.com/api/list';
    $cn_match = 'www.example.com';

    $data = array (     
        'apikey' => '[example api key here]',               
        'limit' => intval($limit),
        'offset' => intval($offset)
        );

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',                
            'content' => http_build_query($data)                
            )
        , 'ssl' => array(
            'verify_peer' => true,
            'cafile' => [path to file] . "cacert.pem",
            'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
            'CN_match' => $cn_match,
            'disable_compression' => true,
            )
        );

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

Hope that helps

Is it possible to forward-declare a function in Python?

If you don't want to define a function before it's used, and defining it afterwards is impossible, what about defining it in some other module?

Technically you still define it first, but it's clean.

You could create a recursion like the following:

def foo():
    bar()

def bar():
    foo()

Python's functions are anonymous just like values are anonymous, yet they can be bound to a name.

In the above code, foo() does not call a function with the name foo, it calls a function that happens to be bound to the name foo at the point the call is made. It is possible to redefine foo somewhere else, and bar would then call the new function.

Your problem cannot be solved because it's like asking to get a variable which has not been declared.

Pandas Merge - How to avoid duplicating columns

can't you just subset the columns in either df first?

[i for i in df.columns if i not in df2.columns]
dfNew = merge(df **[i for i in df.columns if i not in df2.columns]**, df2, left_index=True, right_index=True, how='outer')

How to set default value for column of new created table from select statement in 11g

You will need to alter table abc modify (salary default 0);

How to maximize a plt.show() window using Python

For me nothing of the above worked. I use the Tk backend on Ubuntu 14.04 which contains matplotlib 1.3.1.

The following code creates a fullscreen plot window which is not the same as maximizing but it serves my purpose nicely:

from matplotlib import pyplot as plt
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
plt.show()

Google Play on Android 4.0 emulator

You could download it from a Android 4.0 phone and then mount the system image rw and copy it over.

Didnt tried it before but it should work.

setting min date in jquery datepicker

Just want to add this for the future programmer.

This code limits the date min and max. The year is fully controlled by getting the current year as max year.

Hope this could help to anyone.

Here's the code.

var dateToday = new Date();
var yrRange = '2014' + ":" + (dateToday.getFullYear());

$(function () {
    $("[id$=txtDate]").datepicker({
        showOn: 'button',
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        buttonImageOnly: true,
        yearRange: yrRange,
        buttonImage: 'calendar3.png',
        buttonImageOnly: true,
        minDate: new Date(2014,1-1,1),
        maxDate: '+50Y',
        inline:true
    });
});

Getting a POST variable

Use the

Request.Form[]

for POST variables,

Request.QueryString[]

for GET.

Swift Set to Array

You can create an array with all elements from a given Swift Set simply with

let array = Array(someSet)

This works because Set conforms to the SequenceType protocol and an Array can be initialized with a sequence. Example:

let mySet = Set(["a", "b", "a"])  // Set<String>
let myArray = Array(mySet)        // Array<String>
print(myArray) // [b, a]

What is the difference between “int” and “uint” / “long” and “ulong”?

uint and ulong are the unsigned versions of int and long. That means they can't be negative. Instead they have a larger maximum value.

Type    Min                           Max                           CLS-compliant
int     -2,147,483,648                2,147,483,647                 Yes
uint    0                             4,294,967,295                 No
long    –9,223,372,036,854,775,808    9,223,372,036,854,775,807     Yes
ulong   0                             18,446,744,073,709,551,615    No

To write a literal unsigned int in your source code you can use the suffix u or U for example 123U.

You should not use uint and ulong in your public interface if you wish to be CLS-Compliant.

Read the documentation for more information:

By the way, there is also short and ushort and byte and sbyte.

SQL how to make null values come last when sorting ascending

SELECT *          
FROM Employees
ORDER BY ISNULL(DepartmentId, 99999);

See this blog post.

How can I create an array with key value pairs?

No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me

class line_details {
   var $commission_one=array();
   foreach($_SESSION['commission'] as $key=>$data){
          $row=  explode('-', $key);
          $this->commission_one[$row['0']]= $row['1'];            
   }

}

Pausing a batch file for amount of time

If choice is available, use this:

choice /C X /T 10 /D X > nul

where /T 10 is the number of seconds to delay. Note the syntax can vary depending on your Windows version, so use CHOICE /? to be sure.

how to parse json using groovy

You can map JSON to specific class in Groovy using as operator:

import groovy.json.JsonSlurper

String json = '''
{
  "name": "John",  
  "age": 20
}
'''

def person = new JsonSlurper().parseText(json) as Person 

with(person) {
    assert name == 'John'
    assert age == 20
}

How to allow download of .json file with ASP.NET

  1. Navigate to C:\Users\username\Documents\IISExpress\config
  2. Open applicationhost.config with Visual Studio or your favorite text-editor.
  3. Search for the word mimeMap, you should find lots of 'em.
  4. Add the following line to the top of the list: .

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

Check your connections in Interface Builder. You're probably referring to a non existent IBOutlet or IBAction.

Reading input files by line using read command in shell scripting skips last line

Use while loop like this:

while IFS= read -r line || [ -n "$line" ]; do
  echo "$line"
done <file

Or using grep with while loop:

while IFS= read -r line; do
  echo "$line"
done < <(grep "" file)

Using grep . instead of grep "" will skip the empty lines.

Note:

  1. Using IFS= keeps any line indentation intact.

  2. You should almost always use the -r option with read.

  3. Don't read lines with for

  4. File without a newline at the end isn't a standard unix text file.

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I normally differentiate these two via this diagram:

Use PrimaryKeyJoinColumn

enter image description here

Use JoinColumn

enter image description here

How to create a zip archive with PowerShell?

If someone needs to zip a single file (and not a folder): http://blogs.msdn.com/b/jerrydixon/archive/2014/08/08/zipping-a-single-file-with-powershell.aspx

[CmdletBinding()]
Param(
     [Parameter(Mandatory=$True)]
     [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
     [string]$sourceFile,

     [Parameter(Mandatory=$True)]
     [ValidateScript({-not(Test-Path -Path $_ -PathType Leaf)})]
     [string]$destinationFile
) 

<#
     .SYNOPSIS
     Creates a ZIP file that contains the specified innput file.

     .EXAMPLE
     FileZipper -sourceFile c:\test\inputfile.txt 
                -destinationFile c:\test\outputFile.zip
#> 

function New-Zip
{
     param([string]$zipfilename)
     set-content $zipfilename 
          ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
     (dir $zipfilename).IsReadOnly = $false
}

function Add-Zip
{
     param([string]$zipfilename) 

     if(-not (test-path($zipfilename)))
     {
          set-content $zipfilename 
               ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
          (dir $zipfilename).IsReadOnly = $false    

     }

     $shellApplication = new-object -com shell.application
     $zipPackage = $shellApplication.NameSpace($zipfilename)


     foreach($file in $input) 
     { 
          $zipPackage.CopyHere($file.FullName)
          Start-sleep -milliseconds 500
     }
}

dir $sourceFile | Add-Zip $destinationFile

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

It's a separate statement.

It's also not possible to insert into a table and select from it and build an index in the same statement either.

The BOL entry contains the information you need:

CLUSTERED | NONCLUSTERED
Indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED, and UNIQUE constraints default to NONCLUSTERED.

In a CREATE TABLE statement, CLUSTERED can be specified for only one constraint. If CLUSTERED is specified for a UNIQUE constraint and a PRIMARY KEY constraint is also specified, the PRIMARY KEY defaults to NONCLUSTERED.

You can create an index on a PK field, but not a non-clustered index on a non-pk non-unique-constrained field.

A NCL index is not relevant to the structure of the table, and is not a constraint on the data inside the table. It's a separate entity that supports the table but is not integral to it's functionality or design.

That's why it's a separate statement. The NCL index is irrelevant to the table from a design perspective (query optimization notwithstanding).

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

Routing HTTP Error 404.0 0x80070002

My solution, after trying EVERYTHING:

Bad deployment, an old PrecompiledApp.config was hanging around my deploy location, and making everything not work.

My final settings that worked:

  • IIS 7.5, Win2k8r2 x64,
  • Integrated mode application pool
  • Nothing changes in the web.config - this means no special handlers for routing. Here's my snapshot of the sections a lot of other posts reference. I'm using FluorineFX, so I do have that handler added, but I did not need any others:

    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <authentication mode="None"/>
    
      <pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
      <httpRuntime requestPathInvalidCharacters=""/>
    
      <httpModules>
        <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx"/>
      </httpModules>
    </system.web>
      <system.webServer>
        <!-- Modules for IIS 7.0 Integrated mode -->
        <modules>
          <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx" />
        </modules>
    
        <!-- Disable detection of IIS 6.0 / Classic mode ASP.NET configuration -->
        <validation validateIntegratedModeConfiguration="false" />
      </system.webServer>
    
  • Global.ashx: (only method of any note)

    void Application_Start(object sender, EventArgs e) {
        // Register routes...
        System.Web.Routing.Route echoRoute = new System.Web.Routing.Route(
              "{*message}",
            //the default value for the message
              new System.Web.Routing.RouteValueDictionary() { { "message", "" } },
            //any regular expression restrictions (i.e. @"[^\d].{4,}" means "does not start with number, at least 4 chars
              new System.Web.Routing.RouteValueDictionary() { { "message", @"[^\d].{4,}" } },
              new TestRoute.Handlers.PassthroughRouteHandler()
           );
    
        System.Web.Routing.RouteTable.Routes.Add(echoRoute);
    }
    
  • PassthroughRouteHandler.cs - this achieved an automatic conversion from http://andrew.arace.info/stackoverflow to http://andrew.arace.info/#stackoverflow which would then be handled by the default.aspx:

    public class PassthroughRouteHandler : IRouteHandler {
    
        public IHttpHandler GetHttpHandler(RequestContext requestContext) {
            HttpContext.Current.Items["IncomingMessage"] = requestContext.RouteData.Values["message"];
            requestContext.HttpContext.Response.Redirect("#" + HttpContext.Current.Items["IncomingMessage"], true);
            return null;
        }
    }
    

Removing All Items From A ComboBox?

I could not get clear to work. (Mac Excel) but this does.

ActiveSheet.DropDowns("CollectionComboBox").RemoveAllItems

C#: Converting byte array to string and printing out to console

For some fun with linq and string interpolation:

public string ByteArrayToString(byte[] bytes)
{
    if ( bytes == null ) return "null";
    string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
    return $"new byte[] {{ {joinedBytes} }}";
}

Test cases:

byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();

Output:

new byte[] { 1, 2, 3, 4 }
null
new byte[] {  }

How to get a JavaScript object's class?

obj.constructor.name

is a reliable method in modern browsers. Function.name was officially added to the standard in ES6, making this a standards-compliant means of getting the "class" of a JavaScript object as a string. If the object is instantiated with var obj = new MyClass(), it will return "MyClass".

It will return "Number" for numbers, "Array" for arrays and "Function" for functions, etc. It generally behaves as expected. The only cases where it fails are if an object is created without a prototype, via Object.create( null ), or the object was instantiated from an anonymously-defined (unnamed) function.

Also note that if you are minifying your code, it's not safe to compare against hard-coded type strings. For example instead of checking if obj.constructor.name == "MyType", instead check obj.constructor.name == MyType.name. Or just compare the constructors themselves, however this won't work across DOM boundaries as there are different instances of the constructor function on each DOM, thus doing an object comparison on their constructors won't work.

Write single CSV file using spark-csv

I'm using this in Python to get a single file:

df.toPandas().to_csv("/tmp/my.csv", sep=',', header=True, index=False)

What is the equivalent of the C++ Pair<L,R> in Java?

For programming languages like Java, the alternate data structure used by most programmers to represent pair like data-structures are two array, and data is accessed via the same index

example: http://www-igm.univ-mlv.fr/~lecroq/string/node8.html#SECTION0080

This isn't ideal as the data should be bound together, but also turn out to be pretty cheap. Also, if your use case demands storing co-ordinates then its better to build your own data structure.

I've something like this in my library

public class Pair<First,Second>{.. }

How can I hide the Android keyboard using JavaScript?

I managed to get it to work with the following

document.body.addEventListener( 'touchend', function(){
    if( document.getElementById('yourInputFiled') )
        document.getElementById('yourInputFiled').blur();    
});

and preventDefault() and stopPropagation() in the listener for your input field

Simulate a specific CURL in PostMan

A simpler approach would be:

  1. Open POSTMAN
  2. Click on "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!
  5. Click Send to post the command

Hope this helps!

jQuery detect if textarea is empty

$.each(["input[type=text][value=]", "textarea[value=]"], function (index, element) {
              //only empty input and textarea will come here
});

Best way to get identity of inserted row?

One other way to guarantee the identity of the rows you insert is to specify the identity values and use the SET IDENTITY_INSERT ON and then OFF. This guarantees you know exactly what the identity values are! As long as the values are not in use then you can insert these values into the identity column.

CREATE TABLE #foo 
  ( 
     fooid   INT IDENTITY NOT NULL, 
     fooname VARCHAR(20) 
  ) 

SELECT @@Identity            AS [@@Identity], 
       Scope_identity()      AS [SCOPE_IDENTITY()], 
       Ident_current('#Foo') AS [IDENT_CURRENT] 

SET IDENTITY_INSERT #foo ON 

INSERT INTO #foo 
            (fooid, 
             fooname) 
VALUES      (1, 
             'one'), 
            (2, 
             'Two') 

SET IDENTITY_INSERT #foo OFF 

SELECT @@Identity            AS [@@Identity], 
       Scope_identity()      AS [SCOPE_IDENTITY()], 
       Ident_current('#Foo') AS [IDENT_CURRENT] 

INSERT INTO #foo 
            (fooname) 
VALUES      ('Three') 

SELECT @@Identity            AS [@@Identity], 
       Scope_identity()      AS [SCOPE_IDENTITY()], 
       Ident_current('#Foo') AS [IDENT_CURRENT] 

-- YOU CAN INSERT  
SET IDENTITY_INSERT #foo ON 

INSERT INTO #foo 
            (fooid, 
             fooname) 
VALUES      (10, 
             'Ten'), 
            (11, 
             'Eleven') 

SET IDENTITY_INSERT #foo OFF 

SELECT @@Identity            AS [@@Identity], 
       Scope_identity()      AS [SCOPE_IDENTITY()], 
       Ident_current('#Foo') AS [IDENT_CURRENT] 

SELECT * 
FROM   #foo 

This can be a very useful technique if you are loading data from another source or merging data from two databases etc.

CSS: borders between table columns only

I know this is an old question, but there is a simple, one line solution which works consistently for Chrome, Firefox, etc., as well as IE8 and above (and, for the most part, works on IE7 too - see http://www.quirksmode.org/css/selectors/ for details):

table td + td { border-left:2px solid red; }


The output is something like this:

Col1 | Col2 | Col3

What is making this work is that you are defining a border only on table cells which are adjacent to another table cell. In other words, you're applying the CSS to all cells in a row except the first one.

By applying a left border to the second through the last child, it gives the appearance of the line being "between" the cells.

How to remove all leading zeroes in a string

you can add "+" in your variable,

example :

$numString = "0000001123000";
echo +$numString;

React onClick function fires on render

JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file.

Writing a for-loop and specifying function as {this.props.removeTaskFunction(todo)} will execute the functions whenever the loop is triggered .

To stop this behaviour we need to return the function to onClick.

The fat arrow function has a hidden return statement along with the bind property. Thus it returns the function to OnClick as Javascript can return functions too !!!!!

Use -

onClick={() => { this.props.removeTaskFunction(todo) }}

which means-

var onClick = function() {
  return this.props.removeTaskFunction(todo);
}.bind(this);

mongodb: insert if not exists

Summary

  • You have an existing collection of records.
  • You have a set records that contain updates to the existing records.
  • Some of the updates don't really update anything, they duplicate what you have already.
  • All updates contain the same fields that are there already, just possibly different values.
  • You want to track when a record was last changed, where a value actually changed.

Note, I'm presuming PyMongo, change to suit your language of choice.

Instructions:

  1. Create the collection with an index with unique=true so you don't get duplicate records.

  2. Iterate over your input records, creating batches of them of 15,000 records or so. For each record in the batch, create a dict consisting of the data you want to insert, presuming each one is going to be a new record. Add the 'created' and 'updated' timestamps to these. Issue this as a batch insert command with the 'ContinueOnError' flag=true, so the insert of everything else happens even if there's a duplicate key in there (which it sounds like there will be). THIS WILL HAPPEN VERY FAST. Bulk inserts rock, I've gotten 15k/second performance levels. Further notes on ContinueOnError, see http://docs.mongodb.org/manual/core/write-operations/

    Record inserts happen VERY fast, so you'll be done with those inserts in no time. Now, it's time to update the relevant records. Do this with a batch retrieval, much faster than one at a time.

  3. Iterate over all your input records again, creating batches of 15K or so. Extract out the keys (best if there's one key, but can't be helped if there isn't). Retrieve this bunch of records from Mongo with a db.collectionNameBlah.find({ field : { $in : [ 1, 2,3 ...}) query. For each of these records, determine if there's an update, and if so, issue the update, including updating the 'updated' timestamp.

    Unfortunately, we should note, MongoDB 2.4 and below do NOT include a bulk update operation. They're working on that.

Key Optimization Points:

  • The inserts will vastly speed up your operations in bulk.
  • Retrieving records en masse will speed things up, too.
  • Individual updates are the only possible route now, but 10Gen is working on it. Presumably, this will be in 2.6, though I'm not sure if it will be finished by then, there's a lot of stuff to do (I've been following their Jira system).

What is a monad?

Monads are to control flow what abstract data types are to data.

In other words, many developers are comfortable with the idea of Sets, Lists, Dictionaries (or Hashes, or Maps), and Trees. Within those data types there are many special cases (for instance InsertionOrderPreservingIdentityHashMap).

However, when confronted with program "flow" many developers haven't been exposed to many more constructs than if, switch/case, do, while, goto (grr), and (maybe) closures.

So, a monad is simply a control flow construct. A better phrase to replace monad would be 'control type'.

As such, a monad has slots for control logic, or statements, or functions - the equivalent in data structures would be to say that some data structures allow you to add data, and remove it.

For example, the "if" monad:

if( clause ) then block

at its simplest has two slots - a clause, and a block. The if monad is usually built to evaluate the result of the clause, and if not false, evaluate the block. Many developers are not introduced to monads when they learn 'if', and it just isn't necessary to understand monads to write effective logic.

Monads can become more complicated, in the same way that data structures can become more complicated, but there are many broad categories of monad that may have similar semantics, but differing implementations and syntax.

Of course, in the same way that data structures may be iterated over, or traversed, monads may be evaluated.

Compilers may or may not have support for user-defined monads. Haskell certainly does. Ioke has some similar capabilities, although the term monad is not used in the language.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are synonyms, no difference at all.Decimal and Numeric data types are numeric data types with fixed precision and scale.

-- Initialize a variable, give it a data type and an initial value

declare @myvar as decimal(18,8) or numeric(18,8)----- 9 bytes needed

-- Increse that the vaue by 1

set @myvar = 123456.7

--Retrieve that value

select @myvar as myVariable

How to trap the backspace key using jQuery?

The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault(). However as the OP alluded to, if you always call it preventDefault() you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.

Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.

// Bind keydown event to this function.  Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){

    // Use jquery's constants rather than an unintuitive magic number.
    // $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
    if (e.keyCode == $.ui.keyCode.BACKSPACE) {

        // Filters out events coming from any of the following tags so Backspace
        // will work when typing text, but not take the page back otherwise.
        var rx = /INPUT|SELECT|TEXTAREA/i;
        if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
            e.preventDefault();
        }

       // Add your code here.
     }
});

How to retrieve an Oracle directory path?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Stash only one file out of multiple files that have changed with Git?

Update (2/14/2015) - I've rewritten the script a bit, to better handle the case of conflicts, which should now be presented as unmerged conflicts rather than .rej files.


I often find it more intuitive to do the inverse of @bukzor's approach. That is, to stage some changes, and then stash only those staged changes.

Unfortunately, git doesn't offer a git stash --only-index or similar, so I whipped up a script to do this.

#!/bin/sh

# first, go to the root of the git repo
cd `git rev-parse --show-toplevel`

# create a commit with only the stuff in staging
INDEXTREE=`git write-tree`
INDEXCOMMIT=`echo "" | git commit-tree $INDEXTREE -p HEAD`

# create a child commit with the changes in the working tree
git add -A
WORKINGTREE=`git write-tree`
WORKINGCOMMIT=`echo "" | git commit-tree $WORKINGTREE -p $INDEXCOMMIT`

# get back to a clean state with no changes, staged or otherwise
git reset -q --hard

# Cherry-pick the index changes back to the index, and stash.
# This cherry-pick is guaranteed to succeed
git cherry-pick -n $INDEXCOMMIT
git stash

# Now cherry-pick the working tree changes. This cherry-pick may fail
# due to conflicts
git cherry-pick -n $WORKINGCOMMIT

CONFLICTS=`git ls-files -u`
if test -z "$CONFLICTS"; then
    # If there are no conflicts, it's safe to reset, so that
    # any previously unstaged changes remain unstaged
    #
    # However, if there are conflicts, then we don't want to reset the files
    # and lose the merge/conflict info.
    git reset -q
fi

You can save the above script as git-stash-index somewhere on your path, and can then invoke it as git stash-index

# <hack hack hack>
git add <files that you want to stash>
git stash-index

Now the stash contains a new entry that only contains the changes you had staged, and your working tree still contains any unstaged changes.

In some cases, the working tree changes may depend on the index changes, so when you stash the index changes, the working tree changes have a conflict. In this case, you'll get the usual unmerged conflicts that you can resolve with git merge/git mergetool/etc.

Bad operand type for unary +: 'str'

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

How can I get the Google cache age of any URL or web page?

you can Use CachedPages website

Cached pages are usually saved and stored by large companies with powerful web servers. Since such servers are usually very fast, a cached page can often be accessed faster than the live page itself:

  • Google usually keeps a recent copy of the page (1 to 15 days old).
  • Coral also keeps a recent copy, although it's usually not as recent as Google.
  • Through Archive.org, you can access several copies of a web page saved throughout the years.

Write objects into file with Node.js

obj is an array in your example.

fs.writeFileSync(filename, data, [options]) requires either String or Buffer in the data parameter. see docs.

Try to write the array in a string format:

// writes 'https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks'
fs.writeFileSync('./data.json', obj.join(',') , 'utf-8'); 

Or:

// writes ['https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks']
var util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');

edit: The reason you see the array in your example is because node's implementation of console.log doesn't just call toString, it calls util.format see console.js source

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

Disabling same-origin policy in Safari

Unfortunately, there is no equivalent for Safari and the argument --disable-web-security doesn't work with Safari.

If you have access to the server side application, you can modify the https response headers to allow access. Mainly the Access-Control-Allow-Origin header. Modifying it will allow Safari to access the resource. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Origin for more information on the response headers that will help.

Name attribute in @Entity and @Table

@Table's name attribute is the actual table name. @Entitiy's name is useful if you have two @Entity classes with the same name and you need a way to differentiate them when running queries.

For loop in Oracle SQL

You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:

-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
  k NUMBER:= 0;
BEGIN
  FOR i IN 1..10 LOOP
    k:= k+1;
    dbms_output.put_line(i||' '||k);
 END LOOP;
END;
/

-- Cursor FOR loop --
set serveroutput on
DECLARE
   CURSOR c1 IS SELECT * FROM scott.emp;
   i NUMBER:= 0;
BEGIN
  FOR e_rec IN c1 LOOP
  i:= i+1;
    dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
  END LOOP;
END;
/

-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
  FROM dual
CONNECT BY LEVEL <= 10
/

How to print the contents of RDD?

There are probably many architectural differences between myRDD.foreach(println) and myRDD.collect().foreach(println) (not only 'collect', but also other actions). One the differences I saw is when doing myRDD.foreach(println), the output will be in a random order. For ex: if my rdd is coming from a text file where each line has a number, the output will have a different order. But when I did myRDD.collect().foreach(println), order remains just like the text file.

Trees in Twitter Bootstrap

If someone wants vertical version of the treeview from Harsh's answer, you can save some time:

http://jsfiddle.net/Fh47n/

.tree li {
    margin: 0px 0;

    list-style-type: none;
    position: relative;
    padding: 20px 5px 0px 5px;
}

.tree li::before{
    content: '';
    position: absolute; 
    top: 0;
    width: 1px; 
    height: 100%;
    right: auto; 
    left: -20px;
    border-left: 1px solid #ccc;
    bottom: 50px;
}
.tree li::after{
    content: '';
    position: absolute; 
    top: 30px; 
    width: 25px; 
    height: 20px;
    right: auto; 
    left: -20px;
    border-top: 1px solid #ccc;
}
.tree li a{
    display: inline-block;
    border: 1px solid #ccc;
    padding: 5px 10px;
    text-decoration: none;
    color: #666;
    font-family: arial, verdana, tahoma;
    font-size: 11px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}

/*Remove connectors before root*/
.tree > ul > li::before, .tree > ul > li::after{
    border: 0;
}
/*Remove connectors after last child*/
.tree li:last-child::before{ 
      height: 30px;
}

/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
    background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after, 
.tree li a:hover+ul li::before, 
.tree li a:hover+ul::before, 
.tree li a:hover+ul ul::before{
    border-color:  #94a0b4;
}

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

How to submit a form using Enter key in react.js?

this is how you do it if you want to listen for the "Enter" key. There is an onKeydown prop that you can use and you can read about it in react doc

and here is a codeSandbox

const App = () => {
    const something=(event)=> {
        if (event.keyCode === 13) {
            console.log('enter')
        }
    }
return (
    <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <input  type='text' onKeyDown={(e) => something(e) }/>
    </div>
);
}

Calculate mean and standard deviation from a vector of samples in C++ using Boost

It seems the following elegant recursive solution has not been mentioned, although it has been around for a long time. Referring to Knuth's Art of Computer Programming,

mean_1 = x_1, variance_1 = 0;            //initial conditions; edge case;

//for k >= 2, 
mean_k     = mean_k-1 + (x_k - mean_k-1) / k;
variance_k = variance_k-1 + (x_k - mean_k-1) * (x_k - mean_k);

then for a list of n>=2 values, the estimate of the standard deviation is:

stddev = std::sqrt(variance_n / (n-1)). 

Hope this helps!

Google Spreadsheet, Count IF contains a string

Try just =COUNTIF(A2:A51,"iPad")

java IO Exception: Stream Closed

You call writer.close(); in writeToFile so the writer has been closed the second time you call writeToFile.

Why don't you merge FileStatus into writeToFile?

How do I configure Apache 2 to run Perl CGI scripts?

If you have successfully installed Apache web server and Perl please follow the following steps to run cgi script using perl on ubuntu systems.

Before starting with CGI scripting it is necessary to configure apache server in such a way that it recognizes the CGI directory (where the cgi programs are saved) and allow for the execution of programs within that directory.

  1. In Ubuntu cgi-bin directory usually resides in path /usr/lib , if not present create the cgi-bin directory using the following command.cgi-bin should be in this path itself.

     mkdir /usr/lib/cgi-bin
    
  2. Issue the following command to check the permission status of the directory.

     ls -l /usr/lib | less
    

Check whether the permission looks as “drwxr-xr-x 2 root root 4096 2011-11-23 09:08 cgi- bin” if yes go to step 3.

If not issue the following command to ensure the appropriate permission for our cgi-bin directory.

     sudo chmod 755 /usr/lib/cgi-bin
     sudo chmod root.root /usr/lib/cgi-bin
  1. Give execution permission to cgi-bin directory

     sudo chmod 755 /usr/lib/cgi-bin
    

Thus your cgi-bin directory is ready to go. This is where you put all your cgi scripts for execution. Our next step is configure apache to recognize cgi-bin directory and allow execution of all programs in it as cgi scripts.

Configuring Apache to run CGI script using perl

  1. A directive need to be added in the configuration file of apache server so it knows the presence of CGI and the location of its directories. Initially go to location of configuration file of apache and open it with your favorite text editor

    cd /etc/apache2/sites-available/ 
    sudo gedit 000-default.conf
    
  2. Copy the below content to the file 000-default.conf between the line of codes “DocumentRoot /var/www/html/” and “ErrorLog $ {APACHE_LOG_DIR}/error.log”

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Require all granted
    

  3. Restart apache server with the following code

    sudo service apache2 restart
    
  4. Now we need to enable cgi module which is present in newer versions of ubuntu by default

    sudo a2enmod cgi.load
    sudo a2enmod cgid.load
    
  5. At this point we can reload the apache webserver so that it reads the configuration files again.

    sudo service apache2 reload
    

The configuration part of apache is over now let us check it with a sample cgi perl program.

Testing it out

  1. Go to the cgi-bin directory and create a cgi file with extension .pl

    cd /usr/lib/cgi-bin/
    sudo gedit test.pl
    
  2. Copy the following code on test.pl and save it.

    #!/usr/bin/perl -w
    print “Content-type: text/html\r\n\r\n”;
    print “CGI working perfectly!! \n”;
    
  3. Now give the test.pl execution permission.

    sudo chmod 755 test.pl
    
  4. Now open that file in your web browser http://Localhost/cgi-bin/test.pl

  5. If you see the output “CGI working perfectly” you are ready to go.Now dump all your programs into the cgi-bin directory and start using them.

NB: Don't forget to give your new programs in cgi-bin, chmod 755 permissions so as to run it successfully without any internal server errors.

Learning to write a compiler

If you have little time, I recommend Niklaus Wirth's "Compiler Construction" (Addison-Wesley. 1996), a tiny little booklet that you can read in a day, but it explains the basics (including how to implement lexers, recursive descent parsers, and your own stack-based virtual machines). After that, if you want a deep dive, there's no way around the Dragon book as other commenters suggest.

EXCEL VBA Check if entry is empty or not 'space'

A common trick is to check like this:

trim(TextBox1.Value & vbnullstring) = vbnullstring

this will work for spaces, empty strings, and genuine null values

NuGet behind a proxy

The solution for me was to include

<configuration>
  <config>
    <add key="http_proxy" value="http://<IP>:<Port>" />
    <add key="http_proxy.user" value="<user>" />
    <add key="http_proxy.password" value="<password>" />
  </config>
</configuration>

In the nuget.config file.

What is the difference between gravity and layout_gravity in Android?

The basic difference between the two is that-

android:gravity is used for child elements of the view.

android:layout_gravity is used for this element with respect to parent view.

Enable the display of line numbers in Visual Studio

As of Visual Studio 2015, you can find the option under:

Tools-> Options -> Text Editor -> All Languages-> General -> Line Numbers

Visual Studio 2013 Line Numbers Option Menu


Or simply go to tools -> options and type on the search bar: "Numbers".

Capture Signature using HTML5 and iPad

Perhaps the best two browser techs for this are Canvas, with Flash as a back up.

We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.

With jSignature ( http://willowsystems.github.com/jSignature/ ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.

How do I select between the 1st day of the current month and current day in MySQL?

I was looking for a similar query where I needed to use the first day of a month in my query. The last_day function didn't work for me but DAYOFMONTH came in handy.

So if anyone is looking for the same issue, the following code returns the date for first day of the current month.

SELECT DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY);

Comparing a date column with the first day of the month :

select * from table_name where date between 
DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY) and CURRENT_DATE

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

To get UserManager in API

return HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();

where AppUserManager is the class that inherits from UserManager.

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

I just ran into this problem myself.

The fix I come out with was to go to the organizer, click on the "provisioning profiles" tab, and press refresh in the low corner.

You ll be asked to give your itunes connect password , just follow the instruction.

Hope it helps

How to use Checkbox inside Select Option

I started from @vitfo answer but I want to have <option> inside <select> instead of checkbox inputs so i put together all the answers to make this, there is my code, I hope it will help someone.

_x000D_
_x000D_
$(".multiple_select").mousedown(function(e) {_x000D_
    if (e.target.tagName == "OPTION") _x000D_
    {_x000D_
      return; //don't close dropdown if i select option_x000D_
    }_x000D_
    $(this).toggleClass('multiple_select_active'); //close dropdown if click inside <select> box_x000D_
});_x000D_
$(".multiple_select").on('blur', function(e) {_x000D_
    $(this).removeClass('multiple_select_active'); //close dropdown if click outside <select>_x000D_
});_x000D_
 _x000D_
$('.multiple_select option').mousedown(function(e) { //no ctrl to select multiple_x000D_
    e.preventDefault(); _x000D_
    $(this).prop('selected', $(this).prop('selected') ? false : true); //set selected options on click_x000D_
    $(this).parent().change(); //trigger change event_x000D_
});_x000D_
_x000D_
 _x000D_
 $("#myFilter").on('change', function() {_x000D_
      var selected = $("#myFilter").val().toString(); //here I get all options and convert to string_x000D_
      var document_style = document.documentElement.style;_x000D_
      if(selected !== "")_x000D_
        document_style.setProperty('--text', "'Selected: "+selected+"'");_x000D_
      else_x000D_
        document_style.setProperty('--text', "'Select values'");_x000D_
 });
_x000D_
:root_x000D_
{_x000D_
 --text: "Select values";_x000D_
}_x000D_
.multiple_select_x000D_
{_x000D_
 height: 18px;_x000D_
 width: 90%;_x000D_
 overflow: hidden;_x000D_
 -webkit-appearance: menulist;_x000D_
 position: relative;_x000D_
}_x000D_
.multiple_select::before_x000D_
{_x000D_
 content: var(--text);_x000D_
 display: block;_x000D_
  margin-left: 5px;_x000D_
  margin-bottom: 2px;_x000D_
}_x000D_
.multiple_select_active_x000D_
{_x000D_
 overflow: visible !important;_x000D_
}_x000D_
.multiple_select option_x000D_
{_x000D_
 display: none;_x000D_
    height: 18px;_x000D_
 background-color: white;_x000D_
}_x000D_
.multiple_select_active option_x000D_
{_x000D_
 display: block;_x000D_
}_x000D_
_x000D_
.multiple_select option::before {_x000D_
  content: "\2610";_x000D_
}_x000D_
.multiple_select option:checked::before {_x000D_
  content: "\2611";_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select id="myFilter" class="multiple_select" multiple>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
  <option>D</option>_x000D_
  <option>E</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How can I send an HTTP POST request to a server from Excel using VBA?

In addition to the anwser of Bill the Lizard:

Most of the backends parse the raw post data. In PHP for example, you will have an array $_POST in which individual variables within the post data will be stored. In this case you have to use an additional header "Content-type: application/x-www-form-urlencoded":

Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("var1=value1&var2=value2&var3=value3")

Otherwise you have to read the raw post data on the variable "$HTTP_RAW_POST_DATA".

bootstrap 3 wrap text content within div for horizontal alignment

Now Update word-wrap is replace by :

overflow-wrap:break-word;

Compatible old navigator and css 3 it's good alternative !

it's evolution of word-wrap ( since 2012... )

See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap

See compatibility full : http://caniuse.com/#search=overflow-wrap

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

You don't need to add the concat package, you can do this via cssmin like this:

cssmin : {
      options: {
            keepSpecialComments: 0
      },
      minify : {
            expand : true,
            cwd : '/library/css',
            src : ['*.css', '!*.min.css'],
            dest : '/library/css',
            ext : '.min.css'
      },
      combine : {
        files: {
            '/library/css/app.combined.min.css': ['/library/css/main.min.css', '/library/css/font-awesome.min.css']
        }
      }
    }

And for js, use uglify like this:

uglify: {
      my_target: {
        files: {
            '/library/js/app.combined.min.js' : ['/app.js', '/controllers/*.js']
        }
      }
    }

How to stop an unstoppable zombie job on Jenkins without restarting the server?

I had same issue at the last half hour...

Was not able to delete a zombie build running in my multi-branch pipeline. Even Server restarts by UI or even from commandline via sudo service jenkins restart did block the execution... The build was not stoppable... It always reapeared.

Used Version: Jenkins ver 2.150.2

I was very annoyed, but... when looking into the log of the build I found something intersting at the end of the log:

Logfile output of an zombie build and showing restart did not stop it

The red marked parts are the "frustrating parts"... As you can see I always wanted to Abort the build from UI but it did not work...

But there is a hyperlink with text Click here to forcibly terminate running steps...(first green one) Now I pressed the link...) After the link execution a message about Still paused appeared with another Link Click here to forcibily kill entire build (second green one) After pressing this link also the build finally was hard killed...

So this seems to work without any special plugins (except the multibranch-pipeline build plugin itself).

How can I write text on a HTML5 canvas element?

Canvas text support is actually pretty good - you can control font, size, color, horizontal alignment, vertical alignment, and you can also get text metrics to get the text width in pixels. In addition, you can also use canvas transforms to rotate, stretch and even invert text.

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

How can I use an http proxy with node.js http.Client?

Imskull's answer almost worked for me, but I had to make some changes. The only real change is adding username, password, and setting rejectUnauthorized to false. I couldn't comment so I put this in an answer.

If you run the code it'll get you the titles of the current stories on Hacker News, per this tutorial: http://smalljs.org/package-managers/npm/

var cheerio = require('cheerio');
var request = require('request');

request({
    'url': 'https://news.ycombinator.com/',
    'proxy': 'http://Username:Password@YourProxy:Port/',
    'rejectUnauthorized': false
}, function(error, response, body) {
    if (!error && response.statusCode == 200) {
        if (response.body) {
            var $ = cheerio.load(response.body);
            $('td.title a').each(function() {
                console.log($(this).text());
            });
       }
    } else {
        console.log('Error or status not equal 200.');
    }
});

How do I create a timer in WPF?

In WPF, you use a DispatcherTimer.

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();


private void dispatcherTimer_Tick(object sender, EventArgs e)
{
  // code goes here
}

Why is there an unexplainable gap between these inline-block div elements?

Using inline-block allows for white-space in your HTML, This usually equates to .25em (or 4px).

You can either comment out the white-space or, a more commons solution, is to set the parent's font-size to 0 and the reset it back to the required size on the inline-block elements.

Convert string to variable name in JavaScript

It can be done like this

_x000D_
_x000D_
(function(X, Y) {_x000D_
  _x000D_
  // X is the local name of the 'class'_x000D_
  // Doo is default value if param X is empty_x000D_
  var X = (typeof X == 'string') ? X: 'Doo';_x000D_
  var Y = (typeof Y == 'string') ? Y: 'doo';_x000D_
  _x000D_
  // this refers to the local X defined above_x000D_
  this[X] = function(doo) {_x000D_
    // object variable_x000D_
    this.doo = doo || 'doo it';_x000D_
  }_x000D_
  // prototypal inheritance for methods_x000D_
  // defined by another_x000D_
  this[X].prototype[Y] = function() {_x000D_
    return this.doo || 'doo';_x000D_
  };_x000D_
  _x000D_
  // make X global_x000D_
  window[X] = this[X];_x000D_
}('Dooa', 'dooa')); // give the names here_x000D_
_x000D_
// test_x000D_
doo = new Dooa('abc');_x000D_
doo2 = new Dooa('def');_x000D_
console.log(doo.dooa());_x000D_
console.log(doo2.dooa());
_x000D_
_x000D_
_x000D_

How can INSERT INTO a table 300 times within a loop in SQL?

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
BEGIN
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1
END

Prime numbers between 1 to 100 in C Programming Language

#include <stdio.h>

int main () {

   int i, j;

   for(i = 2; i<100; i++) {

      for(j = 2; j <= (i/j); j++) 
      if(!(i%j)) break; // if factor found, not prime
      if(j > (i/j)) printf("%d is prime", i);
   }

   return 0;
}

Difference between window.location.href=window.location.href and window.location.reload()

As said, modifying the href when there is a hash (#) in the url would not reload the page. Thus, I use this to reload it instead of regular expressions:

if (!window.location.hash) {
    window.location.href = window.location.href;
} else {
    window.location.reload();
}

Format Instant to String

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.toString(formatter);
LocalDate date = LocalDate.parse(text, formatter);

I believe this might help, you may need to use some sort of localdate variation instead of instant

Fill remaining vertical space - only CSS

Flexbox solution

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  width: 300px;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.first {_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
.second {_x000D_
  flex-grow: 1;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="first" style="background:#b2efd8">First</div>_x000D_
  <div class="second" style="background:#80c7cd">Second</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

This can be done by Firebug Plugin called scrapbook

You can check Javascript option in setting

enter image description here

Edit:

This can also help

Firequark is an extension to Firebug to aid the process of HTML Screen Scraping. Firequark automatically extracts css selector for a single or multiple html node(s) from a web page using Firebug (a web development plugin for Firefox). The css selector generated can be given as an input to html screen scrapers like Scrapi to extract information. Firequark is built to unleash the power of css selector for use of html screen scraping.

Laravel 5.4 Specific Table Migration

You can run command like this

php artisan migrate --path=/database/migrations/2020_04_10_130703_create_test_table.php

How to start an application using android ADB tools?

You can find your app package name by below command:

adb shell pm list packages

Above command returns package list of all apps, Example:

org.linphone.debug
.
.
com.android.email

Now I want to start app linphone by using below command and this worked for me:

adb shell am start org.belphone.debug

Among $_REQUEST, $_GET and $_POST which one is the fastest?

GET vs. POST

1) Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

2) Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

3) $_GET is an array of variables passed to the current script via the URL parameters.

4) $_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?

Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

How to create a DB link between two oracle instances

as a simple example:

CREATE DATABASE LINK _dblink_name_
  CONNECT TO _username_
    IDENTIFIED BY _passwd_
      USING '$_ORACLE_SID_'

for more info: http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_5005.htm

Exploitable PHP functions

i'd particularly want to add unserialize() to this list. It has had a long history of various vulnerabilities including arbitrary code execution, denial of service and memory information leakage. It should never be called on user-supplied data. Many of these vuls have been fixed in releases over the last dew years, but it still retains a couple of nasty vuls at the current time of writing.

For other information about dodgy php functions/usage look around the Hardened PHP Project and its advisories. Also the recent Month of PHP Security and 2007's Month of PHP Bugs projects

Also note that, by design, unserializing an object will cause the constructor and destructor functions to execute; another reason not to call it on user-supplied data.

How do you format a Date/Time in TypeScript?

One more to add @kamalakar's answer, need to import the same in app.module and add DateFormatPipe to providers.

    import {DateFormatPipe} from './DateFormatPipe';
    @NgModule
    ({ declarations: [],  
        imports: [],
        providers: [DateFormatPipe]
    })

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

Edit line thickness of CSS 'underline' attribute

_x000D_
_x000D_
a {_x000D_
  text-decoration: none;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
a.underline {_x000D_
  text-decoration: underline;_x000D_
}_x000D_
_x000D_
a.shadow {_x000D_
   box-shadow: inset 0 -4px 0 white, inset 0 -4.5px 0 blue;_x000D_
}
_x000D_
<h1><a href="#" class="underline">Default: some text alpha gamma<br>the quick brown fox</a></h1>_x000D_
<p>Working:</p>_x000D_
<h1><a href="#" class="shadow">Using Shadow: some text alpha gamma<br>the quick brown fox<br>even works with<br>multiple lines</a></h1>_x000D_
<br>
_x000D_
_x000D_
_x000D_

Final Solution: http://codepen.io/vikrant-icd/pen/gwNqoM

a.shadow {
   box-shadow: inset 0 -4px 0 white, inset 0 -4.5px 0 blue;
}

How to call a View Controller programmatically?

You need to instantiate the view controller from the storyboard and then show it:

ViewControllerInfo* infoController = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerInfo"];
[self.navigationController pushViewController:infoController animated:YES];

This example assumes that you have a navigation controller in order to return to the previous view. You can of course also use presentViewController:animated:completion:. The main point is to have your storyboard instantiate your target view controller using the target view controller's ID.

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

Round to 2 decimal places

double formattedNumber = Double.parseDouble(new DecimalFormat("#.##").format(unformattedNumber));

worked for me :)

How can I get date and time formats based on Culture Info?

You could take a look at the DateTimeFormat property which contains the culture specific formats.

Multiple glibc libraries on a single host

@msb gives a safe solution.

I met this problem when I did import tensorflow as tf in conda environment in CentOS 6.5 which only has glibc-2.12.

ImportError: /lib64/libc.so.6: version `GLIBC_2.16' not found (required by /home/

I want to supply some details:

First install glibc to your home directory:

mkdir ~/glibc-install; cd ~/glibc-install
wget http://ftp.gnu.org/gnu/glibc/glibc-2.17.tar.gz
tar -zxvf glibc-2.17.tar.gz
cd glibc-2.17
mkdir build
cd build
../configure --prefix=/home/myself/opt/glibc-2.17  # <-- where you install new glibc
make -j<number of CPU Cores>  # You can find your <number of CPU Cores> by using **nproc** command
make install

Second, follow the same way to install patchelf;

Third, patch your Python:

[myself@nfkd ~]$ patchelf --set-interpreter /home/myself/opt/glibc-2.17/lib/ld-linux-x86-64.so.2 --set-rpath /home/myself/opt/glibc-2.17/lib/ /home/myself/miniconda3/envs/tensorflow/bin/python

as mentioned by @msb

Now I can use tensorflow-2.0 alpha in CentOS 6.5.

ref: https://serverkurma.com/linux/how-to-update-glibc-newer-version-on-centos-6-x/

typesafe select onChange event using reactjs and typescript

I tried using React.FormEvent<HTMLSelectElement> but it led to an error in the editor, even though there is no EventTarget visible in the code:

The property 'value' does not exist on value of type 'EventTarget'

Then I changed React.FormEvent to React.ChangeEvent and it helped:

private changeName(event: React.ChangeEvent<HTMLSelectElement>) {
    event.preventDefault();
    this.props.actions.changeName(event.target.value);
}

Is it possible to listen to a "style change" event?

I think the best answer if from Mike in the case you can't launch your event because is not from your code. But I get some errors when I used it. So I write a new answer for show you the code that I use.

Extension

// Extends functionality of ".css()"
// This could be renamed if you'd like (i.e. "$.fn.cssWithListener = func ...")
(function() {
    orig = $.fn.css;
    $.fn.css = function() {
        var result = orig.apply(this, arguments);
        $(this).trigger('stylechanged');
        return result;
    }
})();

Usage

// Add listener
$('element').on('stylechanged', function () {
    console.log('css changed');
});

// Perform change
$('element').css('background', 'red');

I got error because var ev = new $.Event('style'); Something like style was not defined in HtmlDiv.. I removed it, and I launch now $(this).trigger("stylechanged"). Another problem was that Mike didn't return the resulto of $(css, ..) then It can make problems in some cases. So I get the result and return it. Now works ^^ In every css change include from some libs that I can't modify and trigger an event.

How can I delete all cookies with JavaScript?

Why do you use new Date instead of a static UTC string?

    function clearListCookies(){
    var cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++){   
            var spcook =  cookies[i].split("=");
            document.cookie = spcook[0] + "=;expires=Thu, 21 Sep 1979 00:00:01 UTC;";                                
        }
    }

How to cast or convert an unsigned int to int in C?

It depends on what you want the behaviour to be. An int cannot hold many of the values that an unsigned int can.

You can cast as usual:

int signedInt = (int) myUnsigned;

but this will cause problems if the unsigned value is past the max int can hold. This means half of the possible unsigned values will result in erroneous behaviour unless you specifically watch out for it.

You should probably reexamine how you store values in the first place if you're having to convert for no good reason.

EDIT: As mentioned by ProdigySim in the comments, the maximum value is platform dependent. But you can access it with INT_MAX and UINT_MAX.

For the usual 4-byte types:

4 bytes = (4*8) bits = 32 bits

If all 32 bits are used, as in unsigned, the maximum value will be 2^32 - 1, or 4,294,967,295.

A signed int effectively sacrifices one bit for the sign, so the maximum value will be 2^31 - 1, or 2,147,483,647. Note that this is half of the other value.

Simplest way to read json from a URL in java

If you don't mind using a couple libraries it can be done in a single line.

Include Apache Commons IOUtils & json.org libraries.

JSONObject json = new JSONObject(IOUtils.toString(new URL("https://graph.facebook.com/me"), Charset.forName("UTF-8")));

Removing ul indentation with CSS

-webkit-padding-start: 0;

will remove padding added by webkit engine

IE11 prevents ActiveX from running

In my IE11, works normally. Version: 11.306.10586.0

We can test if ActiveX works at IE, in this site: http://www.pcpitstop.com/testax.asp

Using Chrome, how to find to which events are bound to an element

Using Chrome 15.0.865.0 dev. There's an "Event Listeners" section on the Elements panel:

enter image description here

And an "Event Listeners Breakpoints" on the Scripts panel. Use a Mouse -> click breakpoint and then "step into next function call" while keeping an eye on the call stack to see what userland function handles the event. Ideally, you'd replace the minified version of jQuery with an unminified one so that you don't have to step in all the time, and use step over when possible.

enter image description here

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

I fixed it by manually selecting a provisioning profile in the build settings for the test target.

Test target settings -> Build settings -> Code signing -> Code sign identity. Previously, it was set to "Don't code sign".

how to make a new line in a jupyter markdown cell

The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:

#### 1.1 My Subtitle  \

1.1 My Subtitle
    Next paragraph text.

An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).

### My Subtitle


1.1 My Subtitle

Next paragraph text.

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null.

Otherwise it is a matter of preference.

Notepad++ - How can I replace blank lines

  1. Press Ctrl+H (Replace)

  2. Select Extended from SearchMode

  3. Put \r\n\r\n in Find What

  4. Put \r\n in ReplaceWith

  5. Click on Replace All

Replace multiple line breaks

How to combine 2 plots (ggplot) into one plot?

Just combine them. I think this should work but it's untested:

p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + 
     geom_smooth(fill="blue", colour="darkblue", size=1)

p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) + 
     geom_smooth(data=visual2, fill="red", colour="red", size=1)

print(p)

How to capture a backspace on the onkeydown event

Try this:

document.addEventListener("keydown", KeyCheck);  //or however you are calling your method
function KeyCheck(event)
{
   var KeyID = event.keyCode;
   switch(KeyID)
   {
      case 8:
      alert("backspace");
      break; 
      case 46:
      alert("delete");
      break;
      default:
      break;
   }
}

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

This sounds weird and I don't know why, but in my case that was happening because my ConnectionString was using "." in "data source" attribute. Once I changed it to "localhost" it workded like a charm. No other change was needed.

How do I pass along variables with XMLHTTPRequest

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

No module named MySQLdb

if your python version is 3.5, do a pip install mysqlclient, other things didn't work for me

jQuery Button.click() event is triggered twice

This can be caused for following reasons:

  1. You have included the script more than once in the same html file
  2. You have added the event listener twice (eg: using onclick attribute on the element and also with jquery
  3. The event is bubbled up to some parent element. (you may consider using event.stopPropagation).
  4. If you use template inheritance like extends in Django, most probably you have included the script in more than one file which are combined together by include or extend template tags
  5. If you are using Django template, you have wrongly placed a block inside another.

So, you should either find them out and remove the duplicate import. It is the best thing to do.

Another solution is to remove all click event listeners first in the script like:

$("#myId").off().on("click", function(event) {
event.stopPropagation();
});

You can skip event.stopPropagation(); if you are sure that the event is not bubbled.

Reading JSON from a file?

Here is a copy of code which works fine for me

import json

with open("test.json") as json_file:
    json_data = json.load(json_file)
    print(json_data)

with the data

{
    "a": [1,3,"asdf",true],
    "b": {
        "Hello": "world"
    }
}

you may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message.

Passing a method parameter using Task.Factory.StartNew

Try this,

        var arg = new { i = 123, j = 456 };
        var task = new TaskFactory().StartNew(new Func<dynamic, int>((argument) =>
        {
            dynamic x = argument.i * argument.j;
            return x;
        }), arg, CancellationToken.None, TaskCreationOptions.AttachedToParent, TaskScheduler.Default);
        task.Wait();
        var result = task.Result;

How to list the size of each file and directory and sort by descending size in Bash?

Simple and fast:

find . -mindepth 1 -maxdepth 1 -type d | parallel du -s | sort -n

*requires GNU Parallel.

Create XML file using java

You can use a DOM XML parser to create an XML file using Java. A good example can be found on this site:

try {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    //root elements
    Document doc = docBuilder.newDocument();

    Element rootElement = doc.createElement("company");
    doc.appendChild(rootElement);

    //staff elements
    Element staff = doc.createElement("Staff");
    rootElement.appendChild(staff);

    //set attribute to staff element
    Attr attr = doc.createAttribute("id");
    attr.setValue("1");
    staff.setAttributeNode(attr);

    //shorten way
    //staff.setAttribute("id", "1");

    //firstname elements
    Element firstname = doc.createElement("firstname");
    firstname.appendChild(doc.createTextNode("yong"));
    staff.appendChild(firstname);

    //lastname elements
    Element lastname = doc.createElement("lastname");
    lastname.appendChild(doc.createTextNode("mook kim"));
    staff.appendChild(lastname);

    //nickname elements
    Element nickname = doc.createElement("nickname");
    nickname.appendChild(doc.createTextNode("mkyong"));
    staff.appendChild(nickname);

    //salary elements
    Element salary = doc.createElement("salary");
    salary.appendChild(doc.createTextNode("100000"));
    staff.appendChild(salary);

    //write the content into xml file
    TransformerFactory transformerFactory =  TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);

    StreamResult result =  new StreamResult(new File("C:\\testing.xml"));
    transformer.transform(source, result);

    System.out.println("Done");

}catch(ParserConfigurationException pce){
    pce.printStackTrace();
}catch(TransformerException tfe){
    tfe.printStackTrace();
}

joining two select statements

You should use UNION if you want to combine different resultsets. Try the following:

(SELECT * 
 FROM ( SELECT * 
        FROM orders_products 
        INNER JOIN orders ON orders_products.orders_id = orders.orders_id  
        WHERE products_id = 181) AS A)
UNION 

(SELECT * 
 FROM ( SELECT * 
        FROM orders_products 
        INNER JOIN orders ON orders_products.orders_id = orders.orders_id 
        WHERE products_id = 180) AS B
ON A.orders_id=B.orders_id)

Button Center CSS

when all else fails I just

<center> content </center>

I know its not "up to standards" any more, but if it works it works

Android activity life cycle - what are all these methods for?

The entire confusion is caused since Google chose non-intuivitive names instead of something as follows:

onCreateAndPrepareToDisplay()   [instead of onCreate() ]
onPrepareToDisplay()            [instead of onRestart() ]
onVisible()                     [instead of onStart() ]
onBeginInteraction()            [instead of onResume() ]
onPauseInteraction()            [instead of onPause() ]
onInvisible()                   [instead of onStop]
onDestroy()                     [no change] 

The Activity Diagram can be interpreted as:

enter image description here

How to set a:link height/width with css?

Thanks to RandomUs 1r for this observation:

changing it to display:inline-block; solves that issue. – RandomUs1r May 14 '13 at 21:59

I tried it myself for a top navigation menu bar, as follows:

First style the "li" element as follows:

display: inline-block;
width: 7em;
text-align: center;

Then style the "a"> element as follows:

width: 100%;

Now the navigation links are all equal width with text centered in each link.

Insert current date in datetime format mySQL

NOW() is used to insert the current date and time in the MySQL table. All fields with datatypes DATETIME, DATE, TIME & TIMESTAMP work good with this function.

YYYY-MM-DD HH:mm:SS

Demonstration:

Following code shows the usage of NOW()

INSERT INTO auto_ins
(MySQL_Function, DateTime, Date, Time, Year, TimeStamp)
VALUES
(“NOW()”, NOW(), NOW(), NOW(), NOW(), NOW());

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

You cannot use properties that are not mapped to a database column in a Where expression. You must build the expression based on mapped properties, like:

var date = DateTime.Now.AddYears(-from);
result = result.Where(p => date >= p.DOB);
// you don't need `AsQueryable()` here because result is an `IQueryable` anyway

As a replacement for your not mapped Age property you can extract this expression into a static method like so:

public class clsProfileDate
{
    // ...
    public DateTime DOB { get; set; } // property mapped to DB table column

    public static Expression<Func<clsProfileDate, bool>> IsOlderThan(int age)
    {
        var date = DateTime.Now.AddYears(-age);
        return p => date >= p.DOB;
    }
}

And then use it this way:

result = result.Where(clsProfileDate.IsOlderThan(from));

How to get the public IP address of a user in C#

For Web Applications ( ASP.NET MVC and WebForm )

/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
    var context = System.Web.HttpContext.Current;
    string ip = String.Empty;

    if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
        ip = context.Request.UserHostAddress;

    if (ip == "::1")
        ip = "127.0.0.1";

    return ip;
}

For Windows Applications ( Windows Form, Console, Windows Service , ... )

    static void Main(string[] args)
    {
        HTTPGet req = new HTTPGet();
        req.Request("http://checkip.dyndns.org");
        string[] a = req.ResponseBody.Split(':');
        string a2 = a[1].Substring(1);
        string[] a3=a2.Split('<');
        string a4 = a3[0];
        Console.WriteLine(a4);
        Console.ReadLine();
    }

Trim Cells using VBA in Excel

The infinite loop is a result of an On Error Resume Next statement somewhere higher up in your code. Get rid of it now. If your code only runs with On Error Resume Next in effect, it needs instant and complete overhaul.

And while you are at it, place an Option Explicit on top of yor module. It forces you to declare all variables, a safeguard against annoying bugs that are the result of mis-typed variable names. (You can modify the VBA editor preferences to have that option set automatically the next time, which is highly recommended.)

The immediate problem with your code is that a cell is an object, and objects cannot be trimmed. You want to trim the text of the cell, so you must do so:

cell.Text = Trim(cell.Text)

Get class name of object as string in Swift

You can try this way:

self.classForCoder.description()

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

It is not the asker's problem in this instance but the first troubleshooting step for a generic "AttributeError: __exit__" should be making sure the brackets are there, e.g.

with SomeContextManager() as foo:
    #works because a new object is referenced...

not

with SomeContextManager as foo:
    #AttributeError because the class is referenced

Catches me out from time to time and I end up here -__-

Can I install/update WordPress plugins without providing FTP access?

WordPress will only prompt you for your FTP connection information while trying to install plugins or a WordPress update if it cannot write to /wp-content directly. Otherwise, if your web server has write access to the necessary files, it will take care of the updates and installation automatically. This method does not require you to have FTP/SFTP or SSH access, but it does require your to have specific file permissions set up on your webserver.

It will try various methods in order, and fall back on FTP if Direct and SSH methods are unavailable.

https://github.com/WordPress/WordPress/blob/4.2.2/wp-admin/includes/file.php#L912

WordPress will try to write a temporary file to your /wp-content directory. If this succeeds, it compares the ownership of the file with its own uid, and if there is a match it will allow you to use the 'direct' method of installing plugins, themes, or updates.

Now, if for some reason you do not want to rely on the automatic check for which filesystem method to use, you can define a constant, 'FS_METHOD' in your wp-config.php file, that is either 'direct', 'ssh', 'ftpext' or 'ftpsockets' and it will use that method. Keep in mind that if you set this to 'direct', but your web user (the username under which your web server runs) does not have proper write permissions, you will receive an error.

In summary, if you do not want to (or you cannot) change permissions on wp-content so your web server has write permissions, then add this to your wp-config.php file:

define('FS_METHOD', 'direct');

Permissions explained here:

Is there a "theirs" version of "git merge -s ours"?

I just recently needed to do this for two separate repositories that share a common history. I started with:

  • Org/repository1 master
  • Org/repository2 master

I wanted all the changes from repository2 master to be applied to repository1 master, accepting all changes that repository2 would make. In git's terms, this should be a strategy called -s theirs BUT it does not exist. Be careful because -X theirs is named like it would be what you want, but it is NOT the same (it even says so in the man page).

The way I solved this was to go to repository2 and make a new branch repo1-merge. In that branch, I ran git pull [email protected]:Org/repository1 -s ours and it merges fine with no issues. I then push it to the remote.

Then I go back to repository1 and make a new branch repo2-merge. In that branch, I run git pull [email protected]:Org/repository2 repo1-merge which will complete with issues.

Finally, you would either need to issue a merge request in repository1 to make it the new master, or just keep it as a branch.

How can I open multiple files using "with open" in Python?

Late answer (8 yrs), but for someone looking to join multiple files into one, the following function may be of help:

def multi_open(_list):
    out=""
    for x in _list:
        try:
            with open(x) as f:
                out+=f.read()
        except:
            pass
            # print(f"Cannot open file {x}")
    return(out)

fl = ["C:/bdlog.txt", "C:/Jts/tws.vmoptions", "C:/not.exist"]
print(multi_open(fl))

2018-10-23 19:18:11.361 PROFILE  [Stop Drivers] [1ms]
2018-10-23 19:18:11.361 PROFILE  [Parental uninit] [0ms]
...
# This file contains VM parameters for Trader Workstation.
# Each parameter should be defined in a separate line and the
...

Adobe Acrobat Pro make all pages the same dimension

The page sizes are looking different in your PDF because the images were originally set to different DPI (even if images are identical HxW in pixels). The good news is - it's only a display issue - and can be fixed easily.

An image with a higher DPI value would display smaller in a PDF (displays at the 'print-size' of the image). To avoid this, open each image in an image editor like GIMP or Photoshop. Open relevant image print control dialog box and set a suitable uniform DPI info for all the images. Remake the PDF with these new images. If in the new PDF images are too big - redo the DPI setting for each to a higher value. If in the new PDF pages are too small to read on-screen without zooming, again - redo DPI adjustment, this time put a lower DPI value. Ideally, 150 DPI should be good enough for images of 2500X2500 pixel - on a 17 inch monitor set to 1366x768 resolution.

BTW, the PDF file shall print each page at the specified DPI of that page. If all images are same DPI, you'll get a uniform printing.

Hope this helps :)

Removing a non empty directory programmatically in C or C++

C++17 has <experimental\filesystem> which is based on the boost version.

Use std::experimental::filesystem::remove_all to remove recursively.

If you need more control, try std::experimental::filesystem::recursive_directory_iterator.

You can also write your own recursion with the non-resursive version of the iterator.

namespace fs = std::experimental::filesystem;
void IterateRecursively(fs::path path)
{
  if (fs::is_directory(path))
  {
    for (auto & child : fs::directory_iterator(path))
      IterateRecursively(child.path());
  }

  std::cout << path << std::endl;
}

How to resolve Unneccessary Stubbing exception

As others pointed out it is usually the simplest to remove the line that is unnecessarily stubbing a method call.

In my case it was in a @BeforeEach and it was relevant most of the time. In the only test where that method was not used I reset the mock, e.g.:

myMock.reset()

Hope this helps others with the same problem.

(Note that if there are multiple mocked calls on the same mock this could be inconvenient as well since you'll have to mock all the other methods except the one that isn't called.)

Chrome: Uncaught SyntaxError: Unexpected end of input

Try Firebug for Mozilla - it will show the position of the missing }.

http://getfirebug.com/