Programs & Examples On #Character

Refers to a symbol that represents a letter or number. Also, the bit pattern used to represent such a symbol.

How to use ArrayList.addAll()?

Use Arrays class in Java which will return you an ArrayList :

final List<String> characters = Arrays.asList("+","-");

You will need a bit more work if you need a List<Character>.

Creating Unicode character from its number

Just cast your int to a char. You can convert that to a String using Character.toString():

String s = Character.toString((char)c);

EDIT:

Just remember that the escape sequences in Java source code (the \u bits) are in HEX, so if you're trying to reproduce an escape sequence, you'll need something like int c = 0x2202.

How to remove certain characters from a string in C++?

I want to remove the "(", ")", and "-" characters from the string.

You can use the std::remove_if() algorithm to remove only the characters you specify:

#include <iostream>
#include <algorithm>
#include <string>

bool IsParenthesesOrDash(char c)
{
    switch(c)
    {
    case '(':
    case ')':
    case '-':
        return true;
    default:
        return false;
    }
}

int main()
{
    std::string str("(555) 555-5555");
    str.erase(std::remove_if(str.begin(), str.end(), &IsParenthesesOrDash), str.end());
    std::cout << str << std::endl; // Expected output: 555 5555555
}

The std::remove_if() algorithm requires something called a predicate, which can be a function pointer like the snippet above.

You can also pass a function object (an object that overloads the function call () operator). This allows us to create an even more general solution:

#include <iostream>
#include <algorithm>
#include <string>

class IsChars
{
public:
    IsChars(const char* charsToRemove) : chars(charsToRemove) {};

    bool operator()(char c)
    {
        for(const char* testChar = chars; *testChar != 0; ++testChar)
        {
            if(*testChar == c) { return true; }
        }
        return false;
    }

private:
    const char* chars;
};

int main()
{
    std::string str("(555) 555-5555");
    str.erase(std::remove_if(str.begin(), str.end(), IsChars("()- ")), str.end());
    std::cout << str << std::endl; // Expected output: 5555555555
}

You can specify what characters to remove with the "()- " string. In the example above I added a space so that spaces are removed as well as parentheses and dashes.

How to convert an ASCII character into an int in C

Use the ASCII to Integer atoi() function which accepts a string and converts it into an integer:

#include <stdlib.h>

int num = atoi("23"); // 23

If the string contains a decimal, the number will be truncated:

int num = atoi("23.21"); // 23

How do I read input character-by-character in Java?

You have several options if you use BufferedReader. This buffered reader is faster than Reader so you can wrap it.

BufferedReader reader = new BufferedReader(new FileReader(path));
reader.read(char[] buffer);

this reads line into char array. You have similar options. Look at documentation.

Indexes of all occurrences of character in a string

I had this problem as well, until I came up with this method.

public static int[] indexesOf(String s, String flag) {
    int flagLen = flag.length();
    String current = s;
    int[] res = new int[s.length()];
    int count = 0;
    int base = 0;
    while(current.contains(flag)) {
        int index = current.indexOf(flag);
        res[count] = index + base;
        base += index + flagLen;
        current = current.substring(current.indexOf(flag) + flagLen, current.length());
        ++ count;
    }
    return Arrays.copyOf(res, count);
}

This method can be used to find indexes of any flag of any length in a string, for example:

public class Main {

    public static void main(String[] args) {
        int[] indexes = indexesOf("Hello, yellow jello", "ll");

        // Prints [2, 9, 16]
        System.out.println(Arrays.toString(indexes));
    }

    public static int[] indexesOf(String s, String flag) {
        int flagLen = flag.length();
        String current = s;
        int[] res = new int[s.length()];
        int count = 0;
        int base = 0;
        while(current.contains(flag)) {
            int index = current.indexOf(flag);
            res[count] = index + base;
            base += index + flagLen;
            current = current.substring(current.indexOf(flag) + flagLen, current.length());
            ++ count;
        }
        return Arrays.copyOf(res, count);
    }
}

Is there an upside down caret character?

I did subscript capital & bolded V. It works perfectly (although it takes some effort, if it needs to be done repetitively)

Syntax:

<sub><strong>v</strong></sub>

Output:
v

How to determine if a String has non-alphanumeric characters?

You have to go through each character in the String and check Character.isDigit(char); or Character.isletter(char);

Alternatively, you can use regex.

Characters allowed in GET parameter

From RFC 1738 on which characters are allowed in URLs:

Only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

The reserved characters are ";", "/", "?", ":", "@", "=" and "&", which means you would need to URL encode them if you wish to use them.

How can I use modulo operator (%) in JavaScript?

That would be the modulo operator, which produces the remainder of the division of two numbers.

In Python, how to check if a string only contains certain characters?

Use python Sets when you need to compare hm... sets of data. Strings can be represented as sets of characters quite fast. Here I test if string is allowed phone number. First string is allowed, second not. Works fast and simple.

In [17]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(898) 64-901-63 ');p.issubset(allowed)").timeit()

Out[17]: 0.8106249139964348

In [18]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(950) 64-901-63 ???');p.issubset(allowed)").timeit()

Out[18]: 0.9240323599951807

Never use regexps if you can avoid them.

What characters are valid for JavaScript variable names?

Here is one quick suggestion for creating variable names. If you want the variable not to conflict when being used in FireFox, do not use the variable name "_content" as this variable name is already being used by the browser. I found this out the hard way and had to change all of the places I used the variable "_content" in a large JavaScript application.

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

getchar() is a standard function that on many platforms requires you to press ENTER to get the input, because the platform buffers input until that key is pressed. Many compilers/platforms support the non-standard getch() that does not care about ENTER (bypasses platform buffering, treats ENTER like just another key).

What method in the String class returns only the first N characters?

string truncatedToNLength = new string(s.Take(n).ToArray());  

This solution has a tiny bonus in that if n is greater than s.Length, it still does the right thing.

How can I get a Unicode character's code?

A more complete, albeit more verbose, way of doing this would be to use the Character.codePointAt method. This will handle 'high surrogate' characters, that cannot be represented by a single integer within the range that a char can represent.

In the example you've given this is not strictly necessary - if the (Unicode) character can fit inside a single (Java) char (such as the registered local variable) then it must fall within the \u0000 to \uffff range, and you won't need to worry about surrogate pairs. But if you're looking at potentially higher code points, from within a String/char array, then calling this method is wise in order to cover the edge cases.

For example, instead of

String input = ...;
char fifthChar = input.charAt(4);
int codePoint = (int)fifthChar;

use

String input = ...;
int codePoint = Character.codePointAt(input, 4);

Not only is this slightly less code in this instance, but it will handle detection of surrogate pairs for you.

What is a vertical tab?

Microsoft Word uses VT as a line separator in order to distinguish it from the normal new line function, which is used as a paragraph separator.

How to check if character is a letter in Javascript?

We can check also in simple way as:

_x000D_
_x000D_
function isLetter(char){_x000D_
    return ( (char >= 'A' &&  char <= 'Z') ||_x000D_
             (char >= 'a' &&  char <= 'z') );_x000D_
}_x000D_
_x000D_
_x000D_
console.log(isLetter("a"));_x000D_
console.log(isLetter(3));_x000D_
console.log(isLetter("H"));
_x000D_
_x000D_
_x000D_

Java String remove all non numeric characters

I would use a regex.

String text = "-jaskdh2367sd.27askjdfh23";
String digits = text.replaceAll("[^0-9.]", "");
System.out.println(digits);

prints

2367.2723

You might like to keep - as well for negative numbers.

Converting String to "Character" array in Java

If you don't want to rely on third party API's, here is a working code for JDK7 or below. I am not instantiating temporary Character Objects as done by other solutions above. foreach loops are more readable, see yourself :)

public static Character[] convertStringToCharacterArray(String str) {
    if (str == null || str.isEmpty()) {
        return null;
    }
    char[] c = str.toCharArray();
    final int len = c.length;
    int counter = 0;
    final Character[] result = new Character[len];
    while (len > counter) {
        for (char ch : c) {
            result[counter++] = ch;
        }
    }
    return result;
}

Remove first 4 characters of a string with PHP

$num = "+918883967576";

$str = substr($num, 3);

echo $str;

Output:8883967576

Getting The ASCII Value of a character in a C# string

Here is another alternative. It will of course give you a bad result if the input char is not ascii. I've not perf tested it but I think it would be pretty fast:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(string s, int index) {
    return GetAsciiVal(s[index]);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(char c) {
    return unchecked(c & 0xFF);
}

Remove last character from string. Swift language

A swift category that's mutating:

extension String {
    mutating func removeCharsFromEnd(removeCount:Int)
    {
        let stringLength = count(self)
        let substringIndex = max(0, stringLength - removeCount)
        self = self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

Use:

var myString = "abcd"
myString.removeCharsFromEnd(2)
println(myString) // "ab"

Max length UITextField

Since delegates are a 1-to-1 relationship and I might want to use it elsewhere for other reasons, I like to restrict textfield length adding this code within their setup:

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        setup()
    }

    required override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    func setup() {

        // your setup...

        setMaxLength()
    }

    let maxLength = 10

    private func setMaxLength() {
            addTarget(self, action: #selector(textfieldChanged(_:)), for: UIControlEvents.editingChanged)
        }

        @objc private func textfieldChanged(_ textField: UITextField) {
            guard let text = text else { return }
            let trimmed = text.characters.prefix(maxLength)
            self.text = String(trimmed)

        }

How to delete Certain Characters in a excel 2010 cell

Another option: =MID(A1,2,LEN(A1)-2)

Or this (for fun): =RIGHT(LEFT(A1,LEN(A1)-1),LEN(LEFT(A1,LEN(A1)-1))-1)

Display special characters when using print statement

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

How to compare character ignoring case in primitive types

You can't actually do the job quite right with toLowerCase, either on a string or in a character. The problem is that there are variant glyphs in either upper or lower case, and depending on whether you uppercase or lowercase your glyphs may or may not be preserved. It's not even clear what you mean when you say that two variants of a lower-case glyph are compared ignoring case: are they or are they not the same? (Note that there are also mixed-case glyphs: \u01c5, \u01c8, \u01cb, \u01f2 or ?, ?, ?, ?, but any method suggested here will work on those as long as they should count as the same as their fully upper or full lower case variants.)

There is an additional problem with using Char: there are some 80 code points not representable with a single Char that are upper/lower case variants (40 of each), at least as detected by Java's code point upper/lower casing. You therefore need to get the code points and change the case on these.

But code points don't help with the variant glyphs.

Anyway, here's a complete list of the glyphs that are problematic due to variants, showing how they fare against 6 variant methods:

  1. Character toLowerCase
  2. Character toUpperCase
  3. String toLowerCase
  4. String toUpperCase
  5. String equalsIgnoreCase
  6. Character toLowerCase(toUpperCase) (or vice versa)

For these methods, S means that the variants are treated the same as each other, D means the variants are treated as different from each other.

Behavior     Unicode                             Glyphs
===========  ==================================  =========
1 2 3 4 5 6  Upper  Lower  Var Up Var Lo Vr Lo2  U L u l l2
- - - - - -  ------ ------ ------ ------ ------  - - - - -
D D D D S S  \u0049 \u0069 \u0130 \u0131         I i I i   
S D S D S S  \u004b \u006b \u212a                K k K     
D S D S S S  \u0053 \u0073        \u017f         S s   ?   
D S D S S S  \u039c \u03bc        \u00b5         ? µ   µ   
S D S D S S  \u00c5 \u00e5 \u212b                Å å Å     
D S D S S S  \u0399 \u03b9        \u0345 \u1fbe  ? ?   ? ? 
D S D S S S  \u0392 \u03b2        \u03d0         ? ß   ?   
D S D S S S  \u0395 \u03b5        \u03f5         ? e   ?   
D D D D S S  \u0398 \u03b8 \u03f4 \u03d1         T ? ? ?   
D S D S S S  \u039a \u03ba        \u03f0         ? ?   ?   
D S D S S S  \u03a0 \u03c0        \u03d6         ? p   ?   
D S D S S S  \u03a1 \u03c1        \u03f1         ? ?   ?   
D S D S S S  \u03a3 \u03c3        \u03c2         S s   ?   
D S D S S S  \u03a6 \u03c6        \u03d5         F f   ?   
S D S D S S  \u03a9 \u03c9 \u2126                O ? ?     
D S D S S S  \u1e60 \u1e61        \u1e9b         ? ?   ?   

Complicating this still further is that there is no way to get the Turkish I's right (i.e. the dotted versions are different than the undotted versions) unless you know you're in Turkish; none of these methods give correct behavior and cannot unless you know the locale (i.e. non-Turkish: i and I are the same ignoring case; Turkish, not).

Overall, using toUpperCase gives you the closest approximation, since you have only five uppercase variants (or four, not counting Turkish).

You can also try to specifically intercept those five troublesome cases and call toUpperCase(toLowerCase(c)) on them alone. If you choose your guards carefully (just toUpperCase if c < 0x130 || c > 0x212B, then work through the other alternatives) you can get only a ~20% speed penalty for characters in the low range (as compared to ~4x if you convert single characters to strings and equalsIgnoreCase them) and only about a 2x penalty if you have a lot in the danger zone. You still have the locale problem with dotted I, but otherwise you're in decent shape. Of course if you can use equalsIgnoreCase on a larger string, you're better off doing that.

Here is sample Scala code that does the job:

def elevateCase(c: Char): Char = {
  if (c < 0x130 || c > 0x212B) Character.toUpperCase(c)
  else if (c == 0x130 || c == 0x3F4 || c == 0x2126 || c >= 0x212A)
    Character.toUpperCase(Character.toLowerCase(c))
  else Character.toUpperCase(c)
}

What characters do I need to escape in XML documents?

Only < and & are required to be escaped if they are to be treated character data and not markup:

2.4 Character Data and Markup

How to read a single character at a time from a file in Python?

You should try f.read(1), which is definitely correct and the right thing to do.

Remove all occurrences of char from string

You can use str = str.replace("X", ""); as mentioned before and you will be fine. For your information '' is not an empty (or a valid) character but '\0' is.

So you could use str = str.replace('X', '\0'); instead.

Python: Get the first character of the first string in a list?

You almost had it right. The simplest way is

mylist[0][0]   # get the first character from the first item in the list

but

mylist[0][:1]  # get up to the first character in the first item in the list

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.

Get nth character of a string in Swift programming language

prob one of the best and simpliest way

        let yourString = "thisString"
        print(Array(yourString)[8])

puts each letters of your string into arrrays and then you sellect the 9th one

Convert data.frame column format from character to factor

Another short way you could use is a pipe (%<>%) from the magrittr package. It converts the character column mycolumn to a factor.

library(magrittr)

mydf$mycolumn %<>% factor

Set the maximum character length of a UITextField in Swift

1.Set the delegate of your textfield:

 textField.delegate = self

2.Implement the method in your view controller :

// MARK: Text field delegate

extension ViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return range.location < maxLength (maxLength can be any maximum length you can define)
    }
}

HTML character codes for this ? or this ?

You don't need to use character codes; just use UTF-8 and put them in literally; like so:

??

If you absolutely must use the entites, they are &#x25b2; and &#x25bc;, respectively.

How to index characters in a Golang string?

The general solution to interpreting a char as a string is string("HELLO"[1]).

Rich's solution also works, of course.

Replace a character at a specific index in a string?

You can overwrite a string, as follows:

String myName = "halftime";
myName = myName.substring(0,4)+'x'+myName.substring(5);  

Note that the string myName occurs on both lines, and on both sides of the second line.

Therefore, even though strings may technically be immutable, in practice, you can treat them as editable by overwriting them.

