Programs & Examples On #Horizontallist

How to make a HTML list appear horizontally instead of vertically using CSS only?

You will have to use something like below

#menu ul{_x000D_
  list-style: none;_x000D_
#menu li{_x000D_
  display: inline;_x000D_
<div id="menu">_x000D_
    <li>First menu item</li>_x000D_
    <li>Second menu item</li>_x000D_
    <li>Third menu item</li>_x000D_


To clear the datagridview write the following code:


Java properties UTF-8 encoding in Eclipse

I recommend you to use Attesoro ( Is simple and easy to use. And is made in java.

Python Requests library redirect new url

the documentation has this blurb

import requests

r = requests.get('')
#returns instead of the http page you asked for 

Removing ul indentation with CSS

Remove this from #info:


Add this for your header:

#info p {
    text-align: center;

Do you need the fixed width etc.? I removed the in my opinion not necessary stuff and centered the header with text-align.


How to change the default browser to debug with in Visual Studio 2008?

If you use ASP-NET MVC, you need to right-click on Default.ASPX which will have a Browse With menu.

Copying data from one SQLite database to another

Consider a example where I have two databases namely allmsa.db and atlanta.db. Say the database allmsa.db has tables for all msas in US and database atlanta.db is empty.

Our target is to copy the table atlanta from allmsa.db to atlanta.db.


  1. sqlite3 atlanta.db(to go into atlanta database)
  2. Attach allmsa.db. This can be done using the command ATTACH '/mnt/fastaccessDS/core/csv/allmsa.db' AS AM; note that we give the entire path of the database to be attached.
  3. check the database list using sqlite> .databases you can see the output as
seq  name             file                                                      
---  ---------------  ----------------------------------------------------------
0    main             /mnt/fastaccessDS/core/csv/atlanta.db                  
2    AM               /mnt/fastaccessDS/core/csv/allmsa.db 
  1. now you come to your actual target. Use the command INSERT INTO atlanta SELECT * FROM AM.atlanta;

This should serve your purpose.

Boxplot show the value of mean

The Magrittr way

I know there is an accepted answer already, but I wanted to show one cool way to do it in single command with the help of magrittr package.

PlantGrowth %$% # open dataset and make colnames accessible with '$'
split(weight,group) %T>% # split by group and side-pipe it into boxplot
boxplot %>% # plot
lapply(mean) %>% # data from split can still be used thanks to side-pipe '%T>%'
unlist %T>% # convert to atomic and side-pipe it to points
points(pch=18)  %>% # add points for means to the boxplot
text(x=.+0.06,labels=.) # use the values to print text

This code will produce a boxplot with means printed as points and values: boxplot with means

I split the command on multiple lines so I can comment on what each part does, but it can also be entered as a oneliner. You can learn more about this in my gist.

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric

# to 

FFT in a single C-file

Your best bet is KissFFT - as its name implies it's simple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.

How to delete a whole folder and content?

Simple way to delete all file from directory :

It is generic function for delete all images from directory by calling only


public static void deleteAllFile(Context context) {
File directory = context.getExternalFilesDir(null);
        if (directory.isDirectory()) {
            for (String fileName: file.list()) {
                new File(file,fileName).delete();

SQL select max(date) and corresponding value

Ah yes, that is how it is intended in SQL. You get the Max of every column seperately. It seems like you want to return values from the row with the max date, so you have to select the row with the max date. I prefer to do this with a subselect, as the queries keep compact easy to read.

SELECT TrainingID, CompletedDate, Notes
FROM HR_EmployeeTrainings ET 
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID) 
AND CompletedDate in 
   (Select Max(CompletedDate) from HR_EmployeeTrainings B
    where B.TrainingID = ET.TrainingID)

If you also want to match by AntiRecID you should include that in the subselect as well.

A monad is just a monoid in the category of endofunctors, what's the problem?

I came to this post by way of better understanding the inference of the infamous quote from Mac Lane's Category Theory For the Working Mathematician.

In describing what something is, it's often equally useful to describe what it's not.

The fact that Mac Lane uses the description to describe a Monad, one might imply that it describes something unique to monads. Bear with me. To develop a broader understanding of the statement, I believe it needs to be made clear that he is not describing something that is unique to monads; the statement equally describes Applicative and Arrows among others. For the same reason we can have two monoids on Int (Sum and Product), we can have several monoids on X in the category of endofunctors. But there is even more to the similarities.

Both Monad and Applicative meet the criteria:

  • endo => any arrow, or morphism that starts and ends in the same place
  • functor => any arrow, or morphism between two Categories

    (e.g., in day to day Tree a -> List b, but in Category Tree -> List)

  • monoid => single object; i.e., a single type, but in this context, only in regards to the external layer; so, we can't have Tree -> List, only List -> List.

The statement uses "Category of..." This defines the scope of the statement. As an example, the Functor Category describes the scope of f * -> g *, i.e., Any functor -> Any functor, e.g., Tree * -> List * or Tree * -> Tree *.

What a Categorical statement does not specify describes where anything and everything is permitted.

In this case, inside the functors, * -> * aka a -> b is not specified which means Anything -> Anything including Anything else. As my imagination jumps to Int -> String, it also includes Integer -> Maybe Int, or even Maybe Double -> Either String Int where a :: Maybe Double; b :: Either String Int.

So the statement comes together as follows:

  • functor scope :: f a -> g b (i.e., any parameterized type to any parameterized type)
  • endo + functor :: f a -> f b (i.e., any one parameterized type to the same parameterized type) ... said differently,
  • a monoid in the category of endofunctor

So, where is the power of this construct? To appreciate the full dynamics, I needed to see that the typical drawings of a monoid (single object with what looks like an identity arrow, :: single object -> single object), fails to illustrate that I'm permitted to use an arrow parameterized with any number of monoid values, from the one type object permitted in Monoid. The endo, ~ identity arrow definition of equivalence ignores the functor's type value and both the type and value of the most inner, "payload" layer. Thus, equivalence returns true in any situation where the functorial types match (e.g., Nothing -> Just * -> Nothing is equivalent to Just * -> Just * -> Just * because they are both Maybe -> Maybe -> Maybe).

Sidebar: ~ outside is conceptual, but is the left most symbol in f a. It also describes what "Haskell" reads-in first (big picture); so Type is "outside" in relation to a Type Value. The relationship between layers (a chain of references) in programming is not easy to relate in Category. The Category of Set is used to describe Types (Int, Strings, Maybe Int etc.) which includes the Category of Functor (parameterized Types). The reference chain: Functor Type, Functor values (elements of that Functor's set, e.g., Nothing, Just), and in turn, everything else each functor value points to. In Category the relationship is described differently, e.g., return :: a -> m a is considered a natural transformation from one Functor to another Functor, different from anything mentioned thus far.

Back to the main thread, all in all, for any defined tensor product and a neutral value, the statement ends up describing an amazingly powerful computational construct born from its paradoxical structure:

  • on the outside it appears as a single object (e.g., :: List); static
  • but inside, permits a lot of dynamics
    • any number of values of the same type (e.g., Empty | ~NonEmpty) as fodder to functions of any arity. The tensor product will reduce any number of inputs to a single value... for the external layer (~fold that says nothing about the payload)
    • infinite range of both the type and values for the inner most layer

In Haskell, clarifying the applicability of the statement is important. The power and versatility of this construct, has absolutely nothing to do with a monad per se. In other words, the construct does not rely on what makes a monad unique.

When trying to figure out whether to build code with a shared context to support computations that depend on each other, versus computations that can be run in parallel, this infamous statement, with as much as it describes, is not a contrast between the choice of Applicative, Arrows and Monads, but rather is a description of how much they are the same. For the decision at hand, the statement is moot.

This is often misunderstood. The statement goes on to describe join :: m (m a) -> m a as the tensor product for the monoidal endofunctor. However, it does not articulate how, in the context of this statement, (<*>) could also have also been chosen. It truly is a an example of six/half dozen. The logic for combining values are exactly alike; same input generates the same output from each (unlike the Sum and Product monoids for Int because they generate different results when combining Ints).

So, to recap: A monoid in the category of endofunctors describes:

   ~t :: m * -> m * -> m *
   and a neutral value for m *

(<*>) and (>>=) both provide simultaneous access to the two m values in order to compute the the single return value. The logic used to compute the return value is exactly the same. If it were not for the different shapes of the functions they parameterize (f :: a -> b versus k :: a -> m b) and the position of the parameter with the same return type of the computation (i.e., a -> b -> b versus b -> a -> b for each respectively), I suspect we could have parameterized the monoidal logic, the tensor product, for reuse in both definitions. As an exercise to make the point, try and implement ~t, and you end up with (<*>) and (>>=) depending on how you decide to define it forall a b.

If my last point is at minimum conceptually true, it then explains the precise, and only computational difference between Applicative and Monad: the functions they parameterize. In other words, the difference is external to the implementation of these type classes.

In conclusion, in my own experience, Mac Lane's infamous quote provided a great "goto" meme, a guidepost for me to reference while navigating my way through Category to better understand the idioms used in Haskell. It succeeds at capturing the scope of a powerful computing capacity made wonderfully accessible in Haskell.

However, there is irony in how I first misunderstood the statement's applicability outside of the monad, and what I hope conveyed here. Everything that it describes turns out to be what is similar between Applicative and Monads (and Arrows among others). What it doesn't say is precisely the small but useful distinction between them.

- E

draw diagonal lines in div background with CSS

You can do it something like this:

    .background {
        background-color: #BCBCBC;
        width: 100px;
        height: 50px;
        padding: 0; 
        margin: 0
    .line1 {
        width: 112px;
        height: 47px;
        border-bottom: 1px solid red;
        position: absolute;
        /* top: -20px; */
    .line2 {
        width: 112px;
        height: 47px;
        border-bottom: 1px solid green;
        position: absolute;
        top: -33px;
        left: -13px;
<div class="background">
    <div class="line1"></div>
    <div class="line2"></div>

Here is a jsfiddle.

Improved version of answer for your purpose.

How do I link a JavaScript file to a HTML file?

this is demo code but it will help 

<!DOCTYPE html>
<title>APITABLE 3</title>
<script src=""></script>


    type: "GET",
    url: "",

    data: '$format=json',

    dataType: 'json',
    success: function (data) {

                        +"</tr>" )




    <table id="apiTable">

        <tbody id="apiData"></tbody>    


Creating multiple objects with different names in a loop to store in an array list

ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
    //get a customerName
    //get an amount
    custArr.add(new Customer(customerName, amount);

For this to work... you'll have to fix your constructor...

Assuming your Customer class has variables called name and sale, your constructor should look like this:

public Customer(String customerName, double amount) {
    name = customerName;
    sale = amount;

Change your Store class to something more like this:

public class Store {

    private ArrayList<Customer> custArr;

    public new Store() {
        custArr = new ArrayList<Customer>();

    public void addSale(String customerName, double amount) {
        custArr.add(new Customer(customerName, amount));

    public Customer getSaleAtIndex(int index) {
        return custArr.get(index);

    //or if you want the entire ArrayList:
    public ArrayList getCustArr() {
        return custArr;

Input from the keyboard in command line application

The top ranked answer to this question suggests using the readLine() method to take in user input from the command line. However, I want to note that you need to use the ! operator when calling this method to return a string instead of an optional:

var response = readLine()!

How to get back to the latest commit after checking out a previous commit?

You can simply do git pull origin branchname. It will fetch the latest commit again.

Shell Script Syntax Error: Unexpected End of File

In my case, I found that placing a here document (like sqplus ... << EOF) statements indented also raise the same error as shown below:

./dbuser_case.ksh: line 25: syntax error: unexpected end of file

So after removing the indentation for this, then it went fine.

Hope it helps...

How do I use the nohup command without getting nohup.out?

If you have a BASH shell on your mac/linux in-front of you, you try out the below steps to understand the redirection practically :

Create a 2 line script called

echo "Hello. This is a proper command"
  • The echo command's output goes into STDOUT filestream (file descriptor 1).
  • The error command's output goes into STDERR filestream (file descriptor 2)

Currently, simply executing the script sends both STDOUT and STDERR to the screen.


Now start with the standard redirection : > zfile.txt

In the above, "echo" (STDOUT) goes into the zfile.txt. Whereas "error" (STDERR) is displayed on the screen.

The above is the same as : 1> zfile.txt

Now you can try the opposite, and redirect "error" STDERR into the file. The STDOUT from "echo" command goes to the screen. 2> zfile.txt

Combining the above two, you get: 1> zfile.txt 2>&1


  • FIRST, send STDOUT 1 to zfile.txt
  • THEN, send STDERR 2 to STDOUT 1 itself (by using &1 pointer).
  • Therefore, both 1 and 2 goes into the same file (zfile.txt)

Eventually, you can pack the whole thing inside nohup command & to run it in the background:

nohup 1> zfile.txt 2>&1&

Align text in a table header


text-align: center;

You may be familiar with the HTML align attribute (which has been discontinued as of HTML 5). The align attribute could be used with tags such as

<table>, <td>, and <img> 

to specify the alignment of these elements. This attribute allowed you to align elements horizontally. HTML also has/had a valign attribute for aligning elements vertically. This has also been discontinued from HTML5.

These attributes were discontinued in favor of using CSS to set the alignment of HTML elements.

There isn't actually a CSS align or CSS valign property. Instead, CSS has the text-align which applies to inline content of block-level elements, and vertical-align property which applies to inline level and table cells.

Get controller and action name from within controller?

string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();

How to find all the subclasses of a class given its name?

A much shorter version for getting a list of all subclasses:

from itertools import chain

def subclasses(cls):
    return list(
            [list(chain.from_iterable([[x], subclasses(x)])) for x in cls.__subclasses__()]

How to use global variables in React Native?

You can use the global keyword to solve this.

Assume that you want to declare a variable called isFromManageUserAccount as a global variable you can use the following code.


After declaring like this you can use this variable anywhere in the application.

Save array in mysql database

$myArray = new array('1', '2');
$seralizedArray = serialize($myArray);

XML serialization in Java?

XStream is pretty good at serializing object to XML without much configuration and money! (it's under BSD license).

We used it in one of our project to replace the plain old java-serialization and it worked almost out of the box.

how to stop a running script in Matlab

To add on:

you can insert a time check within a loop with intensive or possible deadlock, ie.


where within this section

if (toc > timeRequiredToBreakOff)     % time conditional break off
      % other options may be:                         
      % 1. display intermediate values with pause;
      % 2. exit;                           % in some cases, extreme : kill/ quit matlab

mysql update column with value from another table

Store your data in temp table

Select * into tempTable from table1

Now update the column

 UPDATE table1
    SET table1.FileName = (select FileName from tempTable where = table1.ID);

How to compare if two structs, slices or maps are equal?

reflect.DeepEqual is often incorrectly used to compare two like structs, as in your question.

cmp.Equal is a better tool for comparing structs.

To see why reflection is ill-advised, let's look at the documentation:

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.


numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

If we compare two time.Time values of the same UTC time, t1 == t2 will be false if their metadata timezone is different.

go-cmp looks for the Equal() method and uses that to correctly compare times.


m1 := map[string]int{
    "a": 1,
    "b": 2,
m2 := map[string]int{
    "a": 1,
    "b": 2,
fmt.Println(cmp.Equal(m1, m2)) // will result in true

Looping through a hash, or using an array in PowerShell

I prefer this variant on the enumerator method with a pipeline, because you don't have to refer to the hash table in the foreach (tested in PowerShell 5):

$hash = @{
    'a' = 3
    'b' = 2
    'c' = 1
$hash.getEnumerator() | foreach {
    Write-Host ("Key = " + $_.key + " and Value = " + $_.value);


Key = c and Value = 1
Key = b and Value = 2
Key = a and Value = 3

Now, this has not been deliberately sorted on value, the enumerator simply returns the objects in reverse order.

But since this is a pipeline, I now can sort the objects received from the enumerator on value:

$hash.getEnumerator() | sort-object -Property value -Desc | foreach {
  Write-Host ("Key = " + $_.key + " and Value = " + $_.value);


Key = a and Value = 3
Key = b and Value = 2
Key = c and Value = 1

How do I get the time difference between two DateTime objects using C#?

The way I usually do it is subtracting the two DateTime and this gets me a TimeSpan that will tell me the diff.

Here's an example:

DateTime start = DateTime.Now;
// Do some work
TimeSpan timeDiff = DateTime.Now - start;

Countdown timer in React

Here is a solution using hooks, Timer component, I'm replicating same logic above with hooks

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

const Timer = (props:any) => {
    const {initialMinute = 0,initialSeconds = 0} = props;
    const [ minutes, setMinutes ] = useState(initialMinute);
    const [seconds, setSeconds ] =  useState(initialSeconds);
    let myInterval = setInterval(() => {
            if (seconds > 0) {
                setSeconds(seconds - 1);
            if (seconds === 0) {
                if (minutes === 0) {
                } else {
                    setMinutes(minutes - 1);
        }, 1000)
        return ()=> {

    return (
        { minutes === 0 && seconds === 0
            ? null
            : <h1> {minutes}:{seconds < 10 ?  `0${seconds}` : seconds}</h1> 

export default Timer;

Twitter Bootstrap alert message close and open again

The problem is caused by using the style="display:none", you should hide the alert with Javascript or at least when showing it, remove the style attribute.

Bulk Insertion in Laravel using eloquent ORM

Eloquent::insert is the proper solution but it wont update the timestamps, so you can do something like below

 $json_array=array_map(function ($a) { 
                        return array_merge($a,['created_at'=> 
                                            Carbon::now(),'updated_at'=> Carbon::now()]
                                     }, $json_array); 

The idea is to add created_at and updated_at on whole array before doing insert

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

1. String otherString = "helen" + character;

2. otherString +=  character;

Make absolute positioned div expand parent div height

Feeela is right but you can get a parent div contracting or expanding to a child element if you reverse your div positioning like this:

.parent {
    position: absolute;
    /* position it in the browser using the `left`, `top` and `margin` 
       attributes */

.child {
    position: relative;
    height: 100%;
    width: 100%;

    overflow: hidden;
    /* to pad or move it around using `left` and `top` inside the parent */

This should work for you.

Redirect on select option in select box

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value=""></option>
    <option value="">Google</option>
    <option value="">Gmail</option>
    <option value="">Youtube</option>

Simplest SOAP example

    <title>Calling Web Service from jQuery</title>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnCallWebService").click(function (event) {
                var wsUrl = "";
                var soapRequest ='<soap:Envelope xmlns:xsi="" xmlns:xsd="" xmlns:soap="">   <soap:Body> <getQuote xmlns:impl="">  <symbol>' + $("#txtName").val() + '</symbol>   </getQuote> </soap:Body></soap:Envelope>';
                    type: "POST",
                    url: wsUrl,
                    contentType: "text/xml",
                    dataType: "xml",
                    data: soapRequest,
                    success: processSuccess,
                    error: processError


        function processSuccess(data, status, req) { alert('success');
            if (status == "success")


        function processError(data, status, req) {
            //alert(req.responseText + " " + status);

        Calling Web Services with jQuery/AJAX
    Enter your name:
    <input id="txtName" type="text" />
    <input id="btnCallWebService" value="Call web service" type="button" />
    <div id="response" ></div>

Hear is best JavaScript with SOAP tutorial with example.

How to clear the entire array?

ReDim aFirstArray(0)

This will resize the array to zero and erase all data.

C++ delete vector, objects, free memory

You can free memory used by vector by this way:

//Removes all elements in vector

//Frees the memory which is not used by the vector

Is there a short cut for going back to the beginning of a file by vi editor?

Key in 1 + G and it will take you to the beginning of the file. Converserly, G will take you to the end of the file.

Populate one dropdown based on selection in another

Could you please have a look at:

Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.

var data = [ // The data
    ['ten', [
    ['twenty', [
        'twentyone', 'twentytwo'

$a = $('#a'); // The dropdowns
$b = $('#b');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       data("sel", i).

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][1]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           data("sel", j).
}).change(); // Trigger once to add options at load of first choice

Passing an Array as Arguments, not an Array, in PHP

Also note that if you want to apply an instance method to an array, you need to pass the function as:

call_user_func_array(array($instance, "MethodName"), $myArgs);

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

Try wrapping your dates in single quotes, like this:


It should be able to parse the date this way.

How to convert signed to unsigned integer in python

To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if unsigned long is 32 bit:

>>> i = -6884376
>>> i & 0xffffffff

or if it is 64 bit:

>>> i & 0xffffffffffffffff

Do be aware though that although that gives you the value you would have in C, it is still a signed value, so any subsequent calculations may give a negative result and you'll have to continue to apply the mask to simulate a 32 or 64 bit calculation.

This works because although Python looks like it stores all numbers as sign and magnitude, the bitwise operations are defined as working on two's complement values. C stores integers in twos complement but with a fixed number of bits. Python bitwise operators act on twos complement values but as though they had an infinite number of bits: for positive numbers they extend leftwards to infinity with zeros, but negative numbers extend left with ones. The & operator will change that leftward string of ones into zeros and leave you with just the bits that would have fit into the C value.

Displaying the values in hex may make this clearer (and I rewrote to string of f's as an expression to show we are interested in either 32 or 64 bits):

>>> hex(i)
>>> hex (i & ((1 << 32) - 1))
>>> hex (i & ((1 << 64) - 1)

For a 32 bit value in C, positive numbers go up to 2147483647 (0x7fffffff), and negative numbers have the top bit set going from -1 (0xffffffff) down to -2147483648 (0x80000000). For values that fit entirely in the mask, we can reverse the process in Python by using a smaller mask to remove the sign bit and then subtracting the sign bit:

>>> u = i & ((1 << 32) - 1)
>>> (u & ((1 << 31) - 1)) - (u & (1 << 31))

Or for the 64 bit version:

>>> u = 18446744073702667240
>>> (u & ((1 << 63) - 1)) - (u & (1 << 63))

This inverse process will leave the value unchanged if the sign bit is 0, but obviously it isn't a true inverse because if you started with a value that wouldn't fit within the mask size then those bits are gone.

Clean up a fork and restart it from the upstream

The simplest solution would be (using 'upstream' as the remote name referencing the original repo forked):

git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master  
git push origin master --force 

(Similar to this GitHub page, section "What should I do if I’m in a bad situation?")

Be aware that you can lose changes done on the master branch (both locally, because of the reset --hard, and on the remote side, because of the push --force).

An alternative would be, if you want to preserve your commits on master, to replay those commits on top of the current upstream/master.
Replace the reset part by a git rebase upstream/master. You will then still need to force push.
See also "What should I do if I’m in a bad situation?"

A more complete solution, backing up your current work (just in case) is detailed in "Cleanup git master branch and move some commit to new branch".

See also "Pull new updates from original GitHub repository into forked GitHub repository" for illustrating what "upstream" is.


Note: recent GitHub repos do protect the master branch against push --force.
So you will have to un-protect master first (see picture below), and then re-protect it after force-pushing).

enter image description here

Note: on GitHub specifically, there is now (February 2019) a shortcut to delete forked repos for pull requests that have been merged upstream.

How to set JAVA_HOME in Linux for all users

The answer is given previous posts is valid. But not one answer is complete with respect to:

  1. Changing the /etc/profile is not recommended simply because of the reason (as stated in /etc/profile):
  • It's NOT a good idea to change this file unless you know what you are doing. It's much better to create a shell script in /etc/profile.d/ to make custom changes to your environment, as this will prevent the need for merging in future updates.*
  1. So as stated above create /etc/profile.d/ file for custom changes.

  2. Now, to always keep updated with newer versions of Java being installed, never put the absolute path, instead use:

#if making jdk as java home

export JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:/bin/javac::")


#if making jre as java home

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:/bin/java::")

  1. And remember to have #! /bin/bash on the file

Polling the keyboard (detect a keypress) in python

I am using this for checking for key presses, can't get much simpler:

# -*- coding: UTF-8 -*-

import curses, time

def main(stdscr):
    """checking for keypress"""
    stdscr.nodelay(True)  # do not wait for input when calling getch
    return stdscr.getch()

while True:
    print("key:", curses.wrapper(main)) # prints: 'key: 97' for 'a' pressed
                                        # '-1' on no presses

While curses is not working on windows, there is a 'unicurses' version, supposedly working on Linux, Windows, Mac but I could not get this to work

Easiest way to flip a boolean value?

Just because I like to question code. I propose that you can also make use of the ternary by doing something like this:


bool flipValue = false;
bool bShouldFlip = true;
flipValue = bShouldFlip ? !flipValue : flipValue;

How to skip to next iteration in jQuery.each() util?

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

The Javascript language

Javascript - The Good Parts

How do I reverse a commit in git?

You can do git push --force but be aware that you are rewriting history and anyone using the repo will have issue with this.

If you want to prevent this problem, don't use reset, but instead use git revert

Improve INSERT-per-second performance of SQLite

Bulk imports seems to perform best if you can chunk your INSERT/UPDATE statements. A value of 10,000 or so has worked well for me on a table with only a few rows, YMMV...

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = => "MainTitle")

How to print something when running Puppet client?

Have you tried what is on the sample. I am new to this but here is the command: puppet --test --trace --debug. I hope this helps.

Drop all tables command

While it is true that there is no DROP ALL TABLES command you can use the following set of commands.

Note: These commands have the potential to corrupt your database, so make sure you have a backup

PRAGMA writable_schema = 1;
delete from sqlite_master where type in ('table', 'index', 'trigger');
PRAGMA writable_schema = 0;

you then want to recover the deleted space with


and a good test to make sure everything is ok


Convert hex color value ( #ffffff ) to integer value

Answer is really simple guys, in android if you want to convert hex color in to int, just use android Color class, example shown as below

this is for light gray color


Thats it and you will get your result.

ToList()-- does it create a new list?

ToList will create a brand new list.

If the items in the list are value types, they will be directly updated, if they are reference types, any changes will be reflected back in the referenced objects.

ASP.NET Temporary files cleanup

Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.

For background, see the Understanding ASP.NET dynamic compilation article on MSDN.

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.

2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

How to extend available properties of User.Identity

For anyone that finds this question looking for how to access custom properties in ASP.NET Core 2.1 - it's much easier: You'll have a UserManager, e.g. in _LoginPartial.cshtml, and then you can simply do (assuming "ScreenName" is a property that you have added to your own AppUser which inherits from IdentityUser):

@using Microsoft.AspNetCore.Identity

@using <namespaceWhereYouHaveYourAppUser>

@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager

@if (SignInManager.IsSignedIn(User)) {
    <form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })" 
          method="post" id="logoutForm" 
          class="form-inline my-2 my-lg-0">

        <ul class="nav navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">
                    Hello @((await UserManager.GetUserAsync(User)).ScreenName)!
                    <!-- Original code, shows Email-Address: @UserManager.GetUserName(User)! -->
            <li class="nav-item">
                <button type="submit" class="btn btn-link nav-item navbar-link nav-link">Logout</button>

} else {
    <ul class="navbar-nav ml-auto">
        <li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Register">Register</a></li>
        <li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Login">Login</a></li>

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).

Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

How to change border color of textarea on :focus

There is an input:focus as there is a textarea:focus

input:focus { 
    outline: none !important;
    border-color: #719ECE;
    box-shadow: 0 0 10px #719ECE;
textarea:focus { 
    outline: none !important;
    border-color: #719ECE;
    box-shadow: 0 0 10px #719ECE;

How can I turn a JSONArray into a JSONObject?


List<String> list = new ArrayList<String>();


JSONArray array = new JSONArray();

for (int i = 0; i < list.size(); i++) {
JSONObject obj = new JSONObject();

try {
    obj.put("result", array);
} catch (JSONException e) {

Getting a Request.Headers value

string strHeader = Request.Headers["XYZComponent"]
bool bHeader = Boolean.TryParse(strHeader, out bHeader ) && bHeader;

if "true" than true
if "false" or anything else ("fooBar") than false


string strHeader = Request.Headers["XYZComponent"]
bool b;
bool? bHeader = Boolean.TryParse(strHeader, out b) ? b : default(bool?);

if "true" than true
if "false" than false
else ("fooBar") than null

How to iterate (keys, values) in JavaScript?

The Object.entries() method has been specified in ES2017 (and is supported in all modern browsers):

for (const [ key, value ] of Object.entries(dictionary)) {
    // do something with `key` and `value`


  • Object.entries() takes an object like { a: 1, b: 2, c: 3 } and turns it into an array of key-value pairs: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ].

  • With for ... of we can loop over the entries of the so created array.

  • Since we are guaranteed that each of the so iterated array items is itself a two-entry array, we can use destructuring to directly assign variables key and value to its first and second item.

SQL Server after update trigger

It is very simple to do that, First create a copy of your table that your want keep the log for For example you have Table dbo.SalesOrder with columns SalesOrderId, FirstName,LastName, LastModified

Your Version archieve table should be dbo.SalesOrderVersionArchieve with columns SalesOrderVersionArhieveId, SalesOrderId, FirstName,LastName, LastModified

Here is the how you will set up a trigger on SalesOrder table

-- =============================================
-- Author:      Karan Dhanu
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE TRIGGER dbo.[CreateVersionArchiveRow]
   ON  dbo.[SalesOrder]
  AFTER Update

INSERT INTO dbo.SalesOrderVersionArchive

   FROM deleted;


Now if you make any changes in saleOrder table it will show you the change in VersionArchieve table

Target class controller does not exist - Laravel 8

in laravel-8 default remove namespace prefix so you can set old way in laravel-7 like:

in RouteServiceProvider.php add this variable

protected $namespace = 'App\Http\Controllers';

and update boot method

public function boot()

       $this->routes(function () {


How to do URL decoding in Java?

This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.

Try something like this:

try {
    String result =,;
} catch (UnsupportedEncodingException e) {
    // not going to happen - value came from JDK's own StandardCharsets

Java 10 added direct support for Charset to the API, meaning there's no need to catch UnsupportedEncodingException:

String result =, StandardCharsets.UTF_8);

Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.

SSL "Peer Not Authenticated" error with HttpClient 4.1

This is thrown when

... the peer was not able to identify itself (for example; no certificate, the particular cipher suite being used does not support authentication, or no peer authentication was established during SSL handshaking) this exception is thrown.

Probably the cause of this exception (where is the stacktrace) will show you why this exception is thrown. Most likely the default keystore shipped with Java does not contain (and trust) the root certificate of the TTP that is being used.

The answer is to retrieve the root certificate (e.g. from your browsers SSL connection), import it into the cacerts file and trust it using keytool which is shipped by the Java JDK. Otherwise you will have to assign another trust store programmatically.

nvm is not compatible with the npm config "prefix" option:

Delete and Reset the prefix

$ npm config delete prefix 
$ npm config set prefix $NVM_DIR/versions/node/v6.11.1

Note: Change the version number with the one indicated in the error message.

nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local" Run "npm config delete prefix" or "nvm use --delete-prefix v6.11.1 --silent" to unset it.

Credits to @gabfiocchi on Github - "You need to overwrite nvm prefix"

Find all elements with a certain attribute value in jquery

Use string concatenation. Try this:

$('div[imageId="'+imageN +'"]').each(function() {

How can I calculate the time between 2 Dates in typescript

// TypeScript

const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);

// Explicitly convert Date to Number
const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );

Getting execute permission to xp_cmdshell

Don't grant control to the user, it's totally unnecessay. Select permission on the database is enough. After you have created the login and the user on master (see above answers):

use YourDatabase
create user [YourDomain\YourUser] for login [YourDomain\YourUser] with default_schema=[dbo]
alter role [db_datareader] add member [YourDomain\YourUser]

When is it appropriate to use UDP instead of TCP?

In some cases, which others have highlighted, guaranteed arrival of packets isn't important, and hence using UDP is fine. There are other cases where UDP is preferable to TCP.

One unique case where you would want to use UDP instead of TCP is where you are tunneling TCP over another protocol (e.g. tunnels, virtual networks, etc.). If you tunnel TCP over TCP, the congestion controls of each will interfere with each other. Hence one generally prefers to tunnel TCP over UDP (or some other stateless protocol). See TechRepublic article: Understanding TCP Over TCP: Effects of TCP Tunneling on End-to-End Throughput and Latency.

React: how to update state.item[1] in state using setState?

Try this it will definetly work,other case i tried but didn't work

import _ from 'lodash';

this.state.var_name  = _.assign(this.state.var_name, {
   obj_prop: 'changed_value',

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

If you are connecting a remote mysql server from your local machine using java see the below steps. Error : "java.sql.SQLException: Access denied for user 'xxxxx'@'' (using password: YES) "

for remote access may be cpanel or others grant the remote access for your local ip address.

In the above error message: "" is my local machine ip. So First we have to give remote access in the Cpanel-> Remote MySQL®. Then run your application to connect.

Connection con=DriverManager.getConnection(  
//here abc is database name, def is username and ghi        
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select * from employee");  
        System.out.println(rs.getInt(1)+" "+rs.getString(2)+"  

Hope it will resolve your issue.


Best practices to test protected methods with PHPUnit

You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a private one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:

class Foo {
  protected function stuff() {
    // secret stuff, you want to test

class SubFoo extends Foo {
  public function exposedStuff() {
    return $this->stuff();

Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.

SFTP Libraries for .NET

For comprehensive SFTP support in .NET try edtFTPnet/PRO. It's been around a long time with support for many different SFTP servers.

We also sell an SFTP server for Windows, CompleteFTP, which is an inexpensive way to get support for SFTP on your Windows machine. Also has FTP and FTPS.

How to use PHP string in mySQL LIKE query?

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

Click in OK button inside an Alert (Selenium IDE)

For selenium, an alert is the one which raised using javascript e.g.


There is one basic check to verify whether your alert is actually a javascript alert or just a div-based box for displaying some message. If its a javascript alert, you wont be able to see it on screen while running the selenium script.

If you are able to see it, then you need to get the locator of the ok button of the alert and use to dismiss the alert. Can help you better if you can provide more context:

  1. IDE or RC?
  2. HTML code of the alert
  3. your selenium script.


How to clear jQuery validation error messages?

I came across this issue myself. I had the need to conditionally validate parts of a form while the form was being constructed based on steps (i.e. certain inputs were dynamically appended during runtime). As a result, sometimes a select dropdown would need validation, and sometimes it would not. However, by the end of the ordeal, it needed to be validated. As a result, I needed a robust method which was not a workaround. I consulted the source code for jquery.validate.

Here is what I came up with:

  • Clear errors by indicating validation success
  • Call handler for error display
  • Clear all storage of success or errors
  • Reset entire form validation

    Here is what it looks like in code:

    function clearValidation(formElement){
     //Internal $.validator is exposed through $(form).validate()
     var validator = $(formElement).validate();
     //Iterate through named elements inside of the form, and mark them as error free
       validator.successList.push(this);//mark as error free
       validator.showErrors();//remove error messages if present
     validator.resetForm();//remove error class on name elements and clear history
     validator.reset();//remove all error and success data
    var myForm = document.getElementById("myFormId");

    minified as a jQuery extension:

    $.fn.clearValidation = function(){var v = $(this).validate();$('[name]',this).each(function(){v.successList.push(this);v.showErrors();});v.resetForm();v.reset();};
  • transform object to array with lodash

    You can do

    var arr = _.values(obj);

    For documentation see here.

    is there a tool to create SVG paths from an SVG file?

    (In reply to the "has the situation improved?" part of the question):

    Unfortunately, not really. Illustrator's support for SVG has always been a little shaky, and, having mucked around in Illustrator's internals, I doubt we'll see much improvement as far as Illustrator is concerned.

    If you're looking for DOM-style access to an Illustrator document, you might want to check out Hanpuku (Disclosure #1: I'm the author. Disclosure #2: It's research code, meaning there are bugs aplenty, and future support is unlikely).

    With Hanpuku, you could do something like:

    1. Select the path of interest in Illustrator
    2. Click the "To D3" button
    3. In the script editor, type:

      selection.attr('d', 'M 0 0 L 20 134 L 233 24 Z');

    4. Click run

    5. If the change is as expected, click "To Illustrator" to apply the changes to the document

    Granted, this approach doesn't expose the original path string. If you follow the instructions toward the end of the plugin's welcome page, it's possible to edit the Illustrator document with Chrome's developer tools, but there will be lots of ugly engineering exposed everywhere (the SVG DOM that mirrors the Illustrator document is buried inside an iframe deep in the extension—changing the DOM with Chrome's tools and clicking "To Illustrator" should still work, but you will likely encounter lots of problems).

    TL;DR: Illustrator uses an internal model that's pretty different from SVG in a lot of ways, meaning that when you iterate between the two, currently, your only choice is to use the subset of features that both support in the same way.

    Reset push notification settings for app

    I have wondered about this in the past and came to the conclusion that it was not actually a valid test case for my code. I don't think your application code can actually tell the difference between somebody declining notifications the first time or later disabling it from the iPhone notification settings. It is true that the user experience is different but that is hidden inside the call to registerForRemoteNotificationTypes.

    Calling unregisterForRemoteNotifications does not completely remove the application from the notifications settings - though it does remove the contents of the settings for that application. So this still will not cause the dialog to be presented a second time to the user the next time the app runs (at least not on v3.1.3 that I am currently testing with). But as I say above you probably should not be worrying about that.

    How do I specify new lines on Python, when writing on files?

    In Python you can just use the new-line character, i.e. \n

    How can I write a heredoc to a file in Bash script?

    Instead of using cat and I/O redirection it might be useful to use tee instead:

    tee newfile <<EOF
    line 1
    line 2
    line 3

    It's more concise, plus unlike the redirect operator it can be combined with sudo if you need to write to files with root permissions.

    "The operation is not valid for the state of the transaction" error and transaction scope

    I've encountered this error when my Transaction is nested within another. Is it possible that the stored procedure declares its own transaction or that the calling function declares one?

    How to succinctly write a formula with many variables from a data frame?

    I build this solution, reformulate does not take care if variable names have white spaces.

    add_backticks = function(x) {
        paste0("`", x, "`")
    x_lm_formula = function(x) {
        paste(add_backticks(x), collapse = " + ")
    build_lm_formula = function(x, y){
        if (length(y)>1){
            stop("y needs to be just one variable")
            paste0("`",y,"`", " ~ ", x_lm_formula(x))
    # Example
    df <- data.frame(
        y = c(1,4,6), 
        x1 = c(4,-1,3), 
        x2 = c(3,9,8), 
        x3 = c(4,-4,-2)
    # Model Specification
    columns = colnames(df)
    y_cols = columns[1]
    x_cols = columns[2:length(columns)]
    formula = build_lm_formula(x_cols, y_cols)
    # output
    # "`y` ~ `x1` + `x2` + `x3`"
    # Run Model
    lm(formula = formula, data = df)
    # output
        lm(formula = formula, data = df)
        (Intercept)           x1           x2           x3  
            -5.6316       0.7895       1.1579           NA  


    How to return JSon object

    You only have one row to serialize. Try something like this :

    List<results> resultRows = new List<results>
    resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
    resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});
    string json = JavaScriptSerializer.Serialize(new { results = resultRows});
    • Edit to match OP's original json output

    ** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :


    Angularjs autocomplete from $http

    I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.

    Here's the demo: And here the documentation and repository:

    So basically you have to return a promise when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $qservice/directive/controller where you issue your HTTP Request.


    function getMyHttpData(){
      var deferred = $q.defer();
        // the promise gets resolved with the data from HTTP
      // return the promise
      return deferred.promise;

    I hope this helps.

    Shortcuts in Objective-C to concatenate NSStrings

    Shortcut by creating AppendString (AS) macro ...

    #define AS(A,B)    [(A) stringByAppendingString:(B)]
    NSString *myString = @"This"; NSString *test = AS(myString,@" is just a test");


    If using a macro, of course just do it with variadic arguments, see EthanB's answer.

    mysql update query with sub query

    Thanks, I didn't have the idea of an UPDATE with INNER JOIN.

    In the original query, the mistake was to name the subquery, which must return a value and can't therefore be aliased.

    UPDATE Competition
    SET Competition.NumberOfTeams =
    (SELECT count(*) -- no column alias
      FROM PicksPoints
      WHERE UserCompetitionID is not NULL
      -- put the join condition INSIDE the subquery :
      AND CompetitionID =  Competition.CompetitionID
      group by CompetitionID
    ) -- no table alias

    should do the trick for every record of Competition.

    To be noticed :

    The effect is NOT EXACTLY the same as the query proposed by mellamokb, which won't update Competition records with no corresponding PickPoints.

    Since SELECT id, COUNT(*) GROUP BY id will only count for existing values of ids,

    whereas a SELECT COUNT(*) will always return a value, being 0 if no records are selected.

    This may, or may not, be a problem for you.

    0-aware version of mellamokb query would be :

    Update Competition as C
    LEFT join (
      select CompetitionId, count(*) as NumberOfTeams
      from PicksPoints as p
      where UserCompetitionID is not NULL
      group by CompetitionID
    ) as A on C.CompetitionID = A.CompetitionID
    set C.NumberOfTeams = IFNULL(A.NumberOfTeams, 0)

    In other words, if no corresponding PickPoints are found, set Competition.NumberOfTeams to zero.

    Java code To convert byte to Hexadecimal

    I couldn't figure out what exactly you meant by byte String, but here are some conversions from byte to String and vice versa, of course there is a lot more on the official documentations

    Integer intValue = 149;

    The corresponding byte value is:

    Byte byteValue = intValue.byteValue(); // this will convert the rightmost byte of the intValue to byte, because Byte is an 8 bit object and Integer is at least 16 bit, and it will give you a signed number in this case -107

    get the integer value back from a Byte variable:

    Integer anInt = byteValue.intValue(); // This will convert the byteValue variable to a signed Integer

    From Byte and Integer to hex String:
    This is the way I do it:

    Integer anInt = 149
    Byte aByte = anInt.byteValue();
    String hexFromInt = "".format("0x%x", anInt); // This will output 0x95
    String hexFromByte = "".format("0x%x", aByte); // This will output 0x95

    Converting an array of bytes to a hex string:
    As far as I know there is no simple function to convert all the elements inside an array of some Object to elements of another Object, So you have to do it yourself. You can use the following functions:

    From byte[] to String:

        public static String byteArrayToHexString(byte[] byteArray){
            String hexString = "";
            for(int i = 0; i < byteArray.length; i++){
                String thisByte = "".format("%x", byteArray[i]);
                hexString += thisByte;
            return hexString;

    And from hex string to byte[]:

    public static byte[] hexStringToByteArray(String hexString){
        byte[] bytes = new byte[hexString.length() / 2];
        for(int i = 0; i < hexString.length(); i += 2){
            String sub = hexString.substring(i, i + 2);
            Integer intVal = Integer.parseInt(sub, 16);
            bytes[i / 2] = intVal.byteValue();
            String hex = "".format("0x%x", bytes[i / 2]);
        return bytes;

    It is too late but I hope this could help some others ;)

    Flutter Countdown Timer

    If all you need is a simple countdown timer, this is a good alternative instead of installing a package. Happy coding!

    countDownTimer() async {
     int timerCount;
     for (int x = 5; x > 0; x--) {
       await Future.delayed(Duration(seconds: 1)).then((_) {
         setState(() {
           timerCount -= 1;

    Where is svn.exe in my machine?

    If Subversion is already installed ,there's no need to reinstall it with the command line client tools.
    Simply Goto

    Start(Rightclick) ->App and Feature ->TortoiseSvn->Modify->Install command line client tools.   

    enter image description here

    C# - insert values from file into two arrays

    string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

    How to make a transparent HTML button?

    Make a div and use your image ( png with transparent background ) as the background of the div, then you can apply any text within that div to hover over the button. Something like this:

    <div class="button" onclick="yourbuttonclickfunction();" >
    Your Button Label Here


    .button {
    background: url("yourimage.png");

    Java: Replace all ' in a string with \'

    Use replace()

     s = s.replace("'", "\\'"); 


    You\'ll be totally awesome, I\'m really terrible

    How to set max and min value for Y axis

    Just set the value for scaleStartValue in your options.

    var options = {
       // ....
       scaleStartValue: 0,

    See the documentation for this here.

    Has anyone gotten HTML emails working with Twitter Bootstrap?

    I apologize for resurecting this old thread, but I just wanted to let everyone know there is a very close Bootstrap like CSS framework specifically created for email styling, here is the link:

    Hope it helps someone.

    Ninja edit: It has since been renamed to Foundation for Emails and the new link is:

    Silent but deadly edit: New link

    Elegant way to check for missing packages and install them?

    You can just use the return value of require:


    I use library after the install because it will throw an exception if the install wasn't successful or the package can't be loaded for some other reason. You make this more robust and reuseable:

    dynamic_require <- function(package){
      if(eval(parse(text=paste("require(",package,")")))) return True
      return eval(parse(text=paste("require(",package,")")))

    The downside to this method is that you have to pass the package name in quotes, which you don't do for the real require.

    Python NameError: name is not defined

    You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.

    You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

    Make function definition in a python file order independent

    Get the last item in an array

    In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.


    arr.lastItem // get last item
    arr.lastItem = 'value' // set last item
    arr.lastIndex // get last index

    You can use polyfill.

    Proposal author: Keith Cirkel(chai autor)

    How to manually update datatables table with new JSON data

    You can use:



    Update. And yes current documentation is not so good but if you are okay using older versions you can refer legacy documentation.

    jQuery UI tabs. How to select a tab based on its id not based on index

    I make a wild assumption that you really have layout as:

    <ul  class="tabs">
      <li id="tabone">one</li>
      <li id="tabtwo">two</li>

    IF that assumption is correct, you simply use the ID to select the "tab"


    EDIT: select the tab on your layout:

    var index = $('.tabs ul').index($('#tabone')); 
    $('.tabs ul').tabs('select', index); 

    Spring Security exclude url patterns in security annotation configurartion

    Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.

    Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.

    I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.

    In addition I have a resource, /admin, which requires higher privledges than the rest of the site.

    The following is working for me.

    protected void configure(HttpSecurity http) throws Exception {

    NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:


    Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:


    Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)

    MySQL Trigger - Storing a SELECT in a variable

    You can declare local variables in MySQL triggers, with the DECLARE syntax.

    Here's an example:

      DECLARE x INT;
      SET x = NEW.i;
      SET @a = x; -- set user variable outside trigger
    SET @a = 0;
    SELECT @a; -- returns 0
    INSERT INTO foo () VALUES ();
    SELECT @a; -- returns 1, the value it got during the trigger

    When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row".

    You can use LIMIT or MAX() to make sure that the local variable is set to a single value.

      DECLARE x INT;
      SET x = (SELECT age FROM users WHERE name = 'Bill'); 
      -- ERROR 1242 if more than one row with 'Bill'
      DECLARE x INT;
      SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
      -- OK even when more than one row with 'Bill'

    Android custom Row Item for ListView

    Use a custom Listview.

    You can also customize how row looks by having a custom background. activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android=""
     android:background="#0095FF"> //background color
    <ListView android:id="@+id/list"


    Define populateString() in MainActivity

     public class MainActivity extends Activity {
       String data_array[];
    protected void onCreate(Bundle savedInstanceState) {
                data_array = populateString(); 
        ListView ll = (ListView) findViewById(;
        CustomAdapter cus = new CustomAdapter();
    class CustomAdapter extends BaseAdapter
        LayoutInflater mInflater;
        public CustomAdapter()
            mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        public int getCount() {
            // TODO Auto-generated method stub
            return data_array.length;//listview item count. 
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position; 
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            final ViewHolder vh;
            vh= new ViewHolder();
            if(convertView==null )
                convertView=mInflater.inflate(R.layout.row, parent,false);
                        //inflate custom layour
                vh.tv2= (TextView)convertView.findViewById(;
                   //vh.tv2.setText("Position = "+position);
                               //set text of second textview based on position
            return convertView;
     class ViewHolder
        TextView tv1,tv2;

    row.xml. Custom layout for each row.

    <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android=""
     android:orientation="vertical" >
        android:text="Header" />
        android:text="TextView" />

    Inflate a custom layout. Use a view holder for smooth scrolling and performance. The talk is about listview performance by android developers.

    enter image description here

    Add image to left of text via css

    Very simple method:

    .create:before {
    content: url(image.png);

    Works in all modern browsers and IE8+.


    Don't use this on large sites though. The :before pseudo-element is horrible in terms of performance.

    Is there a short contains function for lists?

    In addition to what other have said, you may also be interested to know that what in does is to call the list.__contains__ method, that you can define on any class you write and can get extremely handy to use python at his full extent.  

    A dumb use may be:

    >>> class ContainsEverything:
        def __init__(self):
            return None
        def __contains__(self, *elem, **k):
            return True
    >>> a = ContainsEverything()
    >>> 3 in a
    >>> a in a
    >>> False in a
    >>> False not in a

    Why use sys.path.append(path) instead of sys.path.insert(1, path)?

    If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):

    virtualenv is a tool to create isolated Python environments.

    The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.

    Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

    Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.

    In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).

    That's why people consider insert(0, to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.

    Adding quotes to a string in VBScript

    I don't think I can improve on these answers as I've used them all, but my preference is declaring a constant and using that as it can be a real pain if you have a long string and try to accommodate with the correct number of quotes and make a mistake. ;)

    How to get an element's top position relative to the browser's viewport?

    You can try:

    node.offsetTop - window.scrollY

    It works on Opera with viewport meta tag defined.

    How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

    Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.

    <a href="Controller/ActionMethod">
        <input type="button" value="Click Me" />

    Adding parameters:

    <a href="Controller/ActionMethod?userName=ted">
        <input type="button" value="Click Me" />

    Adding parameters from a non-enumerated Model:

    <a href="Controller/[email protected]">
        <input type="button" value="Click Me" />

    You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!

    POSTing JSON to URL via WebClient in C#

    The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

    var vm = new { k = "1", a = "2", c = "3", v=  "4" };
    using (var client = new WebClient())
       var dataString = JsonConvert.SerializeObject(vm);
       client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
       client.UploadString(new Uri(""), "POST", dataString);

    Prerequisites: Json.NET library

    postgresql - sql - count of `true` values

    Since PostgreSQL 9.4 there's the FILTER clause, which allows for a very concise query to count the true values:

    select count(*) filter (where myCol)
    from tbl;

    The above query is a bad example in that a simple WHERE clause would suffice, and is for demonstrating the syntax only. Where the FILTER clause shines is that it is easy to combine with other aggregates:

    select count(*), -- all
           count(myCol), -- non null
           count(*) filter (where myCol) -- true
    from tbl;

    The clause is especially handy for aggregates on a column that uses another column as the predicate, while allowing to fetch differently filtered aggregates in a single query:

    select count(*),
           sum(otherCol) filter (where myCol)
    from tbl;

    Rename Files and Directories (Add Prefix)

    Use the rename script this way:

    $ rename 's/^/PRE_/' *

    There are no problems with metacharacters or whitespace in filenames.

    Removing the password from a VBA project

    I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.

    This one does not use SendKeys.

    Let me know if this helps! JFV

    How to sort by Date with DataTables jquery plugin?

    I realize this is a two year old question, but I still found it useful. I ended up using the sample code provided by Fudgey but with a minor mod. Saved me some time, thanks!

    jQuery.fn.dataTableExt.oSort['us_date-asc']  = function(a,b) { 
      var x = new Date($(a).text()),
      y = new Date($(b).text());
      return ((x < y) ? -1 : ((x > y) ?  1 : 0)); 
    jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) { 
      var x = new Date($(a).text()),
      y = new Date($(b).text());
      return ((x < y) ? 1 : ((x > y) ?  -1 : 0)); 

    How to find sum of multiple columns in a table in SQL Server 2005?

    Another example using COALESCE.

    SELECT (COALESCE(SUM(val1),0) + COALESCE(SUM(val2), 0)
    + COALESCE(SUM(val3), 0) + COALESCE(SUM(val4), 0)) AS 'TOTAL'
    FROM Emp

    Convert timestamp to date in MySQL query

    To just get a date you can cast it

    cast(user.registration as date)

    and to get a specific format use date_format

    date_format(registration, '%Y-%m-%d')

    SQLFiddle demo

    HTML embed autoplay="false", but still plays automatically

    None of the video settings posted above worked in modern browsers I tested (like Firefox) using the embed or object elements in HTML5. For video or audio elements they did stop autoplay. For embed and object they did not.

    I tested this using the embed and object elements using several different media types as well as HTML attributes (like autostart and autoplay). These videos always played regardless of any combination of settings in several browsers. Again, this was not an issue using the newer HTML5 video or audio elements, just when using embed and object.

    It turns out the new browser settings for video "autoplay" have changed. Firefox will now ignore the autoplay attributes on these tags and play videos anyway unless you explicitly set to "block audio and video" autoplay in your browser settings.

    To do this in Firefox I have posted the settings below:

    1. Open up your Firefox Browser, click the menu button, and select "Options"
    2. Select the "Privacy & Security" panel and scroll down to the "Permissions" section
    3. Find "Autoplay" and click the "Settings" button. In the dropdown change it to block audio and video. The default is just audio.

    Your videos will NOT autoplay now when displaying videos in web pages using object or embed elements.

    Android Studio - Gradle sync project failed

    I know this is an old thread but I ended up here with the same issue.

    I solved it by comparing the dependencies classpath in the build.gradle script(Project) to the installed version.

    The error message was pointing to the following folder

    C:\Program Files\Android\android-studio3 preview\gradle\m2repository\com\android\tools\build\gradle

    It turned out that the alpha2 version was installed but the classpath was still pointing to alpaha1. A simple change to the classpath ('') was all that was needed.

    This may not help everyone, but I do hope it help most people out.

    How do I check if a C++ string is an int?

    Ok, the way I see it you have 3 options.

    1: If you simply wish to check whether the number is an integer, and don't care about converting it, but simply wish to keep it as a string and don't care about potential overflows, checking whether it matches a regex for an integer would be ideal here.

    2: You can use boost::lexical_cast and then catch a potential boost::bad_lexical_cast exception to see if the conversion failed. This would work well if you can use boost and if failing the conversion is an exceptional condition.

    3: Roll your own function similar to lexical_cast that checks the conversion and returns true/false depending on whether it's successful or not. This would work in case 1 & 2 doesn't fit your requirements.

    Oracle - How to create a materialized view with FAST REFRESH and JOINS

    To start with, from the Oracle Database Data Warehousing Guide:

    Restrictions on Fast Refresh on Materialized Views with Joins Only


    • Rowids of all the tables in the FROM list must appear in the SELECT list of the query.

    This means that your statement will need to look something like this:

        SELECT V.*, P.*, V.ROWID as V_ROWID, P.ROWID as P_ROWID 
             TPM_PROJECT P 

    Another key aspect to note is that your materialized view logs must be created as with rowid.

    Below is a functional test scenario:

    CREATE TABLE bar(foo NUMBER, bar NUMBER, CONSTRAINT bar_pk PRIMARY KEY(foo, bar));
                                        foo.ROWID AS foo_rowid, 
                                        bar.ROWID AS bar_rowid 
                                   FROM foo, bar
                                  WHERE =;

    When should you use a class vs a struct in C++?

    You can use "struct" in C++ if you are writing a library whose internals are C++ but the API can be called by either C or C++ code. You simply make a single header that contains structs and global API functions that you expose to both C and C++ code as this:

    // C access Header to a C++ library
    #ifdef __cpp
    extern "C" {
    // Put your C struct's here
    struct foo
    // NOTE: the typedef is used because C does not automatically generate
    // a typedef with the same name as a struct like C++.
    typedef struct foo foo;
    // Put your C API functions here
    void bar(foo *fun);
    #ifdef __cpp

    Then you can write a function bar() in a C++ file using C++ code and make it callable from C and the two worlds can share data through the declared struct's. There are other caveats of course when mixing C and C++ but this is a simplified example.

    How can I make content appear beneath a fixed DIV element?

    There is (at least) one wayhack to get truly dynamic height without javascript: insert the menu twice:

    • Once in the flow to position the following elements, and
    • once fixed for the desired visual effect.

    <div id="the-menu-container">_x000D_
        <nav class="position-static">...</nav>_x000D_
        <nav class="position-fixed">...</nav>_x000D_

    Depending on the rest of your site, you might have to tweak the z-index styles of the <nav> elements.

    Scrolling to an Anchor using Transition/CSS3

    Using the scroll-behavior CSS property:

    (which is supported in modern browsers but not Edge):

    a {
      display: inline-block;
      padding: 5px 7%;
      text-decoration: none;
    nav, section {
      display: block;
      margin: 0 auto;
      text-align: center;
    nav {
      width: 350px;
      padding: 5px;
    section {
      width: 350px;
      height: 130px;
      overflow-y: scroll;
      border: 1px solid black;
      font-size: 0; 
      scroll-behavior: smooth;    /* <----- THE SECRET ---- */
    section div{
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      font-size: 8vw;
      <a href="#page-1">1</a>
      <a href="#page-2">2</a>
      <a href="#page-3">3</a>
      <div id="page-1">1</div>
      <div id="page-2">2</div>
      <div id="page-3">3</div>

    Bootstrap 3 Align Text To Bottom of Div

    You can do this:


    #container {
    #container h3{

    Then in HTML:

    <div class="row">
        <div class="col-sm-6">
            <img src="//" alt="Logo" />
        <div id="container" class="col-sm-6">
            <h3>Some Text</h3>

    EDIT: add the <

    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

    Check if an object exists

    You can use:

       # get your models
    except ObjectDoesNotExist:
       # do something

    How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

    If you want to compare to a string literal you need to put it in (single) quotes:

    <xsl:if test="Count != 'N/A'">

    In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

    Use next:

    (1..10).each do |a|
      next if a.even?
      puts a



    For additional coolness check out also redo and retry.

    Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

    For more info see

    How to create a link to another PHP page

    echo "<a href='index.php'>Index Page</a>";

    if you wanna use html tag like anchor tag you have to put in echo

    Delete column from pandas DataFrame

    In pandas 0.16.1+ you can drop columns only if they exist per the solution posted by @eiTanLaVi. Prior to that version, you can achieve the same result via a conditional list comprehension:

    df.drop([col for col in ['col_name_1','col_name_2',...,'col_name_N'] if col in df], 
            axis=1, inplace=True)

    How an 'if (A && B)' statement is evaluated?

    You are asking about the && operator, not the if statement.

    && short-circuits, meaning that if while working it meets a condition which results in only one answer, it will stop working and use that answer.

    So, 0 && x will execute 0, then terminate because there is no way for the expression to evaluate non-zero regardless of what is the second parameter to &&.

    How can I schedule a daily backup with SQL Server Express?

    Eduardo Molteni had a great answer:

    Using Windows Scheduled Tasks:

    In the batch file

    "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S 
    (local)\SQLExpress -i D:\dbbackups\SQLExpressBackups.sql

    In SQLExpressBackups.sql

    BACKUP DATABASE MyDataBase1 TO  DISK = N'D:\DBbackups\MyDataBase1.bak' 
    BACKUP DATABASE MyDataBase2 TO  DISK = N'D:\DBbackups\MyDataBase2.bak' 

    What GRANT USAGE ON SCHEMA exactly do?

    For a production system, you can use this configuration :

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

    Extension exists but uuid_generate_v4 fails

    if you do it from unix command (apart from PGAdmin) dont forget to pass the DB as a parameter. otherwise this extension will not be enabled when executing requests on this DB

    psql -d -c "create EXTENSION pgcrypto;"

    Updating Python on Mac

    This article helped me to make the right choices eventually since mac 10.14.6 by default came with python 2.7* and I had to upgrade to 3.7.*

    brew install python3
    brew update && brew upgrade python
    alias python=/usr/local/bin/python3

    Referred The right and wrong way to set Python 3 as default on a Mac article

    What's the difference between unit, functional, acceptance, and integration tests?

    This is very simple.

    1. Unit testing: This is the testing actually done by developers that have coding knowledge. This testing is done at the coding phase and it is a part of white box testing. When a software comes for development, it is developed into the piece of code or slices of code known as a unit. And individual testing of these units called unit testing done by developers to find out some kind of human mistakes like missing of statement coverage etc..

    2. Functional testing: This testing is done at testing (QA) phase and it is a part of black box testing. The actual execution of the previously written test cases. This testing is actually done by testers, they find the actual result of any functionality in the site and compare this result to the expected result. If they found any disparity then this is a bug.

    3. Acceptance testing: know as UAT. And this actually done by the tester as well as developers, management team, author, writers, and all who are involved in this project. To ensure the project is finally ready to be delivered with bugs free.

    4. Integration testing: The units of code (explained in point 1) are integrated with each other to complete the project. These units of codes may be written in different coding technology or may these are of different version so this testing is done by developers to ensure that all units of the code are compatible with other and there is no any issue of integration.

    Best way to parse RSS/Atom feeds with PHP

    The HTML Tidy library is able to fix some malformed XML files. Running your feeds through that before passing them on to the parser may help.

    Possible to iterate backwards through a foreach?

    Before using foreach for iteration, reverse the list by the reverse method:

        foreach( List listItem in myList)

    How do I copy the contents of one stream to another?

    The basic questions that differentiate implementations of "CopyStream" are:

    • size of the reading buffer
    • size of the writes
    • Can we use more than one thread (writing while we are reading).

    The answers to these questions result in vastly different implementations of CopyStream and are dependent on what kind of streams you have and what you are trying to optimize. The "best" implementation would even need to know what specific hardware the streams were reading and writing to.

    Python object.__repr__(self) should be an expression?

    "but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?"

    Wow, that's a lot of hand-wringing.

    1. An "an example of the sort of expression you could use" would not be a representation of a specific object. That can't be useful or meaningful.

    2. What is the difference between "an actual expression, that can ... recreate the object" and "a rehasing of the actual expression which was used [to create the object]"? Both are an expression that creates the object. There's no practical distinction between these. A repr call could produce either a new expression or the original expression. In many cases, they're the same.

    Note that this isn't always possible, practical or desirable.

    In some cases, you'll notice that repr() presents a string which is clearly not an expression of any kind. The default repr() for any class you define isn't useful as an expression.

    In some cases, you might have mutual (or circular) references between objects. The repr() of that tangled hierarchy can't make sense.

    In many cases, an object is built incrementally via a parser. For example, from XML or JSON or something. What would the repr be? The original XML or JSON? Clearly not, since they're not Python. It could be some Python expression that generated the XML. However, for a gigantic XML document, it might not be possible to write a single Python expression that was the functional equivalent of parsing XML.

    FileNotFoundException while getting the InputStream object from HttpURLConnection

    The solution:
    just change localhost for the IP of your PC
    if you want to know this: Windows+r > cmd > ipconfig
    just replace for your own IP (don't try because it's same as localhost)

    Insert array into MySQL database with PHP

    Insert array data into mysql php

    I Have array data.. I want post that data in database

    1: this is my array data:

    stdClass Object
        [questions] => Array
                [0] => stdClass Object
                        [question_id] => 54
                        [question] => Which%20of%20the%20following%20is%20a%20rational%20number%20(s)%3F%3Cbr%20%2F%3E%0D%0A%3Cbr%20%2F%3E
                        [option_1] => %3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F010779c34ce28fee25778247e127b82d.png%22%20alt%3D%22%22%20%2F%3E%3Cspan%20class%3D%22Apple-tab-span%22%20style%3D%22white-space%3A%20pre%3B%20%22%3E%09%3C%2Fspan%3E
                        [option_2] => %26nbsp%3B%3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F3af35a16c371ffaaf9ea6891fb732478.png%22%20alt%3D%22%22%20%2F%3E
                        [option_3] => %26nbsp%3B%3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F4a57d5766a79f0ddf659d63c7443982b.png%22%20alt%3D%22%22%20%2F%3E
                        [option_4] => %26nbsp%3BAll%20the%20above%26nbsp%3B
                        [iscorrect] => yes
                        [answerGiven] => D
                        [marksobtain] => 2
                        [timetaken] => 3
                        [difficulty_levelval] => 2
       [1] => stdClass Object
                        [question_id] => 58
                        [question] => %3Cdiv%3EIf%20A%20%26nbsp%3B%3A%20Every%20whole%20number%20is%20a%20natural%20number%20and%3C%2Fdiv%3E%0D%0A%3Cdiv%3E%26nbsp%3B%20%26nbsp%3BR%20%3A%200%20is%20not%20a%20natural%20number%2C%3C%2Fdiv%3E%0D%0A%3Cdiv%3EThen%20which%20of%20the%20following%20statement%20is%20true%3F%3C%2Fdiv%3E
                        [option_1] => %26nbsp%3BA%20is%20False%20and%20R%20is%20true.
                        [option_2] => A%20is%20True%20and%20R%20is%20the%20correct%20explanation%20of%20A
                        [option_3] => %26nbsp%3BA%20is%20True%20and%20R%20is%20false
                        [option_4] => %26nbsp%3BBoth%20A%20and%20R%20are%20True
                        [iscorrect] => no
                        [answerGiven] => D
                        [marksobtain] => 0
                        [timetaken] => 2
                        [difficulty_levelval] => 2

    code used i used to insert that data:

    Code ::

    $data = file_get_contents('php://input');
    $arr_data = explode("=",$data);
    $final_data = urldecode($arr_data[1]);
    $final_data2 = json_decode($final_data);
     //print_r ($final_data2);
    echo 'i am in array ';
        $sql = "INSERT INTO p_user_test_details(question_id, question, option_1, option_2, option_3, option_4,iscorrect,answerGiven,marksobtain,timetaken,difficulty_levelval) values ";
        $valuesArr = array();
        foreach($final_data2 as $row){
            $question_id = (int) $row['question_id'];
            $question = mysql_real_escape_string( $row['question'] );
            $option_1 = mysql_real_escape_string( $row['option_1'] );
        $option_2 = mysql_real_escape_string( $row['option_2'] );
        $option_3 = mysql_real_escape_string( $row['option_3'] );
        $option_4 = mysql_real_escape_string( $row['option_4'] );
        $iscorrect = mysql_real_escape_string( $row['iscorrect'] );
        $answerGiven = mysql_real_escape_string( $row['answerGiven'] );
            $marksobtain = mysql_real_escape_string( $row['marksobtain'] );
            $timetaken = mysql_real_escape_string( $row['timetaken'] );
            $difficulty_levelval = mysql_real_escape_string( $row['difficulty_levelval'] );
            $valuesArr[] = "('$question_id', '$question', '$option_1','$option_2','$option_3','$option_4','$iscorrect','$answerGiven','$marksobtain','$timetaken','$difficulty_levelval')";
        $sql .= implode(',', $valuesArr);
        mysql_query($sql) or exit(mysql_error()); 
    echo 'no one is there ';

    How do you set up use HttpOnly cookies in PHP

    You can specify it in the set cookie function see the php manual

    setcookie('Foo','Bar',0,'/', ''  , FALSE, TRUE);

    Get child Node of another Node, given node name

    Check if the Node is a Dom Element, cast, and call getElementsByTagName()

    Node doc = docs.item(i);
    if(doc instanceof Element) {
        Element docElement = (Element)doc;
        cell = doc.getElementsByTagName("aoo").item(0);

    How to enable explicit_defaults_for_timestamp?

    On my system (Windows 8.1), the problem was with the server configuration. The server worked for the first time when I installed it. However, I forgot to check the "run as a service" option and this caused all the problem. I tried all possible solutions available on SO but nothing worked. So, I decided to reinstall MySQL Workbench. On executing the same msi file that I earlier used to install MySQL workbench, I reconfigured the server and allowed to run the server as a service.

    How to set cursor position in EditText?

    Remember call requestFocus() before setSelection for edittext.

    Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

    Being au fait with patterns as defined by (say) the GOF book, and naming objects after these gets me a long way in naming classes, organising them and communicating intent. Most people will understand this nomenclature (or at least a major part of it).

    How do you list the primary key of a SQL Server table?

    This version displays the schema, the table name and an ordered, comma separated list of primary keys. Object_Id() does not work for link servers so we filter by the table name.

    Without the REPLACE(Si1.Column_Name, '', '') it would show the xml opening and closing tags for Column_Name on the database I was testing on. I am not sure why the database required a replace for 'Column_Name' so if someone knows then please comment.

    DECLARE @TableName VARCHAR(100) = '';
    WITH Sysinfo
        AS (SELECT Kcu.Table_Name
                , Kcu.Table_Schema AS Schema_Name
                , Kcu.Column_Name
                , Kcu.Ordinal_Position
            FROM   [LinkServer].Information_Schema.Key_Column_Usage Kcu
                 JOIN [LinkServer].Information_Schema.Table_Constraints AS Tc ON Tc.Constraint_Name = Kcu.Constraint_Name
            WHERE  Tc.Constraint_Type = 'Primary Key')
        SELECT           Schema_Name
                        , STUFF(
                                 SELECT ', '
                                     , REPLACE(Si1.Column_Name, '', '')
                                 FROM    Sysinfo Si1
                                 WHERE  Si1.Table_Name = Si2.Table_Name
                                 ORDER BY Si1.Table_Name
                                       , Si1.Ordinal_Position
                                 FOR XML PATH('')
                              ), 1, 2, '') AS Primary_Keys
        FROM Sysinfo Si2
        WHERE Table_Name = CASE
                           WHEN @TableName NOT IN( '', 'All')
                           THEN @TableName
                           ELSE Table_Name
        GROUP BY Si2.Table_Name, Si2.Schema_Name;

    And the same pattern using George's query:

    DECLARE @TableName VARCHAR(100) = '';
    WITH Sysinfo
        AS (SELECT S.Name AS Schema_Name
                , T.Name AS Table_Name
                , Tc.Name AS Column_Name
                , Ic.Key_Ordinal AS Ordinal_Position
            FROM   [LinkServer].Sys.Schemas S
                 JOIN [LinkServer].Sys.Tables T ON S.Schema_Id = T.Schema_Id
                 JOIN [LinkServer].Sys.Indexes I ON T.Object_Id = I.Object_Id
                 JOIN [LinkServer].Sys.Index_Columns Ic ON I.Object_Id = Ic.Object_Id
                                                           AND I.Index_Id = Ic.Index_Id
                 JOIN [LinkServer].Sys.Columns Tc ON Ic.Object_Id = Tc.Object_Id
                                                      AND Ic.Column_Id = Tc.Column_Id
            WHERE  I.Is_Primary_Key = 1)
        SELECT           Schema_Name
                        , STUFF(
                                 SELECT ', '
                                     , REPLACE(Si1.Column_Name, '', '')
                                 FROM    Sysinfo Si1
                                 WHERE  Si1.Table_Name = Si2.Table_Name
                                 ORDER BY Si1.Table_Name
                                       , Si1.Ordinal_Position
                                 FOR XML PATH('')
                              ), 1, 2, '') AS Primary_Keys
        FROM Sysinfo Si2
        WHERE Table_Name = CASE
                           WHEN @TableName NOT IN('', 'All')
                           THEN @TableName
                           ELSE Table_Name
        GROUP BY Si2.Table_Name, Si2.Schema_Name;

    Remove element by id

    From what I understand, removing a node directly does not work in Firefox, only Internet Explorer. So, to support Firefox, you have to go up to the parent to remove it's child.


    Any free WPF themes?

    We use the Assergs Application Framework themes:

    They have a nice office look and feel to it :)

    How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

    Try something like this:

    foreach (ListItem listItem in YrChkBox.Items)
        if (listItem.Selected)
           //do some work 
          //do something else 

    Uncaught TypeError: undefined is not a function on loading jquery-min.js

    Yes, i also I fixed it changing in the js libraries to the unminified.

    For example, in the tag, change:

    <script type="text/javascript" src="js/jquery.ui.core.min.js"></script>
    <script type="text/javascript" src="js/jquery.ui.widget.min.js"></script>
    <script type="text/javascript" src="js/jquery.ui.rcarousel.min.js"></script>


    <script type="text/javascript" src="js/jquery.ui.core.js"></script>
    <script type="text/javascript" src="js/jquery.ui.widget.js"></script>
    <script type="text/javascript" src="js/jquery.ui.rcarousel.js"></script>

    Quiting the 'min' as unminified.

    Thanks for the idea.

    Current Subversion revision command

    Newer versions of svn support the --show-item argument:

    svn info --show-item revision

    For the revision number of your local working copy, use:

    svn info --show-item last-changed-revision

    You can use os.system() to execute a command line like this:

    svn info | grep "Revision" | awk '{print $2}'

    I do that in my nightly build scripts.

    Also on some platforms there is a svnversion command, but I think I had a reason not to use it. Ahh, right. You can't get the revision number from a remote repository to compare it to the local one using svnversion.

    Right Align button in horizontal LinearLayout

    I know this question was asked awhile ago, but I have done this before and it allows for more control when aligning items.If you look at it like web programming, it helps. You just nest another LinearLayout that will contain your button inside of it. You can then change the gravity of the button's layout and make it go to the right while the TextView is still on the left.

    Try this code:

        android:orientation="horizontal" >

    You may have to play with the padding on the nested layout so that it acts how you want it.

    ansible: lineinfile for several lines?

    You can use a loop to do it. Here's an example using a with_items loop:

    - name: Set some kernel parameters
        dest: /etc/sysctl.conf
        regexp: "{{ item.regexp }}"
        line: "{{ item.line }}"
        - { regexp: '^kernel.shmall', line: 'kernel.shmall = 2097152' }
        - { regexp: '^kernel.shmmax', line: 'kernel.shmmax = 134217728' }
        - { regexp: '^fs.file-max', line: 'fs.file-max = 65536' }

    jQuery Get Selected Option From Dropdown

    If you are in event context, in jQuery, you can retrieve the selected option element using :
    $(this).find('option:selected') like this :

    $('dropdown_selector').change(function() {
        //Use $option (with the "$") to see that the variable is a jQuery object
        var $option = $(this).find('option:selected');
        //Added with the EDIT
        var value = $option.val();//to get content of "value" attrib
        var text = $option.text();//to get <option>Text</option> content


    As mentioned by PossessWithin, My answer just answer to the question : How to select selected "Option".

    Next, to get the option value, use option.val().

    How to insert new row to database with AUTO_INCREMENT column without specifying column names?

    For some databases, you can just explicitly insert a NULL into the auto_increment column:

    INSERT INTO table_name VALUES (NULL, 'my name', 'my group')

    How to draw a line with matplotlib?

    This will draw a line that passes through the points (-1, 1) and (12, 4), and another one that passes through the points (1, 3) et (10, 2)

    x1 are the x coordinates of the points for the first line, y1 are the y coordinates for the same -- the elements in x1 and y1 must be in sequence.

    x2 and y2 are the same for the other line.

    import matplotlib.pyplot as plt
    x1, y1 = [-1, 12], [1, 4]
    x2, y2 = [1, 10], [3, 2]
    plt.plot(x1, y1, x2, y2, marker = 'o')

    enter image description here

    I suggest you spend some time reading / studying the basic tutorials found on the very rich matplotlib website to familiarize yourself with the library.

    What if I don't want line segments?

    There are no direct ways to have lines extend to infinity... matplotlib will either resize/rescale the plot so that the furthest point will be on the boundary and the other inside, drawing line segments in effect; or you must choose points outside of the boundary of the surface you want to set visible, and set limits for the x and y axis.

    As follows:

    import matplotlib.pyplot as plt
    x1, y1 = [-1, 12], [1, 10]
    x2, y2 = [-1, 10], [3, -1]
    plt.xlim(0, 8), plt.ylim(-2, 8)
    plt.plot(x1, y1, x2, y2, marker = 'o')

    enter image description here

    sql ORDER BY multiple values in specific order?

    I found a much cleaner solution for this:

    ORDER BY array_position(ARRAY['f', 'p', 'i', 'a']::varchar[], x_field)

    Note: array_position needs Postgres v9.5 or higher.

    How to exit from Python without traceback?

    something like import sys; sys.exit(0) ?

    How can I generate an MD5 hash?

    My not very revealing answer:

    private String md5(String s) {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(s.getBytes(), 0, s.length());
            BigInteger i = new BigInteger(1,m.digest());
            return String.format("%1$032x", i);         
        } catch (NoSuchAlgorithmException e) {
        return null;

    R plot: size and resolution

    A reproducible example:

    the_plot <- function()
      x <- seq(0, 1, length.out = 100)
      y <- pbeta(x, 1, 10)
        xlab = "False Positive Rate",
        ylab = "Average true positive rate",
        type = "l"

    James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

      width     = 3.25,
      height    = 3.25,
      units     = "in",
      res       = 1200,
      pointsize = 4
      mar      = c(5, 5, 2, 2),
      xaxs     = "i",
      yaxs     = "i",
      cex.axis = 2,
      cex.lab  = 2

    Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

    ggplot_alternative <- function()
      the_data <- data.frame(
        x <- seq(0, 1, length.out = 100),
        y = pbeta(x, 1, 10)
    ggplot(the_data, aes(x, y)) +
        geom_line() +
        xlab("False Positive Rate") +
        ylab("Average true positive rate") +
        coord_cartesian(0:1, 0:1)
      width = 3.25,
      height = 3.25,
      dpi = 1200

    Visual Studio: How to break on handled exceptions?

    There is an 'exceptions' window in VS2005 ... try Ctrl+Alt+E when debugging and click on the 'Thrown' checkbox for the exception you want to stop on.

    iTunes Connect: How to choose a good SKU?

    Spending some time coming up with an SKU naming strategy can help you. You’ll be able to make it easy for team members to read and understand what each SKU represents. Use a value that is meaningful to your organization.

    Ultimately, your SKU is a way to record important product information, so the more straightforward it is, the better for everyone.

    Sticking to alphanumeric SKUs and substituting “-” or “_” for space is always the safest and best bet.

    E.g. Your app name: Social Point, Submit year: 2020 = Your SKU is: Social_Point_2020

    Multiline text in JLabel

    You can use JTextArea and remove editing capabilities to get normal read-only multiline text.

    JTextArea textArea = new JTextArea("line\nline\nline");



    How to get TimeZone from android mobile?

    On my device TimeZone.getDefault() is always returning UTC time zone.

    I need to do this to get user configured time zone :

    val tz = TimeZone.getDefault()

    It will return user selected timezone.

    WHERE Clause to find all records in a specific month

    If you're using SQL Server, look into DATEPART.


    You can then use normal integer logic with it. Same for year, just use yy instead of mm.

    Numpy: Get random set of rows from 2D array

    >>> A = np.random.randint(5, size=(10,3))
    >>> A
    array([[1, 3, 0],
           [3, 2, 0],
           [0, 2, 1],
           [1, 1, 4],
           [3, 2, 2],
           [0, 1, 0],
           [1, 3, 1],
           [0, 4, 1],
           [2, 4, 2],
           [3, 3, 1]])
    >>> idx = np.random.randint(10, size=2)
    >>> idx
    array([7, 6])
    >>> A[idx,:]
    array([[0, 4, 1],
           [1, 3, 1]])

    Putting it together for a general case:

    A[np.random.randint(A.shape[0], size=2), :]

    For non replacement (numpy 1.7.0+):

    A[np.random.choice(A.shape[0], 2, replace=False), :]

    I do not believe there is a good way to generate random list without replacement before 1.7. Perhaps you can setup a small definition that ensures the two values are not the same.

    Using putty to scp from windows to Linux

    You need to tell scp where to send the file. In your command that is not working:

    scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~

    You have not mentioned a remote server. scp uses : to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c from the host C to your local home directory.

    The correct upload command, based on your comments, should be something like:

    C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:

    If you are running the command from your home directory, you can use a relative path:

    C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:

    You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:

    C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/

    How to detect the OS from a Bash script?

    I wrote a personal Bash library and scripting framework that uses GNU shtool to do a rather accurate platform detection.

    GNU shtool is a very portable set of scripts that contains, among other useful things, the 'shtool platform' command. Here is the output of:

    shtool platform -v -F "%sc (%ac) %st (%at) %sp (%ap)"

    on a few different machines:

    Mac OS X Leopard: 
        4.4BSD/Mach3.0 (iX86) Apple Darwin 9.6.0 (i386) Apple Mac OS X 10.5.6 (iX86)
    Ubuntu Jaunty server:
        LSB (iX86) GNU/Linux 2.9/2.6 (i686) Ubuntu 9.04 (iX86)
    Debian Lenny:
        LSB (iX86) GNU/Linux 2.7/2.6 (i686) Debian GNU/Linux 5.0 (iX86)

    This produces pretty satisfactory results, as you can see. GNU shtool is a little slow, so I actually store and update the platform identification in a file on the system that my scripts call. It's my framework, so that works for me, but your mileage may vary.

    Now, you'll have to find a way to package shtool with your scripts, but it's not a hard exercise. You can always fall back on uname output, also.


    I missed the post by Teddy about config.guess (somehow). These are very similar scripts, but not the same. I personally use shtool for other uses as well, and it has been working quite well for me.

    How to write a PHP ternary operator

    You wouldn’t: it’s messy and hard to read.

    You’re looking for the switch statement in the first case. The second is fine as it is but still could be converted for consistency

    Ternary statements are much more suited to boolean values and alternating logic.

    Simplest way to detect a mobile device in PHP

    I was wondering, until now, why someone had not posted a slightly alteration of the accepted answer to the use of implode() in order to have a better readability of the code. So here it goes:

    $uaFull = strtolower($_SERVER['HTTP_USER_AGENT']);
    $uaStart = substr($uaFull, 0, 4);
    $uaPhone = [
        'lge ',
        'opera m(ob|in)i',
        'palm( os)?',
        'windows ce',
    $uaMobile = [
        'a wa', 
        'au(di|\-m|r |s )', 
        'g1 u', 
        'hp( i|ip)', 
        'ht(c(\-| |_|a|g|p|s|t)|tp)', 
        'iac( |\-|\/)', 
        'kgt( |\/)', 
        'kpt ', 
        'lg( g|\/(k|l|u)|50|54|\-[a-w])', 
        'mo(01|02|bi|de|do|t(\-| |o|v)|zz)', 
        'mt(50|p1|v )', 
        'sp(01|h\-|v\-|v )', 
        'w3c(\-| )', 
        'wi(g |nc|nw)', 
    $isPhone = preg_match('/' . implode($uaPhone, '|') . '/i', $uaFull);
    $isMobile = preg_match('/' . implode($uaMobile, '|') . '/i', $uaStart);
    if($isPhone || $isMobile) {
        // do something with that device
    } else {
        // process normally

    Determining image file size + dimensions via Javascript?

    How about this:

    var imageUrl = '';
    var blob = null;
    var xhr = new XMLHttpRequest();'GET', imageUrl, true); 
    xhr.responseType = 'blob';
    xhr.onload = function() 
        blob = xhr.response;
        console.log(blob, blob.size);

    due to Same Origin Policy, only work under same origin

    ! [rejected] master -> master (fetch first)

    enter image description here

    ! [rejected] master -> master (fetch first) error: failed to push some refs to '[email protected]:'

    enter image description here

    Successfully solved the problem using --force command. so, you must used
    git push origin master --force

    psql - save results of command to a file

    If you got the following error

    ufgtoolspg=> COPY (SELECT foo, bar FROM baz) TO '/tmp/query.csv' (format csv, delimiter ';');
    ERROR:  must be superuser to COPY to or from a file
    HINT:  Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.

    you can run it in this way:

    psql somepsqllink_or_credentials -c "COPY (SELECT foo, bar FROM baz) TO STDOUT (format csv, delimiter ';')"  > baz.csv

    How to define an optional field in protobuf 3

    To expand on @cybersnoopy 's suggestion here

    if you had a .proto file with a message like so:

    message Request {
        oneof option {
            int64 option_value = 1;

    You can make use of the case options provided (java generated code):

    So we can now write some code as follows:

    Request.OptionCase optionCase = request.getOptionCase();
    OptionCase optionNotSet = OPTION_NOT_SET;
    if (optionNotSet.equals(optionCase)){
        // value not set
    } else {
        // value set

    Add Marker function with Google Maps API

    <div id="map" style="width:100%;height:500px"></div>
    function myMap() {
      var myCenter = new google.maps.LatLng(51.508742,-0.120850);
      var mapCanvas = document.getElementById("map");
      var mapOptions = {center: myCenter, zoom: 5};
      var map = new google.maps.Map(mapCanvas, mapOptions);
      var marker = new google.maps.Marker({position:myCenter});
    <script src=""></script>

    How to print a Groovy variable in Jenkins?

    You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

    Delete all documents from index/type without deleting type

    Elasticsearch 2.3 the option

        action.destructive_requires_name: true

    in elasticsearch.yml do the trip

        curl -XDELETE http://localhost:9200/twitter/tweet

    How to trigger click on page load?

    You can do the following :-


    How to remove unused imports in Intellij IDEA on commit?

    Or you can do the following shortcut :

    MAC : Shift + Command + A (Enter Action menu pops up)

    And write : Optimize Imports

    php: Get html source code with cURL

    I found a tool in Github that could possibly be a solution to this question. I hope that will be useful

    Loop in Jade (currently known as "Pug") template engine

    Just adding another possibility as it might help someone that's trying to both iterate over an array AND maintain a count. For example, the code below goes through an array named items and only displays the first 3 items. Notice that the each and the if are native jade and don't need a hyphen.

      - var count = 0;
      each item in items
        if count < 3
        - count++;

    Setting up foreign keys in phpMyAdmin?

    If you want to use phpMyAdmin to set up relations, you have to do 2 things. First of all, you have to define an index on the foreign key column in the referring table (so foo_bar.foo_id, in your case). Then, go to relation view (in the referring table) and select the referred column (so in your case and the on update and on delete actions.

    I think foreign keys are useful if you have multiple tables linked to one another, in particular, your delete scripts will become very short if you set the referencing options correctly.

    EDIT: Make sure both of the tables have the InnoDB engine selected.

    Best way to "negate" an instanceof

    I agree that in most cases the if (!(x instanceof Y)) {...} is the best approach, but in some cases creating an isY(x) function so you can if (!isY(x)) {...} is worthwhile.

    I'm a typescript novice, and I've bumped into this S/O question a bunch of times over the last few weeks, so for the googlers the typescript way to do this is to create a typeguard like this:


    export function isHTMLInputElement (value: any): value is HTMLInputElement {
      return value instanceof HTMLInputElement


    if (!isHTMLInputElement(x)) throw new RangeError()
    // do something with an HTMLInputElement

    I guess the only reason why this might be appropriate in typescript and not regular js is that typeguards are a common convention, so if you're writing them for other interfaces, it's reasonable / understandable / natural to write them for classes too.

    There's more detail about user defined type guards like this in the docs

    Where to put the file

    Gradle looks for files in these places:

    • in project build dir (that is where your build script is)
    • in sub-project dir
    • in gradle user home (defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle)

    Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).


    The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

    I found solution. It works fine when I throw away next line from form:


    And now it pass all parameters at request ok:

     <form action="/registration" method="post">
       <%-- error messages --%>
       <div class="form-group">
        <c:forEach items="${registrationErrors}" var="error">
        <p class="error">${error}</p>

    How to print all key and values from HashMap in Android?

    For everyone who clicked on this to find out what the content of your HashMap is, the toString method (docs) actually works with most objects. (note: a java array is not an object!)

    So this woks perfectly fine for debugging purposes:

    >>> {key1=value1, key2=value2}

    What is the location of mysql client ".my.cnf" in XAMPP for Windows?

    Go to control panel ? services, look for MySQL and right click choose properties. If there, in “path to EXE file”, there is a parameter like


    this is the file the server actually uses (independent of what mysql --help prints).

    Java random number with given length

    Would that work for you?

    public class Main {
    public static void main(String[] args) {
        Random r = new Random(System.currentTimeMillis());
        System.out.println(r.nextInt(100000) * 0.000001);


    result e.g. 0.019007

    javascript create array from for loop

    Remove obj and just do this inside your for loop:


    Also, the i < yearEnd condition will not include the final year, so change it to i <= yearEnd.

    How to unbind a listener that is calling event.preventDefault() (using jQuery)?

    if it is a link then $(this).unbind("click"); would re-enable the link clicking and the default behavior would be restored.

    I have created a demo JS fiddle to demonstrate how this works:

    Here is the code of the JS fiddle:


    <script src=""></script>
    <a href="">Default click action is prevented, only on the third click it would be enabled</a>
    <div id="log"></div>


    var counter = 1;
    $( "a" ).click(function( event ) {
      $( "<div>" )
        .append( "default " + event.type + " prevented "+counter )
        .appendTo( "#log" );
        if(counter == 2)
            $( "<div>" )
        .append( "now enable click" )
        .appendTo( "#log" );
        $(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
            $( "<div>" )
        .append( "still disabled" )
        .appendTo( "#log" );

    How to open child forms positioned within MDI parent in VB.NET?

    You will want to set the MdiParent property of your new form to the name of the MDI parent form, as follows:

    dim form as new yourform
    form.MdiParent = nameParent