Programs & Examples On #Input

Input is usually related to user input, i.e., to the data that user supplies to a running application. In many systems this input is considered to be potentially dangerous and needs to be sanitized to ensure that the user has not injected runnable code into the application.

Difference between <input type='button' /> and <input type='submit' />

<input type="button"> can be used anywhere, not just within form and they do not submit form if they are in one. Much better suited with Javascript.

<input type="submit"> should be used in forms only and they will send a request (either GET or POST) to specified URL. They should not be put in any HTML place.

Escaping backslash in string - javascript

Escape the backslash character.

foo.split('\\')

How to take character input in java

import java.util.Scanner;

class SwiCas {

    public static void main(String as[]) {   
        Scanner s= new Scanner(System.in);

        char a=s.next().charAt(0);//this line shows how to take character input in java

        switch(a) {    
            case 'a':
                System.out.println("Vowel....");   
                break;    
            case 'e':
                System.out.println("Vowel....");   
                break;   
            case 'i':
                System.out.println("Vowel....");   
                break;
            case 'o':
                System.out.println("Vowel....");    
                break;    
            case 'u':
                System.out.println("Vowel....");   
                break;    
            case 'A':
                System.out.println("Vowel....");    
                break;    
            case 'E':
                System.out.println("Vowel....");  
                break;    
            case 'I':
                System.out.println("Vowel....");    
                break;    
            case 'O':
                System.out.println("Vowel....");    
                break;   
            case 'U':
                System.out.println("Vowel....");    
                break;    
            default:    
                System.out.println("Consonants....");
        }
    }
}

Two values from one input in python?

This is a sample code to take two inputs seperated by split command and delimiter as ","


>>> var1, var2 = input("enter two numbers:").split(',')
>>>enter two numbers:2,3
>>> var1
'2'
>>> var2
'3'


Other variations of delimiters that can be used are as below :
var1, var2 = input("enter two numbers:").split(',')
var1, var2 = input("enter two numbers:").split(';')
var1, var2 = input("enter two numbers:").split('/')
var1, var2 = input("enter two numbers:").split(' ')
var1, var2 = input("enter two numbers:").split('~')

Disable Button in Angular 2

Change ng-disabled="!contractTypeValid" to [disabled]="!contractTypeValid"

How to handle onchange event on input type=file in jQuery?

It should work fine, are you wrapping the code in a $(document).ready() call? If not use that or use live i.e.

$('#fileupload1').live('change', function(){ 
    alert("hola");
});

Here is a jsFiddle of this working against jQuery 1.4.4

Clear text field value in JQuery

If you are using jQuery, then you can use this:

// var doc_val_check = $('#doc_title').val(); - No need of this!
if ($('#doc_title').val().length > 0) {
    $('#doc_title').val("");
}

Input type "number" won't resize

What you want is maxlength.

Valid for text, search, url, tel, email, and password, it defines the maximum number of characters (as UTF-16 code units) the user can enter into the field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the field has no maximum length. This value must also be greater than or equal to the value of minlength.

You might consider using one of these input types.

How to read multiple Integer values from a single line of input in Java?

i know it's old discuss :) i tested below code it's worked

`String day = "";
 day = sc.next();
 days[i] = Integer.parseInt(day);`

How to make HTML input tag only accept numerical values?

I use this for Zip Codes, quick and easy.

<input type="text" id="zip_code" name="zip_code" onkeypress="return event.charCode > 47 && event.charCode < 58;" pattern="[0-9]{5}" required></input>

HTML checkbox onclick called in Javascript

Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll() when you click on a label, right? Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label

<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
  <input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
  Select All
</label>

find all unchecked checkbox in jquery

As the error message states, jQuery does not include a :unchecked selector.
Instead, you need to invert the :checked selector:

$("input:checkbox:not(:checked)")

How to set date format in HTML date input tag?

If you're using jQuery, here's a nice simple method

$("#dateField").val(new Date().toISOString().substring(0, 10));

Or there's the old traditional way:

document.getElementById("dateField").value = new Date().toISOString().substring(0, 10)

Get the value of input text when enter key pressed

$("input").on("keydown",function search(e) {
    if(e.keyCode == 13) {
        alert($(this).val());
    }
});

jsFiddle example : http://jsfiddle.net/NH8K2/1/

Override browser form-filling and input highlighting with HTML/CSS

Please try with autocomplete="none" in your input tag

This works for me

Get list of all input objects using JavaScript, without accessing a form object

querySelectorAll returns a NodeList which has its own forEach method:

document.querySelectorAll('input').forEach( input => {
  // ...
});

getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:

Array.from(document.getElementsByTagName('input')).forEach( input => {
  // ...
});

how to customise input field width in bootstrap 3

In Bootstrap 3, .form-control (the class you give your inputs) has a width of 100%, which allows you to wrap them into col-lg-X divs for arrangement. Example from the docs:

<div class="row">
  <div class="col-lg-2">
    <input type="text" class="form-control" placeholder=".col-lg-2">
  </div>
  <div class="col-lg-3">
    <input type="text" class="form-control" placeholder=".col-lg-3">
  </div>
  <div class="col-lg-4">
    <input type="text" class="form-control" placeholder=".col-lg-4">
  </div>
</div>

See under Column sizing.

It's a bit different than in Bootstrap 2.3.2, but you get used to it quickly.

jquery background-color change on focus and blur

Even easier, just CSS can resolve the problem:

input[type="text"], input[type="password"], textarea, select { 
    width: 200px;
    border: 1px solid;
    border-color: #C0C0C0 #E4E4E4 #E4E4E4 #C0C0C0;
    background: #FFF;
    padding: 8px 5px;
    font: 16px Arial, Tahoma, Helvetica, sans-serif;
    -moz-box-shadow: 0 0 5px #C0C0C0;
    -moz-border-radius: 5px;
    -webkit-box-shadow: 0 0 5px #C0C0C0;
    -webkit-border-radius: 5px;
    box-shadow: 0 0 5px #C0C0C0;
    border-radius: 5px;
}
input[type="text"]:focus, input[type="password"]:focus, textarea:focus, select:focus { 
    border-color: #B6D5F7 #B6D5F7 #B6D5F7 #B6D5F7;
    outline: none;
    -moz-box-shadow: 0 0 10px #B6D5F7;
    -webkit-box-shadow: 0 0 10px #B6D5F7;
    box-shadow: 0 0 10px #B6D5F7;
}

Force decimal point instead of comma in HTML5 number input (client-side)

Sadly, the coverage of this input field in the modern browsers is very low:

http://caniuse.com/#feat=input-number

Therefore, I recommend to expect the fallback and rely on a heavy-programmatically-loaded input[type=text] to do the job, until the field is generally accepted.

So far, only Chrome, Safari and Opera have a neat implementation, but all other browsers are buggy. Some of them, don't even seem to support decimals (like BB10)!

How do I request and receive user input in a .bat and use it to run a certain program?

I have improved batch file with yes or no prompt. If user enter any character except y and n , then it will again prompt user for valid input. It Works for me.

    @echo off

    :ConfirmBox 
        set /P c= Are you sure want to contine (y/n)?

    if /I "%c%" EQU "Y" (
    goto :FnYes 
    ) else if /I "%c%" EQU "N" ( 
    goto :FnNo
    ) else ( 
    goto :InValid 
    )


:FnYes
     echo You have entered Y
     goto :END

:FnNo
     echo You have entered N
     goto :END

:InValid
     echo Invalid selection. Enter Y or N
     goto :ConfirmBox

:END
    pause
    exit  

/I in if condition will validate both lowercase and uppercase characters.

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

These are really two questions.

The first one is answered here: Calling a Sub in VBA

To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.

CSS Input with width: 100% goes outside parent's bound

You also have an error in your css with the exclamation point in this line:

background:rgb(242, 242, 242);!important;

remove the semi-colon before it. However, !important should be used rarely and can largely be avoided.

How to get the HTML's input element of "file" type to only accept pdf files?

To get the HTML file input form element to only accept PDFs, you can use the accept attribute in modern browsers such as Firefox 9+, Chrome 16+, Opera 11+ and IE10+ like such:

<input name="file1" type="file" accept="application/pdf">

You can string together multiple mime types with a comma.

The following string will accept JPG, PNG, GIF, PDF, and EPS files:

<input name="foo" type="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps">

In older browsers the native OS file dialog cannot be restricted – you'd have to use Flash or a Java applet or something like that to handle the file transfer.

And of course it goes without saying that this doesn't do anything to verify the validity of the file type. You'll do that on the server-side once the file has uploaded.

A little update – with javascript and the FileReader API you could do more validation client-side before uploading huge files to your server and checking them again.

Taking inputs with BufferedReader in Java

BufferedReader#read reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.

            String s= inp.readLine();
            int[] m= new int[2];
            String[] s1 = inp.readLine().split(" ");
            m[0]=Integer.parseInt(s1[0]);
            m[1]=Integer.parseInt(s1[1]);

            // Checking whether I am taking the inputs correctly
            System.out.println(s);
            System.out.println(m[0]);
            System.out.println(m[1]);

You can check also Scanner vs. BufferedReader.

Input button target="_blank" isn't causing the link to load in a new window/tab

In a similar use case, this worked for me...

<button onclick="window.open('https://www.w3.org/', '_blank');">  My Button </button>

HTML Input - already filled in text

All you have to do is use the value attribute of input tags:

<input type="text" value="Your Value" />

Or, in the case of a textarea:

<textarea>Your Value</textarea>

How do I make an input field accept only letters in javaScript?

If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:

function validate() {
    if (document.myForm.name.value == "") {
        alert("Enter a name");
        document.myForm.name.focus();
        return false;
    }
    if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
        alert("Invalid characters");
        document.myForm.name.focus();
        return false;
    }
}

How to read a single character from the user?

Try using this: http://home.wlu.edu/~levys/software/kbhit.py It's non-blocking (that means that you can have a while loop and detect a key press without stopping it) and cross-platform.

import os

# Windows
if os.name == 'nt':
    import msvcrt

# Posix (Linux, OS X)
else:
    import sys
    import termios
    import atexit
    from select import select


class KBHit:

    def __init__(self):
        '''Creates a KBHit object that you can call to do various keyboard things.'''

        if os.name == 'nt':
            pass

        else:

            # Save the terminal settings
            self.fd = sys.stdin.fileno()
            self.new_term = termios.tcgetattr(self.fd)
            self.old_term = termios.tcgetattr(self.fd)

            # New terminal setting unbuffered
            self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)

            # Support normal-terminal reset at exit
            atexit.register(self.set_normal_term)


    def set_normal_term(self):
        ''' Resets to normal terminal.  On Windows this is a no-op.
        '''

        if os.name == 'nt':
            pass

        else:
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)


    def getch(self):
        ''' Returns a keyboard character after kbhit() has been called.
            Should not be called in the same program as getarrow().
        '''

        s = ''

        if os.name == 'nt':
            return msvcrt.getch().decode('utf-8')

        else:
            return sys.stdin.read(1)


    def getarrow(self):
        ''' Returns an arrow-key code after kbhit() has been called. Codes are
        0 : up
        1 : right
        2 : down
        3 : left
        Should not be called in the same program as getch().
        '''

        if os.name == 'nt':
            msvcrt.getch() # skip 0xE0
            c = msvcrt.getch()
            vals = [72, 77, 80, 75]

        else:
            c = sys.stdin.read(3)[2]
            vals = [65, 67, 66, 68]

        return vals.index(ord(c.decode('utf-8')))


    def kbhit(self):
        ''' Returns True if keyboard character was hit, False otherwise.
        '''
        if os.name == 'nt':
            return msvcrt.kbhit()

        else:
            dr,dw,de = select([sys.stdin], [], [], 0)
            return dr != []

An example to use this:

import kbhit

kb = kbhit.KBHit()

while(True): 
    print("Key not pressed") #Do something
    if kb.kbhit(): #If a key is pressed:
        k_in = kb.getch() #Detect what key was pressed
        print("You pressed ", k_in, "!") #Do something
kb.set_normal_term()

Or you could use the getch module from PyPi. But this would block the while loop

Check if input is integer type in C

There are several problems with using scanf with the %d conversion specifier to do this:

  1. If the input string starts with a valid integer (such as "12abc"), then the "12" will be read from the input stream and converted and assigned to num, and scanf will return 1, so you'll indicate success when you (probably) shouldn't;

  2. If the input string doesn't start with a digit, then scanf will not read any characters from the input stream, num will not be changed, and the return value will be 0;

  3. You don't specify if you need to handle non-decimal formats, but this won't work if you have to handle integer values in octal or hexadecimal formats (0x1a). The %i conversion specifier handles decimal, octal, and hexadecimal formats, but you still have the first two problems.

First of all, you'll need to read the input as a string (preferably using fgets). If you aren't allowed to use atoi, you probably aren't allowed to use strtol either. So you'll need to examine each character in the string. The safe way to check for digit values is to use the isdigit library function (there are also the isodigit and isxdigit functions for checking octal and hexadecimal digits, respectively), such as

while (*input && isdigit(*input))
   input++;    

(if you're not even allowed to use isdigit, isodigit, or isxdigit, then slap your teacher/professor for making the assignment harder than it really needs to be).

If you need to be able to handle octal or hex formats, then it gets a little more complicated. The C convention is for octal formats to have a leading 0 digit and for hex formats to have a leading 0x. So, if the first non-whitespace character is a 0, you have to check the next character before you can know which non-decimal format to use.

The basic outline is

  1. If the first non-whitespace character is not a '-', '+', '0', or non-zero decimal digit, then this is not a valid integer string;
  2. If the first non-whitespace character is '-', then this is a negative value, otherwise we assume a positive value;
  3. If the first character is '+', then this is a positive value;
  4. If the first non-whitespace and non-sign character is a non-zero decimal digit, then the input is in decimal format, and you will use isdigit to check the remaining characters;
  5. If the first non-whitespace and non-sign character is a '0', then the input is in either octal or hexadecimal format;
  6. If the first non-whitespace and non-sign character was a '0' and the next character is a digit from '0' to '7', then the input is in octal format, and you will use isodigit to check the remaining characters;
  7. If the first non-whitespace and non-sign character was a 0 and the second character is x or X, then the input is in hexadecimal format and you will use isxdigit to check the remaining characters;
  8. If any of the remaining characters do not satisfy the check function specified above, then this is not a valid integer string.

HTML form input tag name element array with JavaScript

document.form.p_id.length ... not count().

You really should give your form an id

<form id="myform">

Then refer to it using:

var theForm = document.getElementById("myform");

Then refer to the elements like:

for(var i = 0; i < theForm.p_id.length; i++){

Min and max value of input in angular4 application

I succeeded by using a form control. This is my html code :

<md-input-container>
    <input type="number" min="0" max="100" required mdInput placeholder="Charge" [(ngModel)]="rateInput" name="rateInput" [formControl]="rateControl">
    <md-error>Please enter a value between 0 and 100</md-error>
</md-input-container>

And in my Typescript code, I have :

this.rateControl = new FormControl("", [Validators.max(100), Validators.min(0)])

So, if we enter a value higher than 100 or smaller than 0, the material design input become red and the field is not validate. So after, if the value is not good, I don't save when I click on the save button.

Width of input type=text element

I believe that is just how the browser renders their standard input. If you set a border on the input:

<input type="text" style="width: 10px; padding: 2px; border: 1px solid black"/>
<div style="width: 10px; border: solid 1px black; padding: 2px"> </div>

Then both are the same width, at least in FF.

Reading Space separated input in python

If you have it in a string, you can use .split() to separate them.

>>> for string in ('Mike 18', 'Kevin 35', 'Angel 56'):
...   l = string.split()
...   print repr(l[0]), repr(int(l[1]))
...
'Mike' 18
'Kevin' 35
'Angel' 56
>>>

How to input matrix (2D list) in Python?

no_of_rows = 3  # For n by n, and even works for n by m but just give no of rows
matrix = [[int(j) for j in input().split()] for i in range(n)]
print(matrix)

If input value is blank, assign a value of "empty" with Javascript

I'm guessing this is what you want...

When the form is submitted, check if the value is empty and if so, send a value = empty.

If so, you could do the following with jQuery.

$('form').submit(function(){
    var input = $('#test').val();
    if(input == ''){
         $('#test').val('empty');
    }    
});

HTML

<form> 
    <input id="test" type="text" />
</form>

http://jsfiddle.net/jasongennaro/NS6Ca/

Click your cursor in the box and then hit enter to see the form submit the value.

Delete default value of an input text on click

we can do it without using js in the following way using the "placeholder" attribute of html5 ( the default text disappears when the user starts to type in ,but not on just clicking )

<input type="email" id="email" placeholder="[email protected]">

see this: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_placeholder

Java JTextField with input hint

Have look at WebLookAndFeel at https://github.com/mgarin/weblaf/

WebTextField txtName = new com.alee.laf.text.WebTextField();

txtName.setHideInputPromptOnFocus(false);

txtName.setInputPrompt("Name");

txtName.setInputPromptFont(new java.awt.Font("Ubuntu", 0, 18));

txtName.setInputPromptForeground(new java.awt.Color(102, 102, 102));

txtName.setInputPromptPosition(0);

Limit number of characters allowed in form input text field

<input type="text" maxlength="5">

the maximum amount of letters that can be in the input is 5.

PHP "php://input" vs $_POST

So I wrote a function that would get the POST data from the php://input stream.

So the challenge here was switching to PUT, DELETE OR PATCH request method, and still obtain the post data that was sent with that request.

I'm sharing this maybe for someone with a similar challenge. The function below is what I came up with and it works. I hope it helps!

    /**
     * @method Post getPostData
     * @return array
     * 
     * Convert Content-Disposition to a post data
     */
    function getPostData() : array
    {
        // @var string $input
        $input = file_get_contents('php://input');

        // continue if $_POST is empty
        if (strlen($input) > 0 && count($_POST) == 0 || count($_POST) > 0) :

            $postsize = "---".sha1(strlen($input))."---";

            preg_match_all('/([-]{2,})([^\s]+)[\n|\s]{0,}/', $input, $match);

            // update input
            if (count($match) > 0) $input = preg_replace('/([-]{2,})([^\s]+)[\n|\s]{0,}/', '', $input);

            // extract the content-disposition
            preg_match_all("/(Content-Disposition: form-data; name=)+(.*)/m", $input, $matches);

            // let's get the keys
            if (count($matches) > 0 && count($matches[0]) > 0)
            {
                $keys = $matches[2];

                foreach ($keys as $index => $key) :
                    $key = trim($key);
                    $key = preg_replace('/^["]/','',$key);
                    $key = preg_replace('/["]$/','',$key);
                    $key = preg_replace('/[\s]/','',$key);
                    $keys[$index] = $key;
                endforeach;

                $input = preg_replace("/(Content-Disposition: form-data; name=)+(.*)/m", $postsize, $input);

                $input = preg_replace("/(Content-Length: )+([^\n]+)/im", '', $input);

                // now let's get key value
                $inputArr = explode($postsize, $input);

                // @var array $values
                $values = [];

                foreach ($inputArr as $index => $val) :
                    $val = preg_replace('/[\n]/','',$val);

                    if (preg_match('/[\S]/', $val)) $values[$index] = trim($val);

                endforeach;

                // now combine the key to the values
                $post = [];

                // @var array $value
                $value = [];

                // update value
                foreach ($values as $i => $val) $value[] = $val;

                // push to post
                foreach ($keys as $x => $key) $post[$key] = isset($value[$x]) ? $value[$x] : '';

                if (is_array($post)) :

                    $newPost = [];

                    foreach ($post as $key => $val) :

                        if (preg_match('/[\[]/', $key)) :

                            $k = substr($key, 0, strpos($key, '['));
                            $child = substr($key, strpos($key, '['));
                            $child = preg_replace('/[\[|\]]/','', $child);
                            $newPost[$k][$child] = $val;

                        else:

                            $newPost[$key] = $val;

                        endif;

                    endforeach;

                    $_POST = count($newPost) > 0 ? $newPost : $post;

                endif;
            }

        endif;

        // return post array
        return $_POST;
    }

Javascript - User input through HTML input tag to set a Javascript variable?

I tried to send/add input tag's values into JavaScript variable which worked well for me, here is the code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function changef()
            {
            var ctext=document.getElementById("c").value;

            document.writeln(ctext);
            }

        </script>
    </head>
    <body>
        <input type="text" id="c" onchange="changef"();>

        <button type="button" onclick="changef()">click</button>
    </body> 
</html>

HTML Input Box - Disable

The syntax to disable an HTML input is as follows:

<input type="text" id="input_id" DISABLED />

How to read numbers separated by space using scanf

int main()
{
char string[200];
int g,a,i,G[20],A[20],met;

gets(string);
g=convert_input(G,string);

for(i=0;i<=g;i++)
    printf("\n%d>>%d",i,G[i]);
return 0;
}

int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
    temp=0;
    while(string[i]!=' ' && string[i]!='\0')
        temp=temp*10 + (string[i++]-'0') ;
    if(string[i]==' ')
        i++;
    K[j++]=temp;
}
return j-1;
}