In Java, should I escape a single quotation mark (') in String (double quoted)?

It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!

The only times you should need to escape are when trying to put " inside a string, or ' in a character:

String quotes = "He said \"Hello, World!\"";
char quote = '\'';

How to Read from a Text File, Character by Character in C++

There is no reason not to use C <stdio.h> in C++, and in fact it is often the optimal choice.

#include <stdio.h>

int
main()  // (void) not necessary in C++
{
    int c;
    while ((c = getchar()) != EOF) {
        // do something with 'c' here
    }
    return 0; // technically not necessary in C++ but still good style
}

How can I check if a single character appears in a string?

You can use 2 methods from the String class.

  • String.contains() which checks if the string contains a specified sequence of char values
  • String.indexOf() which returns the index within the string of the first occurence of the specified character or substring or returns -1 if the character is not found (there are 4 variations of this method)

Method 1:

String myString = "foobar";
if (myString.contains("x") {
    // Do something.
}

Method 2:

String myString = "foobar";
if (myString.indexOf("x") >= 0 {
    // Do something.
}

Links by: Zach Scrivena

How to get the number of characters in a string

There are several ways to get a string length:

package main

import (
    "bytes"
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    b := "?????"
    len1 := len([]rune(b))
    len2 := bytes.Count([]byte(b), nil) -1
    len3 := strings.Count(b, "") - 1
    len4 := utf8.RuneCountInString(b)
    fmt.Println(len1)
    fmt.Println(len2)
    fmt.Println(len3)
    fmt.Println(len4)

}

Java character array initializer

You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?

When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
}

It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
  System.out.println(array[count]);
}

At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.

String ini = "Hi there";

for (int count = 0; count < ini.length(); count++) {
   System.out.println(ini.charAt(count));
}

Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string

String ini = "Hi there"; // stored in String constant pool

is stored differently in memory than

String ini = new String("Hi there"); // stored in heap memory and String constant pool

, which is stored differently than

char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string

.

How to check the first character in a string in Bash or UNIX shell?

Consider the case statement as well which is compatible with most sh-based shells:

case $str in
/*)
    echo 1
    ;;
*)
    echo 0
    ;;
esac

Output single character in C

As mentioned in one of the other answers, you can use putc(int c, FILE *stream), putchar(int c) or fputc(int c, FILE *stream) for this purpose.

What's important to note is that using any of the above functions is from some to signicantly faster than using any of the format-parsing functions like printf.

Using printf is like using a machine gun to fire one bullet.

getch and arrow codes

getch () function returns two keycodes for arrow keys (and some other special keys), as mentioned in the comment by FatalError. It returns either 0 (0x00) or 224 (0xE0) first, and then returns a code identifying the key that was pressed.

For the arrow keys, it returns 224 first followed by 72 (up), 80 (down), 75 (left) and 77 (right). If the num-pad arrow keys (with NumLock off) are pressed, getch () returns 0 first instead of 224.

Please note that getch () is not standardized in any way, and these codes might vary from compiler to compiler. These codes are returned by MinGW and Visual C++ on Windows.

A handy program to see the action of getch () for various keys is:

#include <stdio.h>
#include <conio.h>

int main ()
{
    int ch;

    while ((ch = _getch()) != 27) /* 27 = Esc key */
    {
        printf("%d", ch);
        if (ch == 0 || ch == 224)
            printf (", %d", _getch ()); 
        printf("\n");
    }

    printf("ESC %d\n", ch);

    return (0);
}

This works for MinGW and Visual C++. These compilers use the name _getch () instead of getch () to indicate that it is a non-standard function.

So, you may do something like:

ch = _getch ();
if (ch == 0 || ch == 224)
{
    switch (_getch ())
    {
        case 72:
            /* Code for up arrow handling */
            break;

        case 80:
            /* Code for down arrow handling */
            break;

        /* ... etc ... */
    }
}

Repeat a string in JavaScript a number of times

Here is an ES6 version

_x000D_
_x000D_
const repeat = (a,n) => Array(n).join(a+"|$|").split("|$|");_x000D_
repeat("A",20).forEach((a,b) => console.log(a,b+1))
_x000D_
_x000D_
_x000D_

Remove all special characters from a string in R?

Convert the Special characters to apostrophe,

Data  <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)