Detect changed input text box

In my case, I had a textbox that was attached to a datepicker. The only solution that worked for me was to handle it inside the onSelect event of the datepicker.

<input type="text"  id="bookdate">

$("#bookdate").datepicker({            
     onSelect: function (selected) {
         //handle change event here
     }
});

Check if input is number or letter javascript

The best and modern way is typeof (variable) if you care about real number not number from string. For example:

var a = 1;
var b = '1';

typeof a: // Output: "number"
typeof b: // Output: "string

HTML input textbox with a width of 100% overflows table cells

The problem lies in border-width of input element. Shortly, try setting the margin-left of the input element to -2px.

table input {
  margin-left: -2px;
}

How to check if string input is a number?

Works fine for check if an input is a positive Integer AND in a specific range

def checkIntValue():
    '''Works fine for check if an **input** is
   a positive Integer AND in a specific range'''
    maxValue = 20
    while True:
        try:
            intTarget = int(input('Your number ?'))
        except ValueError:
            continue
        else:
            if intTarget < 1 or intTarget > maxValue:
                continue
            else:
                return (intTarget)

Why is `input` in Python 3 throwing NameError: name... is not defined

You're running your Python 3 code with a Python 2 interpreter. If you weren't, your print statement would throw up a SyntaxError before it ever prompted you for input.

The result is that you're using Python 2's input, which tries to eval your input (presumably sdas), finds that it's invalid Python, and dies.

Reading an integer from user input

You need to typecast the input. try using the following

int input = Convert.ToInt32(Console.ReadLine()); 

It will throw exception if the value is non-numeric.

Edit

I understand that the above is a quick one. I would like to improve my answer:

String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
      switch(selectedOption) 
      {
           case 1:
                 //your code here.
                 break;
           case 2:
                //another one.
                break;
           //. and so on, default..
      }

} 
else
{
     //print error indicating non-numeric input is unsupported or something more meaningful.
}

Do checkbox inputs only post data if they're checked?

input type="hidden" name="is_main" value="0"

input type="checkbox" name="is_main" value="1"

so you can control like this as I did in the application. if it checks then send value 1 otherwise 0

Getting value of HTML text input

Yes, you can use jQuery to make this done, the idea is

Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.

<form name="input" action="handle_email.php" method="post">
  <input type="hidden" name="email" id="email" />
  <input type="submit" value="Submit" />
</form> 

<script>
   $("form").submit(function() {
     var emailFromOtherTextBox = $("#email_textbox").val();
     $("#email").val(emailFromOtherTextBox ); 
     return true;
  });
</script>

also see http://api.jquery.com/submit/

CSS to hide INPUT BUTTON value text

This works in Firefox 3, Internet Explorer 8, Internet Explorer 8 compatibility mode, Opera, and Safari.

*Note: table cell containing this has padding:0 and text-align:center.

background: none;
background-image: url(../images/image.gif);
background-repeat:no-repeat;
overflow:hidden;
border: NONE;
width: 41px; /*width of image*/
height: 19px; /*height of image*/
font-size: 0;
padding: 0 0 0 41px;
cursor:pointer;

How to use unicode characters in Windows command line?

Try:

chcp 65001

which will change the code page to UTF-8. Also, you need to use Lucida console fonts.

Is there any way to change input type="date" format?

i found a way to change format ,its a tricky way, i just changed the appearance of the date input fields using just a CSS code.

_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {_x000D_
  color: #fff;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit-year-field{_x000D_
  position: absolute !important;_x000D_
  border-left:1px solid #8c8c8c;_x000D_
  padding: 2px;_x000D_
  color:#000;_x000D_
  left: 56px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit-month-field{_x000D_
  position: absolute !important;_x000D_
  border-left:1px solid #8c8c8c;_x000D_
  padding: 2px;_x000D_
  color:#000;_x000D_
  left: 26px;_x000D_
}_x000D_
_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit-day-field{_x000D_
  position: absolute !important;_x000D_
  color:#000;_x000D_
  padding: 2px;_x000D_
  left: 4px;_x000D_
  _x000D_
}
_x000D_
<input type="date" value="2019-12-07">
_x000D_
_x000D_
_x000D_

Why cannot change checkbox color whatever I do?

Although the question is answered and is older, In exploring some options to overcome the the styling of check boxes issue I encountered this awesome set of CSS3 only styling of check boxes and radio buttons controlling background colors and other appearances. Thought this might be right up the alley of this question.

JSFiddle

_x000D_
_x000D_
body {_x000D_
    background: #555;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
    color: #eee;_x000D_
    font: 30px Arial, sans-serif;_x000D_
    -webkit-font-smoothing: antialiased;_x000D_
    text-shadow: 0px 1px black;_x000D_
    text-align: center;_x000D_
    margin-bottom: 50px;_x000D_
}_x000D_
_x000D_
input[type=checkbox] {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
/* SLIDE ONE */_x000D_
.slideOne {_x000D_
    width: 50px;_x000D_
    height: 10px;_x000D_
    background: #333;_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    position: relative;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideOne label {_x000D_
    display: block;_x000D_
    width: 16px;_x000D_
    height: 16px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-transition: all .4s ease;_x000D_
    -moz-transition: all .4s ease;_x000D_
    -o-transition: all .4s ease;_x000D_
    -ms-transition: all .4s ease;_x000D_
    transition: all .4s ease;_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    top: -3px;_x000D_
    left: -3px;_x000D_
_x000D_
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.slideOne input[type=checkbox]:checked + label {_x000D_
    left: 37px;_x000D_
}_x000D_
_x000D_
/* SLIDE TWO */_x000D_
.slideTwo {_x000D_
    width: 80px;_x000D_
    height: 30px;_x000D_
    background: #333;_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    position: relative;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideTwo:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    top: 14px;_x000D_
    left: 14px;_x000D_
    height: 2px;_x000D_
    width: 52px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    background: #111;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideTwo label {_x000D_
    display: block;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-transition: all .4s ease;_x000D_
    -moz-transition: all .4s ease;_x000D_
    -o-transition: all .4s ease;_x000D_
    -ms-transition: all .4s ease;_x000D_
    transition: all .4s ease;_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    top: 4px;_x000D_
    z-index: 1;_x000D_
    left: 4px;_x000D_
_x000D_
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.slideTwo label:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 10px;_x000D_
    height: 10px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    background: #333;_x000D_
    left: 6px;_x000D_
    top: 6px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9);_x000D_
}_x000D_
_x000D_
.slideTwo input[type=checkbox]:checked + label {_x000D_
    left: 54px;_x000D_
}_x000D_
_x000D_
.slideTwo input[type=checkbox]:checked + label:after {_x000D_
    background: #00bf00;_x000D_
}_x000D_
_x000D_
/* SLIDE THREE */_x000D_
.slideThree {_x000D_
    width: 80px;_x000D_
    height: 26px;_x000D_
    background: #333;_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    position: relative;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideThree:after {_x000D_
    content: 'OFF';_x000D_
    font: 12px/26px Arial, sans-serif;_x000D_
    color: #000;_x000D_
    position: absolute;_x000D_
    right: 10px;_x000D_
    z-index: 0;_x000D_
    font-weight: bold;_x000D_
    text-shadow: 1px 1px 0px rgba(255,255,255,.15);_x000D_
}_x000D_
_x000D_
.slideThree:before {_x000D_
    content: 'ON';_x000D_
    font: 12px/26px Arial, sans-serif;_x000D_
    color: #00bf00;_x000D_
    position: absolute;_x000D_
    left: 10px;_x000D_
    z-index: 0;_x000D_
    font-weight: bold;_x000D_
}_x000D_
_x000D_
.slideThree label {_x000D_
    display: block;_x000D_
    width: 34px;_x000D_
    height: 20px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-transition: all .4s ease;_x000D_
    -moz-transition: all .4s ease;_x000D_
    -o-transition: all .4s ease;_x000D_
    -ms-transition: all .4s ease;_x000D_
    transition: all .4s ease;_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    top: 3px;_x000D_
    left: 3px;_x000D_
    z-index: 1;_x000D_
_x000D_
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.slideThree input[type=checkbox]:checked + label {_x000D_
    left: 43px;_x000D_
}_x000D_
_x000D_
/* ROUNDED ONE */_x000D_
.roundedOne {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.roundedOne label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.roundedOne label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 16px;_x000D_
    height: 16px;_x000D_
    background: #00bf00;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -moz-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -o-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -ms-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    top: 2px;_x000D_
    left: 2px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
}_x000D_
_x000D_
.roundedOne label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.roundedOne input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* ROUNDED TWO */_x000D_
.roundedTwo {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.roundedTwo label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.roundedTwo label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 5px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #fcfff4;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.roundedTwo label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.roundedTwo input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* SQUARED ONE */_x000D_
.squaredOne {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredOne label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredOne label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 16px;_x000D_
    height: 16px;_x000D_
    background: #00bf00;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -moz-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -o-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -ms-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
_x000D_
    top: 2px;_x000D_
    left: 2px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
}_x000D_
_x000D_
.squaredOne label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.squaredOne input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* SQUARED TWO */_x000D_
.squaredTwo {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredTwo label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredTwo label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 4px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #fcfff4;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.squaredTwo label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.squaredTwo input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
_x000D_
/* SQUARED THREE */_x000D_
.squaredThree {_x000D_
    width: 20px;    _x000D_
    margin: 20px auto;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredThree label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    top: 0;_x000D_
    border-radius: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,.4);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,.4);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,.4);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredThree label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 4px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #fcfff4;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.squaredThree label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.squaredThree input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* SQUARED FOUR */_x000D_
.squaredFour {_x000D_
    width: 20px;    _x000D_
    margin: 20px auto;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredFour label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    top: 0;_x000D_
    border-radius: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredFour label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 4px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #333;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.squaredFour label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.5;_x000D_
}_x000D_
_x000D_
.squaredFour input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}
_x000D_
<h1>CSS3 Checkbox Styles</h1>_x000D_
_x000D_
<!-- Slide ONE -->_x000D_
<div class="slideOne">  _x000D_
    <input type="checkbox" value="None" id="slideOne" name="check" />_x000D_
    <label for="slideOne"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Slide TWO -->_x000D_
<div class="slideTwo">  _x000D_
    <input type="checkbox" value="None" id="slideTwo" name="check" />_x000D_
    <label for="slideTwo"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Slide THREE -->_x000D_
<div class="slideThree">    _x000D_
    <input type="checkbox" value="None" id="slideThree" name="check" />_x000D_
    <label for="slideThree"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Rounded ONE -->_x000D_
<div class="roundedOne">_x000D_
    <input type="checkbox" value="None" id="roundedOne" name="check" />_x000D_
    <label for="roundedOne"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Rounded TWO -->_x000D_
<div class="roundedTwo">_x000D_
    <input type="checkbox" value="None" id="roundedTwo" name="check" />_x000D_
    <label for="roundedTwo"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared ONE -->_x000D_
<div class="squaredOne">_x000D_
    <input type="checkbox" value="None" id="squaredOne" name="check" />_x000D_
    <label for="squaredOne"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared TWO -->_x000D_
<div class="squaredTwo">_x000D_
    <input type="checkbox" value="None" id="squaredTwo" name="check" />_x000D_
    <label for="squaredTwo"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared THREE -->_x000D_
<div class="squaredThree">_x000D_
    <input type="checkbox" value="None" id="squaredThree" name="check" />_x000D_
    <label for="squaredThree"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared FOUR -->_x000D_
<div class="squaredFour">_x000D_
    <input type="checkbox" value="None" id="squaredFour" name="check" />_x000D_
    <label for="squaredFour"></label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

input() error - NameError: name '...' is not defined

You can change which python you're using with your IDE, if you've already downloaded python 3.x it shouldn't be too hard to switch. But your script works fine on python 3.x, I would just change

print ("your name is" + input_variable)

to

print ("your name is", input_variable)

Because with the comma it prints with a whitespace in between your name is and whatever the user inputted. AND: if you're using 2.7 just use raw_input instead of input.

Forcing label to flow inline with input that they label

Put the input in the label, and ditch the for attribute

<label>
  label1:
  <input type="text" id="id1" name="whatever" />
</label>

But of course, what if you want to style the text? Just use a span.

<label id="id1">
  <span>label1:</span>
  <input type="text" name="whatever" />
</label>

jquery input select all on focus

There are some decent answers here and @user2072367 's is my favorite, but it has an unexpected result when you focus via tab rather than via click. ( unexpected result: to select text normally after focus via tab, you must click one additional time )

This fiddle fixes that small bug and additionally stores $(this) in a variable to avoid redundant DOM selection. Check it out! (:

Tested in IE > 8

$('input').on('focus', function() {
    var $this = $(this)
        .one('mouseup.mouseupSelect', function() {
            $this.select();
            return false;
        })
        .one('mousedown', function() {
            // compensate for untriggered 'mouseup' caused by focus via tab
            $this.off('mouseup.mouseupSelect');
        })
        .select();
});

Replace input type=file by an image

I would use SWFUpload or Uploadify. They need Flash but do everything you want without troubles.

Any <input type="file"> based workaround that tries to trigger the "open file" dialog by means other than clicking on the actual control could be removed from browsers for security reasons at any time. (I think in the current versions of FF and IE, it is not possible any more to trigger that event programmatically.)

Resource leak: 'in' is never closed

You need call in.close(), in a finally block to ensure it occurs.

From the Eclipse documentation, here is why it flags this particular problem (emphasis mine):

Classes implementing the interface java.io.Closeable (since JDK 1.5) and java.lang.AutoCloseable (since JDK 1.7) are considered to represent external resources, which should be closed using method close(), when they are no longer needed.

The Eclipse Java compiler is able to analyze whether code using such types adheres to this policy.

...

The compiler will flag [violations] with "Resource leak: 'stream' is never closed".

Full explanation here.

Image convert to Base64

It's useful to work with Deferred Object in this case, and return promise:

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;
    if (files && files[0]) {
        var fr= new FileReader();
        fr.onload = function(e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL( files[0] );
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

And above function could be used in this way:

var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
    alert(base64Data);
});

Or in your case:

$(input).on('change',function(){
  readImage($(this)).done(function(base64Data){ alert(base64Data); });
});

How to get folder directory from HTML input type "file" or any other way?

Stumbled on this page as well, and then found out this is possible with just javascript (no plugins like ActiveX or Flash), but just in chrome:

https://plus.google.com/+AddyOsmani/posts/Dk5UhZ6zfF3

Basically, they added support for a new attribute on the file input element "webkitdirectory". You can use it like this:

<input type="file" id="ctrl" webkitdirectory directory multiple/>

It allows you to select directories. The multiple attribute is a good fallback for browsers that support multiple file selection but not directory selection.

When you select a directory the files are available through the dom object for the control (document.getElementById('ctrl')), just like they are with the multiple attribute. The browsers adds all files in the selected directory to that list recursively.

You can already add the directory attribute as well in case this gets standardized at some point (couldn't find any info regarding that)

change html input type by JS?

Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).

You’ll need to create a new input element, set its type to the one you want, and clone all other properties from the existing one.

I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84

To work in Internet Explorer:

  • dynamically create a new element
  • copy the properties of the old element into the new element
  • set the type of the new element to the new type
  • replace the old element with the new element

The function below accomplishes the above tasks for you:

<script>
function changeInputType(oldObject, oType) {
    var newObject = document.createElement('input');
    newObject.type = oType;
    if(oldObject.size) newObject.size = oldObject.size;
    if(oldObject.value) newObject.value = oldObject.value;
    if(oldObject.name) newObject.name = oldObject.name;
    if(oldObject.id) newObject.id = oldObject.id;
    if(oldObject.className) newObject.className = oldObject.className;
    oldObject.parentNode.replaceChild(newObject,oldObject);
    return newObject;
}
</script>

JavaScript: Check if mouse button down?

I think the best approach to this is to keep your own record of the mouse button state, as follows:

var mouseDown = 0;
document.body.onmousedown = function() { 
    mouseDown = 1;
}
document.body.onmouseup = function() {
    mouseDown = 0;
}

and then, later in your code:

if (mouseDown == 1) {
    // the mouse is down, do what you have to do.
}

remove inner shadow of text input

here is a small snippet that might be cool to try out:

input {
border-radius: 10px;
border-color: violet;
border-style: solid;
}

note that: border-style removes the inner shadow.

_x000D_
_x000D_
input {_x000D_
    border-radius: 10px;_x000D_
    border-color: violet;_x000D_
    border-style: solid;_x000D_
  }
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

Set Value of Input Using Javascript Function

Try

gadget_url.value=''

_x000D_
_x000D_
addGadgetUrl.addEventListener('click', () => {_x000D_
   gadget_url.value = '';_x000D_
});
_x000D_
<div>_x000D_
  <p>URL</p>_x000D_
  <input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input" value="some value" />_x000D_
  <input type="button" id="addGadgetUrl" value="add gadget" />_x000D_
  <br>_x000D_
  <span id="error"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Update

I don't know why so many downovotes (and no comments) - however (for future readers) don't think that this solution not work - It works with html provided in OP question and this is SHORTEST working solution - you can try it by yourself HERE

How to get an input text value in JavaScript

Do not use global variables in this way. Even if this could work, it's bad programming style. You can inadvertently overwrite important data in this way. Do this instead:

<script type="text/javascript">
   function kk(){
       var lol = document.getElementById('lolz').value;
       alert(lol);
   }
</script>

If you insist var lol to be set outside the function kk, then I propose this solution:

<body>
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" OnClick="kk()"/>
    <script type="text/javascript">
       var lol = document.getElementById('lolz');
       function kk() {
           alert(lol.value);
       }
    </script>
</body>

Note that the script element must follow the input element it refers to, because elements are only queryable with getElementById if they already have been parsed and created.

Both examples work, tested in jsfiddler.

Edit: I removed the language="javascript" attribute, because it's deprecated. See W3 HTML4 Specification, the SCRIPT element:

language = cdata [CI]

Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.

and

A deprecated element or attribute is one that has been outdated by newer constructs. […] Deprecated elements may become obsolete in future versions of HTML. […] This specification includes examples that illustrate how to avoid using deprecated elements. […]

Add padding to HTML text input field

padding-right works for me in Firefox/Chrome on Windows but not in IE. Welcome to the wonderful world of IE standards non-compliance.

See: http://jsfiddle.net/SfPju/466/

HTML

<input type="text" class="foo" value="abcdefghijklmnopqrstuvwxyz"/>

CSS

.foo
{
    padding-right: 20px;
}

HTML: How to make a submit button with text + image in it?

Let's say your image is a 16x16 .png icon called icon.png Use the power of CSS!

CSS:

input#image-button{
    background: #ccc url('icon.png') no-repeat top left;
    padding-left: 16px;
    height: 16px;
}

HTML:

<input type="submit" id="image-button" value="Text"></input>

This will put the image to the left of the text.

jQuery selector for inputs with square brackets in the name attribute

If the selector is contained within a variable, the code below may be helpful:

selector_name = $this.attr('name');
//selector_name = users[0][first:name]

escaped_selector_name = selector_name.replace(/(:|\.|\[|\])/g,'\\$1');
//escaped_selector_name = users\\[0\\]\\[first\\:name\\]

In this case we prefix all special characters with double backslash.

Using a PHP variable in a text input value = statement

I have been doing PHP for my project, and I can say that the following code works for me. You should try it.

echo '<input type = "text" value = '.$idtest.'>'; 

Is there a float input type in HTML5?

You can use:

<input type="number" step="any" min="0" max="100" value="22.33">

How to read keyboard-input?

try

raw_input('Enter your input:')  # If you use Python 2
input('Enter your input:')      # If you use Python 3

and if you want to have a numeric value just convert it:

try:
    mode=int(raw_input('Input:'))
except ValueError:
    print "Not a number"

Reading string from input with space character?

Here is an example of how you can get input containing spaces by using the fgets function.

#include <stdio.h>

int main()
{
    char name[100];
    printf("Enter your name: ");
    fgets(name, 100, stdin); 
    printf("Your Name is: %s", name);
    return 0;
}

How to get text of an input text box during onKeyPress?

There is a better way to do this. Use the concat Method. Example

declare a global variable. this works good on angular 10, just pass it to Vanilla JavaScript. Example:

HTML

<input id="edValue" type="text" onKeyPress="edValueKeyPress($event)"><br>
<span id="lblValue">The text box contains: </span>

CODE

emptyString = ''

edValueKeyPress ($event){
   this.emptyString = this.emptyString.concat($event.key);
   console.log(this.emptyString);
}

How do I see which checkbox is checked?

If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.

if (isset($_POST['mycheckbox'])) {
    echo "checked!";
}

Mobile Safari: Javascript focus() method on inputfield only works with click?

Please try using on-tap instead of ng-click event. I had this issue. I resolved it by making my clear-search-box button inside search form label and replaced ng-click of clear-button by on-tap. It works fine now.

Getting Keyboard Input

If you have Java 6 (You should have, btw) or higher, then simply do this :

 Console console = System.console();
 String str = console.readLine("Please enter the xxxx : ");

Please remember to do :

 import java.io.Console;

Thats it!

How to get the containing form of an input?

simply as:

alert( $(this.form).attr('name') );

File upload from <input type="file">

Try this small lib, works with Angular 5.0.0

Quickstart example with ng2-file-upload 1.3.0:

User clicks custom button, which triggers upload dialog from hidden input type="file" , uploading started automatically after selecting single file.

app.module.ts:

import {FileUploadModule} from "ng2-file-upload";

your.component.html:

...
  <button mat-button onclick="document.getElementById('myFileInputField').click()" >
    Select and upload file
  </button>
  <input type="file" id="myFileInputField" ng2FileSelect [uploader]="uploader" style="display:none">
...

your.component.ts:

import {FileUploader} from 'ng2-file-upload';
...    
uploader: FileUploader;
...
constructor() {
   this.uploader = new FileUploader({url: "/your-api/some-endpoint"});
   this.uploader.onErrorItem = item => {
       console.error("Failed to upload");
       this.clearUploadField();
   };
   this.uploader.onCompleteItem = (item, response) => {
       console.info("Successfully uploaded");
       this.clearUploadField();

       // (Optional) Parsing of response
       let responseObject = JSON.parse(response) as MyCustomClass;

   };

   // Asks uploader to start upload file automatically after selecting file
  this.uploader.onAfterAddingFile = fileItem => this.uploader.uploadAll();
}

private clearUploadField(): void {
    (<HTMLInputElement>window.document.getElementById('myFileInputField'))
    .value = "";
}

Alternative lib, works in Angular 4.2.4, but requires some workarounds to adopt to Angular 5.0.0

Get input value from TextField in iOS alert in Swift

Updated for Swift 3 and above:

//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.text = "Some default text"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.present(alert, animated: true, completion: nil)

Swift 2.x

Assuming you want an action alert on iOS:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

How to delete a specific line in a file?

I like this method using fileinput and the 'inplace' method:

import fileinput
for line in fileinput.input(fname, inplace =1):
    line = line.strip()
    if not 'UnwantedWord' in line:
        print(line)

It's a little less wordy than the other answers and is fast enough for

Clear input fields on form submit

Use the reset function, which is available on the form element.

var form = document.getElementById("myForm");
form.reset();

How to detect when cancel is clicked on file input?

function file_click() {
    document.body.onfocus = () => {
        setTimeout(_=>{
            let file_input = document.getElementById('file_input');
            if (!file_input.value) alert('please choose file ')
            else alert(file_input.value)
            document.body.onfocus = null
        },100)
    }
}

Using setTimeout to get the certain value of the input.

jquery how to empty input field

To reset text, number, search, textarea inputs:

$('#shares').val('');

To reset select:

$('#select-box').prop('selectedIndex',0);

To reset radio input:

$('#radio-input').attr('checked',false);

To reset file input:

$("#file-input").val(null);

Change input value onclick button - pure javascript or jQuery

Try This(Simple javascript):-

_x000D_
_x000D_
 <!DOCTYPE html>_x000D_
    <html>_x000D_
       <script>_x000D_
          function change(value){_x000D_
          document.getElementById("count").value= 500*value;_x000D_
          document.getElementById("totalValue").innerHTML= "Total price: $" + 500*value;_x000D_
          }_x000D_
          _x000D_
       </script>_x000D_
       <body>_x000D_
          Product price: $500_x000D_
          <br>_x000D_
          <div id= "totalValue">Total price: $500 </div>_x000D_
          <br>_x000D_
          <input type="button" onclick="change(2)" value="2&#x00A;Qty">_x000D_
          <input type="button" onclick="change(4)" value="4&#x00A;Qty">_x000D_
          <br>_x000D_
          Total <input type="text" id="count" value="1">_x000D_
       </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Hope this will help you..

jQuery: Get the cursor position of text in input without browser specific code?

Using the syntax text_element.selectionStart we can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.value and in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd.

Use it as follows:

<input type=text id=t1 value=abcd>
<button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>

I'm giving you the fiddle_demo

Java using scanner enter key pressed

Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        Double d = scan.nextDouble();


        String newStr = "";
        Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
        while( charScanner.hasNext() ) { 
            String  c = charScanner.next();

            if (c.equalsIgnoreCase("\r")) {
                break;
            }
            else {
                newStr += c;    
            }
        }

        System.out.println("String: " + newStr);
        System.out.println("Int: " + i);
        System.out.println("Double: " + d);

This code works fine

Phone mask with jQuery and Masked Input Plugin

With jquery.mask.js

http://jsfiddle.net/brynner/f9kd0aes/

HTML

<input type="text" class="phone" maxlength="15" value="85999998888">
<input type="text" class="phone" maxlength="15" value="8533334444">

JS

// Function
function phoneMask(e){
    var s=e.val();
    var s=s.replace(/[_\W]+/g,'');
    var n=s.length;
    if(n<11){var m='(00) 0000-00000';}else{var m='(00) 00000-00000';}
    $(e).mask(m);
}

// Type
$('body').on('keyup','.phone',function(){   
    phoneMask($(this));
});

// On load
$('.phone').keyup();

Only jQuery

http://jsfiddle.net/brynner/6vbrqe6z/

HTML

<p class="phone">85999998888</p>
<p class="phone">8599998888</p>

jQuery

$('.phone').text(function(i, text) {
    var n = (text.length)-6;
    if(n==4){var p=n;}else{var p=5;}
    var regex = new RegExp('(\\d{2})(\\d{'+p+'})(\\d{4})');
    var text = text.replace(regex, "($1) $2-$3");
    return text;
});

What does "for" attribute do in HTML <label> tag?

It labels whatever input is the parameter for the for attribute.

_x000D_
_x000D_
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
_x000D_
_x000D_

How to trigger HTML button when you press Enter in textbox?

Do not use Javascript for this!

Modern HTML pages automatically allow a form's submit button to submit the page with the ENTER/RETURN key when any form field control in the web page has focus by the user, autofocus attribute is set on a form field or button, or user tab's into any of the form fields.

So instead of Javascripting this, an easier solution is to add tabindex=0 on your form fields and button inside a form element then autofocus on the first input control. The user can then press "ENTER" to submit the form at any point as they enter data:

<form id="buttonform2" name="buttonform2" action="#" method="get" role="form">
  <label for="username1">Username</label>
  <input type="text" id="username1" name="username" value="" size="20" maxlength="20" title="Username" tabindex="0" autofocus="autofocus" />
  <label for="password1">Password</label>
  <input type="password" id="password1" name="password" size="20" maxlength="20" value="" title="Password" tabindex="0" role="textbox" aria-label="Password" />
  <button id="button2" name="button2" type="submit" value="submit" form="buttonform2" title="Submit" tabindex="0" role="button" aria-label="Submit">Submit</button>
</form>

CSS Input field text color of inputted text

replace:

input, select, textarea{
    color: #000;
}

with:

input, select, textarea{
    color: #f00;
}

or color: #ff0000;

More than 1 row in <Input type="textarea" />

As said by Sparky in comments on many answers to this question, there is NOT any textarea value for the type attribute of the input tag.

On other terms, the following markup is not valid :

<input type="textarea" />

And the browser replaces it by the default :

<input type="text" />

To define a multi-lines text input, use :

<textarea></textarea>

See the textarea element documentation for more details.

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

What's a Good Javascript Time Picker?

CSS Gallery has variety of Time Pickers. Have a look.

Perifer Design's time picker is similar to google one

Take a char input from the Scanner

You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.
Exmple :

    import java.util.Scanner;

    public class InputC{


            public static void main(String[] args) {
                // TODO Auto-generated method stub
                   // Declare the object and initialize with
                   // predefined standard input object
                    Scanner scanner = new Scanner(System.in);
                    System.out.println("Enter a character: ");
                    // Character input
                    char c = scanner.next().charAt(0);
                    // Print the read value
                    System.out.println("You have entered: "+c);
            }


        }

output

Enter a character: 
a
You have entered: a

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

If the question is: "Is it possible to add value on ESC" than the answer is yes. You can do something like that. For example with use of jQuery it would look like below.

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

<input type="text" value="default!" id="myInput" />

JavaScript

$(document).ready(function (){
    $('#myInput').keyup(function(event) {
        // 27 is key code of ESC
        if (event.keyCode == 27) {
            $('#myInput').val('default!');
            // Loose focus on input field
            $('#myInput').blur();
        }
    });
});

Working source can be found here: http://jsfiddle.net/S3N5H/1/

Please let me know if you meant something different, I can adjust the code later.

How to avoid pressing Enter with getchar() for reading a single character only?

I/O is an operating system function. In many cases, the operating system won't pass typed character to a program until ENTER is pressed. This allows the user to modify the input (such as backspacing and retyping) before sending it to the program. For most purposes, this works well, presents a consistent interface to the user, and relieves the program from having to deal with this. In some cases, it's desirable for a program to get characters from keys as they are pressed.

The C library itself deals with files, and doesn't concern itself with how data gets into the input file. Therefore, there's no way in the language itself to get keys as they are pressed; instead, this is platform-specific. Since you haven't specified OS or compiler, we can't look it up for you.

Also, the standard output is normally buffered for efficiency. This is done by the C libraries, and so there is a C solution, which is to fflush(stdout); after each character written. After that, whether the characters are displayed immediately is up to the operating system, but all the OSes I'm familiar with will display the output immediately, so that's not normally a problem.

How to change font-color for disabled input?

You could use the following style with opacity

input[disabled="disabled"], select[disabled="disabled"], textarea[disabled="disabled"] {
    opacity: 0.85 !important;
}

or a specific CSS class

.ui-state-disabled{
    opacity: 0.85 !important;
}

How to get the user input in Java?

You can make a simple program to ask for user's name and print what ever the reply use inputs.

Or ask user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like a behavior of a calculator.

So there you need Scanner class. You have to import java.util.Scanner; and in the code you need to use

Scanner input = new Scanner(System.in);

Input is a variable name.

Scanner input = new Scanner(System.in);

System.out.println("Please enter your name : ");
s = input.next(); // getting a String value

System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer

System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double

See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();

According to a String, int and a double varies same way for the rest. Don't forget the import statement at the top of your code.

Also see the blog post "Scanner class and getting User Inputs".

Can jQuery check whether input content has changed?

You can also store the initial value in a data attribute and check it against the current value.

<input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" /> 

$("#id_someid").keyup(function() {
    return $(this).val() == $(this).data().initial;
});

Would return true if the initial value has not changed.

How to make borders collapse (on a div)?

You could also use negative margins:

_x000D_
_x000D_
.column {_x000D_
  float: left;_x000D_
  overflow: hidden;_x000D_
  width: 120px;_x000D_
}_x000D_
.cell {_x000D_
  border: 1px solid red;_x000D_
  width: 120px;_x000D_
  height: 20px;_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
.cell:not(:first-child) {_x000D_
  margin-top: -1px;_x000D_
}_x000D_
.column:not(:first-child) > .cell {_x000D_
  margin-left: -1px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="column">_x000D_
    <div class="cell"></div>_x000D_
    <div class="cell"></div>_x000D_
    <div class="cell"></div>_x000D_
  </div>_x000D_
  <div class="column">_x000D_
    <div class="cell"></div>_x000D_
    <div class="cell"></div>_x000D_
    <div class="cell"></div>_x000D_
  </div>_x000D_
  <div class="column">_x000D_
    <div class="cell"></div>_x000D_
    <div class="cell"></div>_x000D_
    <div class="cell"></div>_x000D_
  </div>_x000D_
  <div class="column">_x000D_
    <div class="cell"></div>_x000D_
    <div class="cell"></div>_x000D_
    <div class="cell"></div>_x000D_
  </div>_x000D_
  <div class="column">_x000D_
    <div class="cell"></div>_x000D_
    <div class="cell"></div>_x000D_
    <div class="cell"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

I also encountered that. Changing "innodb_log_file_size","innodb_log_buffer_size" and the other settings in "my.ini" file did not solve my problem. I pass it by changing my column types "text" to varchar(20) and not using varchar values bigger than 20 . Maybe you can decrease the size of columns, too, if it possible. text--->varchar(20) varchar(256) --> varchar(20)

Pandas sum by groupby, but exclude certain columns

You can select the columns of a groupby:

In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
                       Y1961  Y1962  Y1963
Country     Item_Code
Afghanistan 15            10     20     30
            25            10     20     30
Angola      15            30     40     50
            25            30     40     50

Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.

Assign variable in if condition statement, good practice or not?

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===. For example, when you see this:

if (value = someFunction()) {
    ...
}

you don't know if that's what they meant to do, or if they intended to write this:

if (value == someFunction()) {
    ...
}

If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:

if ((value = someFunction()) === <whatever truthy value you are expecting>) {
    ...
}

Generate list of all possible permutations of a string

You are going to get a lot of strings, that's for sure...

\sum_{i=x}^y{\frac{r!}{{(r-i)}!}}
Where x and y is how you define them and r is the number of characters we are selecting from --if I am understanding you correctly. You should definitely generate these as needed and not get sloppy and say, generate a powerset and then filter the length of strings.

The following definitely isn't the best way to generate these, but it's an interesting aside, none-the-less.

Knuth (volume 4, fascicle 2, 7.2.1.3) tells us that (s,t)-combination is equivalent to s+1 things taken t at a time with repetition -- an (s,t)-combination is notation used by Knuth that is equal to {t \choose {s+t}. We can figure this out by first generating each (s,t)-combination in binary form (so, of length (s+t)) and counting the number of 0's to the left of each 1.

10001000011101 --> becomes the permutation: {0, 3, 4, 4, 4, 1}

Java ArrayList of Arrays?

  1. Create the ArrayList like ArrayList action.

    In JDK 1.5 or higher use ArrayList <string[]> reference name.

    In JDK 1.4 or lower use ArrayList reference name.

  2. Specify the access specifiers:

    • public, can be accessed anywhere
    • private, accessed within the class
    • protected, accessed within the class and different package subclasses
  3. Then specify the reference it will be assigned in

    action = new ArrayList<String[]>();
    
  4. In JVM new keyword will allocate memory in runtime for the object.

    You should not assigned the value where declared, because you are asking without fixed size.

  5. Finally you can be use the add() method in ArrayList. Use like

    action.add(new string[how much you need])
    

    It will allocate the specific memory area in heap.

Is it possible to embed animated GIFs in PDFs?

It's not really possible. You could, but if you're going to it would be useless without appropriate plugins. You'd be better using some other form. PDF's are used to have a consolidated output to printers and the screen, so animations won't work without other resources, and then it's not really a PDF.

Can I call methods in constructor in Java?

Can I put my method readConfig() into constructor?

Invoking a not overridable method in a constructor is an acceptable approach.
While if the method is only used by the constructor you may wonder if extracting it into a method (even private) is really required.

If you choose to extract some logic done by the constructor into a method, as for any method you have to choose a access modifier that fits to the method requirement but in this specific case it matters further as protecting the method against the overriding of the method has to be done at risk of making the super class constructor inconsistent.

So it should be private if it is used only by the constructor(s) (and instance methods) of the class.
Otherwise it should be both package-private and final if the method is reused inside the package or in the subclasses.

which would give me benefit of one time calling or is there another mechanism to do that ?

You don't have any benefit or drawback to use this way.
I don't encourage to perform much logic in constructors but in some cases it may make sense to init multiple things in a constructor.
For example the copy constructor may perform a lot of things.
Multiple JDK classes illustrate that.
Take for example the HashMap copy constructor that constructs a new HashMap with the same mappings as the specified Map parameter :

public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            resize();
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}

Extracting the logic of the map populating in putMapEntries() is a good thing because it allows :

  • reusing the method in other contexts. For example clone() and putAll() use it too
  • (minor but interesting) giving a meaningful name that conveys the performed logic

Tips for using Vim as a Java IDE?

I found the following summary very useful: http://www.techrepublic.com/article/configure-vi-for-java-application-development/5054618. The description of :make was for ant not maven, but otherwise a nice summary.

Best way to get child nodes

Don't let white space fool you. Just test this in a console browser.

Use native javascript. Here is and example with two 'ul' sets with the same class. You don't need to have your 'ul' list all in one line to avoid white space just use your array count to jump over white space.

How to get around white space with querySelector() then childNodes[] js fiddle link: https://jsfiddle.net/aparadise/56njekdo/

var y = document.querySelector('.list');
var myNode = y.childNodes[11].style.backgroundColor='red';

<ul class="list">
    <li>8</li>
    <li>9</li>
    <li>100</li>
</ul>

<ul class="list">
    <li>ABC</li>
    <li>DEF</li>
    <li>XYZ</li>
</ul>

How do I adb pull ALL files of a folder present in SD Card

If you want to pull a directory with restricted access from a rooted device you need to restart adb as root: type adb root before pull. Otherwise you'll get an error saying remote object '/data/data/xxx.example.app' does not exist

Instant run in Android Studio 2.0 (how to turn off)

I tried all above but nothing helps, at last i just figured out that under setting >> apps, device still has an entry for uninstalled application as disabled, i just uninstalled from there and it starts working.

:) might be useful for someone

Reading a file character by character in C

Either of the two should do the trick -

char *readFile(char *fileName)
{
  FILE *file;
  char *code = malloc(1000 * sizeof(char));
  char *p = code;
  file = fopen(fileName, "r");
  do 
  {
    *p++ = (char)fgetc(file);
  } while(*p != EOF);
  *p = '\0';
  return code;
}

char *readFile(char *fileName)
{
  FILE *file;
  int i = 0;
  char *code = malloc(1000 * sizeof(char));
  file = fopen(fileName, "r");
  do 
  {
    code[i++] = (char)fgetc(file);
  } while(code[i-1] != EOF);
  code[i] = '\0'
  return code;
}

Like the other posters have pointed out, you need to ensure that the file size does not exceed 1000 characters. Also, remember to free the memory when you're done using it.

How to interpolate variables in strings in JavaScript, without concatenation?

String.prototype.interpole = function () {
    var c=0, txt=this;
    while (txt.search(/{var}/g) > 0){
        txt = txt.replace(/{var}/, arguments[c]);
        c++;
    }
    return txt;
}

Uso:

var hello = "foo";
var my_string = "I pity the {var}".interpole(hello);
//resultado "I pity the foo"

How to use Python's "easy_install" on Windows ... it's not so easy

I also agree with the OP that all these things should come with Python already set. I guess we will have to deal with it until that day comes. Here is a solution that actually worked for me :

installing easy_install faster and easier

I hope it helps you or anyone with the same problem!

How to calculate time elapsed in bash script?

Bash has a handy SECONDS builtin variable that tracks the number of seconds that have passed since the shell was started. This variable retains its properties when assigned to, and the value returned after the assignment is the number of seconds since the assignment plus the assigned value.

Thus, you can just set SECONDS to 0 before starting the timed event, simply read SECONDS after the event, and do the time arithmetic before displaying.

SECONDS=0
# do some work
duration=$SECONDS
echo "$(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed."

As this solution doesn't depend on date +%s (which is a GNU extension), it's portable to all systems supported by Bash.

How to export data to CSV in PowerShell?

This solution creates a psobject and adds each object to an array, it then creates the csv by piping the contents of the array through Export-CSV.

$results = @()
foreach ($computer in $computerlist) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    {
        foreach ($file in $REMOVE) {
            Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
            Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"            
        }
    } else {

        $details = @{            
                Date             = get-date              
                ComputerName     = $Computer                 
                Destination      = $Destination 
        }                           
        $results += New-Object PSObject -Property $details  
    }
}
$results | export-csv -Path c:\temp\so.csv -NoTypeInformation

If you pipe a string object to a csv you will get its length written to the csv, this is because these are properties of the string, See here for more information.

This is why I create a new object first.

Try the following:

write-output "test" | convertto-csv -NoTypeInformation

This will give you:

"Length"
"4"

If you use the Get-Member on Write-Output as follows:

write-output "test" | Get-Member -MemberType Property

You will see that it has one property - 'length':

   TypeName: System.String

Name   MemberType Definition
----   ---------- ----------
Length Property   System.Int32 Length {get;}

This is why Length will be written to the csv file.


Update: Appending a CSV Not the most efficient way if the file gets large...

$csvFileName = "c:\temp\so.csv"
$results = @()
if (Test-Path $csvFileName)
{
    $results += Import-Csv -Path $csvFileName
}
foreach ($computer in $computerlist) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    {
        foreach ($file in $REMOVE) {
            Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
            Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"            
        }
    } else {

        $details = @{            
                Date             = get-date              
                ComputerName     = $Computer                 
                Destination      = $Destination 
        }                           
        $results += New-Object PSObject -Property $details  
    }
}
$results | export-csv -Path $csvFileName -NoTypeInformation

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

You can return a JSON with the URL and change the window.location using JavaScript at client side. I prefer this way than calling a JavaScript function from the server, which I think that it's breaking the separation of concerns.

Server side:

return Json(new {result = "Redirect", url = Url.Action("ActionName", "ControllerName")});

Client side:

if (response.result == 'Redirect')
    window.location = response.url;

Of course you can add more logic because there could be an error on the server side and in that case the result property could indicate this situation and avoid the redirection.

C++: constructor initializer for arrays

You can use C++0x auto keyword together with template specialization on for example a function named boost::make_array() (similar to make_pair()). For the case of where N is either 1 or 2 arguments we can then write variant A as

namespace boost
{
/*! Construct Array from @p a. */
template <typename T>
boost::array<T,1> make_array(const T & a)
{
    return boost::array<T,2> ({{ a }});
}
/*! Construct Array from @p a, @p b. */
template <typename T>
boost::array<T,2> make_array(const T & a, const T & b)
{
    return boost::array<T,2> ({{ a, b }});
}
}

and variant B as

namespace boost {
/*! Construct Array from @p a. */
template <typename T>
boost::array<T,1> make_array(const T & a)
{
    boost::array<T,1> x;
    x[0] = a;
    return x;
}
/*! Construct Array from @p a, @p b. */
template <typename T>
boost::array<T,2> make_array(const T & a, const T & b)
{
    boost::array<T,2> x;
    x[0] = a;
    x[1] = b;
    return x;
}
}

GCC-4.6 with -std=gnu++0x and -O3 generates the exact same binary code for

auto x = boost::make_array(1,2);

using both A and B as it does for

boost::array<int, 2> x = {{1,2}};

For user defined types (UDT), though, variant B results in an extra copy constructor, which usually slow things down, and should therefore be avoided.

Note that boost::make_array errors when calling it with explicit char array literals as in the following case

auto x = boost::make_array("a","b");

I believe this is a good thing as const char* literals can be deceptive in their use.

Variadic templates, available in GCC since 4.5, can further be used reduce all template specialization boiler-plate code for each N into a single template definition of boost::make_array() defined as

/*! Construct Array from @p a, @p b. */
template <typename T, typename ... R>
boost::array<T,1+sizeof...(R)> make_array(T a, const R & ... b)
{
    return boost::array<T,1+sizeof...(R)>({{ a, b... }});
}

This works pretty much as we expect. The first argument determines boost::array template argument T and all other arguments gets converted into T. For some cases this may undesirable, but I'm not sure how if this is possible to specify using variadic templates.

Perhaps boost::make_array() should go into the Boost Libraries?

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

Make sure that the htaccess file is readable by apache:

chmod 644 /var/www/abc/.htaccess 

And make sure the directory it's in is readable and executable:

chmod 755 /var/www/abc/

What does <T> (angle brackets) mean in Java?

<T> is a generic and can usually be read as "of type T". It depends on the type to the left of the <> what it actually means.

I don't know what a Pool or PoolFactory is, but you also mention ArrayList<T>, which is a standard Java class, so I'll talk to that.

Usually, you won't see "T" in there, you'll see another type. So if you see ArrayList<Integer> for example, that means "An ArrayList of Integers." Many classes use generics to constrain the type of the elements in a container, for example. Another example is HashMap<String, Integer>, which means "a map with String keys and Integer values."

Your Pool example is a bit different, because there you are defining a class. So in that case, you are creating a class that somebody else could instantiate with a particular type in place of T. For example, I could create an object of type Pool<String> using your class definition. That would mean two things:

  • My Pool<String> would have an interface PoolFactory<String> with a createObject method that returns Strings.
  • Internally, the Pool<String> would contain an ArrayList of Strings.

This is great news, because at another time, I could come along and create a Pool<Integer> which would use the same code, but have Integer wherever you see T in the source.

How to reset AUTO_INCREMENT in MySQL?

I tried to alter the table and set auto_increment to 1 but it did not work. I resolved to delete the column name I was incrementing, then create a new column with your preferred name and set that new column to increment from the onset.

How to get selected value of a dropdown menu in ReactJS

Implement your Dropdown as

<select id = "dropdown" ref = {(input)=> this.menu = input}>
    <option value="N/A">N/A</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

Now, to obtain the selected option value of the dropdown menu just use:

let res = this.menu.value;

$watch'ing for data changes in an Angular directive

Because if you want to trigger your data with deep of it,you have to pass 3th argument true of your listener.By default it's false and it meens that you function will trigger,only when your variable will change not it's field.

How to check encoding of a CSV file

Or you can execute in python console or in Jupyter Notebook:

import csv
data = open("file.csv","r") 
data

You will see information about the data object like this:

<_io.TextIOWrapper name='arch.csv' mode='r' encoding='cp1250'>

As you can see it contains encoding infotmation.

Easiest way to mask characters in HTML(5) text input

A little late, but a useful plugin that will actually use a mask to give a bit more restriction on user input.

<div class="col-sm-3 col-md-6 col-lg-4">
  <div class="form-group">
     <label for="addPhone">Phone Number *</label>
      <input id="addPhone" name="addPhone" type="text" class="form-control 
       required" data-mask="(999) 999-9999"placeholder>
    <span class="help-block">(999) 999-9999</span>
  </div>
</div>

 <!-- Input Mask -->
 <script src="js/plugins/jasny/jasny-bootstrap.min.js"></script>

enter image description here

More info on the plugin https://www.jasny.net/bootstrap/2.3.1/javascript.html#inputmask

How to run Java program in terminal with external library JAR

For compiling the java file having dependency on a jar

javac -cp path_of_the_jar/jarName.jar className.java

For executing the class file

java -cp .;path_of_the_jar/jarName.jar className

Efficient way to return a std::vector in c++

A common pre-C++11 idiom is to pass a reference to the object being filled.

Then there is no copying of the vector.

void f( std::vector & result )
{
  /*
    Insert elements into result
  */
} 

Time comparison

I am using this class for time in this format "hh:mm:ss" u can use it with "hh:mm:00" (zero seconds) for your example. Here is the complete code. It has compare and between function and also checks the time format (in case of invalid time and throws TimeException). Hope you can use it or modify it for your needs.

Time class:

package es.utility.time;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author adrian
 */
public class Time {

    private int hours; //Hours of the day
    private int minutes; //Minutes of the day
    private int seconds; //Seconds of the day
    private String time; //Time of the day

    /**
     * Constructor of Time class
     *
     * @param time
     * @throws TimeException if time parameter is not valid
     */
    public Time(String time) throws TimeException {
        //Check if valid time
        if (!validTime(time)) {
            throw new TimeException();
        }
        //Init class parametars
        String[] params = time.split(":");
        this.time = time;
        this.hours = Integer.parseInt(params[0]);
        this.minutes = Integer.parseInt(params[1]);
        this.seconds = Integer.parseInt(params[2]);
    }

    /**
     * Constructor of Time class
     *
     * @param hours
     * @param minutes
     * @param seconds
     * @throws TimeException if time parameter is not valid
     */
    public Time(int hours, int minutes, int seconds) throws TimeException {
        //Check if valid time
        if (!validTime(hours, minutes, seconds)) {
            throw new TimeException();
        }
        this.time = timeToString(hours, minutes, seconds);
        this.hours = hours;
        this.minutes = minutes;
        this.seconds = seconds;

    }

    /**
     * Checks if the sting can be parsed as time
     *
     * @param time (correct from hh:mm:ss)
     * @return true if ok <br/> false if not ok
     */
    private boolean validTime(String time) {
        String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(time);
        return m.matches();
    }

    /**
     * Checks if the sting can be parsed as time
     *
     * @param hours hours
     * @param minutes minutes
     * @param seconds seconds
     * @return true if ok <br/> false if not ok
     */
    private boolean validTime(int hours, int minutes, int seconds) {
        return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59 && seconds >= 0 && seconds <= 59;
    }

    /**
     * From Integer values to String time
     *
     * @param hours
     * @param minutes
     * @param seconds
     * @return String generated from int values for hours minutes and seconds
     */
    private String timeToString(int hours, int minutes, int seconds) {
        StringBuilder timeBuilder = new StringBuilder("");
        if (hours < 10) {
            timeBuilder.append("0").append(hours);
        } else {
            timeBuilder.append(hours);
        }
        timeBuilder.append(":");
        if (minutes < 10) {
            timeBuilder.append("0").append(minutes);
        } else {
            timeBuilder.append(minutes);
        }
        timeBuilder.append(":");
        if (seconds < 10) {
            timeBuilder.append("0").append(seconds);
        } else {
            timeBuilder.append(seconds);
        }
        return timeBuilder.toString();
    }

    /**
     * Compare this time to other
     *
     * @param compare
     * @return -1 time is before <br/> 0 time is equal <br/> time is after
     */
    public int compareTime(Time compare) {
        //Check hours
        if (this.getHours() < compare.getHours()) { //If hours are before return -1
            return -1;
        }
        if (this.getHours() > compare.getHours()) { //If hours are after return 1
            return 1;
        }
        //If no return hours are equeal
        //Check minutes
        if (this.getMinutes() < compare.getMinutes()) { //If minutes are before return -1
            return -1;
        }
        if (this.getMinutes() > compare.getMinutes()) { //If minutes are after return 1
            return 1;
        }
        //If no return minutes are equeal
        //Check seconds
        if (this.getSeconds() < compare.getSeconds()) { //If minutes are before return -1
            return -1;
        }
        if (this.getSeconds() > compare.getSeconds()) { //If minutes are after return 1
            return 1;
        }
        //If no return seconds are equeal and return 0
        return 0;
    }

    public boolean isBetween(Time before, Time after) throws TimeException{
        if(before.compareTime(after)== 1){
            throw new TimeException("Time 'before' is after 'after' time");
        }
        //Compare with before and after
        if (this.compareTime(before) == -1 || this.compareTime(after) == 1) { //If time is before before time return false or time is after after time
            return false;
        } else {
            return true;
        }
    }

    public int getHours() {
        return hours;
    }

    public void setHours(int hours) {
        this.hours = hours;
    }

    public int getMinutes() {
        return minutes;
    }

    public void setMinutes(int minutes) {
        this.minutes = minutes;
    }

    public int getSeconds() {
        return seconds;
    }

    public void setSeconds(int seconds) {
        this.seconds = seconds;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    /**
     * Override the toString method and return all of the class private
     * parameters
     *
     * @return String Time{" + "hours=" + hours + ", minutes=" + minutes + ",
     * seconds=" + seconds + ", time=" + time + '}'
     */
    @Override
    public String toString() {
        return "Time{" + "hours=" + hours + ", minutes=" + minutes + ", seconds=" + seconds + ", time=" + time + '}';
    }

}

TimeException class:

package es.utility.time;

/**
 *
 * @author adrian
 */
public class TimeException extends Exception {

    public TimeException() {
        super("Cannot create time with this params");
    }

    public TimeException(String message) {
        super(message);
    }

}

How to allow only one radio button to be checked?

Add "name" attribute and keep the name same for all the radio buttons in a form.

i.e.,

<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3

Hope that would help.

jQuery if Element has an ID?

You can do this:

if ($(".parent a[Id]").length > 0) {

    /* then do something here */

}

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

instead of

 http://localhost/xampp/htdocs/index.html

try just

http://localhost/index.html

or if index.html is saved in a folder in htdocs then

http://localhost/<folder-name>/index.html

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

In my case the NDEBUG macro definition in the "Preprocessor Definitions" needed to be changed to _DEBUG. I am building a static library for use in a .exe which was complaining about the very same error listed in the question. Go to Configuration Properties ("Project" menu, "Properties" menu item) and then click the C/C++, section, then the Preprocessor section under that, and then edit your Preprocessor Definitions so that NDEBUG is changed to _DEBUG (to match the setting in the exe).

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

T-SQL: How to Select Values in Value List that are NOT IN the Table?

You need to somehow create a table with these values and then use NOT IN. This can be done with a temporary table, a CTE (Common Table Expression) or a Table Values Constructor (available in SQL-Server 2008):

SELECT email
FROM
    ( VALUES 
        ('email1')
      , ('email2')
      , ('email3')
    ) AS Checking (email)
WHERE email NOT IN 
      ( SELECT email 
        FROM Users
      ) 

The second result can be found with a LEFT JOIN or an EXISTS subquery:

SELECT email
     , CASE WHEN EXISTS ( SELECT * 
                          FROM Users u
                          WHERE u.email = Checking.email
                        ) 
            THEN 'Exists'
            ELSE 'Not exists'
       END AS status 
FROM
    ( VALUES 
        ('email1')
      , ('email2')
      , ('email3')
    ) AS Checking (email)

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

Error when deploying an artifact in Nexus

For 400 error, check the repository "Deployment policy" usually its "Disable redeploy". Most of the time your library version is already there that is why you received a message "Could not PUT put 'https://yoururl/some.jar'. Received status code 400 from server: Repository does not allow updating assets: "your repository name"

So, you have a few options to resolve this. 1- allow redeploy 2- delete the version from your repository which you are trying to upload 3- change the version number

C char array initialization

The relevant part of C11 standard draft n1570 6.7.9 initialization says:

14 An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

and

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Thus, the '\0' is appended, if there is enough space, and the remaining characters are initialized with the value that a static char c; would be initialized within a function.

Finally,

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

[--]

  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;

[--]

Thus, char being an arithmetic type the remainder of the array is also guaranteed to be initialized with zeroes.

Wildcards in jQuery selectors

Try the jQuery starts-with

selector, '^=', eg

[id^="jander"]

I have to ask though, why don't you want to do this using classes?

How to implement and do OCR in a C# project?

Some online API's work pretty well: ocr.space and Google Cloud Vision. Both of these are free, as long as you do less than 1000 OCR's per month. You can drag & drop an image to do a quick manual test to see how they perform for your images.

I find OCR.space easier to use (no messing around with nuget libraries), but, for my purpose, Google Cloud Vision provided slightly better results than OCR.space.

Google Cloud Vision example:

GoogleCredential cred = GoogleCredential.FromJson(json);
Channel channel = new Channel(ImageAnnotatorClient.DefaultEndpoint.Host, ImageAnnotatorClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
ImageAnnotatorClient client = ImageAnnotatorClient.Create(channel);
Image image = Image.FromStream(stream);

EntityAnnotation googleOcrText = client.DetectText(image).First();
Console.Write(googleOcrText.Description);

OCR.space example:

string uri = $"https://api.ocr.space/parse/imageurl?apikey=helloworld&url={imageUri}";
string responseString = WebUtilities.DoGetRequest(uri);
OcrSpaceResult result = JsonConvert.DeserializeObject<OcrSpaceResult>(responseString);
if ((!result.IsErroredOnProcessing) && !String.IsNullOrEmpty(result.ParsedResults[0].ParsedText))
  return result.ParsedResults[0].ParsedText;

Is there a Java equivalent or methodology for the typedef keyword in C++?

You could use an Enum, although that's semantically a bit different than a typedef in that it only allows a restricted set of values. Another possible solution is a named wrapper class, e.g.

public class Apple {
      public Apple(Integer i){this.i=i; }
}

but that seems way more clunky, especially given that it's not clear from the code that the class has no other function than as an alias.

Remove Server Response Header IIS7

Actually the coded modules and the Global.asax examples shown above only work for valid requests.

For example, add < on the end of your URL and you will get a "Bad request" page which still exposes the server header. A lot of developers overlook this.

The registry settings shown do not work either. URLScan is the ONLY way to remove the "server" header (at least in IIS 7.5).

Keeping ASP.NET Session Open / Alive

If you are using ASP.NET MVC – you do not need an additional HTTP handler and some modifications of the web.config file. All you need – just to add some simple action in a Home/Common controller:

[HttpPost]
public JsonResult KeepSessionAlive() {
    return new JsonResult {Data = "Success"};
}

, write a piece of JavaScript code like this one (I have put it in one of site’s JavaScript file):

var keepSessionAlive = false;
var keepSessionAliveUrl = null;

function SetupSessionUpdater(actionUrl) {
    keepSessionAliveUrl = actionUrl;
    var container = $("#body");
    container.mousemove(function () { keepSessionAlive = true; });
    container.keydown(function () { keepSessionAlive = true; });
    CheckToKeepSessionAlive();
}

function CheckToKeepSessionAlive() {
    setTimeout("KeepSessionAlive()", 5*60*1000);
}

function KeepSessionAlive() {
    if (keepSessionAlive && keepSessionAliveUrl != null) {
        $.ajax({
            type: "POST",
            url: keepSessionAliveUrl,
            success: function () { keepSessionAlive = false; }
        });
    }
    CheckToKeepSessionAlive();
}

, and initialize this functionality by calling a JavaScript function:

SetupSessionUpdater('/Home/KeepSessionAlive');

Please note! I have implemented this functionality only for authorized users (there is no reason to keep session state for guests in most cases) and decision to keep session state active is not only based on – is browser open or not, but authorized user must do some activity on the site (move a mouse or type some key).

Angular 2: 404 error occur when I refresh through the browser

For people reading this that use Angular 2 rc4 or later, it appears LocationStrategy has been moved from router to common. You'll have to import it from there.

Also note the curly brackets around the 'provide' line.

main.ts

// Imports for loading & configuring the in-memory web api
import { XHRBackend } from '@angular/http';

// The usual bootstrapping imports
import { bootstrap }      from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent }         from './app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
import { Location, LocationStrategy, HashLocationStrategy} from '@angular/common';

bootstrap(AppComponent, [
    APP_ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

Query based on multiple where clauses in Firebase

I've written a personal library that allows you to order by multiple values, with all the ordering done on the server.

Meet Querybase!

Querybase takes in a Firebase Database Reference and an array of fields you wish to index on. When you create new records it will automatically handle the generation of keys that allow for multiple querying. The caveat is that it only supports straight equivalence (no less than or greater than).

const databaseRef = firebase.database().ref().child('people');
const querybaseRef = querybase.ref(databaseRef, ['name', 'age', 'location']);

// Automatically handles composite keys
querybaseRef.push({ 
  name: 'David',
  age: 27,
  location: 'SF'
});

// Find records by multiple fields
// returns a Firebase Database ref
const queriedDbRef = querybaseRef
 .where({
   name: 'David',
   age: 27
 });

// Listen for realtime updates
queriedDbRef.on('value', snap => console.log(snap));

How do I get current scope dom-element in AngularJS controller?

The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element to do DOM operations. The method defined in the directive controller is accessible in the main controller.

Example, finding a child element:

var app = angular.module('myapp', []);
app.directive("testDir", function () {
    function link(scope, element) { 

    }
    return {
        restrict: "AE", 
        link: link, 
        controller:function($scope,$element){
            $scope.name2 = 'this is second name';
            var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
    }
    };
})

app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});

Delete empty rows

If you are trying to delete empty spaces , try using ='' instead of is null. Hence , if your row contains empty spaces , is null will not capture those records. Empty space is not null and null is not empty space.

Dec  Hex     Binary    Char-acter Description
0    00  00000000      NUL        null

32  20  00100000      Space       space

So I recommend:

delete  from foo_table  where bar = ''

#or 

delete  from foo_table  where bar = '' or bar is null 

#or even better , 

delete from foo_table where rtrim(ltrim(isnull(bar,'')))='';

Why would one mark local variables and method parameters as "final" in Java?

Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.

Finalizing local var's seems somewhat overkill IMO.

Python "extend" for a dictionary

A beautiful gem in this closed question:

The "oneliner way", altering neither of the input dicts, is

basket = dict(basket_one, **basket_two)

Learn what **basket_two (the **) means here.

In case of conflict, the items from basket_two will override the ones from basket_one. As one-liners go, this is pretty readable and transparent, and I have no compunction against using it any time a dict that's a mix of two others comes in handy (any reader who has trouble understanding it will in fact be very well served by the way this prompts him or her towards learning about dict and the ** form;-). So, for example, uses like:

x = mungesomedict(dict(adict, **anotherdict))

are reasonably frequent occurrences in my code.

Originally submitted by Alex Martelli

Note: In Python 3, this will only work if every key in basket_two is a string.

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

How to stop EditText from gaining focus at Activity startup in Android

Make sure to remove the line "<requestFocus />" from the EditText tag in xml.

<EditText
   android:id="@+id/input"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content">

   <requestFocus /> <!-- remove this line --> 
</EditText>

Do you need to dispose of objects and set them to null?

Normally, there's no need to set fields to null. I'd always recommend disposing unmanaged resources however.

From experience I'd also advise you to do the following:

  • Unsubscribe from events if you no longer need them.
  • Set any field holding a delegate or an expression to null if it's no longer needed.

I've come across some very hard to find issues that were the direct result of not following the advice above.

A good place to do this is in Dispose(), but sooner is usually better.

In general, if a reference exists to an object the garbage collector (GC) may take a couple of generations longer to figure out that an object is no longer in use. All the while the object remains in memory.

That may not be a problem until you find that your app is using a lot more memory than you'd expect. When that happens, hook up a memory profiler to see what objects are not being cleaned up. Setting fields referencing other objects to null and clearing collections on disposal can really help the GC figure out what objects it can remove from memory. The GC will reclaim the used memory faster making your app a lot less memory hungry and faster.

PostgreSQL delete all content

For small tables DELETE is often faster and needs less aggressive locking (for heavy concurrent load):

DELETE FROM tbl;

With no WHERE condition.

For medium or bigger tables, go with TRUNCATE tbl, like @Greg posted.

Python: Writing to and Reading from serial port

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

How do I create dynamic variable names inside a loop?

Use an array for this.

var markers = [];
for (var i = 0; i < coords.length; ++i) {
    markers[i] = "some stuff";
}

How to automatically add user account AND password with a Bash script?

I've tested in my own shell script.

  • $new_username means newly created user
  • $new_password means newly password

For CentOS

echo "$new_password" | passwd --stdin "$new_username"

For Debian/Ubuntu

echo "$new_username:$new_password" | chpasswd

For OpenSUSE

echo -e "$new_password\n$new_password" | passwd "$new_username"

Git: How to find a deleted file in the project commit history?

Here is my solution:

git log --all --full-history --oneline -- <RELATIVE_FILE_PATH>
git checkout <COMMIT_SHA>^ -- <RELATIVE_FILE_PATH>

Linux command for extracting war file?

You can use the unzip command.

password-check directive in angularjs

As of angular 1.3.0-beta12, invalid inputs don't write to ngModel, so you can't watch AND THEN validate as you can see here: http://plnkr.co/edit/W6AFHF308nyKVMQ9vomw?p=preview. A new validators pipeline was introduced and you can attach to this to achieve the same thing.

Actually, on that note I've created a bower component for common extra validators: https://github.com/intellix/angular-validators which includes this.

angular.module('validators').directive('equals', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel)
        {
            if (!ngModel) return;

            attrs.$observe('equals', function() {
                ngModel.$validate();
            });

            ngModel.$validators.equals = function(value) {
                return value === attrs.equals;
            };
        }
    };
});