Below code it to remove extra ''' apostrophe

Data <- gsub("''","" , Data ,ignore.case = TRUE)

Use gsub(..) function for replacing the special character with apostrophe

Representing EOF in C code?

The value of EOF can't be confused with any real character.

If a= getchar(), then we must declare a big enough to hold any value that getchar() returns. We can't use char since a must be big enough to hold EOF in addition to characters.

What is the difference between a string and a byte string?

The Python languages includes str and bytes as standard "Built-in Types". In other words, they are both classes. I don't think it's worthwhile trying to rationalize why Python has been implemented this way.

Having said that, str and bytes are very similar to one another. Both share most of the same methods. The following methods are unique to the str class:

casefold
encode
format
format_map
isdecimal
isidentifier
isnumeric
isprintable

The following methods are unique to the bytes class:

decode
fromhex
hex

How to concatenate characters in java?

System.out.print(a + "" + b + "" + c);

Converting a character code to char (VB.NET)

you can also use

Dim intValue as integer = 65  ' letter A for instance
Dim strValue As String = Char.ConvertFromUtf32(intValue)

this doesn't requirement Microsoft.VisualBasic reference

How can I escape square brackets in a LIKE clause?

I needed to exclude names that started with an underscore from a query, so I ended up with this:

WHERE b.[name] not like '\_%' escape '\'  -- use \ as the escape character

How do I use a char as the case in a switch-case?

Here's an example:

public class Main {

    public static void main(String[] args) {

        double val1 = 100;
        double val2 = 10;
        char operation = 'd';
        double result = 0;

        switch (operation) {

            case 'a':
                result = val1 + val2; break;

            case 's':
                result = val1 - val2; break;
            case 'd':
                if (val2 != 0)
                    result = val1 / val2; break;
            case 'm':
                result = val1 * val2; break;

            default: System.out.println("Not a defined operation");


        }

        System.out.println(result);
    }
}

Converting characters to integers in Java

43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back. http://en.wikipedia.org/wiki/ASCII

How can I remove a character from a string using JavaScript?

You can use this: if ( str[4] === 'r' ) str = str.slice(0, 4) + str.slice(5)

Explanation:

  1. if ( str[4] === 'r' )
    Check if the 5th character is a 'r'

  2. str.slice(0, 4)
    Slice the string to get everything before the 'r'

  3. + str.slice(5)
    Add the rest of the string.

Minified: s=s[4]=='r'?s.slice(0,4)+s.slice(5):s [37 bytes!]

DEMO:

_x000D_
_x000D_
function remove5thR (s) {_x000D_
  s=s[4]=='r'?s.slice(0,4)+s.slice(5):s;_x000D_
  console.log(s); // log output_x000D_
}_x000D_
_x000D_
remove5thR('crt/r2002_2')  // > 'crt/2002_2'_x000D_
remove5thR('crt|r2002_2')  // > 'crt|2002_2'_x000D_
remove5thR('rrrrr')        // > 'rrrr'_x000D_
remove5thR('RRRRR')        // > 'RRRRR' (no change)
_x000D_
_x000D_
_x000D_

Handling the TAB character in Java

Yes the tab character is one character. You can match it in java with "\t".

Better way to remove specific characters from a Perl string

With a character class this big it is easier to say what you want to keep. A caret in the first position of a character class inverts its sense, so you can write

$varTemp =~ s/[^"%'+\-0-9<=>a-z_{|}]+//gi

or, using the more efficient tr

$varTemp =~ tr/"%'+\-0-9<=>A-Z_a-z{|}//cd

tr docs

Invisible characters - ASCII

An invisible Character is ?, or U+200b

?

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

There are some dedicated classes for this:

import java.text.*;

final CharacterIterator it = new StringCharacterIterator(s);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
   // process c
   ...
}

How to convert integers to characters in C?

Program Converts ASCII to Alphabet

#include<stdio.h>

void main ()
{

  int num;
  printf ("=====This Program Converts ASCII to Alphabet!=====\n");
  printf ("Enter ASCII: ");
  scanf ("%d", &num);
  printf("%d is ASCII value of '%c'", num, (char)num );
}

Program Converts Alphabet to ASCII code

#include<stdio.h>

void main ()
{

  char alphabet;
  printf ("=====This Program Converts Alphabet to ASCII code!=====\n");
  printf ("Enter Alphabet: ");
  scanf ("%c", &alphabet);
  printf("ASCII value of '%c' is %d", alphabet, (char)alphabet );
}

How many characters can you store with 1 byte?

The syntax of TINYINT data type is TINYINT(M),

where M indicates the maximum display width (used only if your MySQL client supports it).

The (m) indicates the column width in SELECT statements; however, it doesn't control the accepted range of numbers for that field.

A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 >bits, BIT(64). For a boolean values, BIT(1) is pretty common.

TINYINT()

How can I list all of the files in a directory with Perl?

Or File::Find

use File::Find;
finddepth(\&wanted, '/some/path/to/dir');
sub wanted { print };

It'll go through subdirectories if they exist.

How to decode viewstate

Here's an online ViewState decoder:

http://ignatu.co.uk/ViewStateDecoder.aspx

Edit: Unfortunatey, the above link is dead - here's another ViewState decoder (from the comments):

http://viewstatedecoder.azurewebsites.net/

Filter Pyspark dataframe column with None value

To obtain entries whose values in the dt_mvmt column are not null we have

df.filter("dt_mvmt is not NULL")

and for entries which are null we have

df.filter("dt_mvmt is NULL")

Filter output in logcat by tagname

Here is how I create a tag:

private static final String TAG = SomeActivity.class.getSimpleName();
 Log.d(TAG, "some description");

You could use getCannonicalName

Here I have following TAG filters:

  • any (*) View - VERBOSE
  • any (*) Activity - VERBOSE
  • any tag starting with Xyz(*) - ERROR
  • System.out - SILENT (since I am using Log in my own code)

Here what I type in terminal:

$  adb logcat *View:V *Activity:V Xyz*:E System.out:S

How to compile .c file with OpenSSL includes?

Your include paths indicate that you should be compiling against the system's OpenSSL installation. You shouldn't have the .h files in your package directory - it should be picking them up from /usr/include/openssl.

The plain OpenSSL package (libssl) doesn't include the .h files - you need to install the development package as well. This is named libssl-dev on Debian, Ubuntu and similar distributions, and libssl-devel on CentOS, Fedora, Red Hat and similar.

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

Window->Show View->device (if not found ->Other->Device) in right most side, there is arrow, click that, you will see reset adb, just click and enjoy!! It worked for me.

mvn clean install vs. deploy vs. release

The clean, install and deploy phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.

mvn clean install

This command invokes the clean phase and then the install phase sequentially:

  • clean: removes files generated at build-time in a project's directory (target by default)
  • install: installs the package into the local repository, for use as a dependency in other projects locally.

mvn deploy

This command invokes the deploy phase:

  • deploy: copies the final package to the remote repository for sharing with other developers and projects.

mvn release

This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare and perform. As documented:

Preparing a release goes through the following release phases:

  • Check that there are no uncommitted changes in the sources
  • Check that there are no SNAPSHOT dependencies
  • Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
  • Transform the SCM information in the POM to include the final destination of the tag
  • Run the project tests against the modified POMs to confirm everything is in working order
  • Commit the modified POMs
  • Tag the code in the SCM with a version name (this will be prompted for)
  • Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
  • Commit the modified POMs

And then:

Performing a release runs the following release phases:

  • Checkout from an SCM URL with optional tag
  • Run the predefined Maven goals to release the project (by default, deploy site-deploy)

See also

Python Web Crawlers and "getting" html source code

If you are using Python > 3.x you don't need to install any libraries, this is directly built in the python framework. The old urllib2 package has been renamed to urllib:

from urllib import request

response = request.urlopen("https://www.google.com")
# set the correct charset below
page_source = response.read().decode('utf-8')
print(page_source)

How to save an activity state using save instance state?

My problem was that I needed persistence only during the application lifetime (i.e. a single execution including starting other sub-activities within the same app and rotating the device etc). I tried various combinations of the above answers but did not get what I wanted in all situations. In the end what worked for me was to obtain a reference to the savedInstanceState during onCreate:

mySavedInstanceState=savedInstanceState;

and use that to obtain the contents of my variable when I needed it, along the lines of:

if (mySavedInstanceState !=null) {
   boolean myVariable = mySavedInstanceState.getBoolean("MyVariable");
}

I use onSaveInstanceStateand onRestoreInstanceState as suggested above but I guess i could also or alternatively use my method to save the variable when it changes (e.g. using putBoolean)

Erasing elements from a vector

Calling erase will invalidate iterators, you could use:

void erase(std::vector<int>& myNumbers_in, int number_in)
{
    std::vector<int>::iterator iter = myNumbers_in.begin();
    while (iter != myNumbers_in.end())
    {
        if (*iter == number_in)
        {
            iter = myNumbers_in.erase(iter);
        }
        else
        {
           ++iter;
        }
    }

}

Or you could use std::remove_if together with a functor and std::vector::erase:

struct Eraser
{
    Eraser(int number_in) : number_in(number_in) {}
    int number_in;
    bool operator()(int i) const
    {
        return i == number_in;
    }
};

std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), Eraser(number_in)), myNumbers.end());

Instead of writing your own functor in this case you could use std::remove:

std::vector<int> myNumbers;
myNumbers.erase(std::remove(myNumbers.begin(), myNumbers.end(), number_in), myNumbers.end());

In C++11 you could use a lambda instead of a functor:

std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), [number_in](int number){ return number == number_in; }), myNumbers.end());

In C++17 std::experimental::erase and std::experimental::erase_if are also available, in C++20 these are (finally) renamed to std::erase and std::erase_if (note: in Visual Studio 2019 you'll need to change your C++ language version to the latest experimental version for support):

std::vector<int> myNumbers;
std::erase_if(myNumbers, Eraser(number_in)); // or use lambda

or:

std::vector<int> myNumbers;
std::erase(myNumbers, number_in);

TSQL select into Temp table from dynamic sql

How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)

DECLARE @sql AS nvarchar(MAX)
declare @Month Nvarchar(1000)

--DROP TABLE #temp
select distinct YYYYMM into #temp from #AccPurch AS ap
SELECT  @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM    #temp

SELECT   @Month= LEFT(@Month,len(@Month)-1)


SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
Select ap.AccPurch ,
       ap.YYYYMM ,
       ap.UserID ,
       ap.AccountNumber
FROM #AccPurch AS ap 
) p
Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'


EXEC sp_executesql @sql

Select * INTO #final From ##final_Donovan_12345

DROP TABLE  ##final_Donovan_12345

Select * From #final AS f

How to disable the back button in the browser using JavaScript

You can't, and you shouldn't.

Every other approach / alternative will only cause really bad user engagement.

That's my opinion.

Sending and Parsing JSON Objects in Android

This is the JsonParser class

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

Note: DefaultHttpClient is no longer supported by sdk 23, so it is advisable to use target sdk 21 with this code.

How to overcome root domain CNAME restrictions?

You have to put a period at the end of the external domain so it doesn't think you mean customer1.mycompanydomain.com.localdomain;

So just change:

customer1.com IN CNAME customer1.mycompanydomain.com

To

customer1.com IN CNAME customer1.mycompanydomain.com.

Converting Epoch time into the datetime

#This adds 10 seconds from now.
from datetime import datetime
import commands

date_string_command="date +%s"
utc = commands.getoutput(date_string_command)
a_date=datetime.fromtimestamp(float(int(utc))).strftime('%Y-%m-%d %H:%M:%S')
print('a_date:'+a_date)
utc = int(utc)+10
b_date=datetime.fromtimestamp(float(utc)).strftime('%Y-%m-%d %H:%M:%S')
print('b_date:'+b_date)

This is a little more wordy but it comes from date command in unix.

Setting a div's height in HTML with CSS

I can think of 2 options

  1. Use javascript to resize the smaller column on page load.
  2. Fake the equal heights by setting the background-color for the column on the container <div/> instead (<div class="separator"/>) with repeat-y

Use string value from a cell to access worksheet of same name

You need INDIRECT function:

=INDIRECT("'"&A5&"'!G7")

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

Well, I like MONEY! It's a byte cheaper than DECIMAL, and the computations perform quicker because (under the covers) addition and subtraction operations are essentially integer operations. @SQLMenace's example—which is a great warning for the unaware—could equally be applied to INTegers, where the result would be zero. But that's no reason not to use integers—where appropriate.

So, it's perfectly 'safe' and appropriate to use MONEY when what you are dealing with is MONEY and use it according to mathematical rules that it follows (same as INTeger).

Would it have been better if SQL Server promoted division and multiplication of MONEY's into DECIMALs (or FLOATs?)—possibly, but they didn't choose to do this; nor did they choose to promote INTegers to FLOATs when dividing them.

MONEY has no precision issue; that DECIMALs get to have a larger intermediate type used during calculations is just a 'feature' of using that type (and I'm not actually sure how far that 'feature' extends).

To answer the specific question, a "compelling reason"? Well, if you want absolute maximum performance in a SUM(x) where x could be either DECIMAL or MONEY, then MONEY will have an edge.

Also, don't forget it's smaller cousin, SMALLMONEY—just 4 bytes, but it does max out at 214,748.3647 - which is pretty small for money—and so is not often a good fit.

To prove the point around using larger intermediate types, if you assign the intermediate explicitly to a variable, DECIMAL suffers the same problem:

declare @a decimal(19,4)
declare @b decimal(19,4)
declare @c decimal(19,4)
declare @d decimal(19,4)

select @a = 100, @b = 339, @c = 10000

set @d = @a/@b

set @d = @d*@c

select @d

Produces 2950.0000 (okay, so at least DECIMAL rounded rather than MONEY truncated—same as an integer would.)

Convert between UIImage and Base64 string

It's a very good to understand do you pass prefix as Tyler Sheaffer told. But for some reason you may need this prefix that describe the mime-type in the beginning of the base64 string, so I suggest this piece of code to pass some options before encoding (Swift 5):

extension UIImage {

    enum Format: String {
        case png = "png"
        case jpeg = "jpeg"
    }

    func toBase64(type: Format = .jpeg, quality: CGFloat = 1, addMimePrefix: Bool = false) -> String? {
        let imageData: Data?
        switch type {
        case .jpeg: imageData = jpegData(compressionQuality: quality)
        case .png:  imageData = pngData()
        }
        guard let data = imageData else { return nil }

        let base64 = data.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)

        var result = base64
        if addMimePrefix {
            let prefix = "data:image/\(type.rawValue);base64,"
            result = prefix + base64
        }
        return result
    }
}

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

iOS Remote Debugging

Open Safari Desktop iOS

Develop -> Responsive Design Mode

Click "Other" under device

Paste this: Mozilla/5.0 (iPad; CPU OS 10_2_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.79 Mobile/14D27 Safari/602.1

Use Safari inspect tools.

How to add an element to Array and shift indexes?

System.arraycopy is more performant but tricky to get right due to indexes calculations. Better stick with jrad answer or ArrayList if you don't have performance requirements.

public static int[] insert(
    int[] array, int elementToInsert, int index) {
  int[] result = new int[array.length + 1];
  // copies first part of the array from the start up until the index
  System.arraycopy(
      array /* src */,
      0 /* srcPos */,
      result /* dest */,
      0 /* destPos */,
      index /* length */);
  // copies second part from the index up until the end shifting by 1 to the right
  System.arraycopy(
      array /* src */,
      index /* srcPos */,
      result /* dest */,
      index + 1 /* destPos */,
      array.length - index /* length */);
  result[index] = elementToInsert;
  return result;
}

And JUnit4 test to check it works as expected.

@Test
public void shouldInsertCorrectly() {
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{1, 3}, 2, 1));
  Assert.assertArrayEquals(
      new int[]{1}, insert(new int[]{}, 1, 0));
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{2, 3}, 1, 0));
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{1, 2}, 3, 2));
}

Angular 2 Checkbox Two Way Data Binding

My angular directive like angularjs (ng-true-value ng-false-value)

@Directive({
    selector: 'input[type=checkbox][checkModel]'
})
export class checkboxDirective {
    @Input() checkModel:any;
    @Input() trueValue:any;
    @Input() falseValue:any;
    @Output() checkModelChange = new EventEmitter<any>();

    constructor(private el: ElementRef) { }

    ngOnInit() {
       this.el.nativeElement.checked = this.checkModel==this.trueValue;
    }

    @HostListener('change', ['$event']) onChange(event:any) {
        this.checkModel = event.target.checked ? this.trueValue : this.falseValue;
        this.checkModelChange.emit(this.checkModel);
    }

}

html

<input type="checkbox" [(checkModel)]="check" [trueValue]="1" [falseValue]="0">

How to replace NaNs by preceding values in pandas DataFrame?

Only one column version

  • Fill NAN with last valid value
df[column_name].fillna(method='ffill', inplace=True)
  • Fill NAN with next valid value
df[column_name].fillna(method='backfill', inplace=True)

How to convert date format to milliseconds?

long millisecond = beginupd.getTime();

Date.getTime() JavaDoc states:

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Echo a blank (empty) line to the console from a Windows batch file

Note: Though my original answer attracted several upvotes, I decided that I could do much better. You can find my original (simplistic and misguided) answer in the edit history.

If Microsoft had the intent of providing a means of outputting a blank line from cmd.exe, Microsoft surely would have documented such a simple operation. It is this omission that motivated me to ask this question.

So, because a means for outputting a blank line from cmd.exe is not documented, arguably one should consider any suggestion for how to accomplish this to be a hack. That means that there is no known method for outputting a blank line from cmd.exe that is guaranteed to work (or work efficiently) in all situations.

With that in mind, here is a discussion of methods that have been recommended for outputting a blank line from cmd.exe. All recommendations are based on variations of the echo command.


echo.

While this will work in many if not most situations, it should be avoided because it is slower than its alternatives and actually can fail (see here, here, and here). Specifically, cmd.exe first searches for a file named echo and tries to start it. If a file named echo happens to exist in the current working directory, echo. will fail with:

'echo.' is not recognized as an internal or external command,
operable program or batch file.

echo:
echo\

At the end of this answer, the author argues that these commands can be slow, for instance if they are executed from a network drive location. A specific reason for the potential slowness is not given. But one can infer that it may have something to do with accessing the file system. (Perhaps because : and \ have special meaning in a Windows file system path?)

However, some may consider these to be safe options since : and \ cannot appear in a file name. For that or another reason, echo: is recommended by SS64.com here.


echo(
echo+
echo,
echo/
echo;
echo=
echo[
echo]

This lengthy discussion includes what I believe to be all of these. Several of these options are recommended in this SO answer as well. Within the cited discussion, this post ends with what appears to be a recommendation for echo( and echo:.

My question at the top of this page does not specify a version of Windows. My experimentation on Windows 10 indicates that all of these produce a blank line, regardless of whether files named echo, echo+, echo,, ..., echo] exist in the current working directory. (Note that my question predates the release of Windows 10. So I concede the possibility that older versions of Windows may behave differently.)

In this answer, @jeb asserts that echo( always works. To me, @jeb's answer implies that other options are less reliable but does not provide any detail as to why that might be. Note that @jeb contributed much valuable content to other references I have cited in this answer.


Conclusion: Do not use echo.. Of the many other options I encountered in the sources I have cited, the support for these two appears most authoritative:

echo(
echo:

But I have not found any strong evidence that the use of either of these will always be trouble-free.


Example Usage:

@echo off
echo Here is the first line.
echo(
echo There is a blank line above this line.

Expected output:

Here is the first line.

There is a blank line above this line.

Add User to Role ASP.NET Identity

Check this link: Assigning Roles to Users. You can add a step to your CreateUserWIzard control and choose the roles in that step.

<asp:CreateUserWizard ID="RegisterUserWithRoles" runat="server" 
    ContinueDestinationPageUrl="~/Default.aspx" LoginCreatedUser="False" 
    onactivestepchanged="RegisterUserWithRoles_ActiveStepChanged">
    <WizardSteps>
        <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
        </asp:CreateUserWizardStep>
        <asp:WizardStep ID="SpecifyRolesStep" runat="server" AllowReturn="False" 
            StepType="Step" Title="Specify Roles">
            <h3>Choose the role.</h3>
            <asp:CheckBoxList ID="RoleList" runat="server">
            </asp:CheckBoxList>
        </asp:WizardStep>
        <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
        </asp:CompleteWizardStep>
    </WizardSteps>
</asp:CreateUserWizard>

And in the code-behind you will have:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // Reference the SpecifyRolesStep WizardStep 
        WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;

        // Reference the RoleList CheckBoxList 
        CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;

        // Bind the set of roles to RoleList 
        RoleList.DataSource = Roles.GetAllRoles();
        RoleList.DataBind();
    } 
}
protected void RegisterUserWithRoles_ActiveStepChanged(object sender, EventArgs e)
{
    // Have we JUST reached the Complete step? 
    if (RegisterUserWithRoles.ActiveStep.Title == "Complete")
    {
        // Reference the SpecifyRolesStep WizardStep 
        WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;

        // Reference the RoleList CheckBoxList 
        CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;

        // Add the checked roles to the just-added user 
        foreach (ListItem li in RoleList.Items)
        {
            if (li.Selected)
                Roles.AddUserToRole(RegisterUserWithRoles.UserName, li.Text);
        }
    }
}

How to create an Array with AngularJS's ng-model

One way is to convert your array to an object and use it in scope (simulation of an array). This way has the benefit of maintaining the template.

$scope.telephone = {};
for (var i = 0, l = $scope.phones.length; i < l; i++) {
  $scope.telephone[i.toString()] = $scope.phone[i];
}

<input type="text" ng-model="telephone[0.toString()]" />
<input type="text" ng-model="telephone[1.toString()]" />

and on save, change it back.

$scope.phones = [];
for (var i in $scope.telephone) {
  $scope.phones[parseInt(i)] = $scope.telephone[i];
}

Does WhatsApp offer an open API?

1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.

2) No. See the whatsapp security white paper.

3) See #1.

Redirect with CodeIgniter

redirect()

URL Helper


The redirect statement in code igniter sends the user to the specified web page using a redirect header statement.

This statement resides in the URL helper which is loaded in the following way:

$this->load->helper('url');

The redirect function loads a local URI specified in the first parameter of the function call and built using the options specified in your config file.

The second parameter allows the developer to use different HTTP commands to perform the redirect "location" or "refresh".

According to the Code Igniter documentation: "Location is faster, but on Windows servers it can sometimes be a problem."

Example:

if ($user_logged_in === FALSE)
{
     redirect('/account/login', 'refresh');
}

Extract code country from phone number [libphonenumber]

I have got kept a handy helper method to take care of this based on one answer posted above:

Imports:

import com.google.i18n.phonenumbers.NumberParseException
import com.google.i18n.phonenumbers.PhoneNumberUtil

Function:

    fun parseCountryCode( phoneNumberStr: String?): String {
        val phoneUtil = PhoneNumberUtil.getInstance()
        return try {
            // phone must begin with '+'
            val numberProto = phoneUtil.parse(phoneNumberStr, "")
            numberProto.countryCode.toString()
        } catch (e: NumberParseException) {
            ""
        }
    }

Where does Oracle SQL Developer store connections?

If you don't find the connections.xml then right-click on Connections in the Connections view of SQLDeveloper, and choose Export connections.

Do the parentheses after the type name make a difference with new?

Assuming that Test is a class with a defined constructor, there's no difference. The latter form makes it a little clearer that Test's constructor is running, but that's about it.

Git: Pull from other remote

git pull is really just a shorthand for git pull <remote> <branchname>, in most cases it's equivalent to git pull origin master. You will need to add another remote and pull explicitly from it. This page describes it in detail:

http://help.github.com/forking/

Handling data in a PHP JSON Object

Just use it like it was an object you defined. i.e.

$trends = $json_output->trends;

Beginner Python Practice?

I used http://codingbat.com/ . A great website that not only takes one answer, like Project Euler, but also checks your code for more robustness by running it through multiple tests. It asks for much broader code than Project Euler, but its also much simpler than most Euler problems. It also has progress graphs which are pretty cool.

Creating a data frame from two vectors using cbind

Vectors and matrices can only be of a single type and cbind and rbind on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.

(Note that in your rbind example, the promotion happens within the c call:

> c(10, "[]", "[[1,2]]")
[1] "10"      "[]"      "[[1,2]]"

If you want a rectangular structure where the columns can be different types, you want a data.frame. Any of the following should get you what you want:

> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
  v1 v2      v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ v1: num  10 20
 $ v2: Factor w/ 1 level "[]": 1 1
 $ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using specifically the data.frame version of cbind)

> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c(10, 20)              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using cbind, but making the first a data.frame so that it combines as data.frames do):

> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c.10..20.              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

Is there a way to return a list of all the image file names from a folder using only Javascript?

No. JavaScript is a client-side technology and cannot do anything on the server. You could however use AJAX to call a server-side script (e.g. PHP) which could return the information you need.

If you want to use AJAX, the easiest way will be to utilise jQuery:

$.post("someScript.php", function(data) {
   console.log(data); //"data" contains whatever someScript.php returned
});

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

Same package error:

  1. Create a new Package in your app with different name.
  2. Copy and paste all file in your old package to new Package.
  3. Save Code.
  4. Delete old Package And Clean and rebuild project.

SQL - HAVING vs. WHERE

You can not use where clause with aggregate functions because where fetch records on the basis of condition, it goes into table record by record and then fetch record on the basis of condition we have give. So that time we can not where clause. While having clause works on the resultSet which we finally get after running a query.

Example query:

select empName, sum(Bonus) 
from employees 
order by empName 
having sum(Bonus) > 5000;

This will store the resultSet in a temporary memory, then having clause will perform its work. So we can easily use aggregate functions here.

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root).

The code I am looking for is adjusting the savefig call to:

fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable

This is apparently similar to calling tight_layout, but instead you allow savefig to consider extra artists in the calculation. This did in fact resize the figure box as desired.

import matplotlib.pyplot as plt
import numpy as np

plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')

This produces:

[edit] The intent of this question was to completely avoid the use of arbitrary coordinate placements of arbitrary text as was the traditional solution to these problems. Despite this, numerous edits recently have insisted on putting these in, often in ways that led to the code raising an error. I have now fixed the issues and tidied the arbitrary text to show how these are also considered within the bbox_extra_artists algorithm.

What is the SQL command to return the field names of a table?

For IBM DB2 (will double check this on Monday to be sure.)

SELECT TABNAME,COLNAME from SYSCAT.COLUMNS where TABNAME='MYTABLE'

Accessing value inside nested dictionaries

My implementation:

def get_nested(data, *args):
    if args and data:
        element  = args[0]
        if element:
            value = data.get(element)
            return value if len(args) == 1 else get_nested(value, *args[1:])

Example usage:

>>> dct={"foo":{"bar":{"one":1, "two":2}, "misc":[1,2,3]}, "foo2":123}
>>> get_nested(dct, "foo", "bar", "one")
1
>>> get_nested(dct, "foo", "bar", "two")
2
>>> get_nested(dct, "foo", "misc")
[1, 2, 3]
>>> get_nested(dct, "foo", "missing")
>>>

There are no exceptions raised in case a key is missing, None value is returned in that case.

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

As of Oct 2019, SQL Server Management Studio, they did not upgraded the SSMS to add create ER Diagram feature.

I would suggest try using DBWeaver from here :

https://dbeaver.io/download/

I am using Mac and Windows both and I was able to download the community edition and logged into my SQL server database and was able to create the ER diagram using the DB Weaver.

ER Diagram using the Community Version Db Viewer

TypeError: got multiple values for argument

Simply put you can't do the following:

class C(object):
    def x(self, y, **kwargs):
        # Which y to use, kwargs or declaration? 
        pass

c = C()
y = "Arbitrary value"
kwargs["y"] = "Arbitrary value"
c.x(y, **kwargs) # FAILS

Because you pass the variable 'y' into the function twice: once as kwargs and once as function declaration.

center image in div with overflow hidden

I have been trying to implement Jaap's answer inside this page of my recent site, with one difference : the .main {height:} was set to auto instead of a fixed px value. As responsive developer i am looking for a solution to synchronize the image height with the left floating text element, yet only in case my text height becomes greater then my actual image height. In that case the image should not be rescaled, but cropped and centered as decribed in the original question here above. Can this be done ? You can simulate the behaviour by slowly downsizing the browser's width.

How to install sklearn?

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

pip install -U scikit-learn

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

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

1) Put =Left(E1,5) in F1

2) Copy F1, then select entire F column and paste.

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

Try to do an UPDATE. If it doesn't modify any row that means it didn't exist, so do an insert. Obviously, you do this inside a transaction.

You can of course wrap this in a function if you don't want to put the extra code on the client side. You also need a loop for the very rare race condition in that thinking.

There's an example of this in the documentation: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html, example 40-2 right at the bottom.

That's usually the easiest way. You can do some magic with rules, but it's likely going to be a lot messier. I'd recommend the wrap-in-function approach over that any day.

This works for single row, or few row, values. If you're dealing with large amounts of rows for example from a subquery, you're best of splitting it into two queries, one for INSERT and one for UPDATE (as an appropriate join/subselect of course - no need to write your main filter twice)

Javascript sleep/delay/wait function

You could use the following code, it does a recursive call into the function in order to properly wait for the desired time.

function exportar(page,miliseconds,totalpages)
{
    if (page <= totalpages)
    {
        nextpage = page + 1;
        console.log('fnExcelReport('+ page +'); nextpage = '+ nextpage + '; miliseconds = '+ miliseconds + '; totalpages = '+ totalpages );
        fnExcelReport(page);
        setTimeout(function(){
            exportar(nextpage,miliseconds,totalpages);
        },miliseconds);
    };
}

Latex - Change margins of only a few pages

Look up \enlargethispage in some LaTeX reference.

for-in statement

The for-in statement is really there to enumerate over object properties, which is how it is implemented in TypeScript. There are some issues with using it on arrays.

I can't speak on behalf of the TypeScript team, but I believe this is the reason for the implementation in the language.

How to disable XDebug

For those interested in disabling it in codeship, run this script before running tests:

rm -f /home/rof/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini

I was receiving this error:

Use of undefined constant XDEBUG_CC_UNUSED - assumed 'XDEBUG_CC_UNUSED' (this will throw an Error in a future version of PHP)

which is now gone!

How to jQuery clone() and change id?

Update: As Roko C.Bulijan pointed out.. you need to use .insertAfter to insert it after the selected div. Also see updated code if you want it appended to the end instead of beginning when cloned multiple times. DEMO

Code:

   var cloneCount = 1;;
   $("button").click(function(){
      $('#id')
          .clone()
          .attr('id', 'id'+ cloneCount++)
          .insertAfter('[id^=id]:last') 
           //            ^-- Use '#id' if you want to insert the cloned 
           //                element in the beginning
          .text('Cloned ' + (cloneCount-1)); //<--For DEMO
   }); 

Try,

$("#id").clone().attr('id', 'id1').after("#id");

If you want a automatic counter, then see below,

   var cloneCount = 1;
   $("button").click(function(){
      $("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
   }); 

How to force page refreshes or reloads in jQuery?

Or better

window.location.assign("relative or absolute address");

that tends to work best across all browsers and mobile

How to convert XML to JSON in Python?

I think the XML format can be so diverse that it's impossible to write a code that could do this without a very strict defined XML format. Here is what I mean:

<persons>
    <person>
        <name>Koen Bok</name>
        <age>26</age>
    </person>
    <person>
        <name>Plutor Heidepeen</name>
        <age>33</age>
    </person>
</persons>

Would become

{'persons': [
    {'name': 'Koen Bok', 'age': 26},
    {'name': 'Plutor Heidepeen', 'age': 33}]
}

But what would this be:

<persons>
    <person name="Koen Bok">
        <locations name="defaults">
            <location long=123 lat=384 />
        </locations>
    </person>
</persons>

See what I mean?

Edit: just found this article: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html

How can I set the default value for an HTML <select> element?

I used this php function to generate the options, and insert it into my HTML

<?php
  # code to output a set of options for a numeric drop down list
  # parameters: (start, end, step, format, default)
  function numericoptions($start, $end, $step, $formatstring, $default)
  {
    $retstring = "";
    for($i = $start; $i <= $end; $i = $i + $step)
    {
      $retstring = $retstring . '<OPTION ';
      $retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"';
      if($default == $i)
      {
        $retstring = $retstring . ' selected="selected"';
      }
      $retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> ';
    }

  return $retstring;
  }

?>

And then in my webpage code I use it as below;

<select id="endmin" name="endmin">
  <?php echo numericoptions(0,55,5,'%02d',$endmin); ?>
</select>

If $endmin is created from a _POST variable every time the page is loaded (and this code is inside a form which posts) then the previously selected value is selected by default.

Tooltip on image

I am set Tooltips On My Working Project That Is 100% Working

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<style>_x000D_
.tooltip {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  border-bottom: 1px dotted black;_x000D_
}_x000D_
_x000D_
.tooltip .tooltiptext {_x000D_
  visibility: hidden;_x000D_
  width: 120px;_x000D_
  background-color: black;_x000D_
  color: #fff;_x000D_
  text-align: center;_x000D_
  border-radius: 6px;_x000D_
  padding: 5px 0;_x000D_
_x000D_
  /* Position the tooltip */_x000D_
  position: absolute;_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
  visibility: visible;_x000D_
}_x000D_
.size_of_img{_x000D_
width:90px}_x000D_
</style>_x000D_
_x000D_
<body style="text-align:center;">_x000D_
_x000D_
<p>Move the mouse over the text below:</p>_x000D_
_x000D_
<div class="tooltip"><img class="size_of_img" src="https://babeltechreviews.com/wp-content/uploads/2018/07/rendition1.img_.jpg" alt="Image 1" /><span class="tooltiptext">grewon.pdf</span></div>_x000D_
_x000D_
<p>Note that the position of the tooltip text isn't very good. Check More Position <a href="https://www.w3schools.com/css/css_tooltip.asp">GO</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give each input a name attribute. Only the clicked input's name attribute will be sent to the server.

<input type="submit" name="publish" value="Publish">
<input type="submit" name="save" value="Save">

And then

<?php
    if (isset($_POST['publish'])) {
        # Publish-button was clicked
    }
    elseif (isset($_POST['save'])) {
        # Save-button was clicked
    }
?>

Edit: Changed value attributes to alt. Not sure this is the best approach for image buttons though, any particular reason you don't want to use input[type=image]?

Edit: Since this keeps getting upvotes I went ahead and changed the weird alt/value code to real submit inputs. I believe the original question asked for some sort of image buttons but there are so much better ways to achieve that nowadays instead of using input[type=image].

How to change TextField's height and width?

To increase the height of TextField Widget just make use of the maxLines: properties that comes with the widget. For Example: TextField( maxLines: 5 ) // it will increase the height and width of the Textfield.

Why does NULL = NULL evaluate to false in SQL server

You work for the government registering information about citizens. This includes the national ID for every person in the country. A child was left at the door of a church some 40 years ago, nobody knows who their parents are. This person's father ID is NULL. Two such people exist. Count people who share the same father ID with at least one other person (people who are siblings). Do you count those two too?

The answer is no, you don’t, because we don’t know if they are siblings or not.

Suppose you don’t have a NULL option, and instead use some pre-determined value to represent “the unknown”, perhaps an empty string or the number 0 or a * character, etc. Then you would have in your queries that * = *, 0 = 0, and “” = “”, etc. This is not what you want (as per the example above), and as you might often forget about these cases (the example above is a clear fringe case outside ordinary everyday thinking), then you need the language to remember for you that NULL = NULL is not true.

Necessity is the mother of invention.

Resize an Array while keeping current elements in Java?

It is not possible to resize an array. However, it is possible change the size of an array through copying the original array to the newly sized one and keep the current elements. The array can also be reduced in size by removing an element and resizing.

import java.util.Arrays 
public class ResizingArray {

    public static void main(String[] args) {

        String[] stringArray = new String[2] //A string array with 2 strings 
        stringArray[0] = "string1";
        stringArray[1] = "string2";

        // increase size and add string to array by copying to a temporary array
        String[] tempStringArray = Arrays.copyOf(stringArray, stringArray.length + 1);
        // Add in the new string 
        tempStringArray[2] = "string3";
        // Copy temp array to original array
        stringArray = tempStringArray;

       // decrease size by removing certain string from array (string1 for example)
       for(int i = 0; i < stringArray.length; i++) {
           if(stringArray[i] == string1) {
               stringArray[i] = stringArray[stringArray.length - 1];
               // This replaces the string to be removed with the last string in the array
               // When the array is resized by -1, The last string is removed 
               // Which is why we copied the last string to the position of the string we wanted to remove
               String[] tempStringArray2 = Arrays.copyOf(arrayString, arrayString.length - 1);
                // Set the original array to the new array
               stringArray = tempStringArray2;
           }
       }
    }    
}

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

To prevent inserting a record that exist already. I'd check if the ID value exists in the database. For the example of a Table created with an IDENTITY PRIMARY KEY:

CREATE TABLE [dbo].[Persons] (    
    ID INT IDENTITY(1,1) PRIMARY KEY,
    LastName VARCHAR(40) NOT NULL,
    FirstName VARCHAR(40)
);

When JANE DOE and JOE BROWN already exist in the database.

SET IDENTITY_INSERT [dbo].[Persons] OFF;
INSERT INTO [dbo].[Persons] (FirstName,LastName)
VALUES ('JANE','DOE'); 
INSERT INTO Persons (FirstName,LastName) 
VALUES ('JOE','BROWN');

DATABASE OUTPUT of TABLE [dbo].[Persons] will be:

ID    LastName   FirstName
1     DOE        Jane
2     BROWN      JOE

I'd check if i should update an existing record or insert a new one. As the following JAVA example:

int NewID = 1;
boolean IdAlreadyExist = false;
// Using SQL database connection
// STEP 1: Set property
System.setProperty("java.net.preferIPv4Stack", "true");
// STEP 2: Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// STEP 3: Open a connection
try (Connection conn1 = DriverManager.getConnection(DB_URL, USER,pwd) {
    conn1.setAutoCommit(true);
    String Select = "select * from Persons where  ID = " + ID;
    Statement st1 = conn1.createStatement();
    ResultSet rs1 = st1.executeQuery(Select);
    // iterate through the java resultset
    while (rs1.next()) {
        int ID = rs1.getInt("ID");
        if (NewID==ID) {
            IdAlreadyExist = true;
        }

    }
    conn1.close();
} catch (SQLException e1) {
    System.out.println(e1);
}
if (IdAlreadyExist==false) {
    //Insert new record code here
} else {
    //Update existing record code here
}

How to construct a std::string from a std::vector<char>?

With C++11, you can do std::string(v.data()) or, if your vector does not contain a '\0' at the end, std::string(v.data(), v.size()).

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

I would do something like the following:

INSERT INTO cache VALUES (key, generation)
ON DUPLICATE KEY UPDATE (key = key, generation = generation + 1);

Setting the generation value to 0 in code or in the sql but the using the ON DUP... to increment the value. I think that's the syntax anyway.

Calling the base class constructor from the derived class constructor

First off, a PetStore is not a farm.

Let's get past this though. You actually don't need access to the private members, you have everything you need in the public interface:

Animal_* getAnimal_(int i);
void addAnimal_(Animal_* newAnimal);

These are the methods you're given access to and these are the ones you should use.

I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ??

Simple, you call addAnimal. It's public and it also increments sizeF.

Also, note that

PetStore()
{
 idF=0;
};

is equivalent to

PetStore() : Farm()
{
 idF=0;
};

i.e. the base constructor is called, base members are initialized.

How to override the path of PHP to use the MAMP path?

To compliment the current accepted answer, if you assume that MAMP uses the most recent version of php5 as the default, you can add grep 'php5' in the middle:

PHP_VERSION= `ls /Applications/MAMP/bin/php/ | sort -n | grep 'php5' | tail -1`

and you are guaranteed to get the most recent php5 regardless of MAMP version.

How can I make a UITextField move up when the keyboard is present - on starting to edit?

Swift 4 .

You Can Easily Move Up And Down UITextField Or UIView With UIKeyBoard With Animation enter image description here

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textField: UITextField!
    @IBOutlet var chatView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillChangeFrame, object: nil)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textField.resignFirstResponder()
    }

    @objc func keyboardWillChange(notification: NSNotification) {

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y
        print("deltaY",deltaY)

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.chatView.frame.origin.y+=deltaY // Here You Can Change UIView To UITextField
        },completion: nil)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

}

Javascript : calling function from another file

Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.

https://jsfiddle.net/mvora/mrLmkxmo/

 /******** PUT THIS CODE IN ONE JS FILE *******/

    var secondFileFuntion = function(){
        this.name = 'XYZ';
    }

    secondFileFuntion.prototype.getSurname = function(){
     return 'ABC';
    }


    var secondFileObject = new secondFileFuntion();

    /******** Till Here *******/

    /******** PUT THIS CODE IN SECOND JS FILE *******/

    function firstFileFunction(){
      var name = secondFileObject.name;
      var surname = secondFileObject.getSurname()
      alert(name);
      alert(surname );
    }

    firstFileFunction();

If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.

Just take care of sequence of including these files in index.html

Change Schema Name Of Table In SQL

Be very very careful renaming objects in sql. You can cause dependencies to fail if you are not fully away with what you are doing. Having said that this works easily(too much so) for renaming things provided you have access proper on the environment:

exec sp_rename 'Nameofobject', 'ReNameofobject'

TSQL DATETIME ISO 8601

If you just need to output the date in ISO8601 format including the trailing Z and you are on at least SQL Server 2012, then you may use FORMAT:

SELECT FORMAT(GetUtcDate(),'yyyy-MM-ddTHH:mm:ssZ')

This will give you something like:

2016-02-18T21:34:14Z

Just as @Pxtl points out in a comment FORMAT may have performance implications, a cost that has to be considered compared to any flexibility it brings.

node.js hash string?

Here you can benchmark all supported hashes on your hardware, supported by your version of node.js. Some are cryptographic, and some is just for a checksum. Its calculating "Hello World" 1 million times for each algorithm. It may take around 1-15 seconds for each algorithm (Tested on the Standard Google Computing Engine with Node.js 4.2.2).

for(var i1=0;i1<crypto.getHashes().length;i1++){
  var Algh=crypto.getHashes()[i1];
  console.time(Algh);
  for(var i2=0;i2<1000000;i2++){
    crypto.createHash(Algh).update("Hello World").digest("hex");
  }
  console.timeEnd(Algh);  
}

Result:
DSA: 1992ms
DSA-SHA: 1960ms
DSA-SHA1: 2062ms
DSA-SHA1-old: 2124ms
RSA-MD4: 1893ms
RSA-MD5: 1982ms
RSA-MDC2: 2797ms
RSA-RIPEMD160: 2101ms
RSA-SHA: 1948ms
RSA-SHA1: 1908ms
RSA-SHA1-2: 2042ms
RSA-SHA224: 2176ms
RSA-SHA256: 2158ms
RSA-SHA384: 2290ms
RSA-SHA512: 2357ms
dsaEncryption: 1936ms
dsaWithSHA: 1910ms
dsaWithSHA1: 1926ms
dss1: 1928ms
ecdsa-with-SHA1: 1880ms
md4: 1833ms
md4WithRSAEncryption: 1925ms
md5: 1863ms
md5WithRSAEncryption: 1923ms
mdc2: 2729ms
mdc2WithRSA: 2890ms
ripemd: 2101ms
ripemd160: 2153ms
ripemd160WithRSA: 2210ms
rmd160: 2146ms
sha: 1929ms
sha1: 1880ms
sha1WithRSAEncryption: 1957ms
sha224: 2121ms
sha224WithRSAEncryption: 2290ms
sha256: 2134ms
sha256WithRSAEncryption: 2190ms
sha384: 2181ms
sha384WithRSAEncryption: 2343ms
sha512: 2371ms
sha512WithRSAEncryption: 2434ms
shaWithRSAEncryption: 1966ms
ssl2-md5: 1853ms
ssl3-md5: 1868ms
ssl3-sha1: 1971ms
whirlpool: 2578ms

Sending mail attachment using Java

To send html file I have used below code in my project.

final String userID = "[email protected]";
final String userPass = "userpass";
final String emailTo = "[email protected]"

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userID, userPass);
            }
        });
try {

    Message message = new MimeMessage(session);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
    message.setSubject("Hello, this is a test mail..");

    Multipart multipart = new MimeMultipart();
    String fileName = "fileName";

    addAttachment(multipart, fileName);

    MimeBodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText("No need to reply.");
    multipart.addBodyPart(messageBodyPart1);

    message.setContent(multipart);

    Transport.send(message);
    System.out.println("Email successfully sent to: " + emailTo);

} catch (MessagingException e) {
    e.printStackTrace();
}



private static void addAttachment(Multipart multipart, String fileName){
    DataSource source = null;
    File f = new File("filepath" +"/"+ fileName);
    if(f.exists() && !f.isDirectory()) {
        source = new FileDataSource("filepath" +"/"+ fileName);
        BodyPart messageBodyPart = new MimeBodyPart();
        try {
            messageBodyPart.setHeader("Content-Type", "text/html");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Allow only numbers to be typed in a textbox

With HTML5 you can do

<input type="number">

You can also use a regex pattern to limit the input text.

<input type="text" pattern="^[0-9]*$" />

One line if-condition-assignment

For the future time traveler from google, here is a new way (available from python 3.8 onward):

b = 1
if a := b:
    # this section is only reached if b is not 0 or false.
    # Also, a is set to b
    print(a, b)

How to generate .env file for laravel?

in console (cmd), go to app root path and execute:

type .env.example > .env

Android Failed to install HelloWorld.apk on device (null) Error

Restarting the device works for me. Using adb install can get the apk installed, but it's annoying to use it everytime you launch the app when debugging within eclipse.

print arraylist element?

Here is an updated solution for Java8, using lambdas and streams:

System.out.println(list.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining("\n")));

Or, without joining the list into one large string:

list.stream().forEach(System.out::println);

how to sort an ArrayList in ascending order using Collections and Comparator

This might work?

Comparator mycomparator = 
    Collections.reverseOrder(Collections.reverseOrder());

adding directory to sys.path /PYTHONPATH

As to me, i need to caffe to my python path. I can add it's path to the file /home/xy/.bashrc by add

export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH.

to my /home/xy/.bashrc file.

But when I use pycharm, the path is still not in.

So I can add path to PYTHONPATH variable, by run -> edit Configuration.

enter image description here

Spark read file from S3 using sc.textFile ("s3n://...)

You can add the --packages parameter with the appropriate jar: to your submission:

bin/spark-submit --packages com.amazonaws:aws-java-sdk-pom:1.10.34,org.apache.hadoop:hadoop-aws:2.6.0 code.py

How do I pass an object from one activity to another on Android?

Maybe it's an unpopular answer, but in the past I've simply used a class that has a static reference to the object I want to persist through activities. So,

public class PersonHelper
{
    public static Person person;
}

I tried going down the Parcelable interface path, but ran into a number of issues with it and the overhead in your code was unappealing to me.

How can I convert a PFX certificate file for use with Apache on a linux server?

SSLSHopper has some pretty thorough articles about moving between different servers.

http://www.sslshopper.com/how-to-move-or-copy-an-ssl-certificate-from-one-server-to-another.html

Just pick the relevant link at bottom of this page.

Note: they have an online converter which gives them access to your private key. They can probably be trusted but it would be better to use the OPENSSL command (also shown on this site) to keep the private key private on your own machine.

Setting default values for columns in JPA

In 2017, JPA 2.1 still has only @Column(columnDefinition='...') to which you put the literal SQL definition of the column. Which is quite unflexible and forces you to also declare the other aspects like type, short-circuiting the JPA implementation's view on that matter.

Hibernate though, has this:

@Column(length = 4096, nullable = false)
@org.hibernate.annotations.ColumnDefault("")
private String description;

Identifies the DEFAULT value to apply to the associated column via DDL.

Two notes to that:

1) Don't be afraid of going non-standard. Working as a JBoss developer, I've seen quite some specification processes. The specification is basically the baseline that the big players in given field are willing to commit to support for the next decade or so. It's true for security, for messaging, ORM is no difference (although JPA covers quite a lot). My experience as a developer is that in a complex application, sooner or later you will need a non-standard API anyway. And @ColumnDefault is an example when it outweigts the negatives of using a non-standard solution.

2) It's nice how everyone waves @PrePersist or constructor member initialization. But that's NOT the same. How about bulk SQL updates? How about statements that don't set the column? DEFAULT has it's role and that's not substitutable by initializing a Java class member.

What is the most effective way to get the index of an iterator of an std::vector?

According to http://www.cplusplus.com/reference/std/iterator/distance/, since vec.begin() is a random access iterator, the distance method uses the - operator.

So the answer is, from a performance point of view, it is the same, but maybe using distance() is easier to understand if anybody would have to read and understand your code.

How to create a signed APK file using Cordova command line interface?

In cordova 6.2.0, it has an easy way to create release build. refer to other steps here Steps 1, 2 and 4

cd cordova/ #change to root cordova folder
platforms/android/cordova/clean #clean if you want
cordova build android --release -- --keystore="/path/to/keystore" --storePassword=password --alias=alias_name #password will be prompted if you have any

Git - Undo pushed commits

git revert HEAD -m 1

In the above code line. "Last argument represents"

  • 1 - reverts one commits.

  • 2 - reverts last two commits.

  • n - reverts last n commits.

You need to push after this command to take the effect on remote. You have other options like specifying the range of commits to revert. This is one of the option.


Later use git commit -am "COMMIT_MESSAGE" then git push or git push -f

Maximum filename length in NTFS (Windows XP and Windows Vista)?

238! I checked it under Win7 32 bit with the following bat script:

set "fname="
for /l %%i in (1, 1, 27) do @call :setname
@echo %fname%
for /l %%i in (1, 1, 100) do @call :check
goto :EOF
:setname
set "fname=%fname%_123456789"
goto :EOF
:check
set "fname=%fname:~0,-1%"
@echo xx>%fname%
if not exist %fname% goto :eof
dir /b
pause
goto :EOF

How to execute an oracle stored procedure?

I use oracle 12 and it tell me that if you need to invoke the procedure then use call keyword. In your case it should be:

begin
  call temp_proc;
end;

Check line for unprintable characters while reading text file

I can find following ways to do.

private static final String fileName = "C:/Input.txt";

public static void main(String[] args) throws IOException {
    Stream<String> lines = Files.lines(Paths.get(fileName));
    lines.toArray(String[]::new);

    List<String> readAllLines = Files.readAllLines(Paths.get(fileName));
    readAllLines.forEach(s -> System.out.println(s));

    File file = new File(fileName);
    Scanner scanner = new Scanner(file);
    while (scanner.hasNext()) {
        System.out.println(scanner.next());
    }

Case Statement Equivalent in R

A case statement actually might not be the right approach here. If this is a factor, which is likely is, just set the levels of the factor appropriately.

Say you have a factor with the letters A to E, like this.

> a <- factor(rep(LETTERS[1:5],2))
> a
 [1] A B C D E A B C D E
Levels: A B C D E

To join levels B and C and name it BC, just change the names of those levels to BC.

> levels(a) <- c("A","BC","BC","D","E")
> a
 [1] A  BC BC D  E  A  BC BC D  E 
Levels: A BC D E

The result is as desired.

setAttribute('display','none') not working

display is not an attribute - it's a CSS property. You need to access the style object for this:

document.getElementById('classRight').style.display = 'none';

Where can I find WcfTestClient.exe (part of Visual Studio)

Mine was here: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE"

jquery get all input from specific form

Use HTML Form "elements" attribute:

$.each($("form").elements, function(){ 
    console.log($(this));
    });

Now it's not necessary to provide such names as "input, textarea, select ..." etc.

How to write files to assets folder or raw folder in android?

You cannot write data's to asset/Raw folder, since it is packed(.apk) and not expandable in size.

If your application need to download dependency files from server, you can go for APK Expansion Files provided by android (http://developer.android.com/guide/market/expansion-files.html).

How to Set the Background Color of a JButton on the Mac OS

Have you tried setting the painted border false?

JButton button = new JButton();
button.setBackground(Color.red);
button.setOpaque(true);
button.setBorderPainted(false);

It works on my mac :)

Playing HTML5 video on fullscreen in android webview

Thank you so much for that class, Cristian.

I made a minor tweak to it so that the custom loading view is optional, like so:

  @Override
    public View getVideoLoadingProgressView() // Video will start loading, only called in the case of VideoView (typically API level 10-)
    {
        if (loadingView == null)
        {
            return super.getVideoLoadingProgressView();
        }
        else
        {
            loadingView.setVisibility(View.VISIBLE);
            return loadingView;
        }
    }

I also added a new constructor that just takes two parameters. Anyway, just a minor simplification if you don't need the loading view. Thanks again for providing this.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

The X-Frame-Options header is a security feature enforced at the browser level.

If you have control over your user base (IT dept for corp app), you could try something like a greasemonkey script (if you can a) deploy greasemonkey across everyone and b) deploy your script in a shared way)...

Alternatively, you can proxy their result. Create an endpoint on your server, and have that endpoint open a connection to the target endpoint, and simply funnel traffic backwards.

Minimum rights required to run a windows service as a domain account

"BypassTraverseChecking" means that you can directly access any deep-level subdirectory even if you don't have all the intermediary access privileges to directories in between, i.e. all directories above it towards root level .

HMAC-SHA256 Algorithm for signature calculation

If you're using Guava, its latest release now lets you use

 Hashing.hmacSha256()

Further documentation here: https://guava.dev/releases/23.0/api/docs/com/google/common/hash/Hashing.html#hmacSha256-byte:A-

Python main call within class

Well, first, you need to actually define a function before you can run it (and it doesn't need to be called main). For instance:

class Example(object):
    def run(self):
        print "Hello, world!"

if __name__ == '__main__':
    Example().run()

You don't need to use a class, though - if all you want to do is run some code, just put it inside a function and call the function, or just put it in the if block:

def main():
    print "Hello, world!"

if __name__ == '__main__':
    main()

or

if __name__ == '__main__':
    print "Hello, world!"

SQL Server CASE .. WHEN .. IN statement

CASE AlarmEventTransactions.DeviceID should just be CASE.

You are mixing the 2 forms of the CASE expression.

Insert string at specified position

Just wanted to add something: I found tim cooper's answer very useful, I used it to make a method which accepts an array of positions and does the insert on all of them so here that is:

EDIT: Looks like my old function assumed $insertstr was only 1 character and that the array was sorted. This works for arbitrary character length.

function stringInsert($str, $pos, $insertstr) {
    if (!is_array($pos)) {
        $pos = array($pos);
    } else {
        asort($pos);
    }
    $insertionLength = strlen($insertstr);
    $offset = 0;
    foreach ($pos as $p) {
        $str = substr($str, 0, $p + $offset) . $insertstr . substr($str, $p + $offset);
        $offset += $insertionLength;
    }
    return $str;
}

QLabel: set color of text and background

You can use QPalette, however you must set setAutoFillBackground(true); to enable background color

QPalette sample_palette;
sample_palette.setColor(QPalette::Window, Qt::white);
sample_palette.setColor(QPalette::WindowText, Qt::blue);

sample_label->setAutoFillBackground(true);
sample_label->setPalette(sample_palette);
sample_label->setText("What ever text");

It works fine on Windows and Ubuntu, I haven't played with any other OS.

Note: Please see QPalette, color role section for more details

Returning a value from thread?

I came across this thread when also trying to obtain the return value of a method that gets executed within a Thread. I thought I would post my solution that works.

This solution uses an class to store both the method to be executed (indirectly) and stores the returning value. The class can be used for any function and any return type. You just instantiate the object using the return value type and then pass the function to call via a lambda (or delegate).


C# 3.0 Implementation


public class ThreadedMethod<T>
{

    private T mResult;
    public T Result 
    {
        get { return mResult; }
        private set { mResult = value; }
    }

    public ThreadedMethod()
    {
    }

    //If supporting .net 3.5
    public void ExecuteMethod(Func<T> func)
    {
        Result = func.Invoke();
    }

    //If supporting only 2.0 use this and 
    //comment out the other overload
    public void ExecuteMethod(Delegate d)
    {
        Result = (T)d.DynamicInvoke();
    }
}

To use this code you can use a Lambda (or a delegate). Here is the example using lambdas:

ThreadedMethod<bool> threadedMethod = new ThreadedMethod<bool>();
Thread workerThread = new Thread((unused) => 
                            threadedMethod.ExecuteMethod(() => 
                                SomeMethod()));
workerThread.Start();
workerThread.Join();
if (threadedMethod.Result == false) 
{
    //do something about it...
}

VB.NET 2008 Implementation


Anyone using VB.NET 2008 can't use lambdas with non-value returning methods. This affects the ThreadedMethod class, so we'll make ExecuteMethod return the value of the function. This doesn't hurt anything.

Public Class ThreadedMethod(Of T)

    Private mResult As T
    Public Property Result() As T
        Get
            Return mResult
        End Get
        Private Set(ByVal value As T)
            mResult = value
        End Set
    End Property

    Sub New()
    End Sub

    'If supporting .net 3.5'
    Function ExecuteMethod(ByVal func As Func(Of T)) As T
        Result = func.Invoke()
        Return Result
    End Function

    'If supporting only 2.0 use this and' 
    'comment out the other overload'
    Function ExecuteMethod(ByVal d As [Delegate]) As T
        Result = DirectCast(d.DynamicInvoke(), T)
        Return Result
    End Function

End Class

SQL: IF clause within WHERE clause

There isn't a good way to do this in SQL. Some approaches I have seen:

1) Use CASE combined with boolean operators:

WHERE
    OrderNumber = CASE 
        WHEN (IsNumeric(@OrderNumber) = 1)
        THEN CONVERT(INT, @OrderNumber)
        ELSE -9999 -- Some numeric value that just cannot exist in the column
    END
    OR 
    FirstName LIKE CASE
        WHEN (IsNumeric(@OrderNumber) = 0)
        THEN '%' + @OrderNumber
        ELSE ''
    END

2) Use IF's outside the SELECT

IF (IsNumeric(@OrderNumber)) = 1
BEGIN
    SELECT * FROM Table
    WHERE @OrderNumber = OrderNumber
END ELSE BEGIN
    SELECT * FROM Table
    WHERE OrderNumber LIKE '%' + @OrderNumber
END

3) Using a long string, compose your SQL statement conditionally, and then use EXEC

The 3rd approach is hideous, but it's almost the only think that works if you have a number of variable conditions like that.

Add quotation at the start and end of each line in Notepad++

  • Place your cursor at the end of the text.
  • Press SHIFT and ->. The cursor will move to the next line.
  • Press CTRL-F and type , in "Replace with:" and press ENTER.

You will need to put a quote at the beginning of your first text and the end of your last.

Could not find a version that satisfies the requirement <package>

This approach (having all dependencies in a directory and not downloading from an index) only works when the directory contains all packages. The directory should therefore contain all dependencies but also all packages that those dependencies depend on (e.g., six, pytz etc).

You should therefore manually include these in requirements.txt (so that the first step downloads them explicitly) or you should install all packages using PyPI and then pip freeze > requirements.txt to store the list of all packages needed.

Which is the correct C# infinite loop, for (;;) or while (true)?

If you're code-golfing, I would suggest for(;;). Beyond that, while(true) has the same meaning and seems more intuitive. At any rate, most coders will likely understand both variations, so it doesn't really matter. Use what's most comfortable.

How to open a web page from my application?

I've been using this line to launch the default browser:

System.Diagnostics.Process.Start("http://www.google.com"); 

How to get the mobile number of current sim card in real device?

As many said:

String phoneNumber = TelephonyManager.getDefault().getLine1Number();

The availability depends strictly on the carrier and the way the number is encoded on the SIM card. If it is hardcoded by the company that makes the SIMs or by the mobile carrier itself. This returns the same as in Settings->about phone.

Bind failed: Address already in use

I was also facing that problem, but I resolved it. Make sure that both the programs for client-side and server-side are on different projects in your IDE, in my case NetBeans. Then assuming you're using localhost, I recommend you to implement both the programs as two different projects.

Use JavaScript to place cursor at end of text in text input element

While this may be an old question with lots of answers, I ran across a similar issue and none of the answers were quite what I wanted and/or were poorly explained. The issue with selectionStart and selectionEnd properties is that they don't exist for input type number (while the question was asked for text type, I reckon it might help others who might have other input types that they need to focus). So if you don't know whether the input type the function will focus is a type number or not, you cannot use that solution.

The solution that works cross browser and for all input types is rather simple:

  • get and store the value of input in a variable
  • focus the input
  • set the value of input to the stored value

That way the cursor is at the end of the input element.
So all you'd do is something like this (using jquery, provided the element selector that one wishes to focus is accessible via 'data-focus-element' data attribute of the clicked element and the function executes after clicking on '.foo' element):

$('.foo').click(function() {
    element_selector = $(this).attr('data-focus-element');
    $focus = $(element_selector);
    value = $focus.val();
    $focus.focus();
    $focus.val(value);
});

Why does this work? Simply, when the .focus() is called, the focus will be added to the beginning of the input element (which is the core problem here), ignoring the fact, that the input element already has a value in it. However, when the value of an input is changed, the cursor is automatically placed at the end of the value inside input element. So if you override the value with the same value that had been previously entered in the input, the value will look untouched, the cursor will, however, move to the end.

How to export data with Oracle SQL Developer?

To export data you need to right click on your results and select export data, after which you will be asked for a specific file format such as insert, loader, or text etc. After selecting this browse your directory and select the export destination.

xcopy file, rename, suppress "Does xxx specify a file name..." message

I met same issue when try to copy file with new name only if file does not exist in destination or exist (with new name), but is older. The solution is to add * char at end of destination file name. Example:

xcopy "C:\src\whee.config.txt" "C:\dest\bee.config.txt*" /D /Y

Select every Nth element in CSS

As the name implies, :nth-child() allows you to construct an arithmetic expression using the n variable in addition to constant numbers. You can perform addition (+), subtraction (-) and coefficient multiplication (an where a is an integer, including positive numbers, negative numbers and zero).

Here's how you would rewrite the above selector list:

div:nth-child(4n)

For an explanation on how these arithmetic expressions work, see my answer to this question, as well as the spec.

Note that this answer assumes that all of the child elements within the same parent element are of the same element type, div. If you have any other elements of different types such as h1 or p, you will need to use :nth-of-type() instead of :nth-child() to ensure you only count div elements:

<body>
  <h1></h1>
  <div>1</div>  <div>2</div>
  <div>3</div>  <div>4</div>
  <h2></h2>
  <div>5</div>  <div>6</div>
  <div>7</div>  <div>8</div>
  <h2></h2>
  <div>9</div>  <div>10</div>
  <div>11</div> <div>12</div>
  <h2></h2>
  <div>13</div> <div>14</div>
  <div>15</div> <div>16</div>
</body>

For everything else (classes, attributes, or any combination of these), where you're looking for the nth child that matches an arbitrary selector, you will not be able to do this with a pure CSS selector. See my answer to this question.


By the way, there's not much of a difference between 4n and 4n + 4 with regards to :nth-child(). If you use the n variable, it starts counting at 0. This is what each selector would match:

:nth-child(4n)

4(0) = 0
4(1) = 4
4(2) = 8
4(3) = 12
4(4) = 16
...

:nth-child(4n+4)

4(0) + 4 = 0  + 4 = 4
4(1) + 4 = 4  + 4 = 8
4(2) + 4 = 8  + 4 = 12
4(3) + 4 = 12 + 4 = 16
4(4) + 4 = 16 + 4 = 20
...

As you can see, both selectors will match the same elements as above. In this case, there is no difference.

Android draw a Horizontal line between views

Try this

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"/>

How does the data-toggle attribute work? (What's its API?)

The data-toggle attribute simple tell Bootstrap what exactly to do by giving it the name of the toggle action it is about to perform on a target element. If you specify collapse. It means bootstrap will collapse or uncollapse the element pointed by data-target of the action you clicked

Note: the target element must have the appropriate class for bootstrap to carry out the action

Source action:
data-toggle = collapse //type of toggle
data-target = #myDiv

Target:
class=collapse //I can collapse
id=myDiv

This is same for other type of toggle actions like tab, modal, dropdown

How to submit form on change of dropdown list?

To those in the answer above. It's definitely JavaScript. It's just inline.

BTW the jQuery equivalent if you want to apply to all selects:

$('form select').on('change', function(){
    $(this).closest('form').submit();
});

select dept names who have more than 2 employees whose salary is greater than 1000

SELECT DEPTNAME
FROM(SELECT D.DEPTNAME,COUNT(EMPID) AS TOTEMP
     FROM DEPT AS D,EMPLOYEE AS E
     WHERE D.DEPTID=E.DEPTID AND SALARY>1000
     GROUP BY D.DEPTID
     )
WHERE TOTEMP>2;

Storing and Retrieving ArrayList values from hashmap

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
     Map.Entry pairs = (Map.Entry)it.next();

     if(pairs.getKey().equals("mango"))
     {
        map.put(pairs.getKey(), pairs.getValue().add(18));
     }

     else if(!map.containsKey("mango"))
     {
        List<Integer> ints = new ArrayList<Integer>();
        ints.add(18);
        map.put("mango",ints);
     }

     it.remove(); // avoids a ConcurrentModificationException
}

EDIT: So inside the while try this:

map.put(pairs.getKey(), pairs.getValue().add(number))

You are getting the error because you are trying to put an integer to the values, whereas it is expected an ArrayList.

EDIT 2: Then put the following inside your while loop:

if(pairs.getKey().equals("mango"))
{
    map.put(pairs.getKey(), pairs.getValue().add(18));
}

else if(!map.containsKey("mango"))
{
     List<Integer> ints = new ArrayList<Integer>();
     ints.add(18);
     map.put("mango",ints);
 }

EDIT 3: By reading your requirements, I come to think you may not need a loop. You may want to only check if the map contains the key mango, and if it does add 18, else create a new entry in the map with key mango and value 18.

So all you may need is the following, without the loop:

if(map.containsKey("mango"))
{
    map.put("mango", map.get("mango).add(18));
}

else
{
    List<Integer> ints = new ArrayList<Integer>();
    ints.add(18);
    map.put("mango", ints);
}

What is a deadlock?

Let me explain a real world (not actually real) example for a deadlock situation from the crime movies. Imagine a criminal holds an hostage and against that, a cop also holds an hostage who is a friend of the criminal. In this case, criminal is not going to let the hostage go if cop won't let his friend to let go. Also the cop is not going to let the friend of criminal let go, unless the criminal releases the hostage. This is an endless untrustworthy situation, because both sides are insisting the first step from each other.

Criminal & Cop Scene

enter image description here

So simply, when two threads needs two different resources and each of them has the lock of the resource that the other need, it is a deadlock.

Another High Level Explanation of Deadlock : Broken Hearts

You are dating with a girl and one day after an argument, both sides are heart-broken to each other and waiting for an I-am-sorry-and-I-missed-you call. In this situation, both sides want to communicate each other if and only if one of them receives an I-am-sorry call from the other. Because that neither of each is going to start communication and waiting in a passive state, both will wait for the other to start communication which ends up in a deadlock situation.

How can I remove item from querystring in asp.net using c#?

My personal preference here is rewriting the query or working with a namevaluecollection at a lower point, but there are times where the business logic makes neither of those very helpful and sometimes reflection really is what you need. In those circumstances you can just turn off the readonly flag for a moment like so:

// reflect to readonly property
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);

// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);

// remove
this.Request.QueryString.Remove("foo");

// modify
this.Request.QueryString.Set("bar", "123");

// make collection readonly again
isreadonly.SetValue(this.Request.QueryString, true, null);

Syntax error: Illegal return statement in JavaScript

In my experience, most often this error message means that you have put an accidental closing brace somewhere, leaving the rest of your statements outside the function.

Example:

function a() {
    if (global_block) //syntax error is actually here - missing opening brace
       return;
    } //this unintentionally ends the function

    if (global_somethingelse) {
       //Chrome will show the error occurring here, 
       //but actually the error is in the previous statement
       return; 
    }

    //do something
}

jQuery UI: Datepicker set year range dropdown to 100 years

Try the following:-

ChangeYear:- When set to true, indicates that the cells of the previous or next month indicated in the calendar of the current month can be selected. This option is used with options.showOtherMonths set to true.

YearRange:- Specifies the range of years in the year dropdown. (Default value: “-10:+10")

Example:-

$(document).ready(function() {
    $("#date").datepicker({
        changeYear:true,
        yearRange: "2005:2015"
    });
});

See:- set year range in jquery datepicker

Use string contains function in oracle SQL query

By lines I assume you mean rows in the table person. What you're looking for is:

select p.name
from   person p
where  p.name LIKE '%A%'; --contains the character 'A'

The above is case sensitive. For a case insensitive search, you can do:

select p.name
from   person p
where  UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'

For the special character, you can do:

select p.name
from   person p
where  p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)

The LIKE operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the % sign as it means match zero or more characters.

Send private messages to friends

This thread says you can't do send private messages to a group of friends on facebook but I found this https://developers.facebook.com/docs/sharing/reference/send-dialog

Differences between unique_ptr and shared_ptr

When wrapping a pointer in a unique_ptr you cannot have multiple copies of unique_ptr. The shared_ptr holds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptr is copied, this counter is incremented. Each time a shared_ptr is destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.

bind/unbind service example (android)

First of all, two things that we need to understand,

Client

  • It makes request to a specific server

bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), mServiceConn, Context.BIND_AUTO_CREATE);

here mServiceConn is instance of ServiceConnection class(inbuilt) it is actually interface that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.

Server

  • It handles the request of the client and makes replica of its own which is private to client only who send request and this raplica of server runs on different thread.

Now at client side, how to access all the methods of server?

  • Server sends response with IBinder Object. So, IBinder object is our handler which accesses all the methods of Service by using (.) operator.

.

MyService myService;
public ServiceConnection myConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder binder) {
        Log.d("ServiceConnection","connected");
        myService = binder;
    }
    //binder comes from server to communicate with method's of 

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
}

Now how to call method which lies in service

myservice.serviceMethod();

Here myService is object and serviceMethod is method in service. and by this way communication is established between client and server.

File Upload ASP.NET MVC 3.0

Alternative method to transfer to byte[] (for saving to DB).

@Arthur's method works pretty good, but doesn't copy perfectly so MS Office documents may fail to open after retrieving them from the database. MemoryStream.GetBuffer() can return extra empty bytes at the end of the byte[], but you can fix that by using MemoryStream.ToArray() instead. However, I found this alternative to work perfectly for all file types:

using (var binaryReader = new BinaryReader(file.InputStream))
{
    byte[] array = binaryReader.ReadBytes(file.ContentLength);
}

Here's my full code:

Document Class:

public class Document
{
    public int? DocumentID { get; set; }
    public string FileName { get; set; }
    public byte[] Data { get; set; }
    public string ContentType { get; set; }
    public int? ContentLength { get; set; }

    public Document()
    {
        DocumentID = 0;
        FileName = "New File";
        Data = new byte[] { };
        ContentType = "";
        ContentLength = 0;
    }
}

File Download:

[HttpGet]
public ActionResult GetDocument(int? documentID)
{
    // Get document from database
    var doc = dataLayer.GetDocument(documentID);

    // Convert to ContentDisposition
    var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = doc.FileName, 

        // Prompt the user for downloading; set to true if you want 
        // the browser to try to show the file 'inline' (display in-browser
        // without prompting to download file).  Set to false if you 
        // want to always prompt them to download the file.
        Inline = true, 
    };
    Response.AppendHeader("Content-Disposition", cd.ToString());

    // View document
    return File(doc.Data, doc.ContentType);
}

File Upload:

[HttpPost]
public ActionResult GetDocument(HttpPostedFileBase file)
{
    // Verify that the user selected a file
    if (file != null && file.ContentLength > 0)
    {
        // Get file info
        var fileName = Path.GetFileName(file.FileName);
        var contentLength = file.ContentLength;
        var contentType = file.ContentType;

        // Get file data
        byte[] data = new byte[] { };
        using (var binaryReader = new BinaryReader(file.InputStream))
        {
            data = binaryReader.ReadBytes(file.ContentLength);
        }

        // Save to database
        Document doc = new Document()
        {
            FileName = fileName,
            Data = data,
            ContentType = contentType,
            ContentLength = contentLength,
        };
        dataLayer.SaveDocument(doc);

        // Show success ...
        return RedirectToAction("Index");
    }
    else
    {
        // Show error ...
        return View("Foo");
    }
}

View (snippet):

@using (Html.BeginForm("GetDocument", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="Upload File" />
}

How to list files in an android directory?

If you are on Android 10/Q and you did all of the correct things to request access permissions to read external storage and it still doesn't work, it's worth reading this answer:

Android Q (10) ask permission to get access all storage. Scoped storage

I had working code, but me device took it upon itself to update when it was on a network connection (it was usually without a connection.) Once in Android 10, the file access no longer worked. The only easy way to fix it without rewriting the code was to add that extra attribute to the manifest as described. The file access now works as in Android 9 again. YMMV, it probably won't continue to work in future versions.

pyplot scatter plot marker size

This can be a somewhat confusing way of defining the size but you are basically specifying the area of the marker. This means, to double the width (or height) of the marker you need to increase s by a factor of 4. [because A = WH => (2W)(2H)=4A]

There is a reason, however, that the size of markers is defined in this way. Because of the scaling of area as the square of width, doubling the width actually appears to increase the size by more than a factor 2 (in fact it increases it by a factor of 4). To see this consider the following two examples and the output they produce.

# doubling the width of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*4**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()

gives

enter image description here

Notice how the size increases very quickly. If instead we have

# doubling the area of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*2**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()

gives

enter image description here

Now the apparent size of the markers increases roughly linearly in an intuitive fashion.

As for the exact meaning of what a 'point' is, it is fairly arbitrary for plotting purposes, you can just scale all of your sizes by a constant until they look reasonable.

Hope this helps!

Edit: (In response to comment from @Emma)

It's probably confusing wording on my part. The question asked about doubling the width of a circle so in the first picture for each circle (as we move from left to right) it's width is double the previous one so for the area this is an exponential with base 4. Similarly the second example each circle has area double the last one which gives an exponential with base 2.

However it is the second example (where we are scaling area) that doubling area appears to make the circle twice as big to the eye. Thus if we want a circle to appear a factor of n bigger we would increase the area by a factor n not the radius so the apparent size scales linearly with the area.

Edit to visualize the comment by @TomaszGandor:

This is what it looks like for different functions of the marker size:

Exponential, Square, or Linear size

x = [0,2,4,6,8,10,12,14,16,18]
s_exp = [20*2**n for n in range(len(x))]
s_square = [20*n**2 for n in range(len(x))]
s_linear = [20*n for n in range(len(x))]
plt.scatter(x,[1]*len(x),s=s_exp, label='$s=2^n$', lw=1)
plt.scatter(x,[0]*len(x),s=s_square, label='$s=n^2$')
plt.scatter(x,[-1]*len(x),s=s_linear, label='$s=n$')
plt.ylim(-1.5,1.5)
plt.legend(loc='center left', bbox_to_anchor=(1.1, 0.5), labelspacing=3)
plt.show()

How to use DISTINCT and ORDER BY in same SELECT statement?

You can use CTE:

WITH DistinctMonitoringJob AS (
    SELECT DISTINCT Category Distinct_Category FROM MonitoringJob 
)

SELECT Distinct_Category 
FROM DistinctMonitoringJob 
ORDER BY Distinct_Category DESC

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

Check for the 32/64 bit you trying to install. both python interpreter and your app which trying to use python might be of different bit.

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

How to align form at the center of the page in html/css

Like this

demo

css

    body {
    background-color : #484848;
    margin: 0;
    padding: 0;
}
h1 {
    color : #000000;
    text-align : center;
    font-family: "SIMPSON";
}
form {
    width: 300px;
    margin: 0 auto;
}

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

I had a similar problem in VS 2017 15.45 - I found when I checked that even though the project compiled and ran it came up with a system.IO.FileNotFoundException with regard to System.Runtime when I tried to access TPL Dataflow objects.

When I checked the projects in the solution, one of them (the top one) was missing the System.Runtime package used by the underlying projects. Once I installed it from Nuget it all worked correctly.

Create an array of integers property in Objective-C

C arrays are not one of the supported data types for properties. See "The Objective-C Programming Language" in Xcode documentation, in the Declared Properties page:

Supported Types

You can declare a property for any Objective-C class, Core Foundation data type, or “plain old data” (POD) type (see C++ Language Note: POD Types). For constraints on using Core Foundation types, however, see “Core Foundation.”

POD does not include C arrays. See http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html

If you need an array, you should use NSArray or NSData.

The workarounds, as I see it, are like using (void *) to circumvent type checking. You can do it, but it makes your code less maintainable.

Select from where field not equal to Mysql Php

Or can also insert the statement inside bracket.

SELECT * FROM tablename WHERE NOT (columnA = 'x')

C#: Dynamic runtime cast

I realize this has been answered, but I used a different approach and thought it might be worth sharing. Also, I feel like my approach might produce unwanted overhead. However, I'm not able to observer or calculate anything happening that is that bad under the loads we observe. I was looking for any useful feedback on this approach.

The problem with working with dynamics is that you can't attach any functions to the dynamic object directly. You have to use something that can figure out the assignments that you don't want to figure out every time.

When planning this simple solution, I looked at what the valid intermediaries are when attempting to retype similar objects. I found that a binary array, string (xml, json) or hard coding a conversion (IConvertable) were the usual approaches. I don't want to get into binary conversions due to a code maintainability factor and laziness.

My theory was that Newtonsoft could do this by using a string intermediary.

As a downside, I am fairly certain that when converting the string to an object, that it would use reflection by searching the current assembly for an object with matching properties, create the type, then instantiate the properties, which would require more reflection. If true, all of this can be considered avoidable overhead.

C#:

//This lives in a helper class
public static ConvertDynamic<T>(dynamic data)
{
     return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(Newtonsoft.Json.JsonConvert.SerializeObject(data));
}

//Same helper, but in an extension class (public static class),
//but could be in a base class also.
public static ToModelList<T>(this List<dynamic> list)
{
    List<T> retList = new List<T>();
    foreach(dynamic d in list)
    {
        retList.Add(ConvertDynamic<T>(d));
    }
}

With that said, this fits another utility I've put together that lets me make any object into a dynamic. I know I had to use reflection to do that correctly:

public static dynamic ToDynamic(this object value)
{
    IDictionary<string, object> expando = new ExpandoObject();

    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
        expando.Add(property.Name, property.GetValue(value));

    return expando as ExpandoObject;
}

I had to offer that function. An arbitrary object assigned to a dynamic typed variable cannot be converted to an IDictionary, and will break the ConvertDynamic function. For this function chain to be used it has to be provided a dynamic of System.Dynamic.ExpandoObject, or IDictionary<string, object>.

Enabling error display in PHP via htaccess only

If you want to see only fatal runtime errors:

php_value display_errors on
php_value error_reporting 4

How to stop BackgroundWorker correctly

The problem is caused by the fact that cmbDataSourceExtractor.CancelAsync() is an asynchronous method, the Cancel operation has not yet completed when cmdDataSourceExtractor.RunWorkerAsync(...) exitst. You should wait for cmdDataSourceExtractor to complete before calling RunWorkerAsync again. How to do this is explained in this SO question.

How to transform numpy.matrix or array to scipy sparse matrix

In Python, the Scipy library can be used to convert the 2-D NumPy matrix into a Sparse matrix. SciPy 2-D sparse matrix package for numeric data is scipy.sparse

The scipy.sparse package provides different Classes to create the following types of Sparse matrices from the 2-dimensional matrix:

  1. Block Sparse Row matrix
  2. A sparse matrix in COOrdinate format.
  3. Compressed Sparse Column matrix
  4. Compressed Sparse Row matrix
  5. Sparse matrix with DIAgonal storage
  6. Dictionary Of Keys based sparse matrix.
  7. Row-based list of lists sparse matrix
  8. This class provides a base class for all sparse matrices.

CSR (Compressed Sparse Row) or CSC (Compressed Sparse Column) formats support efficient access and matrix operations.

Example code to Convert Numpy matrix into Compressed Sparse Column(CSC) matrix & Compressed Sparse Row (CSR) matrix using Scipy classes:

import sys                 # Return the size of an object in bytes
import numpy as np         # To create 2 dimentional matrix
from scipy.sparse import csr_matrix, csc_matrix 
# csr_matrix: used to create compressed sparse row matrix from Matrix
# csc_matrix: used to create compressed sparse column matrix from Matrix

create a 2-D Numpy matrix

A = np.array([[1, 0, 0, 0, 0, 0],\
              [0, 0, 2, 0, 0, 1],\
              [0, 0, 0, 2, 0, 0]])
print("Dense matrix representation: \n", A)
print("Memory utilised (bytes): ", sys.getsizeof(A))
print("Type of the object", type(A))

Print the matrix & other details:

Dense matrix representation: 
 [[1 0 0 0 0 0]
 [0 0 2 0 0 1]
 [0 0 0 2 0 0]]
Memory utilised (bytes):  184
Type of the object <class 'numpy.ndarray'>

Converting Matrix A to the Compressed sparse row matrix representation using csr_matrix Class:

S = csr_matrix(A)
print("Sparse 'row' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'row' matrix:
(0, 0) 1
(1, 2) 2
(1, 5) 1
(2, 3) 2
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csr.csc_matrix'>

Converting Matrix A to Compressed Sparse Column matrix representation using csc_matrix Class:

S = csc_matrix(A)
print("Sparse 'column' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'column' matrix:
(0, 0) 1
(1, 2) 2
(2, 3) 2
(1, 5) 1
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csc.csc_matrix'>

As it can be seen the size of the compressed matrices is 56 bytes and the original matrix size is 184 bytes.

For a more detailed explanation and code examples please refer to this article: https://limitlessdatascience.wordpress.com/2020/11/26/sparse-matrix-in-machine-learning/

Properly Handling Errors in VBA (Excel)

Block 2 doesn't work because it doesn't reset the Error Handler potentially causing an endless loop. For Error Handling to work properly in VBA, you need a Resume statement to clear the Error Handler. The Resume also reactivates the previous Error Handler. Block 2 fails because a new error would go back to the previous Error Handler causing an infinite loop.

Block 3 fails because there is no Resume statement so any attempt at error handling after that will fail.

Every error handler must be ended by exiting the procedure or a Resume statement. Routing normal execution around an error handler is confusing. This is why error handlers are usually at the bottom.

But here is another way to handle an error in VBA. It handles the error inline like Try/Catch in VB.net There are a few pitfalls, but properly managed it works quite nicely.

Sub InLineErrorHandling()

    'code without error handling

BeginTry1:

    'activate inline error handler
    On Error GoTo ErrHandler1

        'code block that may result in an error
        Dim a As String: a = "Abc"
        Dim c As Integer: c = a 'type mismatch

ErrHandler1:

    'handle the error
    If Err.Number <> 0 Then

        'the error handler has deactivated the previous error handler

        MsgBox (Err.Description)

        'Resume (or exit procedure) is the only way to get out of an error handling block
        'otherwise the following On Error statements will have no effect
        'CAUTION: it also reactivates the previous error handler
        Resume EndTry1
    End If

EndTry1:
    'CAUTION: since the Resume statement reactivates the previous error handler
    'you must ALWAYS use an On Error GoTo statement here
    'because another error here would cause an endless loop
    'use On Error GoTo 0 or On Error GoTo <Label>
    On Error GoTo 0

    'more code with or without error handling

End Sub

Sources:

The key to making this work is to use a Resume statement immediately followed by another On Error statement. The Resume is within the error handler and diverts code to the EndTry1 label. You must immediately set another On Error statement to avoid problems as the previous error handler will "resume". That is, it will be active and ready to handle another error. That could cause the error to repeat and enter an infinite loop.

To avoid using the previous error handler again you need to set On Error to a new error handler or simply use On Error Goto 0 to cancel all error handling.

ERROR 2003 (HY000): Can't connect to MySQL server (111)

Check that your remote host (i.e. the web hosting server you're trying to connect FROM) allows OUTGOING traffic on port 3306.

I saw the (100) error in this situation. I could connect from my PC/Mac, but not from my website. The MySQL instance was accessible via the internet, but my hosting company wasn't allowing my website to connect to the database on port 3306.

Once I asked my hosting company to open my web hosting account up to outgoing traffic on port 3306, my website could connect to my remote database.

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Some special characters give this type of error, so use

$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";

Pass by Reference / Value in C++

I'm not sure if I understand your question correctly. It is a bit unclear. However, what might be confusing you is the following:

  1. When passing by reference, a reference to the same object is passed to the function being called. Any changes to the object will be reflected in the original object and hence the caller will see it.

  2. When passing by value, the copy constructor will be called. The default copy constructor will only do a shallow copy, hence, if the called function modifies an integer in the object, this will not be seen by the calling function, but if the function changes a data structure pointed to by a pointer within the object, then this will be seen by the caller due to the shallow copy.

I might have mis-understood your question, but I thought I would give it a stab anyway.

Adding placeholder text to textbox

I wrote a reusable custom control, maybe it can help someone that need to implement multiple placeholder textboxes in his project.
here is the custom class with implementation example of an instance, you can test easily by pasting this code on a new winforms project using VS:

namespace reusebleplaceholdertextbox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // implementation
            CustomPlaceHolderTextbox myCustomTxt = new CustomPlaceHolderTextbox(
                "Please Write Text Here...", Color.Gray, new Font("ARIAL", 11, FontStyle.Italic)
                , Color.Black, new Font("ARIAL", 11, FontStyle.Regular)
                );

            myCustomTxt.Multiline = true;
            myCustomTxt.Size = new Size(200, 50);
            myCustomTxt.Location = new Point(10, 10);
            this.Controls.Add(myCustomTxt);
        }
    }

    class CustomPlaceHolderTextbox : System.Windows.Forms.TextBox
    {
        public string PlaceholderText { get; private set; }
        public Color PlaceholderForeColor { get; private set; }
        public Font PlaceholderFont { get; private set; }

        public Color TextForeColor { get; private set; }
        public Font TextFont { get; private set; }

        public CustomPlaceHolderTextbox(string placeholdertext, Color placeholderforecolor,
            Font placeholderfont, Color textforecolor, Font textfont)
        {
            this.PlaceholderText = placeholdertext;
            this.PlaceholderFont = placeholderfont;
            this.PlaceholderForeColor = placeholderforecolor;
            this.PlaceholderFont = placeholderfont;
            this.TextForeColor = textforecolor;
            this.TextFont = textfont;
            if (!string.IsNullOrEmpty(this.PlaceholderText))
            {
                SetPlaceHolder(true);
                this.Update();
            }
        }

        private void SetPlaceHolder(bool addEvents)
        {
            if (addEvents)
            {  
                this.LostFocus += txt_lostfocus;
                this.Click += txt_click;
            }

            this.Text = PlaceholderText;
            this.ForeColor = PlaceholderForeColor;
            this.Font = PlaceholderFont;
        }

        private void txt_click(object sender, EventArgs e)
        {
            // IsNotFirstClickOnThis:
            // if there is no other control in the form
            // we will have a problem after the first load
            // because we dont other focusable control to move the focus to
            // and we dont want to remove the place holder
            // only on first time the place holder will be removed by click event
            RemovePlaceHolder();
            this.GotFocus += txt_focus;
            // no need for this event listener now
            this.Click -= txt_click;
        }

        private void RemovePlaceHolder()
        {
            this.Text = "";
            this.ForeColor = TextForeColor;
            this.Font = TextFont;
        }
        private void txt_lostfocus(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.Text))
            {
                // set placeholder again
                SetPlaceHolder(false);
            }
        }

        private void txt_focus(object sender, EventArgs e)
        {
            if (this.Text == PlaceholderText)
            {
                // IsNotFirstClickOnThis:
                // if there is no other control in the form
                // we will have a problem after the first load
                // because we dont other focusable control to move the focus to
                // and we dont want to remove the place holder
                RemovePlaceHolder();
            }
        }
    }
}

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

How do I copy items from list to list without foreach?

Easy to map different set of list by linq without for loop

var List1= new List<Entities1>();

var List2= new List<Entities2>();

var List2 = List1.Select(p => new Entities2
        {
            EntityCode = p.EntityCode,
            EntityId = p.EntityId,
            EntityName = p.EntityName
        }).ToList();

Responsive design with media query : screen size?

Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience

When you design your responsive website you should consider the size of the screen and not the device type. The media queries helps you do that.

If you want to style your site per device, you can use the user agent value, but this is not recommended since you'll have to work hard to maintain your code for new devices, new browsers, browsers versions etc while when using the screen size, all of this does not matter.

You can see some standard resolutions in this link.

BUT, in my opinion, you should first design your website layout, and only then adjust it with media queries to fit possible screen sizes.

Why? As I said before, the screen resolutions variety is big and if you'll design a mobile version that is targeted to 320px your site won't be optimized to 350px screens or 400px screens.

TIPS

  1. When designing a responsive page, open it in your desktop browser and change the width of the browser to see how the width of the screen affects your layout and style.
  2. Use percentage instead of pixels, it will make your work easier.

Example

I have a table with 5 columns. The data looks good when the screen size is bigger than 600px so I add a breakpoint at 600px and hides 1 less important column when the screen size is smaller. Devices with big screens such as desktops and tablets will display all the data, while mobile phones with small screens will display part of the data.


State of mind

Not directly related to the question but important aspect in responsive design. Responsive design also relate to the fact that the user have a different state of mind when using a mobile phone or a desktop. For example, when you open your bank's site in the evening and check your stocks you want as much data on the screen. When you open the same page in the your lunch break your probably want to see few important details and not all the graphs of last year.

How to get names of classes inside a jar file?

Description OF Solution : Eclipse IDE can be used for this by creating a sample java project and add all jars in the Project Build path

STEPS below:

  1. Create a sample Eclipse Java project.

  2. All all the jars you have in its Build Path

  3. CTRL+SHIFT+T and Type the full class name .

  4. Results will be displayed in the window with all the jars having that class. See attached picture . enter image description here

How to check if NSString begins with a certain character

You can use the -hasPrefix: method of NSString:

Objective-C:

NSString* output = nil;
if([string hasPrefix:@"*"]) {
    output = [string substringFromIndex:1];
}

Swift:

var output:String?
if string.hasPrefix("*") {
    output = string.substringFromIndex(string.startIndex.advancedBy(1))
}

What function is to replace a substring from a string in C?

You can use strrep()

char* strrep ( const char * cadena, const char * strf, const char * strr )

strrep (String Replace). Replaces 'strf' with 'strr' in 'cadena' and returns the new string. You need to free the returned string in your code after using strrep.

Parameters cadena The string with the text. strf The text to find. strr The replacement text.

Returns The text updated wit the replacement.

Project can be found at https://github.com/ipserc/strrep

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

An explicit call to a parent class constructor is required any time the parent class lacks a no-argument constructor. You can either add a no-argument constructor to the parent class or explicitly call the parent class constructor in your child class.

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

How to run a program automatically as admin on Windows 7 at startup?

Setting compatibility of your application to administrator (Run theprogram as an administrator).

Plug it into task scheduler, then turn off UAC.

Java integer list

If you want to rewrite a line on console, print a control character \r (carriage return).

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
Iterator<Integer> myListIterator = myCoords.iterator(); 
while (myListIterator.hasNext()) {
    Integer coord = myListIterator.next();     
    System.out.print("\r");
    System.out.print(coord);
    Thread.sleep(2000);
}

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

Check your computer's Date and Time. If it is wrong, update it to the current time or set it automatically to get the time from the Internet.

Because certificates are tied to a fixed time period, if your clock is wrong, you are likely to get errors like this. In that scenario, by fixing the time, the problem will be fixed.

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

For 'Bad' red:

  • The Font Is: (156,0,6)
  • The Background Is: (255,199,206)

For 'Good' green:

  • The Font Is: (0,97,0)
  • The Background Is: (198,239,206)

For 'Neutral' yellow:

  • The Font Is: (156,101,0)
  • The Background Is: (255,235,156)

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

Go to installed updates and just uninstall Internet Explorer 11 Windows update. It works for me.

Maven Out of Memory Build Failure

What type of OS are you running on?

In order to assign more than 2GB of ram it needs to be at least a 64bit OS.

Then there is another problem. Even if your OS has Unlimited RAM, but that is fragmented in a way that not a single free block of 2GB is available, you'll get out of memory exceptions too. And keep in mind that the normal Heap memory is only part of the memory the VM process is using. So on a 32bit machine you will probably never be able to set Xmx to 2048MB.

I would also suggest to set min an max memory to the same value, because in this case as soon as the VM runs out of memory the frist time 1GB is allocated from the start, the VM then allocates a new block (assuming it increases with 500MB blocks) of 1,5GB after that is allocated, it would copy all the stuff from block one to the new one and free Memory after that. If it runs out of Memory again the 2GB are allocated and the 1,5 GB are then copied, temporarily allocating 3,5GB of memory.

Best way to use multiple SSH private keys on one client

I love the approach to set the following in file ~/.ssh/config:

# Configuration for GitHub to support multiple GitHub  keys
Host  github.com
  HostName github.com
  User git

# UseKeychain adds each keys passphrase to the keychain so you
# don't have to enter the passphrase each time.
  UseKeychain yes

# AddKeysToAgent would add the key to the agent whenever it is
# used, which might lead to debugging confusion since then
# sometimes the one repository works and sometimes the
# other depending on which key is used first.
#  AddKeysToAgent yes

# I only use my private id file so all private
# repositories don't need the environment variable
# `GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa"` to be set.
  IdentityFile ~/.ssh/id_rsa

Then in your repository you can create a .env file which contains the ssh command to be used:

GIT_SSH_COMMAND="ssh -i ~/.ssh/your_ssh_key"

If you then use e.g. dotenv the environment environment variable is exported automatically and whoop whoop, you can specify the key you want per project/directory. The passphrase is asked for only once since it is added to the keychain.

This solution works perfectly with Git and is designed to work on a Mac (due to UseKeychain).

Flask ImportError: No Module Named Flask

my answer just for any users that use Visual Studio Flesk Web project :

Just Right Click on "Python Environment" and Click to "Add Environment"

HTML -- two tables side by side

With CSS: table {float:left;}? ?

Linker Error C++ "undefined reference "

Your header file Hash.h declares "what class hash should look like", but not its implementation, which is (presumably) in some other source file we'll call Hash.cpp. By including the header in your main file, the compiler is informed of the description of class Hash when compiling the file, but not how class Hash actually works. When the linker tries to create the entire program, it then complains that the implementation (toHash::insert(int, char)) cannot be found.

The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:

g++ -o main Hash.cpp main.cpp

will create the main program called "main".

Instagram API to fetch pictures with specific hashtags

It is not possible yet to search for content using multiple tags, for now only single tags are supported.

Firstly, the Instagram API endpoint "tags" required OAuth authentication.

This is not quite true, you only need an API-Key. Just register an application and add it to your requests. Example:

https://api.instagram.com/v1/users/userIdYouWantToGetMediaFrom/media/recent?client_id=yourAPIKey

Also note that the username is not the user-id. You can look up user-Id`s here.

A workaround for searching multiple keywords would be if you start one request for each tag and compare the results on your server. Of course this could slow down your site depending on how much keywords you want to compare.

How to run ~/.bash_profile in mac terminal

On MacOS: add source ~/.bash_profile to the end of ~/.zshrc. Then this profile will be in effect when you open zsh.

Why can't static methods be abstract in Java?

A static method, by definition, doesn't need to know this. Thus, it cannot be a virtual method (that is overloaded according to dynamic subclass information available through this); instead, a static method overload is solely based on info available at compile time (this means: once you refer a static method of superclass, you call namely the superclass method, but never a subclass method).

According to this, abstract static methods would be quite useless because you will never have its reference substituted by some defined body.

Quoting backslashes in Python string literals

What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.

infile = open('c:/folder/subfolder/file.txt')

The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system or the subprocess module).

Newtonsoft JSON Deserialize

You can implement a class that holds the fields you have in your JSON

class MyData
{
    public string t;
    public bool a;
    public object[] data;
    public string[][] type;
}

and then use the generic version of DeserializeObject:

MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
    // Do something with typeStr
}

Documentation: Serializing and Deserializing JSON

Could not open input file: artisan

First create the project from the following link to create larave 7 project: Create Project

Now you need to enter your project folder using the following command:

cd myproject

Now try to run artisan command, such as, php artisan.

Or it may happen if you didn't install compose. So if you didn't install composer then run composer install and try again artisan command.

How to empty the content of a div

If by saying without destroying it, you mean to a keep a reference to the children, you can do:

var oldChildren = [];

while(element.hasChildNodes()) {
    oldChildren.push(element.removeChild(element.firstChild));
}

Regarding the original tagging (html css) of your question:

You cannot remove content with CSS. You could only hide it. E.g. you can hide all children of a certain node with:

#someID > * {
    display: none;
}

This doesn't work in IE6 though (but you could use #someID *).

INNER JOIN ON vs WHERE clause

ANSI join syntax is definitely more portable.

I'm going through an upgrade of Microsoft SQL Server, and I would also mention that the =* and *= syntax for outer joins in SQL Server is not supported (without compatibility mode) for 2005 SQL server and later.

How do I get the position selected in a RecyclerView?

A different method - using setTag() and getTag() methods of the View class.

  1. use setTag() in the onBindViewHolder method of your adapter

    @Override
    public void onBindViewHolder(myViewHolder viewHolder, int position) {
        viewHolder.mCardView.setTag(position);
    }
    

    where mCardView is defined in the myViewHolder class

    private class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
               public View mCardView;
    
               public myViewHolder(View view) {
                   super(view);
                   mCardView = (CardView) view.findViewById(R.id.card_view);
    
                   mCardView.setOnClickListener(this);
               }
           }
    
  2. use getTag() in your OnClickListener implementation

    @Override
    public void onClick(View view) {
        int position = (int) view.getTag();           
    
    //display toast with position of cardview in recyclerview list upon click
    Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
    }
    

see https://stackoverflow.com/a/33027953/4658957 for more details

How create a new deep copy (clone) of a List<T>?

I'm disappointed Microsoft didn't offer a neat, fast and easy solution like Ruby are doing with the clone() method.

Except that does not create a deep copy, it creates a shallow copy.

With deep copying, you have to be always careful, what exactly do you want to copy. Some examples of possible issues are:

  1. Cycle in the object graph. For example, Book has an Author and Author has a list of his Books.
  2. Reference to some external object. For example, an object could contain open Stream that writes to a file.
  3. Events. If an object contains an event, pretty much anyone could be subscribed to it. This can get especially problematic if the subscriber is something like a GUI Window.

Now, there are basically two ways how to clone something:

  1. Implement a Clone() method in each class that you need cloned. (There is also ICloneable interface, but you should not use that; using a custom ICloneable<T> interface as Trevor suggested is okay.) If you know that all you need is to create a shallow copy of each field of this class, you could use MemberwiseClone() to implement it. As an alternative, you could create a “copy constructor”: public Book(Book original).
  2. Use serialization to serialize your objects into a MemoryStream and then deserialize them back. This requires you to mark each class as [Serializable] and it can also be configured what exactly (and how) should be serialized. But this is more of a “quick and dirty” solution, and will most likely also be less performant.

is there a require for json in node.js

You can import json files by using the node.js v14 experimental json modules flag. More details here

file.js

import data from './folder/file.json'

export default {
  foo () {
    console.log(data)
  }
}

And you call it with node --experimental-json-modules file.js

How to make rectangular image appear circular with CSS

You can make it like that:

    <html>
<head>
    <style>
        .round {
            display:block;
            width: 55px;
            height: 55px;
            border-radius: 50%;
            overflow: hidden;
            padding:5px 4px;
        }
        .round img {
            width: 45px;
        }
    </style>
</head>
<body>
    <div class="round">
        <img src="image.jpg" />
    </div>
</body>

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

Using Google Finance as an example to retrieve the ticker's last close price and the updated date & time. You may visit YouTiming.com for the run-time execution.

The service:

MyApp.service('getData', 
  [
    '$http',
    function($http) {

      this.getQuote = function(ticker) {
        var _url = 'https://www.google.com/finance/info?q=' + ticker;
        return $http.get(_url); //Simply return the promise to the caller
      };
    }
  ]
);

The controller:

MyApp.controller('StockREST', 
  [
    '$scope',
    'getData', //<-- the service above
    function($scope, getData) {
      var getQuote = function(symbol) {
        getData.getQuote(symbol)
        .success(function(response, status, headers, config) {
          var _data = response.substring(4, response.length);
          var _json = JSON.parse(_data);
          $scope.stockQuoteData = _json[0];
          // ticker: $scope.stockQuoteData.t
          // last price: $scope.stockQuoteData.l
          // last updated time: $scope.stockQuoteData.ltt, such as "7:59PM EDT"
          // last updated date & time: $scope.stockQuoteData.lt, such as "Sep 29, 7:59PM EDT"
        })
        .error(function(response, status, headers, config) {
          console.log('@@@ Error: in retrieving Google Finance stock quote, ticker = ' + symbol);
        });
      };

      getQuote($scope.ticker.tick.name); //Initialize
      $scope.getQuote = getQuote; //as defined above
    }
  ]
);

The HTML:

<span>{{stockQuoteData.l}}, {{stockQuoteData.lt}}</span>

At the top of YouTiming.com home page, I have placed the notes for how to disable the CORS policy on Chrome and Safari.

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

If it gets into the selinux arena you've got a much more complicated issue. It's not a good idea to remove the selinux protection but to embrace it and use the tools that were designed to manage it.

If you are serving content out of /var/www/abc, you can verify the selinux permissions with a Z appended to the normal ls -l command. i.e. ls -laZ will give the selinux context.

To add a directory to be served by selinux you can use the semanage command like this. This will change the label on /var/www/abc to httpd_sys_content_t

semanage fcontext -a -t httpd_sys_content_t /var/www/abc

this will update the label for /var/www/abc

restorecon /var/www/abc 

This answer was taken from unixmen and modified to fit this question. I had been searching for this answer for a while and finally found it so felt like I needed to share somewhere. Hope it helps someone.

Ruby array to string conversion

try this code ['12','34','35','231']*","

will give you result "12,34,35,231"

I hope this is the result you, let me know

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I had this problem and tried various solutions to solve it including many of those listed above (config file, debug ssh etc). In the end, I resolved it by including the -u switch in the git push, per the github instructions when creating a new repository onsite - Github new Repository

How to match letters only using java regex, matches method?

"[a-zA-Z]" matches only one character. To match multiple characters, use "[a-zA-Z]+".

Since a dot is a joker for any character, you have to mask it: "abc\." To make the dot optional, you need a question mark: "abc\.?"

If you write the Pattern as literal constant in your code, you have to mask the backslash:

System.out.println ("abc".matches ("abc\\.?"));
System.out.println ("abc.".matches ("abc\\.?"));
System.out.println ("abc..".matches ("abc\\.?"));

Combining both patterns:

System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));

Instead of a-zA-Z, \w is often more appropriate, since it captures foreign characters like äöüßø and so on:

System.out.println ("abc.".matches ("\\w+\\.?"));   

Any way to make a WPF textblock selectable?

Really nice and easy solution, exactly what I wanted !

I bring some small modifications

public class TextBlockMoo : TextBlock 
{
    public String SelectedText = "";

    public delegate void TextSelectedHandler(string SelectedText);
    public event TextSelectedHandler OnTextSelected;
    protected void RaiseEvent()
    {
        if (OnTextSelected != null){OnTextSelected(SelectedText);}
    }

    TextPointer StartSelectPosition;
    TextPointer EndSelectPosition;
    Brush _saveForeGroundBrush;
    Brush _saveBackGroundBrush;

    TextRange _ntr = null;

    protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);

        if (_ntr!=null) {
            _ntr.ApplyPropertyValue(TextElement.ForegroundProperty, _saveForeGroundBrush);
            _ntr.ApplyPropertyValue(TextElement.BackgroundProperty, _saveBackGroundBrush);
        }

        Point mouseDownPoint = e.GetPosition(this);
        StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true);            
    }

    protected override void OnMouseUp(MouseButtonEventArgs e)
    {
        base.OnMouseUp(e);
        Point mouseUpPoint = e.GetPosition(this);
        EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);

        _ntr = new TextRange(StartSelectPosition, EndSelectPosition);

        // keep saved
        _saveForeGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.ForegroundProperty);
        _saveBackGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.BackgroundProperty);
        // change style
        _ntr.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
        _ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.DarkBlue));

        SelectedText = _ntr.Text;
    }
}

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

link_to image tag. how to add class to a tag

You can also try this

<li><%= link_to "", application_welcome_path, class: "navbar-brand metas-logo"    %></li>

Where "metas-logo" is a css class with a background image

HTML Mobile -forcing the soft keyboard to hide

Since the soft keyboard is part of the OS, more often than not, you won't be able to hide it - also, on iOS, hiding the keyboard drops focus from the element.

However, if you use the onFocus attribute on the input, and then blur() the text input immediately, the keyboard will hide itself and the onFocus event can set a variable to define which text input was focused last.

Then alter your on-page keyboard to only alter the last-focused (check using the variable) text input, rather than simulating a key press.

Programmatically check Play Store for app updates

Coming From a Hybrid Application POV. This is a javascript example, I have a Update Available footer on my main menu. If an update is available (ie. my version number within the config file is less than the version retrieved, display the footer) This will then direct the user to the app/play store, where the user can then click the update button.

I also get the whats new data (ie Release Notes) and display these in a modal on login if its the first time on this version.

On device Ready, set your store URL

        if (device.platform == 'iOS')
           storeURL = 'https://itunes.apple.com/lookup?bundleId=BUNDLEID';
        else
           storeURL = 'https://play.google.com/store/apps/details?id=BUNDLEID';

The Update Available method can be ran as often as you like. Mine is ran every time the user navigates to the home screen.

function isUpdateAvailable() {
    if (device.platform == 'iOS') {
        $.ajax(storeURL, {
            type: "GET",
            cache: false,
            dataType: 'json'
        }).done(function (data) {
            isUpdateAvailable_iOS(data.results[0]);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            commsErrorHandler(jqXHR, textStatus, false);
        });
    } else {
        $.ajax(storeURL, {
            type: "GET",
            cache: false
        }).done(function (data) {
            isUpdateAvailable_Android(data);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            commsErrorHandler(jqXHR, textStatus, false);
        });
    }
}

iOS Callback: Apple have an API, so very easy to get

function isUpdateAvailable_iOS (data) {
    var storeVersion = data.version;
    var releaseNotes = data.releaseNotes;
    // Check store Version Against My App Version ('1.14.3' -> 1143)
    var _storeV = parseInt(storeVersion.replace(/\./g, ''));
    var _appV = parseInt(appVersion.substring(1).replace(/\./g, ''));
    $('#ft-main-menu-btn').off();
    if (_storeV > _appV) {
        // Update Available
        $('#ft-main-menu-btn').text('Update Available');
        $('#ft-main-menu-btn').click(function () {
            openStore();
        });

    } else {
        $('#ft-main-menu-btn').html('&nbsp;');
        // Release Notes
        settings.updateReleaseNotes('v' + storeVersion, releaseNotes);
    }
}

Android Callback: PlayStore you have to scrape, as you can see the version is relatively easy to grab and the whats new i take the html instead of the text as this way I can use their formatting (ie new lines etc)

function isUpdateAvailable_Android(data) {
    var html = $(data);
    var storeVersion = html.find('div[itemprop=softwareVersion]').text().trim();
    var releaseNotes = html.find('.whatsnew')[0].innerHTML;
    // Check store Version Against My App Version ('1.14.3' -> 1143)
    var _storeV = parseInt(storeVersion.replace(/\./g, ''));
    var _appV = parseInt(appVersion.substring(1).replace(/\./g, ''));
    $('#ft-main-menu-btn').off();
    if (_storeV > _appV) {
        // Update Available
        $('#ft-main-menu-btn').text('Update Available');
        $('#ft-main-menu-btn').click(function () {
            openStore();
        });

    } else {
        $('#ft-main-menu-btn').html('&nbsp;');
        // Release Notes
        settings.updateReleaseNotes('v' + storeVersion, releaseNotes);
    }
}

The open store logic is straight forward, but for completeness

function openStore() {
    var url = 'https://itunes.apple.com/us/app/appname/idUniqueID';
    if (device.platform != 'iOS')
       url = 'https://play.google.com/store/apps/details?id=appid'
   window.open(url, '_system')
}

Ensure Play Store and App Store have been Whitelisted:

  <access origin="https://itunes.apple.com"/>
  <access origin="https://play.google.com"/>

javascript set cookie with expire time

document.cookie = "cookie_name=cookie_value; max-age=31536000; path=/";

Will set the value for a year.

c# search string in txt file

If your pair of lines will only appear once in your file, you could use

File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .Skip(1) // optional
    .TakeWhile(line => !line.Contains("CustomerCh"));

If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:

List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
    if (line.Contains("CustomerEN") && current == null)
        current = new List<string>();
    else if (line.Contains("CustomerCh") && current != null)
    {
        groups.Add(current);
        current = null;
    }
    if (current != null)
        current.Add(line);
}

Unable to run Java code with Intellij IDEA

Move your code inside of the src folder. Once it's there, it'll be compiled on-the-fly every time it's saved.

IntelliJ only recognizes files in specific locations as part of the project - namely, anything inside of a blue folder is specifically considered to be source code.

Also - while I can't see all of your source code - be sure that it's proper Java syntax, with a class declared the same as the file and that it has a main method (specifically public static void main(String[] args)). IntelliJ won't run code without a main method (rather, it can't - neither it nor Java would know where to start).

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

This code makes json my default and allows me to use the XML format as well. I'll just append the xml=true.

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Thanks everyone!

Scrolling to an Anchor using Transition/CSS3

Just apply scroll behaviour to all elements with this one-line code:

_x000D_
_x000D_
*{
scroll-behavior: smooth !important;
}
_x000D_
_x000D_
_x000D_

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Regex expressions in Java, \\s vs. \\s+

Those two replaceAll calls will always produce the same result, regardless of what x is. However, it is important to note that the two regular expressions are not the same:

  • \\s - matches single whitespace character
  • \\s+ - matches sequence of one or more whitespace characters.

In this case, it makes no difference, since you are replacing everything with an empty string (although it would be better to use \\s+ from an efficiency point of view). If you were replacing with a non-empty string, the two would behave differently.

How do I restart a service on a remote machine in Windows?

I would suggest you to have a look at RSHD

You do not need to bother for a client, Windows has it by default.

relative path to CSS file

Background

Absolute: The browser will always interpret / as the root of the hostname. For example, if my site was http://google.com/ and I specified /css/images.css then it would search for that at http://google.com/css/images.css. If your project root was actually at /myproject/ it would not find the css file. Therefore, you need to determine where your project folder root is relative to the hostname, and specify that in your href notation.

Relative: If you want to reference something you know is in the same path on the url - that is, if it is in the same folder, for example http://mysite.com/myUrlPath/index.html and http://mysite.com/myUrlPath/css/style.css, and you know that it will always be this way, you can go against convention and specify a relative path by not putting a leading / in front of your path, for example, css/style.css.

Filesystem Notations: Additionally, you can use standard filesystem notations like ... If you do http://google.com/images/../images/../images/myImage.png it would be the same as http://google.com/images/myImage.png. If you want to reference something that is one directory up from your file, use ../myFile.css.


Your Specific Case

In your case, you have two options:

  • <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
  • <link rel="stylesheet" type="text/css" href="css/styles.css"/>

The first will be more concrete and compatible if you move things around, however if you are planning to keep the file in the same location, and you are planning to remove the /ServletApp/ part of the URL, then the second solution is better.

Read input stream twice

if your InputStream support using mark, then you can mark() your inputStream and then reset() it . if your InputStrem doesn't support mark then you can use the class java.io.BufferedInputStream,so you can embed your stream inside a BufferedInputStream like this

    InputStream bufferdInputStream = new BufferedInputStream(yourInputStream);
    bufferdInputStream.mark(some_value);
    //read your bufferdInputStream 
    bufferdInputStream.reset();
    //read it again