angular.module('validators').directive('notEquals', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel)
        {
            if (!ngModel) return;

            attrs.$observe('notEquals', function() {
                ngModel.$validate();
            });

            ngModel.$validators.notEquals = function(value) {
                return value === attrs.notEquals;
            };
        }
    };
});

How to vertically align text with icon font?

Add this to your CSS:

.menu i.large.icon,
.menu i.large.basic.icon {
    vertical-align:baseline;
}

DEMO

How to change text color of cmd with windows batch script every 1 second

echo off & cls
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F
for %%y in (%NUM%) do ( 
    for %%x in (%NUM%) do (
        color %%y%%x & for /l %%A in (1,1,200) do (dir /s)
        timeout 1 >nul
    )
)
pause

Find distance between two points on map using Google Map API V2

Coming rather late, but seeing that this is one of the top results on Google search for the topic I'll share another way:

Use a one-liner with Googles utility class SphericalUtil

SphericalUtil.computeDistanceBetween(latLngFrom, latLngTo)

You will need the utility classes.

You can simply include them in your project using gradle:

implementation 'com.google.maps.android:android-maps-utils:0.5+'

Short circuit Array.forEach like calling break

If you need to break based on the value of elements that are already in your array as in your case (i.e. if break condition does not depend on run-time variable that may change after array is assigned its element values) you could also use combination of slice() and indexOf() as follows.

If you need to break when forEach reaches 'Apple' you can use

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var fruitsToLoop = fruits.slice(0, fruits.indexOf("Apple"));
// fruitsToLoop = Banana,Orange,Lemon

fruitsToLoop.forEach(function(el) {
    // no need to break
});

As stated in W3Schools.com the slice() method returns the selected elements in an array, as a new array object. The original array will not be changed.

See it in JSFiddle

Hope it helps someone.

What is the purpose of Order By 1 in SQL select statement?

This will sort your results by the first column returned. In the example it will sort by payment_date.

C dynamically growing array

Well, I guess if you need to remove an element you will make a copy of the array despising the element to be excluded.

// inserting some items
void* element_2_remove = getElement2BRemove();

for (int i = 0; i < vector->size; i++){
       if(vector[i]!=element_2_remove) copy2TempVector(vector[i]);
       }

free(vector->items);
free(vector);
fillFromTempVector(vector);
//

Assume that getElement2BRemove(), copy2TempVector( void* ...) and fillFromTempVector(...) are auxiliary methods to handle the temp vector.

Difference between == and ===

>>> is unsigned-shift; it'll insert 0. >> is signed, and will extend the sign bit.

JLS 15.19 Shift Operators

The shift operators include left shift <<, signed right shift >>, and unsigned right shift >>>.

The value of n>>s is n right-shifted s bit positions with sign-extension.

The value of n>>>s is n right-shifted s bit positions with zero-extension.

    System.out.println(Integer.toBinaryString(-1));
    // prints "11111111111111111111111111111111"
    System.out.println(Integer.toBinaryString(-1 >> 16));
    // prints "11111111111111111111111111111111"
    System.out.println(Integer.toBinaryString(-1 >>> 16));
    // prints "1111111111111111"

To make things more clear adding positive counterpart

System.out.println(Integer.toBinaryString(121));
// prints "1111001"
System.out.println(Integer.toBinaryString(121 >> 1));
// prints "111100"
System.out.println(Integer.toBinaryString(121 >>> 1));
// prints "111100"

Since it is positive both signed and unsigned shifts will add 0 to left most bit.

Related questions

No route matches "/users/sign_out" devise rails 3

Many answers to the question already. For me the problem was two fold:

  1. when I expand my routes:

    devise_for :users do 
       get '/users/sign_out' => 'devise/sessions#destroy'
    end
    
  2. I was getting warning that this is depreciated so I have replaced it with:

    devise_scope :users do
       get '/users/sign_out' => 'devise/sessions#destroy'
    end
    
  3. I thought I will remove my jQuery. Bad choice. Devise is using jQuery to "fake" DELETE request and send it as GET. Therefore you need to:

    //= require jquery
    //= require jquery_ujs
    
  4. and of course same link as many mentioned before:

    <%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
    

Simplest way to merge ES6 Maps/Sets?

Edit:

I benchmarked my original solution against other solutions suggests here and found that it is very inefficient.

The benchmark itself is very interesting (link) It compares 3 solutions (higher is better):

  • @fregante (formerly called @bfred.it) solution, which adds values one by one (14,955 op/sec)
  • @jameslk's solution, which uses a self invoking generator (5,089 op/sec)
  • my own, which uses reduce & spread (3,434 op/sec)

As you can see, @fregante's solution is definitely the winner.

Performance + Immutability

With that in mind, here's a slightly modified version which doesn't mutates the original set and excepts a variable number of iterables to combine as arguments:

function union(...iterables) {
  const set = new Set();

  for (const iterable of iterables) {
    for (const item of iterable) {
      set.add(item);
    }
  }

  return set;
}

Usage:

const a = new Set([1, 2, 3]);
const b = new Set([1, 3, 5]);
const c = new Set([4, 5, 6]);

union(a,b,c) // {1, 2, 3, 4, 5, 6}

Original Answer

I would like to suggest another approach, using reduce and the spread operator:

Implementation

function union (sets) {
  return sets.reduce((combined, list) => {
    return new Set([...combined, ...list]);
  }, new Set());
}

Usage:

const a = new Set([1, 2, 3]);
const b = new Set([1, 3, 5]);
const c = new Set([4, 5, 6]);

union([a, b, c]) // {1, 2, 3, 4, 5, 6}

Tip:

We can also make use of the rest operator to make the interface a bit nicer:

function union (...sets) {
  return sets.reduce((combined, list) => {
    return new Set([...combined, ...list]);
  }, new Set());
}

Now, instead of passing an array of sets, we can pass an arbitrary number of arguments of sets:

union(a, b, c) // {1, 2, 3, 4, 5, 6}

Can two Java methods have same name with different return types?

You can have two methods with the same arguments and different return types only if one of the methods is inherited and the return types are compatible.

For example:

public class A
{
    Object foo() { return null; }
}

public class B
    extends A
{
    String foo() { return null; }
}

how to toggle (hide/show) a table onClick of <a> tag in java script

visibility property makes the element visible or invisible.

function showTable(){
    document.getElementById('table').style.visibility = "visible";
}
function hideTable(){
    document.getElementById('table').style.visibility = "hidden";
}

Making a button invisible by clicking another button in HTML

write this

To hide

{document.getElementById("p2").style.display="none";}

to show

{document.getElementById("p2").style.display="block";}

Using `date` command to get previous, current and next month

the main problem occur when you don't have date --date option available and you don't have permission to install it, then try below -

Previous month
#cal -3|awk 'NR==1{print toupper(substr($1,1,3))"-"$2}'
DEC-2016 
Current month
#cal -3|awk 'NR==1{print toupper(substr($3,1,3))"-"$4}'
JAN-2017
Next month
#cal -3|awk 'NR==1{print toupper(substr($5,1,3))"-"$6}'
FEB-2017

col align right

From the documentation, you do it like:

<div class="row">
    <div class="col-md-6">left</div>
    <div class="col-md-push-6">content needs to be right aligned</div>
</div>

Docs

Batch file include external file for variables

Kinda old subject but I had same question a few days ago and I came up with another idea (maybe someone will still find it usefull)

For example you can make a config.bat with different subjects (family, size, color, animals) and apply them individually in any order anywhere you want in your batch scripts:

@echo off
rem Empty the variable to be ready for label config_all
set config_all_selected=

rem Go to the label with the parameter you selected
goto :config_%1

REM This next line is just to go to end of file 
REM in case that the parameter %1 is not set
goto :end

REM next label is to jump here and get all variables to be set
:config_all
set config_all_selected=1


:config_family
set mother=Mary
set father=John
set sister=Anna
rem This next line is to skip going to end if config_all label was selected as parameter
if not "%config_all_selected%"=="1" goto :end

:config_test
set "test_parameter_all=2nd set: The 'all' parameter WAS used before this echo"
if not "%config_all_selected%"=="1" goto :end

:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end


:config_color
set first_color=blue
set second_color=green
if not "%config_all_selected%"=="1" goto :end


:config_animals
set dog=Max
set cat=Miau
if not "%config_all_selected%"=="1" goto :end


:end

After that, you can use it anywhere by calling fully with 'call config.bat all' or calling only parts of it (see example bellow) The idea in here is that sometimes is more handy when you have the option not to call everything at once. Some variables maybe you don't want to be called yet so you can call them later.

Example test.bat

@echo off

rem This is added just to test the all parameter
set "test_parameter_all=1st set: The 'all' parameter was NOT used before this echo"

call config.bat size

echo My birthday present had a width of %width% and a height of %height%

call config.bat family
call config.bat animals

echo Yesterday %father% and %mother% surprised %sister% with a cat named %cat%
echo Her brother wanted the dog %dog%

rem This shows you if the 'all' parameter was or not used (just for testing)
echo %test_parameter_all%

call config.bat color

echo His lucky color is %first_color% even if %second_color% is also nice.

echo.
pause

Hope it helps the way others help me in here with their answers.

A short version of the above:

config.bat

@echo off
set config_all_selected=
goto :config_%1
goto :end

:config_all
set config_all_selected=1

:config_family
set mother=Mary
set father=John
set daughter=Anna
if not "%config_all_selected%"=="1" goto :end

:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end

:end

test.bat

@echo off

call config.bat size
echo My birthday present had a width of %width% and a height of %height%

call config.bat family
echo %father% and %mother% have a daughter named %daughter%

echo.
pause

Good day.

How can I view live MySQL queries?

You can run the MySQL command SHOW FULL PROCESSLIST; to see what queries are being processed at any given time, but that probably won't achieve what you're hoping for.

The best method to get a history without having to modify every application using the server is probably through triggers. You could set up triggers so that every query run results in the query being inserted into some sort of history table, and then create a separate page to access this information.

Do be aware that this will probably considerably slow down everything on the server though, with adding an extra INSERT on top of every single query.


Edit: another alternative is the General Query Log, but having it written to a flat file would remove a lot of possibilities for flexibility of displaying, especially in real-time. If you just want a simple, easy-to-implement way to see what's going on though, enabling the GQL and then using running tail -f on the logfile would do the trick.

<select> HTML element with height

You can also "center" the text with:

vertical-align: middle;

Change the column label? e.g.: change column "A" to column "Name"

If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok

When is the init() function run?

mutil init function in one package execute order:

  1. const and variable defined file init() function execute

  2. init function execute order by the filename asc

How to check if a date is in a given range?

Use the DateTime class if you have PHP 5.3+. Easier to use, better functionality.

DateTime internally supports timezones, with the other solutions is up to you to handle that.

<?php    
/**
 * @param DateTime $date Date that is to be checked if it falls between $startDate and $endDate
 * @param DateTime $startDate Date should be after this date to return true
 * @param DateTime $endDate Date should be before this date to return true
 * return bool
 */
function isDateBetweenDates(DateTime $date, DateTime $startDate, DateTime $endDate) {
    return $date > $startDate && $date < $endDate;
}

$fromUser = new DateTime("2012-03-01");
$startDate = new DateTime("2012-02-01 00:00:00");
$endDate = new DateTime("2012-04-30 23:59:59");

echo isDateBetweenDates($fromUser, $startDate, $endDate);

graphing an equation with matplotlib

To plot an equation that is not solved for a specific variable (like circle or hyperbola):

import numpy as np  
import matplotlib.pyplot as plt  
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100) 
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1  #  'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()

More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf

How do I get the last inserted ID of a MySQL table in PHP?

Use mysqli as mysql is depricating

<?php
$mysqli = new mysqli("localhost", "yourUsername", "yourPassword", "yourDB");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
// Conside employee table with id,name,designation
$query = "INSERT INTO myCity VALUES (NULL, 'Ram', 'Developer')";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* close connection */
$mysqli->close();
?>

R numbers from 1 to 100

If you need the construct for a quick example to play with, use the : operator.

But if you are creating a vector/range of numbers dynamically, then use seq() instead.

Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.

In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,

seq(a, b, -1)

will raise an error for a=2, b=6, because the coder expected a decreasing sequence.

How to switch between python 2.7 to python 3 from command line?

You can try to rename the python executable in the python3 folder to python3, that is if it was named python formally... it worked for me

How to properly apply a lambda function into a pandas data frame column

You need mask:

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)

Another solution with loc and boolean indexing:

sample.loc[sample['PR'] < 90, 'PR'] = np.nan

Sample:

import pandas as pd
import numpy as np

sample = pd.DataFrame({'PR':[10,100,40] })
print (sample)
    PR
0   10
1  100
2   40

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
print (sample)
      PR
0    NaN
1  100.0
2    NaN
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
print (sample)
      PR
0    NaN
1  100.0
2    NaN

EDIT:

Solution with apply:

sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)

Timings len(df)=300k:

sample = pd.concat([sample]*100000).reset_index(drop=True)

In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
10 loops, best of 3: 102 ms per loop

In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.71 ms per loop

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Rephrasing Yuri, Fábio, and Frosts answers for the Django noob (i.e. me) - almost certainly a simplification, but a good starting point?

  • render_to_response() is the "original", but requires you putting context_instance=RequestContext(request) in nearly all the time, a PITA.

  • direct_to_template() is designed to be used just in urls.py without a view defined in views.py but it can be used in views.py to avoid having to type RequestContext

  • render() is a shortcut for render_to_response() that automatically supplies context_instance=Request.... Its available in the django development version (1.2.1) but many have created their own shortcuts such as this one, this one or the one that threw me initially, Nathans basic.tools.shortcuts.py

Setting max-height for table cell contents

I had the same problem with a table layout I was creating. I used Joseph Marikle's solution but made it work for FireFox as well, and added a table-row style for good measure. Pure CSS solution since using Javascript for this seems completely unnecessary and overkill.

html

<div class='wrapper'>
    <div class='table'>
        <div class='table-row'>
            <div class='table-cell'>
                content here
            </div>
            <div class='table-cell'>
                <div class='cell-wrap'>
                    lots of content here
                </div>
            </div>
            <div class='table-cell'>
                content here
            </div>
            <div class='table-cell'>
                content here
            </div>
        </div>
    </div>
</div>

css

.wrapper {height: 200px;}
.table {position: relative; overflow: hidden; display: table; width: 100%; height: 50%;}
.table-row {display: table-row; height: 100%;}
.table-cell {position: relative; overflow: hidden; display: table-cell;}
.cell-wrap {position: absolute; overflow: hidden; top: 0; left: 0; width: 100%; height: 100%;}

You need a wrapper around the table if you want the table to respect a percentage height, otherwise you can just set a pixel height on the table element.

Check that an email address is valid on iOS

to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.

essentially it will look something like this

^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?

It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.

So do the regular expression and validate the structure but forget about validating against a service.

Java - ignore exception and continue

Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

How to use a different version of python during NPM install?

for quick one time use this works, npm install --python="c:\python27"

Angular 2 optional route parameter

With angular4 we just need to organise routes together in hierarchy

const appRoutes: Routes = [
  { 
    path: '', 
    component: MainPageComponent 
  },
  { 
    path: 'car/details', 
    component: CarDetailsComponent 
  },
  { 
    path: 'car/details/platforms-products', 
    component: CarProductsComponent 
  },
  { 
    path: 'car/details/:id', 
    component: CadDetailsComponent 
  },
  { 
    path: 'car/details/:id/platforms-products', 
    component: CarProductsComponent 
  }
];

This works for me . This way router know what is the next route based on option id parameters.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

In my case, I was dealing with a file that was generated by hadoop on a linux box. When I tried to import to sql I had this issue. The fix wound up being to use the hex value for 'line feed' 0x0a. It also worked for bulk insert

bulk insert table from 'file' 
WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '0x0a')

ng-model for `<input type="file"/>` (with directive DEMO)

This is a slightly modified version that lets you specify the name of the attribute in the scope, just as you would do with ng-model, usage:

    <myUpload key="file"></myUpload>

Directive:

.directive('myUpload', function() {
    return {
        link: function postLink(scope, element, attrs) {
            element.find("input").bind("change", function(changeEvent) {                        
                var reader = new FileReader();
                reader.onload = function(loadEvent) {
                    scope.$apply(function() {
                        scope[attrs.key] = loadEvent.target.result;                                
                    });
                }
                if (typeof(changeEvent.target.files[0]) === 'object') {
                    reader.readAsDataURL(changeEvent.target.files[0]);
                };
            });

        },
        controller: 'FileUploadCtrl',
        template:
                '<span class="btn btn-success fileinput-button">' +
                '<i class="glyphicon glyphicon-plus"></i>' +
                '<span>Replace Image</span>' +
                '<input type="file" accept="image/*" name="files[]" multiple="">' +
                '</span>',
        restrict: 'E'

    };
});

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

How to show two figures using matplotlib?

Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)
plt.hist........
............
f.show()

g = plt.figure(2)
plt.hist(........
................
g.show()

raw_input()

In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

Format number to always show 2 decimal places

Here's also a generic function that can format to any number of decimal places:

function numberFormat(val, decimalPlaces) {

    var multiplier = Math.pow(10, decimalPlaces);
    return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}

How to set the current working directory?

It work for Mac also

import os
path="/Users/HOME/Desktop/Addl Work/TimeSeries-Done"
os.chdir(path)

To check working directory

os.getcwd()

What's the best way to build a string of delimited items in Java?

With Java 5 variable args, so you don't have to stuff all your strings into a collection or array explicitly:

import junit.framework.Assert;
import org.junit.Test;

public class StringUtil
{
    public static String join(String delim, String... strings)
    {
        StringBuilder builder = new StringBuilder();

        if (strings != null)
        {
            for (String str : strings)
            {
                if (builder.length() > 0)
                {
                    builder.append(delim).append(" ");
                }
                builder.append(str);
            }
        }           
        return builder.toString();
    }
    @Test
    public void joinTest()
    {
        Assert.assertEquals("", StringUtil.join(",", null));
        Assert.assertEquals("", StringUtil.join(",", ""));
        Assert.assertEquals("", StringUtil.join(",", new String[0]));
        Assert.assertEquals("test", StringUtil.join(",", "test"));
        Assert.assertEquals("foo, bar", StringUtil.join(",", "foo", "bar"));
        Assert.assertEquals("foo, bar, x", StringUtil.join(",", "foo", "bar", "x"));
    }
}

How can I center text (horizontally and vertically) inside a div block?

Common techniques as of 2014:


  • Approach 1 - transform translateX/translateY:

    Example Here / Full Screen Example

    In supported browsers (most of them), you can use top: 50%/left: 50% in combination with translateX(-50%) translateY(-50%) to dynamically vertically/horizontally center the element.

    .container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%) translateY(-50%);
    }
    

  • Approach 2 - Flexbox method:

    Example Here / Full Screen Example

    In supported browsers, set the display of the targeted element to flex and use align-items: center for vertical centering and justify-content: center for horizontal centering. Just don't forget to add vendor prefixes for additional browser support (see example).

    html, body, .container {
        height: 100%;
    }
    .container {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    

  • Approach 3 - table-cell/vertical-align: middle:

    Example Here / Full Screen Example

    In some cases, you will need to ensure that the html/body element's height is set to 100%.

    For vertical alignment, set the parent element's width/height to 100% and add display: table. Then for the child element, change the display to table-cell and add vertical-align: middle.

    For horizontal centering, you could either add text-align: center to center the text and any other inline children elements. Alternatively, you could use margin: 0 auto assuming the element is block level.

    html, body {
        height: 100%;
    }
    .parent {
        width: 100%;
        height: 100%;
        display: table;
        text-align: center;
    }
    .parent > .child {
        display: table-cell;
        vertical-align: middle;
    }
    

  • Approach 4 - Absolutely positioned 50% from the top with displacement:

    Example Here / Full Screen Example

    This approach assumes that the text has a known height - in this instance, 18px. Just absolutely position the element 50% from the top, relative to the parent element. Use a negative margin-top value that is half of the element's known height, in this case - -9px.

    html, body, .container {
        height: 100%;
    }
    .container {
        position: relative;
        text-align: center;
    }
    .container > p {
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        margin-top: -9px;
    }
    

  • Approach 5 - The line-height method (Least flexible - not suggested):

    Example Here

    In some cases, the parent element will have a fixed height. For vertical centering, all you have to do is set a line-height value on the child element equal to the fixed height of the parent element.

    Though this solution will work in some cases, it's worth noting that it won't work when there are multiple lines of text - like this.

    .parent {
        height: 200px;
        width: 400px;
        text-align: center;
    }
    .parent > .child {
        line-height: 200px;
    }
    

Methods 4 and 5 aren't the most reliable. Go with one of the first 3.

How to make rounded percentages add up to 100%

If you are rounding it there is no good way to get it exactly the same in all case.

You can take the decimal part of the N percentages you have (in the example you gave it is 4).

Add the decimal parts. In your example you have total of fractional part = 3.

Ceil the 3 numbers with highest fractions and floor the rest.

(Sorry for the edits)

How to capture Curl output to a file?

If you want to store your output into your desktop, follow the below command using post command in git bash.It worked for me.

curl https://localhost:8080 --request POST --header "Content-Type: application/json" -o "C:\Desktop\test.txt"

How to get folder path from file path with CMD

In case the accepted answer by Wadih didn't work for you, try echo %CD%

CocoaPods Errors on Project Build

Had the same issue saying /Pods/Pods-resources.sh: No such file or directory even after files etc related to pods were removed.

Got rid of it by going to target->Build phases and then removing the build phase "Copy Pod Resources".

Http Get using Android HttpURLConnection

If you just need a very simple call, you can use URL directly:

import java.net.URL;

    new URL("http://wheredatapp.com").openStream();

biggest integer that can be stored in a double

Wikipedia has this to say in the same context with a link to IEEE 754:

On a typical computer system, a 'double precision' (64-bit) binary floating-point number has a coefficient of 53 bits (one of which is implied), an exponent of 11 bits, and one sign bit.

2^53 is just over 9 * 10^15.

CSS selector for text input fields?

The attribute selectors are often used for inputs. This is the list of attribute selectors:

[title] All elements with the title attribute are selected.

[title=banana] All elements which have the 'banana' value of the title attribute.

[title~=banana] All elements which contain 'banana' in the value of the title attribute.

[title|=banana] All elements which value of the title attribute starts with 'banana'.

[title^=banana] All elements which value of the title attribute begins with 'banana'.

[title$=banana] All elements which value of the title attribute ends with 'banana'.

[title*=banana] All elements which value of the title attribute contains the substring 'banana'.

Reference: https://kolosek.com/css-selectors/

How to add new column to MYSQL table?

Based on your comment it looks like your'e only adding the new column if: mysql_query("SELECT * FROM assessment"); returns false. That's probably not what you wanted. Try removing the '!' on front of $sql in the first 'if' statement. So your code will look like:

$sql=mysql_query("SELECT * FROM assessment");
if ($sql) {
 mysql_query("ALTER TABLE assessment ADD q6 INT(1) NOT NULL AFTER q5");
 echo 'Q6 created'; 
}else...

How to return data from PHP to a jQuery ajax call

It's an argument passed to your success function:

$.ajax({
  type: "POST",
  url: "somescript.php",
  datatype: "html",
  data: dataString,
  success: function(data) {
    alert(data);
    }
});

The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)

Show Error on the tip of the Edit Text Android

you could use an onchange event to trigger a validation and then you can display a toast if this is enough for you

How can I search an array in VB.NET?

check this..

        string[] strArray = { "ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI" };
        Array.IndexOf(strArray, "C"); // not found, returns -1
        Array.IndexOf(strArray, "CDE"); // found, returns index

Drop primary key using script in SQL Server database

simply click

'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'

and run the below query is :

Query:alter Table 'TableName' drop constraint PK__TableName__30242045

How to export collection to CSV in MongoDB?

For all those who are stuck with an error.

Let me give you guys a solution with a brief explanation of the same:-

command to connect:-

mongoexport --host your_host --port your_port -u your_username -p your_password --db your_db --collection your_collection --type=csv --out file_name.csv --fields all_the_fields --authenticationDatabase admin

--host --> host of Mongo server

--port --> port of Mongo server

-u --> username

-p --> password

--db --> db from which you want to export

--collection --> collection you want to export

--type --> type of export in my case CSV

--out --> file name where you want to export

--fields --> all the fields you want to export (don't give spaces in between two field name in between commas in case of CSV)

--authenticationDatabase --> database where all your user information is stored

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

You always need to check for XACT_STATE(), irrelevant of the XACT_ABORT setting. I have an example of a template for stored procedures that need to handle transactions in the TRY/CATCH context at Exception handling and nested transactions:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(),
               @message = ERROR_MESSAGE(), 
               @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
    end catch   
end

onSaveInstanceState () and onRestoreInstanceState ()

I just ran into this and was noticing that the documentation had my answer:

"This function will never be called with a null state."

https://developer.android.com/reference/android/view/View.html#onRestoreInstanceState(android.os.Parcelable)

In my case, I was wondering why the onRestoreInstanceState wasn't being called on initial instantiation. This also means that if you don't store anything, it'll not be called when you go to reconstruct your view.

What is the difference between Serializable and Externalizable in Java?

The Externalizable interface was not actually provided to optimize the serialization process performance! but to provide means of implementing your own custom processing and offer complete control over the format and contents of the stream for an object and its super types!

Examples of this is the implementation of AMF (ActionScript Message Format) remoting to transfer native action script objects over the network.

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

How to encrypt String in Java

Warning

Do not use this as some kind of security measurement.

The encryption mechanism in this post is a One-time pad, which means that the secret key can be easily recovered by an attacker using 2 encrypted messages. XOR 2 encrypted messages and you get the key. That simple!

Pointed out by Moussa


I am using Sun's Base64Encoder/Decoder which is to be found in Sun's JRE, to avoid yet another JAR in lib. That's dangerous from point of using OpenJDK or some other's JRE. Besides that, is there another reason I should consider using Apache commons lib with Encoder/Decoder?

public class EncryptUtils {
    public static final String DEFAULT_ENCODING = "UTF-8"; 
    static BASE64Encoder enc = new BASE64Encoder();
    static BASE64Decoder dec = new BASE64Decoder();

    public static String base64encode(String text) {
        try {
            return enc.encode(text.getBytes(DEFAULT_ENCODING));
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }//base64encode

    public static String base64decode(String text) {
        try {
            return new String(dec.decodeBuffer(text), DEFAULT_ENCODING);
        } catch (IOException e) {
            return null;
        }
    }//base64decode

    public static void main(String[] args) {
        String txt = "some text to be encrypted";
        String key = "key phrase used for XOR-ing";
        System.out.println(txt + " XOR-ed to: " + (txt = xorMessage(txt, key)));

        String encoded = base64encode(txt);       
        System.out.println(" is encoded to: " + encoded + " and that is decoding to: " + (txt = base64decode(encoded)));
        System.out.print("XOR-ing back to original: " + xorMessage(txt, key));
    }

    public static String xorMessage(String message, String key) {
        try {
            if (message == null || key == null) return null;

            char[] keys = key.toCharArray();
            char[] mesg = message.toCharArray();

            int ml = mesg.length;
            int kl = keys.length;
            char[] newmsg = new char[ml];

            for (int i = 0; i < ml; i++) {
                newmsg[i] = (char)(mesg[i] ^ keys[i % kl]);
            }//for i

            return new String(newmsg);
        } catch (Exception e) {
            return null;
        }
    }//xorMessage
}//class

How do I change screen orientation in the Android emulator?

With Android Studio:

Windows: Ctrl+Left-Arrow and Ctrl+Right-Arrow

Visualizing branch topology in Git

Git official site enlisted some third party platform specific GUI tools. Hit here git GUI Tools for Linux Platform

I have used gitg and GitKraken for linux platform. Both good to understand the commit tree

How do I output an ISO 8601 formatted string in JavaScript?

There is already a function called toISOString():

var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"

If, somehow, you're on a browser that doesn't support it, I've got you covered:

if ( !Date.prototype.toISOString ) {
  ( function() {

    function pad(number) {
      var r = String(number);
      if ( r.length === 1 ) {
        r = '0' + r;
      }
      return r;
    }

    Date.prototype.toISOString = function() {
      return this.getUTCFullYear()
        + '-' + pad( this.getUTCMonth() + 1 )
        + '-' + pad( this.getUTCDate() )
        + 'T' + pad( this.getUTCHours() )
        + ':' + pad( this.getUTCMinutes() )
        + ':' + pad( this.getUTCSeconds() )
        + '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
        + 'Z';
    };

  }() );
}

How can I copy columns from one sheet to another with VBA in Excel?

The following works fine for me in Excel 2007. It is simple, and performs a full copy (retains all formatting, etc.):

Sheets("Sheet1").Columns(1).Copy Destination:=Sheets("Sheet2").Columns(2)

"Columns" returns a Range object, and so this is utilizing the "Range.Copy" method. "Destination" is an option to this method - if not provided the default is to copy to the paste buffer. But when provided, it is an easy way to copy.

As when manually copying items in Excel, the size and geometry of the destination must support the range being copied.

Exception of type 'System.OutOfMemoryException' was thrown.

I just restarted Visual Studio and did IISRESET which solved the problem.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

Check if there is any conflict in your IIS authentication. i.e. you enable the anonymous authentication and ASP.NET impersonation both might cause the error also.

How to make pylab.savefig() save image for 'maximized' window instead of default size

I did the same search time ago, it seems that he exact solution depends on the backend.

I have read a bunch of sources and probably the most useful was the answer by Pythonio here How to maximize a plt.show() window using Python I adjusted the code and ended up with the function below. It works decently for me on windows, I mostly use Qt, where I use it quite often, while it is minimally tested with other backends.

Basically it consists in identifying the backend and calling the appropriate function. Note that I added a pause afterwards because I was having issues with some windows getting maximized and others not, it seems this solved for me.

def maximize(backend=None,fullscreen=False):
    """Maximize window independently on backend.
    Fullscreen sets fullscreen mode, that is same as maximized, but it doesn't have title bar (press key F to toggle full screen mode)."""
    if backend is None:
        backend=matplotlib.get_backend()
    mng = plt.get_current_fig_manager()

    if fullscreen:
        mng.full_screen_toggle()
    else:
        if backend == 'wxAgg':
            mng.frame.Maximize(True)
        elif backend == 'Qt4Agg' or backend == 'Qt5Agg':
            mng.window.showMaximized()
        elif backend == 'TkAgg':
            mng.window.state('zoomed') #works fine on Windows!
        else:
            print ("Unrecognized backend: ",backend) #not tested on different backends (only Qt)
    plt.show()

    plt.pause(0.1) #this is needed to make sure following processing gets applied (e.g. tight_layout)

How can I get the order ID in WooCommerce?

As of woocommerce 3.0

$order->id;

will not work, it will generate notice, use getter function:

$order->get_id();

The same applies for other woocommerce objects like procut.

Iterating over every property of an object in javascript using Prototype?

There's no need for Prototype here: JavaScript has for..in loops. If you're not sure that no one messed with Object.prototype, check hasOwnProperty() as well, ie

for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
        doSomethingWith(obj[prop]);
}

How can I remove the gloss on a select element in Safari on Mac?

2019 Version

Shorter inline image URL, shows only down arrow, customisable arrow colour...

From https://codepen.io/jonmircha/pen/PEvqPa

Author is probably Jonathan MirCha

select {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='%238C98F2'><polygon points='0,0 100,0 50,50'/></svg>") no-repeat;
  background-size: 12px;
  background-position: calc(100% - 20px) center;
  background-repeat: no-repeat;
  background-color: #efefef;
}

How to SELECT by MAX(date)?

Are you only wanting it to show the last date_entered, or to order by starting with the last_date entered?

SELECT report_id, computer_id, date_entered
FROM reports
GROUP BY computer_id
ORDER BY date_entered DESC
-- LIMIT 1 -- uncomment to only show the last date.

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here
    </script>
    

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>
    

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <html>
    <!-- ... -->
    <body>
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->
    </body>
    </html>
    

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    }_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

How to filter JSON Data in JavaScript or jQuery?

The values can be retrieved during the parsing:

_x000D_
_x000D_
var yahoo = [], j = `[{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]`_x000D_
_x000D_
var data = JSON.parse(j, function(key, value) { _x000D_
      if ( value.website === "yahoo" ) yahoo.push(value); _x000D_
      return value; })_x000D_
_x000D_
console.log( yahoo )
_x000D_
_x000D_
_x000D_

Get characters after last / in url

$str = "http://www.vimeo.com/1234567";
$s = explode("/",$str);
print end($s);

How to create Android Facebook Key Hash?

Run either this in your app :

FacebookSdk.sdkInitialize(getApplicationContext());
Log.d("AppLog", "key:" + FacebookSdk.getApplicationSignature(this)+"=");

Or this:

public static void printHashKey(Context context) {
    try {
        final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
        for (android.content.pm.Signature signature : info.signatures) {
            final MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            final String hashKey = new String(Base64.encode(md.digest(), 0));
            Log.i("AppLog", "key:" + hashKey + "=");
        }
    } catch (Exception e) {
        Log.e("AppLog", "error:", e);
    }
}

And then look at the logs.

The result should end with "=" .

Solution is based on here and here .

How to represent matrices in python

((1,2,3,4),
 (5,6,7,8),
 (9,0,1,2))

Using tuples instead of lists makes it marginally harder to change the data structure in unwanted ways.

If you are going to do extensive use of those, you are best off wrapping a true number array in a class, so you can define methods and properties on them. (Or, you could NumPy, SciPy, ... if you are going to do your processing with those libraries.)

Testing two JSON objects for equality ignoring child order in Java

You could try using json-lib's JSONAssert class:

JSONAssert.assertEquals(
  "{foo: 'bar', baz: 'qux'}",
  JSONObject.fromObject("{foo: 'bar', baz: 'xyzzy'}")
);

Gives:

junit.framework.ComparisonFailure: objects differed at key [baz]; expected:<[qux]> but was:<[xyzzy]>

How do I output lists as a table in Jupyter notebook?

You could try to use the following function

def tableIt(data):
    for lin in data:
        print("+---"*len(lin)+"+")
        for inlin in lin:
            print("|",str(inlin),"", end="")
        print("|")
    print("+---"*len(lin)+"+")

data = [[1,2,3,2,3],[1,2,3,2,3],[1,2,3,2,3],[1,2,3,2,3]]

tableIt(data)

Provide an image for WhatsApp link sharing

I documented the perfect detailed solution here - https://amprandom.blogspot.com/2016/12/blogger-whatsapp-rich-link-preview.html There are seven steps to be done to get the perfect preview.

Title : Add Keyword rich title to your webpage with maximum of 65 characters.

Meta Description : Describe your web page in a maximum of 155 characters.

og:title : Maximum 35 characters.

og:url : Full link to your webpage address.

og:description : Maximum 65 characters.

og:image : Image(JPG or PNG) of size less than 300KB and minimum dimension of 300 x 200 pixel is advised.

favicon : A small icon of dimensions 32 x 32 pixels.

In the above page, you have the required specifications, the character limit and sample tags. Do upvote once you find it satisfactory.

read.csv warning 'EOF within quoted string' prevents complete reading of file

I'm a new-ish R user and thought I'd post this in case it helps anyone else. I was trying to read in data from a text file (separated with commas) that included a few Spanish characters and it took me forever to figure it out. I knew I needed to use UTF-8 encoding, set the header arg to TRUE, and that I need to set the sep arguemnt to ",", but then I still got hang ups. After reading this post I tried setting the fill arg to TRUE, but then got the same "EOF within quoted string" which I was able to fix in the same manner as above. My successful read.table looks like this:

target <- read.table("target2.txt", fill=TRUE, header=TRUE, quote="", sep=",", encoding="UTF-8")

The result has Spanish language characters and same dims I had originally, so I'm calling it a success! Thanks all!

Git Symlinks in Windows

One simple trick we use is to just call git add --all twice in a row.

For example, our Windows 7 commit script calls:

$ git add --all
$ git add --all

The first add treats the link as text and adds the folders for delete.

The second add traverses the link correctly and undoes the delete by restoring the files.

It's less elegant than some of the other proposed solutions but it is a simple fix to some of our legacy environments that got symlinks added.

What is SOA "in plain english"?

SOA is a buzzword that was invented by technology vendors to help sell their Enterprise Service Bus related technologies. The idea is that you make your little island applications in the enterprise (eg: accounting system, stock control system, etc) all expose services, so that they can be orchestrated flexibly into 'applications', or rather become parts of aggregate enterprise scoped business logic.

Basically a load of old bollocks that nearly never works, because it misses the point that the reasons why technology is the way it is in an organisation is down to culture, evolution, history of the firm, and the lock in is so high that any attempt to restructure the technology is bound to fail.

Typescript: How to extend two classes?

In design patterns there is a principle called "favouring composition over inheritance". It says instead of inheriting Class B from Class A ,put an instance of class A inside class B as a property and then you can use functionalities of class A inside class B. You can see some examples of that here and here.

What does it mean when Statement.executeUpdate() returns -1?

This doesn't explain why it should be like that, but it explains why it could happen. The following byte-code sets -1 to the internal updateCount flag in the SQLServerStatement constructor:

// Method descriptor #401 (Lcom/microsoft/sqlserver/jdbc/SQLServerConnection;II)V
// Stack: 5, Locals: 8
SQLServerStatement(
  com.microsoft.sqlserver.jdbc.SQLServerConnection arg0, int arg1, int arg2) 
throws com.microsoft.sqlserver.jdbc.SQLServerException;

// [...]

34 aload_0 [this]
35 iconst_m1
36 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

Now, I will not analyse all possible control-flows, but I'd just say that this is the internal default initialisation value that somehow leaks out to client code. Note, this is also done in other methods:

// Method descriptor #383 ()V
// Stack: 2, Locals: 1
final void resetForReexecute() 
throws com.microsoft.sqlserver.jdbc.SQLServerException;

// [...]

10 aload_0 [this]
11 iconst_m1
12 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

// Method descriptor #383 ()V
// Stack: 3, Locals: 3
final void clearLastResult();
0 aload_0 [this]
1 iconst_m1
2 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

In other words, you're probably safe interpreting -1 as being the same as 0. If you rely on this result value, maybe stay on the safe side and do your checks as follows:

// No rows affected
if (stmt.executeUpdate() <= 0) {
}
// Rows affected
else {
}

UPDATE: While reading Mark Rotteveel's answer, I tend to agree with him, assuming that -1 is the JDBC-compliant value for "unknown update counts". Even if this isn't documented on the relevant method's Javadoc, it's documented in the JDBC specs, chapter 13.1.2.3 Returning Unknown or Multiple Results. In this very case, it could be said that an IF .. INSERT .. statement will have an "unknown update count", as this statement isn't SQL-standard compliant anyway.

Make WPF Application Fullscreen (Cover startmenu)

When you're doing it by code the trick is to call

WindowStyle = WindowStyle.None;

first and then

WindowState = WindowState.Maximized;

to get it to display over the Taskbar.

What causes javac to issue the "uses unchecked or unsafe operations" warning

The "unchecked or unsafe operations" warning was added when java added Generics, if I remember correctly. It's usually asking you to be more explicit about types, in one way or another.

For example. the code ArrayList foo = new ArrayList(); triggers that warning because javac is looking for ArrayList<String> foo = new ArrayList<String>();

Predict() - Maybe I'm not understanding it

First, you want to use

model <- lm(Total ~ Coupon, data=df)

not model <-lm(df$Total ~ df$Coupon, data=df).

Second, by saying lm(Total ~ Coupon), you are fitting a model that uses Total as the response variable, with Coupon as the predictor. That is, your model is of the form Total = a + b*Coupon, with a and b the coefficients to be estimated. Note that the response goes on the left side of the ~, and the predictor(s) on the right.

Because of this, when you ask R to give you predicted values for the model, you have to provide a set of new predictor values, ie new values of Coupon, not Total.

Third, judging by your specification of newdata, it looks like you're actually after a model to fit Coupon as a function of Total, not the other way around. To do this:

model <- lm(Coupon ~ Total, data=df)
new.df <- data.frame(Total=c(79037022, 83100656, 104299800))
predict(model, new.df)

How to undo a SQL Server UPDATE query?

A non-committed transaction can be reverted by issuing the command ROLLBACK

But if you are running in auto-commit mode there is nothing you can do....

List all column except for one in R

In addition to tcash21's numeric indexing if OP may have been looking for negative indexing by name. Here's a few ways I know, some are risky than others to use:

mtcars[, -which(names(mtcars) == "carb")]  #only works on a single column
mtcars[, names(mtcars) != "carb"]          #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")] 
mtcars[, -match(c("carb", "mpg"), names(mtcars))] 
mtcars2 <- mtcars; mtcars2$hp <- NULL         #lost column (risky)


library(gdata) 
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE) 

Generally I use:

mtcars[, !names(mtcars) %in% c("carb", "mpg")] 

because I feel it's safe and efficient.

document.createElement("script") synchronously

I am used to having multiple .js files on my web site that depend one on another. To load them and ensure that the dependencies are evaluated in the right order, I have written a function that loads all the files and then, once they are all received, eval() them. The main drawback is that since this does not work with CDN. For such libraries (e.g., jQuery) it is better to include them statically. Note that inserting script nodes in the HTML dynamically won't guarantee that scripts are evaluated in the right order, at least not in Chrome (this was the major reason for writing this function).

function xhrs(reqs) {
  var requests = [] , count = [] , callback ;

  callback = function (r,c,i) {
    return function () {
      if  ( this.readyState == 4 ) {
        if (this.status != 200 ) {
          r[i]['resp']="" ;
        } 
        else {
          r[i]['resp']= this.responseText ;
        }
        c[0] = c[0] - 1 ;
        if ( c[0] == 0 ) {
          for ( var j = 0 ; j < r.length ; j++ ) {
            eval(r[j]['resp']) ;
          }
        }
      }
    }
  } ;
  if ( Object.prototype.toString.call( reqs ) === '[object Array]' ) {
    requests.length = reqs.length ;
  }
  else {
    requests.length = 1 ;
    reqs = [].concat(reqs);
  }
  count[0] = requests.length ;
  for ( var i = 0 ; i < requests.length ; i++ ) {
    requests[i] = {} ;
    requests[i]['xhr'] = new XMLHttpRequest () ;
    requests[i]['xhr'].open('GET', reqs[i]) ;
    requests[i]['xhr'].onreadystatechange = callback(requests,count,i) ;
    requests[i]['xhr'].send(null);
  }
}

I haven't figured out how to make references to the same value without creating an array (for count). Otherwise I think it is self-explanatory (when everything is loaded, eval() every file in the order given, otherwise just store the response).

Usage example:

xhrs( [
       root + '/global.js' ,
       window.location.href + 'config.js' ,
       root + '/js/lib/details.polyfill.min.js',
       root + '/js/scripts/address.js' ,
       root + '/js/scripts/tableofcontents.js' 
]) ;

How to sort the files according to the time stamp in unix?

File modification:

ls -t

Inode change:

ls -tc

File access:

ls -tu

"Newest" one at the bottom:

ls -tr

None of this is a creation time. Most Unix filesystems don't support creation timestamps.

Cannot read property length of undefined

perhaps, you can first determine if the DOM does really exists,

function walkmydog() {
    //when the user starts entering
    var dom = document.getElementById('WallSearch');
    if(dom == null){
        alert('sorry, WallSearch DOM cannot be found');
        return false;    
    }

    if(dom.value.length == 0){
        alert("nothing");
    }
}

if (document.addEventListener){
    document.addEventListener("DOMContentLoaded", walkmydog, false);
}

How can you customize the numbers in an ordered list?

Stole a lot of this from other answers, but this is working in FF3 for me. It has upper-roman, uniform indenting, a close bracket.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> new document </title>
<style type="text/css">
<!--
ol {
  counter-reset: item;
  margin-left: 0;
  padding-left: 0;
}
li {
  margin-bottom: .5em;
}
li:before {
  display: inline-block;
  content: counter(item, upper-roman) ")";
  counter-increment: item;
  width: 3em;
}
-->
</style>
</head>

<body>
<ol>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li>Six</li>
  <li>Seven</li>
  <li>Eight</li>
  <li>Nine</li>
  <li>Ten</li>
</ol>
</body>
</html>

How to call a Parent Class's method from Child Class in Python?

This is a more abstract method:

super(self.__class__,self).baz(arg)

Using group by on multiple columns

Group By X means put all those with the same value for X in the one group.

Group By X, Y means put all those with the same values for both X and Y in the one group.

To illustrate using an example, let's say we have the following table, to do with who is attending what subject at a university:

Table: Subject_Selection

+---------+----------+----------+
| Subject | Semester | Attendee |
+---------+----------+----------+
| ITB001  |        1 | John     |
| ITB001  |        1 | Bob      |
| ITB001  |        1 | Mickey   |
| ITB001  |        2 | Jenny    |
| ITB001  |        2 | James    |
| MKB114  |        1 | John     |
| MKB114  |        1 | Erica    |
+---------+----------+----------+

When you use a group by on the subject column only; say:

select Subject, Count(*)
from Subject_Selection
group by Subject

You will get something like:

+---------+-------+
| Subject | Count |
+---------+-------+
| ITB001  |     5 |
| MKB114  |     2 |
+---------+-------+

...because there are 5 entries for ITB001, and 2 for MKB114

If we were to group by two columns:

select Subject, Semester, Count(*)
from Subject_Selection
group by Subject, Semester

we would get this:

+---------+----------+-------+
| Subject | Semester | Count |
+---------+----------+-------+
| ITB001  |        1 |     3 |
| ITB001  |        2 |     2 |
| MKB114  |        1 |     2 |
+---------+----------+-------+

This is because, when we group by two columns, it is saying "Group them so that all of those with the same Subject and Semester are in the same group, and then calculate all the aggregate functions (Count, Sum, Average, etc.) for each of those groups". In this example, this is demonstrated by the fact that, when we count them, there are three people doing ITB001 in semester 1, and two doing it in semester 2. Both of the people doing MKB114 are in semester 1, so there is no row for semester 2 (no data fits into the group "MKB114, Semester 2")

Hopefully that makes sense.

Appending a byte[] to the end of another byte[]

Using System.arraycopy(), something like the following should work:

// create a destination array that is the size of the two arrays
byte[] destination = new byte[ciphertext.length + mac.length];

// copy ciphertext into start of destination (from pos 0, copy ciphertext.length bytes)
System.arraycopy(ciphertext, 0, destination, 0, ciphertext.length);

// copy mac into end of destination (from pos ciphertext.length, copy mac.length bytes)
System.arraycopy(mac, 0, destination, ciphertext.length, mac.length);

How to add a second x-axis in matplotlib

I'm taking a cue from the comments in @Dhara's answer, it sounds like you want to set a list of new_tick_locations by a function from the old x-axis to the new x-axis. The tick_function below takes in a numpy array of points, maps them to a new value and formats them:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

X = np.linspace(0,1,1000)
Y = np.cos(X*20)

ax1.plot(X,Y)
ax1.set_xlabel(r"Original x-axis: $X$")

new_tick_locations = np.array([.2, .5, .9])

def tick_function(X):
    V = 1/(1+X)
    return ["%.3f" % z for z in V]

ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(tick_function(new_tick_locations))
ax2.set_xlabel(r"Modified x-axis: $1/(1+X)$")
plt.show()

enter image description here

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Please ensure that you have following import. Ofcourse other standard imports

import org.springframework.core.io.FileSystemResource


    void uploadzipFiles(String token) {

        RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)

        def zipFile = new File("testdata.zip")
        def Id = "001G00000"
        MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
        form.add("id", id)
        form.add('file',new FileSystemResource(zipFile))
        def urld ='''http://URL''';
        def resp = rest.post(urld) {
            header('X-Auth-Token', clientSecret)
            contentType "multipart/form-data"
            body(form)
        }
        println "resp::"+resp
        println "resp::"+resp.text
        println "resp::"+resp.headers
        println "resp::"+resp.body
        println "resp::"+resp.status
    }

How do I wait for a promise to finish before returning the variable of a function?

You don't want to make the function wait, because JavaScript is intended to be non-blocking. Rather return the promise at the end of the function, then the calling function can use the promise to get the server response.

var promise = query.find(); 
return promise; 

//Or return query.find(); 

How can I set the default value for an HTML <select> element?

value attribute of tag is missing, so it doesn't show as u desired selected. By default first option show on dropdown page load, if value attribute is set on tag.... I got solved my problem this way

run a python script in terminal without the python command

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

#!/usr/bin/env python

make the file executable:

chmod +x arbitraryname

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

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

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

AngularJS - Animate ng-view transitions

I'm not sure about a way to do it directly with AngularJS but you could set the display to none for both welcome and login and animate the opacity with an directive once they are loaded.

I would do it some way like so. 2 Directives for fading in the content and fading it out when a link is clicked. The directive for fadeouts could simply animate a element with an unique ID or call a service which broadcasts the fadeout

Template:

<div class="tmplWrapper" onLoadFadeIn>
    <a href="somewhere/else" fadeOut>
</div>

Directives:

angular
  .directive('onLoadFadeIn', ['Fading', function('Fading') {
    return function(scope, element, attrs) {
      $(element).animate(...);
      scope.$on('fading', function() {
    $(element).animate(...);
      });
    }
  }])
  .directive('fadeOut', function() {
    return function(scope, element, attrs) {
      element.bind('fadeOut', function(e) {
    Fading.fadeOut(e.target);
  });
    }
  });

Service:

angular.factory('Fading', function() {
  var news;
  news.setActiveUnit = function() {
    $rootScope.$broadcast('fadeOut');
  };
  return news;
})

I just have put together this code quickly so there may be some bugs :)

Text vertical alignment in WPF TextBlock

I've found that modifying the textbox style (ie: controltemplate) and then modifying the PART_ContentHost vertical alignment to Center will do the trick

Changing one character in a string

Strings are immutable in Python, which means you cannot change the existing string. But if you want to change any character in it, you could create a new string out it as follows,

def replace(s, position, character):
    return s[:position] + character + s[position+1:]

replace('King', 1, 'o')
// result: Kong

Note: If you give the position value greater than the length of the string, it will append the character at the end.

replace('Dog', 10, 's')
// result: Dogs

Radio/checkbox alignment in HTML/CSS

I wouldn't use tables for this at all. CSS can easily do this.

I would do something like this:

   <p class="clearfix">
      <input id="option1" type="radio" name="opt" />
      <label for="option1">Option 1</label>
   </p>

p { margin: 0px 0px 10px 0px; }
input { float: left; width: 50px; }
label { margin: 0px 0px 0px 10px; float: left; }

Note: I have used the clearfix class from : http://www.positioniseverything.net/easyclearing.html

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

.clearfix {display: inline-block;}

/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Find Java classes implementing an interface

Package Level Annotations

I know this question has already been answered a long time ago but another solution to this problem is to use Package Level Annotations.

While its pretty hard to go find all the classes in the JVM its actually pretty easy to browse the package hierarchy.

Package[] ps = Package.getPackages();
for (Package p : ps) {
  MyAno a = p.getAnnotation(MyAno.class)
  // Recursively descend
}

Then just make your annotation have an argument of an array of Class. Then in your package-info.java for a particular package put the MyAno.

I'll add more details (code) if people are interested but most probably get the idea.

MetaInf Service Loader

To add to @erickson answer you can also use the service loader approach. Kohsuke has an awesome way of generating the the required META-INF stuff you need for the service loader approach:

http://weblogs.java.net/blog/kohsuke/archive/2009/03/my_project_of_t.html

How to import jquery using ES6 syntax?

Based on the solution of Édouard Lopez, but in two lines:

import jQuery from "jquery";
window.$ = window.jQuery = jQuery;

How to embed images in html email

This is the code I'm using to embed images into HTML mail and PDF documents.

<?php
$logo_path = 'http://localhost/img/logo.jpg';
$type = pathinfo($logo_path, PATHINFO_EXTENSION);
$image_contents = file_get_contents($logo_path);
$image64 = 'data:image/' . $type . ';base64,' . base64_encode($image_contents);

echo '<img src="' . $image64 .'" />';
?>

Center a DIV horizontally and vertically

For modern browsers

When you have that luxury. There's flexbox too, but that's not broadly supported at the time of this writing.

HTML:

<div class="content">This works with any content</div>

CSS:

.content {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

Tinker with it further on Codepen or on JSBin

For older browser support, look elsewhere in this thread.

What's the Use of '\r' escape sequence?

The program is printing "Hey this is my first hello world ", then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.

Cmake doesn't find Boost

There is more help available by reading the FindBoost.cmake file itself. It is located in your 'Modules' directory.

A good start is to set(Boost_DEBUG 1) - this will spit out a good deal of information about where boost is looking, what it's looking for, and may help explain why it can't find it.

It can also help you to figure out if it is picking up on your BOOST_ROOT properly.

FindBoost.cmake also sometimes has problems if the exact version of boost is not listed in the Available Versions variables. You can find more about this by reading FindBoost.cmake.

Lastly, FindBoost.cmake has had some bugs in the past. One thing you might try is to take a newer version of FindBoost.cmake out of the latest version of CMake, and stick it into your project folder alongside CMakeLists.txt - then even if you have an old version of boost, it will use the new version of FindBoost.cmake that is in your project's folder.

Good luck.

How to add text to JFrame?

You can add a multi-line label with the following:

JLabel label = new JLabel("My label");

label.setText("<html>This is a<br>multline label!<br> Try it yourself!</html>");

From here, simply add the label to the frame using the add() method, and you're all set!

Java file path in Linux

I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.

File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");

How to limit depth for recursive file list?

Checkout the -maxdepth flag of find

find . -maxdepth 1 -type d -exec ls -ld "{}" \;

Here I used 1 as max level depth, -type d means find only directories, which then ls -ld lists contents of, in long format.

Spring Data JPA - "No Property Found for Type" Exception

this might help someone who had similar issue like me , i followed all naming and interface standards., But i was still facing issue.

My param name was -->  update_datetime 

I wanted to fetch my entities based on the update_datetime in the descending order, and i was getting the error

org.springframework.data.mapping.PropertyReferenceException: No property update found for type Release!

Somehow it was not reading the Underscore character --> ( _ )

so for workaround i changed the property name as  --> updateDatetime 

and then used the same for using JpaRepository methods.

It Worked !

IPython/Jupyter Problems saving notebook as PDF

2015-4-22: It looks like an IPython update means that --to pdf should be used instead of --to latex --post PDF. There is a related Github issue.

Troubleshooting "Illegal mix of collations" error in mysql

You can try this script, that converts all of your databases and tables to utf8.

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

Uninstalling the app on device and then reinstalling fixed it for me.

Tried all the other options, nothing. Finally found this post. This is after adding permission (below) and cleaning build.

<uses-permission android:name="android.permission.INTERNET"/>

How do I PHP-unserialize a jQuery-serialized form?

Modified Murtaza Hussain answer:

function unserializeForm($str) {
    $strArray = explode("&", $str);
    foreach($strArray as $item) {
        $array = explode("=", $item);
        $returndata[] = $array;
    }
    return $returndata;
}

Maven: best way of linking custom external JAR to my project?

The most efficient and cleanest way I have found to deal with this problem is by using Github Packages

  1. Create a simple empty public/private repository on GitHub as per your requirement whether you want your external jar to be publicly hosted or not.

  2. Run below maven command to deploy you external jar in above created github repository

    mvn deploy:deploy-file \ -DgroupId= your-group-id \ -DartifactId= your-artifact-id \ -Dversion= 1.0.0 -Dpackaging= jar -Dfile= path-to-file \ -DrepositoryId= id-to-map-on-server-section-of-settings.xml \ -Durl=https://maven.pkg.github.com/github-username/github-reponame-created-in-above-step

    Above command will deploy you external jar in GitHub repository mentioned in -Durl=. You can refer this link on How to deploy dependencies as GitHub Packages GitHub Package Deployment Tutorial

  3. After that you can add the dependency using groupId,artifactId and version mentioned in above step in maven pom.xml and run mvn install

  4. Maven will fetch the dependency of external jar from GitHub Packages registry and provide in your maven project.

  5. For this to work you will also need to configure you maven's settings.xml to fetch from GitHub Package registry.

Two onClick actions one button

Try it:

<input type="button" value="Dont show this again! " onClick="fbLikeDump();WriteCookie();" />

Or also

<script>
function clickEvent(){
    fbLikeDump();
    WriteCookie();
}
</script>
<input type="button" value="Dont show this again! " onClick="clickEvent();" />

How to search a Git repository by commit message?

Try this!

git log | grep -b3 "Build 0051"

How can I save an image with PIL?

The error regarding the file extension has been handled, you either use BMP (without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL is telling you that it doesn't accept float data to save as BMP.

Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray) for doing the conversion for proper visualization:

import sys
import numpy
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')

im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))

visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())

result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')

How to sort an STL vector?

Overload less than operator, then sort. This is an example I found off the web...

class MyData
{
public:
  int m_iData;
  string m_strSomeOtherData;
  bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};

std::sort(myvector.begin(), myvector.end());

Source: here

Reference alias (calculated in SELECT) in WHERE clause

As a workaround to force the evaluation of the SELECT clause before the WHERE clause, you could put the former in a sub-query while the latter remains in the main query:

SELECT * FROM (
  SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
  FROM Invoices) AS temp
WHERE BalanceDue > 0
  

JSON.parse unexpected character error

You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify() .

Updated your line below,

JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));

or if you have JSON stored in some variable:

JSON.parse(JSON.stringify(yourJSONobject));

How to make a script wait for a pressed key?

Cross Platform, Python 2/3 code:

# import sys, os

def wait_key():
    ''' Wait for a key press on the console and return it. '''
    result = None
    if os.name == 'nt':
        import msvcrt
        result = msvcrt.getch()
    else:
        import termios
        fd = sys.stdin.fileno()

        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, newattr)

        try:
            result = sys.stdin.read(1)
        except IOError:
            pass
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)

    return result

I removed the fctl/non-blocking stuff because it was giving IOErrors and I didn't need it. I'm using this code specifically because I want it to block. ;)

Addendum:

I implemented this in a package on PyPI with a lot of other goodies called console:

>>> from console.utils import wait_key

>>> wait_key()
'h'

Which is the best IDE for Python For Windows

U can use eclipse. but u need to download pydev addon for that.

Short IF - ELSE statement

I'm a little late to the party but for future readers.

From what i can tell, you're just wanting to toggle the visibility state right? Why not just use the ! operator?

jxPanel6.setVisible(!jxPanel6.isVisible);

It's not an if statement but I prefer this method for code related to your example.

How do you run a command for each line of a file?

Read a file line by line and execute commands: 4 answers

This is because there is not only 1 answer...

  1. shell command line expansion
  2. xargs dedicated tool
  3. while read with some remarks
  4. while read -u using dedicated fd, for interactive processing (sample)

Regarding the OP request: running chmod on all targets listed in file, xargs is the indicated tool. But for some other applications, small amount of files, etc...

  1. Read entire file as command line argument.

    If your file is not too big and all files are well named (without spaces or other special chars like quotes), you could use shell command line expansion. Simply:

    chmod 755 $(<file.txt)
    

    For small amount of files (lines), this command is the lighter one.

  2. xargs is the right tool

    For bigger amount of files, or almost any number of lines in your input file...

    For many binutils tools, like chown, chmod, rm, cp -t ...

    xargs chmod 755 <file.txt
    

    If you have special chars and/or a lot of lines in file.txt.

    xargs -0 chmod 755 < <(tr \\n \\0 <file.txt)
    

    if your command need to be run exactly 1 time by entry:

    xargs -0 -n 1 chmod 755 < <(tr \\n \\0 <file.txt)
    

    This is not needed for this sample, as chmod accept multiple files as argument, but this match the title of question.

    For some special case, you could even define location of file argument in commands generateds by xargs:

    xargs -0 -I '{}' -n 1 myWrapper -arg1 -file='{}' wrapCmd < <(tr \\n \\0 <file.txt)
    

    Test with seq 1 5 as input

    Try this:

    xargs -n 1 -I{} echo Blah {} blabla {}.. < <(seq 1 5)
    Blah 1 blabla 1..
    Blah 2 blabla 2..
    Blah 3 blabla 3..
    Blah 4 blabla 4..
    Blah 5 blabla 5..
    

    Where commande is done once per line.

  3. while read and variants.

    As OP suggest cat file.txt | while read in; do chmod 755 "$in"; done will work, but there is 2 issues:

    • cat | is an useless fork, and

    • | while ... ;done will become a subshell where environment will disapear after ;done.

    So this could be better written:

    while read in; do chmod 755 "$in"; done < file.txt
    

    But,

    • You may be warned about $IFS and read flags:

      help read
      
      read: read [-r] ... [-d delim] ... [name ...]
          ...
          Reads a single line from the standard input... The line is split
          into fields as with word splitting, and the first word is assigned
          to the first NAME, the second word to the second NAME, and so on...
          Only the characters found in $IFS are recognized as word delimiters.
          ...
          Options:
            ...
            -d delim   continue until the first character of DELIM is read, 
                       rather than newline
            ...
            -r do not allow backslashes to escape any characters
          ...
          Exit Status:
          The return code is zero, unless end-of-file is encountered...
      

      In some case, you may need to use

      while IFS= read -r in;do chmod 755 "$in";done <file.txt
      

      For avoiding problems with stranges filenames. And maybe if you encouter problems with UTF-8:

      while LANG=C IFS= read -r in ; do chmod 755 "$in";done <file.txt
      
    • While you use STDIN for reading file.txt, your script could not be interactive (you cannot use STDIN anymore).

  4. while read -u, using dedicated fd.

    Syntax: while read ...;done <file.txt will redirect STDIN to file.txt. That mean, you won't be able to deal with process, until they finish.

    If you plan to create interactive tool, you have to avoid use of STDIN and use some alternative file descriptor.

    Constants file descriptors are: 0 for STDIN, 1 for STDOUT and 2 for STDERR. You could see them by:

    ls -l /dev/fd/
    

    or

    ls -l /proc/self/fd/
    

    From there, you have to choose unused number, between 0 and 63 (more, in fact, depending on sysctl superuser tool) as file descriptor:

    For this demo, I will use fd 7:

    exec 7<file.txt      # Without spaces between `7` and `<`!
    ls -l /dev/fd/
    

    Then you could use read -u 7 this way:

    while read -u 7 filename;do
        ans=;while [ -z "$ans" ];do
            read -p "Process file '$filename' (y/n)? " -sn1 foo
            [ "$foo" ]&& [ -z "${foo/[yn]}" ]&& ans=$foo || echo '??'
        done
        if [ "$ans" = "y" ] ;then
            echo Yes
            echo "Processing '$filename'."
        else
            echo No
        fi
    done 7<file.txt
    

    done
    

    To close fd/7:

    exec 7<&-            # This will close file descriptor 7.
    ls -l /dev/fd/
    

    Nota: I let striked version because this syntax could be usefull, when doing many I/O with parallels process:

    mkfifo sshfifo
    exec 7> >(ssh -t user@host sh >sshfifo)
    exec 6<sshfifo
    

How to delete mysql database through shell command

Another suitable way:

$ mysql -u you -p
<enter password>

>>> DROP DATABASE foo;

Uncaught ReferenceError: $ is not defined

In my case it was a typo, I forgot a backslash and was referencing the source incorrectly.

Before src="/scripts/jquery.js"

After    src="scripts/jquery.js"

Dynamically add script tag with src that may include document.write

var my_awesome_script = document.createElement('script');

my_awesome_script.setAttribute('src','http://example.com/site.js');

document.head.appendChild(my_awesome_script);

Java: How to stop thread?

One possible way is to do something like this:

public class MyThread extends Thread {
    @Override
    public void run() {
        while (!this.isInterrupted()) {
            //
        }
    }
}

And when you want to stop your thread, just call a method interrupt():

myThread.interrupt();

Of course, this won't stop thread immediately, but in the following iteration of the loop above. In the case of downloading, you need to write a non-blocking code. It means, that you will attempt to read new data from the socket only for a limited amount of time. If there are no data available, it will just continue. It may be done using this method from the class Socket:

mySocket.setSoTimeout(50);

In this case, timeout is set up to 50 ms. After this time has gone and no data was read, it throws an SocketTimeoutException. This way, you may write iterative and non-blocking thread, which may be killed using the construction above.

It's not possible to kill thread in any other way and you've to implement such a behavior yourself. In past, Thread had some method (not sure if kill() or stop()) for this, but it's deprecated now. My experience is, that some implementations of JVM doesn't even contain that method currently.

Algorithm to detect overlapping periods

I'm building a booking system and found this page. I'm interested in range intersection only, so I built this structure; it is enough to play with DateTime ranges.

You can check Intersection and check if a specific date is in range, and get the intersection type and the most important: you can get intersected Range.

public struct DateTimeRange
{

    #region Construction
    public DateTimeRange(DateTime start, DateTime end) {
        if (start>end) {
            throw new Exception("Invalid range edges.");
        }
        _Start = start;
        _End = end;
    }
    #endregion

    #region Properties
    private DateTime _Start;

    public DateTime Start {
        get { return _Start; }
        private set { _Start = value; }
    }
    private DateTime _End;

    public DateTime End {
        get { return _End; }
        private set { _End = value; }
    }
    #endregion

    #region Operators
    public static bool operator ==(DateTimeRange range1, DateTimeRange range2) {
        return range1.Equals(range2);
    }

    public static bool operator !=(DateTimeRange range1, DateTimeRange range2) {
        return !(range1 == range2);
    }
    public override bool Equals(object obj) {
        if (obj is DateTimeRange) {
            var range1 = this;
            var range2 = (DateTimeRange)obj;
            return range1.Start == range2.Start && range1.End == range2.End;
        }
        return base.Equals(obj);
    }
    public override int GetHashCode() {
        return base.GetHashCode();
    }
    #endregion

    #region Querying
    public bool Intersects(DateTimeRange range) {
        var type = GetIntersectionType(range);
        return type != IntersectionType.None;
    }
    public bool IsInRange(DateTime date) {
        return (date >= this.Start) && (date <= this.End);
    }
    public IntersectionType GetIntersectionType(DateTimeRange range) {
        if (this == range) {
            return IntersectionType.RangesEqauled;
        }
        else if (IsInRange(range.Start) && IsInRange(range.End)) {
            return IntersectionType.ContainedInRange;
        }
        else if (IsInRange(range.Start)) {
            return IntersectionType.StartsInRange;
        }
        else if (IsInRange(range.End)) {
            return IntersectionType.EndsInRange;
        }
        else if (range.IsInRange(this.Start) && range.IsInRange(this.End)) {
            return IntersectionType.ContainsRange;
        }
        return IntersectionType.None;
    }
    public DateTimeRange GetIntersection(DateTimeRange range) {
        var type = this.GetIntersectionType(range);
        if (type == IntersectionType.RangesEqauled || type==IntersectionType.ContainedInRange) {
            return range;
        }
        else if (type == IntersectionType.StartsInRange) {
            return new DateTimeRange(range.Start, this.End);
        }
        else if (type == IntersectionType.EndsInRange) {
            return new DateTimeRange(this.Start, range.End);
        }
        else if (type == IntersectionType.ContainsRange) {
            return this;
        }
        else {
            return default(DateTimeRange);
        }
    }
    #endregion


    public override string ToString() {
        return Start.ToString() + " - " + End.ToString();
    }
}
public enum IntersectionType
{
    /// <summary>
    /// No Intersection
    /// </summary>
    None = -1,
    /// <summary>
    /// Given range ends inside the range
    /// </summary>
    EndsInRange,
    /// <summary>
    /// Given range starts inside the range
    /// </summary>
    StartsInRange,
    /// <summary>
    /// Both ranges are equaled
    /// </summary>
    RangesEqauled,
    /// <summary>
    /// Given range contained in the range
    /// </summary>
    ContainedInRange,
    /// <summary>
    /// Given range contains the range
    /// </summary>
    ContainsRange,
}

"multiple target patterns" Makefile error

I also got this error (within the Eclipse-based STM32CubeIDE on Windows).

After double-clicking on the "multiple target patterns" error it showed a path to a .ld file. It turns out to be another "illegal character" problem. The offending character was the (wait for it): =

Heuristic of the week: use only [a..z] in your paths, as there are bound to be other illegal characters </vomit>.

The GNU make manual doesn't explicitly document this.