Programs & Examples On #Unicode

Unicode is a standard for the encoding, representation and handling of text with the intention of supporting all the characters required for written text incorporating all writing systems, technical symbols and punctuation.

Write a file in UTF-8 using FileWriter (Java)?

You need to use the OutputStreamWriter class as the writer parameter for your BufferedWriter. It does accept an encoding. Review javadocs for it.

Somewhat like this:

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("jedis.txt"), "UTF-8"
));

Or you can set the current system encoding with the system property file.encoding to UTF-8.

java -Dfile.encoding=UTF-8 com.jediacademy.Runner arg1 arg2 ...

You may also set it as a system property at runtime with System.setProperty(...) if you only need it for this specific file, but in a case like this I think I would prefer the OutputStreamWriter.

By setting the system property you can use FileWriter and expect that it will use UTF-8 as the default encoding for your files. In this case for all the files that you read and write.

EDIT

  • Starting from API 19, you can replace the String "UTF-8" with StandardCharsets.UTF_8

  • As suggested in the comments below by tchrist, if you intend to detect encoding errors in your file you would be forced to use the OutputStreamWriter approach and use the constructor that receives a charset encoder.

    Somewhat like

    CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
    encoder.onMalformedInput(CodingErrorAction.REPORT);
    encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("jedis.txt"),encoder));
    

    You may choose between actions IGNORE | REPLACE | REPORT

Also, this question was already answered here.

How to replace unicode characters in string with something else python?

import re
regex = re.compile("u'2022'",re.UNICODE)
newstring = re.sub(regex, something, yourstring, <optional flags>)

Difference between UTF-8 and UTF-16?

Security: Use only UTF-8

Difference between UTF-8 and UTF-16? Why do we need these?

There have been at least a couple of security vulnerabilities in implementations of UTF-16. See Wikipedia for details.

WHATWG and W3C have now declared that only UTF-8 is to be used on the Web.

The [security] problems outlined here go away when exclusively using UTF-8, which is one of the many reasons that is now the mandatory encoding for all things.

Other groups are saying the same.

So while UTF-16 may continue being used internally by some systems such as Java and Windows, what little use of UTF-16 you may have seen in the past for data files, data exchange, and such, will likely fade away entirely.

How to use Greek symbols in ggplot2?

You do not need the latex2exp package to do what you wanted to do. The following code would do the trick.

ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) + 
  geom_point() + 
  labs(title=expression("Fuel Efficiency"~(alpha*Omega)), 
color=expression(alpha*Omega), x=expression(Delta~price))

enter image description here

Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*") works, so I suggest giving it a try.

More comments asked about getting ? Price and I find the most straightforward way to achieve that is expression(Delta~price)). If you need to add something before the Greek letter, you can also do this: expression(Indicative~Delta~price) which gets you:

enter image description here

What's HTML character code 8203?

I landed here with the same issue, then figured it out on my own. This weird character was appearing with my HTML.

The issue is most likely your code editor. I use Espresso and sometimes run into issues like this.

To fix it, simply highlight the affected code, then go to the menu and click "convert to numeric entities". You'll see the numeric value of this character appear; simply delete it and it's gone forever.

How do I see what character set a MySQL database / table / column is?

I always just look at SHOW CREATE TABLE mydatabase.mytable.

For the database, it appears you need to look at SELECT DEFAULT_CHARACTER_SET_NAME FROM information_schema.SCHEMATA.

python encoding utf-8

Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python

What is the difference between UTF-8 and Unicode?

UTF-8 is one possible encoding scheme for Unicode text.

Unicode is a broad-scoped standard which defines over 140,000 characters and allocates each a numerical code (a code point). It also defines rules for how to sort this text, normalise it, change its case, and more. A character in Unicode is represented by a code point from zero up to 0x10FFFF inclusive, though some code points are reserved and cannot be used for characters.

There is more than one way that a string of Unicode code points can be encoded into a binary stream. These are called "encodings". The most straightforward encoding is UTF-32, which simply stores each code point as a 32-bit integer, with each being 4 bytes wide.

UTF-8 is another encoding, and is becoming the de-facto standard, due to a number of advantages over UTF-32 and others. UTF-8 encodes each code point as a sequence of either 1, 2, 3 or 4 byte values. Code points in the ASCII range are encoded as a single byte value, to be compatible with ASCII. Code points outside this range use either 2, 3, or 4 bytes each, depending on what range they are in.

UTF-8 has been designed with these properties in mind:

  • ASCII characters are encoded exactly as they are in ASCII, such that an ASCII string is also a valid UTF-8 string representing the same characters.

  • Binary sorting: Sorting UTF-8 strings using a binary sort will still result in all code points being sorted in numerical order.

  • When a code point uses multiple bytes, none of those bytes contain values in the ASCII range, ensuring that no part of them could be mistaken for an ASCII character. This is also a security feature.

  • UTF-8 can be easily validated, and distinguished from other character encodings by a validator. Text in other 8-bit or multi-byte encodings will very rarely also validate as UTF-8 due to the very specific structure of UTF-8.

  • Random access: At any point in a UTF-8 string it is possible to tell if the byte at that position is the first byte of a character or not, and to find the start of the next or current character, without needing to scan forwards or backwards more than 3 bytes or to know how far into the string we started reading from.

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines in the script solved the issue for me.

# !/usr/bin/python
# coding=utf-8

Hope it helps !

HTML for the Pause symbol in audio and video control

Following may come in handy:

  • &#x23e9;
  • &#x23ea;
  • &#x24eb;
  • &#x23ec;
  • &#x23ed;
  • &#x23ee;
  • &#x23ef;
  • &#x23f4;
  • &#x23f5;
  • &#x23f6;
  • &#x23f7;
  • &#x23f8;
  • &#x23f9;
  • &#x23fa;

NOTE: apparently, these characters aren't very well supported in popular fonts, so if you plan to use it on the web, be sure to pick a webfont that supports these.

How to convert a string to utf-8 in Python

If I understand you correctly, you have a utf-8 encoded byte-string in your code.

Converting a byte-string to a unicode string is known as decoding (unicode -> byte-string is encoding).

You do that by using the unicode function or the decode method. Either:

unicodestr = unicode(bytestr, encoding)
unicodestr = unicode(bytestr, "utf-8")

Or:

unicodestr = bytestr.decode(encoding)
unicodestr = bytestr.decode("utf-8")

Convert International String to \u Codes in java

this type name is Decode/Unescape Unicode. this site link online convertor.

Converting Symbols, Accent Letters to English Alphabet

I'm late to the party, but after facing this issue today, I found this answer to be very good:

String asciiName = Normalizer.normalize(unicodeName, Normalizer.Form.NFD)
    .replaceAll("[^\\p{ASCII}]", "");

Reference: https://stackoverflow.com/a/16283863

How many bytes does one Unicode character take?

Unicode is a standard which provides a unique number for every character. These unique numbers are called code points (which is just unique code) to all characters existing in the world (some's are still to be added).

For different purposes, you might need to represent this code points in bytes (most programming languages do so), and here's where Character Encoding kicks in.

UTF-8, UTF-16, UTF-32 and so on are all Character Encodings, and Unicode's code points are represented in these encodings, in different ways.


UTF-8 encoding has a variable-width length, and characters, encoded in it, can occupy 1 to 4 bytes inclusive;

UTF-16 has a variable length and characters, encoded in it, can take either 1 or 2 bytes (which is 8 or 16 bits). This represents only part of all Unicode characters called BMP (Basic Multilingual Plane) and it's enough for almost all the cases. Java uses UTF-16 encoding for its strings and characters;

UTF-32 has fixed length and each character takes exactly 4 bytes (32 bits).

How to replace � in a string

Character issues like this are difficult to diagnose because information is easily lost through misinterpretation of characters via application bugs, misconfiguration, cut'n'paste, etc.

As I (and apparently others) see it, you've pasted three characters:

codepoint   glyph   escaped    windows-1252    info
=======================================================================
U+00ef      ï       \u00ef     ef,             LATIN_1_SUPPLEMENT, LOWERCASE_LETTER
U+00bf      ¿       \u00bf     bf,             LATIN_1_SUPPLEMENT, OTHER_PUNCTUATION
U+00bd      ½       \u00bd     bd,             LATIN_1_SUPPLEMENT, OTHER_NUMBER

To identify the character, download and run the program from this page. Paste your character into the text field and select the glyph mode; paste the report into your question. It'll help people identify the problematic character.

Java FileReader encoding issue

FileInputStream with InputStreamReader is better than directly using FileReader, because the latter doesn't allow you to specify encoding charset.

Here is an example using BufferedReader, FileInputStream and InputStreamReader together, so that you could read lines from a file.

List<String> words = new ArrayList<>();
List<String> meanings = new ArrayList<>();
public void readAll( ) throws IOException{
    String fileName = "College_Grade4.txt";
    String charset = "UTF-8";
    BufferedReader reader = new BufferedReader(
        new InputStreamReader(
            new FileInputStream(fileName), charset)); 

    String line; 
    while ((line = reader.readLine()) != null) { 
        line = line.trim();
        if( line.length() == 0 ) continue;
        int idx = line.indexOf("\t");
        words.add( line.substring(0, idx ));
        meanings.add( line.substring(idx+1));
    } 
    reader.close();
}

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Reading Email using Pop3 in C#

I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.

Also, the project is mostly dormant... the last release was in 2004.

For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The error you're seeing means the data you receive from the remote end isn't valid JSON. JSON (according to the specifiation) is normally UTF-8, but can also be UTF-16 or UTF-32 (in either big- or little-endian.) The exact error you're seeing means some part of the data was not valid UTF-8 (and also wasn't UTF-16 or UTF-32, as those would produce different errors.)

Perhaps you should examine the actual response you receive from the remote end, instead of blindly passing the data to json.loads(). Right now, you're reading all the data from the response into a string and assuming it's JSON. Instead, check the content type of the response. Make sure the webpage is actually claiming to give you JSON and not, for example, an error message that isn't JSON.

(Also, after checking the response use json.load() by passing it the file-like object returned by opener.open(), instead of reading all data into a string and passing that to json.loads().)

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

Josh says: "....Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h."

I'm a native Spanish Speaker and "ch" is not a letter but two "c" and "h" and the Spanish alphabet is like: abcdefghijklmn ñ opqrstuvwxyz We don't expect "ch" after "h" but "i" The alphabet is the same as in English except for the ñ or in HTML "&ntilde ;"

Alex

Is there Unicode glyph Symbol to represent "Search"

I'd recommend using http://shapecatcher.com/ to help search for unicode characters. It allows you to draw the shape you're after, and then lists the closest matches to that shape.

UnicodeDecodeError, invalid continuation byte

It is invalid UTF-8. That character is the e-acute character in ISO-Latin1, which is why it succeeds with that codeset.

If you don't know the codeset you're receiving strings in, you're in a bit of trouble. It would be best if a single codeset (hopefully UTF-8) would be chosen for your protocol/application and then you'd just reject ones that didn't decode.

If you can't do that, you'll need heuristics.

UnicodeDecodeError when reading CSV file in Pandas with Python

You can try with:

df = pd.read_csv('./file_name.csv', encoding='gbk')

How do you properly use WideCharToMultiByte

Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:

#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>

/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";

int main() 
{

    size_t wcsChars = wcslen( wcsString);

    size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1, 
                                               NULL, 0,  NULL, NULL);

    printf( "Wide chars in wcsString: %u\n", wcsChars);
    printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);

    sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
                                        NULL, 0,  NULL, NULL);
    printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);
}

And the output:

Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

If file = open(filename, encoding="utf8") doesn't work, try
file = open(filename, errors="ignore"), if you want to remove unneeded characters.

Font Awesome & Unicode

For those who may stumble across this post, you need to set

font-family: FontAwesome; 

as a property in your CSS selector and then unicode will work fine in CSS

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

Creating Unicode character from its number

Here is a block to print out unicode chars between \u00c0 to \u00ff:

char[] ca = {'\u00c0'};
for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 16; j++) {
        String sc = new String(ca);
        System.out.print(sc + " ");
        ca[0]++;
    }
    System.out.println();
}

Fixing broken UTF-8 encoding

In my case, I found out by using "mb_convert_encoding" that the previous encoding was iso-8859-1 (which is latin1) then I fixed my problem by using an sql query :

UPDATE myDB.myTable SET myColumn = CAST(CAST(CONVERT(myColumn USING latin1) AS binary) AS CHAR)

However, it is stated in the mysql documentations that conversion may be lossy if the column contains characters that are not in both character sets.

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

I have found PercentEscaper class from google-http-java-client library, that can be used to implement encodeURIComponent quite easily.

PercentEscaper from google-http-java-client javadoc google-http-java-client home

Get unicode value of a character

are you picky with using Unicode because with java its more simple if you write your program to use "dec" value or (HTML-Code) then you can simply cast data types between char and int

char a = 98;
char b = 'b';
char c = (char) (b+0002);

System.out.println(a);
System.out.println((int)b);
System.out.println((int)c);
System.out.println(c);

Gives this output

b
98
100
d

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

Concrete Javascript Regex for Accented Characters (Diacritics)

The easier way to accept all accents is this:

[A-zÀ-ú] // accepts lowercase and uppercase characters
[A-zÀ-ÿ] // as above but including letters with an umlaut (includes [ ] ^ \ × ÷)
[A-Za-zÀ-ÿ] // as above but not including [ ] ^ \
[A-Za-zÀ-ÖØ-öø-ÿ] // as above but not including [ ] ^ \ × ÷

See https://unicode-table.com/en/ for characters listed in numeric order.

What is the difference between encode/decode?

The decode method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.

unicode().decode() will perform an implicit encoding of s using the default (ascii) codec. Verify this like so:

>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

>>> s.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

The error messages are exactly the same.

For str().encode() it's the other way around -- it attempts an implicit decoding of s with the default encoding:

>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)

Used like this, str().encode() is also superfluous.

But there is another application of the latter method that is useful: there are encodings that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way:

>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'

You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate byte and string types in Python 3, this is no longer an issue.

What is the proper way to URL encode Unicode characters?

I would always encode in UTF-8. From the Wikipedia page on percent encoding:

The generic URI syntax mandates that new URI schemes that provide for the representation of character data in a URI must, in effect, represent characters from the unreserved set without translation, and should convert all other characters to bytes according to UTF-8, and then percent-encode those values. This requirement was introduced in January 2005 with the publication of RFC 3986. URI schemes introduced before this date are not affected.

It seems like because there were other accepted ways of doing URL encoding in the past, browsers attempt several methods of decoding a URI, but if you're the one doing the encoding you should use UTF-8.

Convert a Unicode string to an escaped ASCII string

For Unescape You can simply use this functions:

System.Text.RegularExpressions.Regex.Unescape(string)

System.Uri.UnescapeDataString(string)

I suggest using this method (It works better with UTF-8):

UnescapeDataString(string)

Usage of unicode() and encode() functions in Python

str is text representation in bytes, unicode is text representation in characters.

You decode text from bytes to unicode and encode a unicode into bytes with some encoding.

That is:

>>> 'abc'.decode('utf-8')  # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'

UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str was renamed to bytes, and unicode was renamed to str.

>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'

Unicode character in PHP string

html_entity_decode('&#x30a8;', 0, 'UTF-8');

This works too. However the json_decode() solution is a lot faster (around 50 times).

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

This is to do with the encoding of your terminal not being set to UTF-8. Here is my terminal

$ echo $LANG
en_GB.UTF-8
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
(?????)?
>>> 

On my terminal the example works with the above, but if I get rid of the LANG setting then it won't work

$ unset LANG
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in range(128)
>>> 

Consult the docs for your linux variant to discover how to make this change permanent.

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

How to convert a string with Unicode encoding to a string of letters

Shorter version:

public static String unescapeJava(String escaped) {
    if(escaped.indexOf("\\u")==-1)
        return escaped;

    String processed="";

    int position=escaped.indexOf("\\u");
    while(position!=-1) {
        if(position!=0)
            processed+=escaped.substring(0,position);
        String token=escaped.substring(position+2,position+6);
        escaped=escaped.substring(position+6);
        processed+=(char)Integer.parseInt(token,16);
        position=escaped.indexOf("\\u");
    }
    processed+=escaped;

    return processed;
}

How can I replace non-printable Unicode characters in Java?

I have redesigned the code for phone numbers +9 (987) 124124 Extract digits from a string in Java

 public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );
    int i=0;
    while ( i< buffer.length()  ) { //buffer.hasRemaining()
        char chr = buffer.get(i);
        if (chr=='u'){
            i=i+5;
            chr=buffer.get(i);
        }

        if ( chr > 39 && chr < 58 )
            result[cursor++] = chr;
        i=i+1;
    }

    return new String( result, 0, cursor );
}

JSON and escaping characters

This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.

So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader instance. Any time you are creating a Reader from an InputStream, you need to specify the character encoding, or java.nio.charset.Charset instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8). If you don't specify a Charset, Java will use your platform default encoding, which on Windows is usually CP-1252.

Python - 'ascii' codec can't decode byte

If you're using Python < 3, you'll need to tell the interpreter that your string literal is Unicode by prefixing it with a u:

Python 2.7.2 (default, Jan 14 2012, 23:14:09) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "??".encode("utf8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'

Further reading: Unicode HOWTO.

String length in bytes in JavaScript

This would work for BMP and SIP/SMP characters.

    String.prototype.lengthInUtf8 = function() {
        var asciiLength = this.match(/[\u0000-\u007f]/g) ? this.match(/[\u0000-\u007f]/g).length : 0;
        var multiByteLength = encodeURI(this.replace(/[\u0000-\u007f]/g)).match(/%/g) ? encodeURI(this.replace(/[\u0000-\u007f]/g, '')).match(/%/g).length : 0;
        return asciiLength + multiByteLength;
    }

    'test'.lengthInUtf8();
    // returns 4
    '\u{2f894}'.lengthInUtf8();
    // returns 4
    '???? ?????'.lengthInUtf8();
    // returns 19, each Arabic/Persian alphabet character takes 2 bytes. 
    '??,JavaScript ??'.lengthInUtf8();
    // returns 26, each Chinese character/punctuation takes 3 bytes. 

How to convert char* to wchar_t*?

You're returning the address of a local variable allocated on the stack. When your function returns, the storage for all local variables (such as wc) is deallocated and is subject to being immediately overwritten by something else.

To fix this, you can pass the size of the buffer to GetWC, but then you've got pretty much the same interface as mbstowcs itself. Or, you could allocate a new buffer inside GetWC and return a pointer to that, leaving it up to the caller to deallocate the buffer.

Unicode characters in URLs

For me this is the correct way, This just worked:

    $linker = rawurldecode("$link");
    <a href="<?php echo $link;?>"   target="_blank"><?php echo $linker ;?></a>

This worked, and now links are displayed properly:

http://newspaper.annahar.com/article/121638-????--????-???-??-??????-?????-????-??????-??????-????-??????-?????-????????

Link found on:

http://www.galeriejaninerubeiz.com/newsite/news

How to remove \xa0 from string in Python?

After trying several methods, to summarize it, this is how I did it. Following are two ways of avoiding/removing \xa0 characters from parsed HTML string.

Assume we have our raw html as following:

raw_html = '<p>Dear Parent, </p><p><span style="font-size: 1rem;">This is a test message, </span><span style="font-size: 1rem;">kindly ignore it. </span></p><p><span style="font-size: 1rem;">Thanks</span></p>'

So lets try to clean this HTML string:

from bs4 import BeautifulSoup
raw_html = '<p>Dear Parent, </p><p><span style="font-size: 1rem;">This is a test message, </span><span style="font-size: 1rem;">kindly ignore it. </span></p><p><span style="font-size: 1rem;">Thanks</span></p>'
text_string = BeautifulSoup(raw_html, "lxml").text
print text_string
#u'Dear Parent,\xa0This is a test message,\xa0kindly ignore it.\xa0Thanks'

The above code produces these characters \xa0 in the string. To remove them properly, we can use two ways.

Method # 1 (Recommended): The first one is BeautifulSoup's get_text method with strip argument as True So our code becomes:

clean_text = BeautifulSoup(raw_html, "lxml").get_text(strip=True)
print clean_text
# Dear Parent,This is a test message,kindly ignore it.Thanks

Method # 2: The other option is to use python's library unicodedata

import unicodedata
text_string = BeautifulSoup(raw_html, "lxml").text
clean_text = unicodedata.normalize("NFKD",text_string)
print clean_text
# u'Dear Parent,This is a test message,kindly ignore it.Thanks'

I have also detailed these methods on this blog which you may want to refer.

Storing and displaying unicode string (??????) using PHP and MySQL

Did you set proper charset in the HTML Head section?

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

or you can set content type in your php script using -

   header( 'Content-Type: text/html; charset=utf-8' ); 

There are already some discussions here on StackOverflow - please have a look

How to make MySQL handle UTF-8 properly setting utf8 with mysql through php

PHP/MySQL with encoding problems

So what i want to know is how can i directly store ???????? into my database and fetch it and display in my webpage using PHP.

I am not sure what you mean by "directly storing in the database" .. did you mean entering data using PhpMyAdmin or any other similar tool? If yes, I have tried using PhpMyAdmin to input unicode data, so it has worked fine for me - You could try inputting data using phpmyadmin and retrieve it using a php script to confirm. If you need to submit data via a Php script just set the NAMES and CHARACTER SET when you create mysql connection, before execute insert queries, and when you select data. Have a look at the above posts to find the syntax. Hope it helps.

** UPDATE ** Just fixed some typos etc

Easy way to convert a unicode list to a list containing python strings?

Just simply use this code

EmployeeList = eval(EmployeeList)
EmployeeList = [str(x) for x in EmployeeList]

How can I remove non-ASCII characters but leave periods and spaces using Python?

You may use the following code to remove non-English letters:

import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)

This will return

123456790 ABC#%? .()

How to convert a UTF-8 string into Unicode?

So the issue is that UTF-8 code unit values have been stored as a sequence of 16-bit code units in a C# string. You simply need to verify that each code unit is within the range of a byte, copy those values into bytes, and then convert the new UTF-8 byte sequence into UTF-16.

public static string DecodeFromUtf8(this string utf8String)
{
    // copy the string as UTF-8 bytes.
    byte[] utf8Bytes = new byte[utf8String.Length];
    for (int i=0;i<utf8String.Length;++i) {
        //Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
        utf8Bytes[i] = (byte)utf8String[i];
    }

    return Encoding.UTF8.GetString(utf8Bytes,0,utf8Bytes.Length);
}

DecodeFromUtf8("d\u00C3\u00A9j\u00C3\u00A0"); // déjà

This is easy, however it would be best to find the root cause; the location where someone is copying UTF-8 code units into 16 bit code units. The likely culprit is somebody converting bytes into a C# string using the wrong encoding. E.g. Encoding.Default.GetString(utf8Bytes, 0, utf8Bytes.Length).


Alternatively, if you're sure you know the incorrect encoding which was used to produce the string, and that incorrect encoding transformation was lossless (usually the case if the incorrect encoding is a single byte encoding), then you can simply do the inverse encoding step to get the original UTF-8 data, and then you can do the correct conversion from UTF-8 bytes:

public static string UndoEncodingMistake(string mangledString, Encoding mistake, Encoding correction)
{
    // the inverse of `mistake.GetString(originalBytes);`
    byte[] originalBytes = mistake.GetBytes(mangledString);
    return correction.GetString(originalBytes);
}

UndoEncodingMistake("d\u00C3\u00A9j\u00C3\u00A0", Encoding(1252), Encoding.UTF8);

What does the 'b' character do in front of a string literal?

Python 3.x makes a clear distinction between the types:

If you're familiar with:

  • Java or C#, think of str as String and bytes as byte[];
  • SQL, think of str as NVARCHAR and bytes as BINARY or BLOB;
  • Windows registry, think of str as REG_SZ and bytes as REG_BINARY.

If you're familiar with C(++), then forget everything you've learned about char and strings, because a character is not a byte. That idea is long obsolete.

You use str when you want to represent text.

print('???? ????')

You use bytes when you want to represent low-level binary data like structs.

NaN = struct.unpack('>d', b'\xff\xf8\x00\x00\x00\x00\x00\x00')[0]

You can encode a str to a bytes object.

>>> '\uFEFF'.encode('UTF-8')
b'\xef\xbb\xbf'

And you can decode a bytes into a str.

>>> b'\xE2\x82\xAC'.decode('UTF-8')
'€'

But you can't freely mix the two types.

>>> b'\xEF\xBB\xBF' + 'Text with a UTF-8 BOM'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str

The b'...' notation is somewhat confusing in that it allows the bytes 0x01-0x7F to be specified with ASCII characters instead of hex numbers.

>>> b'A' == b'\x41'
True

But I must emphasize, a character is not a byte.

>>> 'A' == b'A'
False

In Python 2.x

Pre-3.0 versions of Python lacked this kind of distinction between text and binary data. Instead, there was:

  • unicode = u'...' literals = sequence of Unicode characters = 3.x str
  • str = '...' literals = sequences of confounded bytes/characters
    • Usually text, encoded in some unspecified encoding.
    • But also used to represent binary data like struct.pack output.

In order to ease the 2.x-to-3.x transition, the b'...' literal syntax was backported to Python 2.6, in order to allow distinguishing binary strings (which should be bytes in 3.x) from text strings (which should be str in 3.x). The b prefix does nothing in 2.x, but tells the 2to3 script not to convert it to a Unicode string in 3.x.

So yes, b'...' literals in Python have the same purpose that they do in PHP.

Also, just out of curiosity, are there more symbols than the b and u that do other things?

The r prefix creates a raw string (e.g., r'\t' is a backslash + t instead of a tab), and triple quotes '''...''' or """...""" allow multi-line string literals.

What is the best way to remove accents (normalize) in a Python unicode string?

How about this:

import unicodedata
def strip_accents(s):
   return ''.join(c for c in unicodedata.normalize('NFD', s)
                  if unicodedata.category(c) != 'Mn')

This works on greek letters, too:

>>> strip_accents(u"A \u00c0 \u0394 \u038E")
u'A A \u0394 \u03a5'
>>> 

The character category "Mn" stands for Nonspacing_Mark, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit).

And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration".

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

What exactly do "u" and "r" string flags do, and what are raw string literals?

'raw string' means it is stored as it appears. For example, '\' is just a backslash instead of an escaping.

Read and Write CSV files including unicode with Python 2.7

I couldn't respond to Mark above, but I just made one modification which fixed the error which was caused if data in the cells was not unicode, i.e. float or int data. I replaced this line into the UnicodeWriter function: "self.writer.writerow([s.encode("utf-8") if type(s)==types.UnicodeType else s for s in row])" so that it became:

class UnicodeWriter:
    def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
       self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()
    def writerow(self, row):
        '''writerow(unicode) -> None
        This function takes a Unicode string and encodes it to the output.
        '''
        self.writer.writerow([s.encode("utf-8") if type(s)==types.UnicodeType else s for s in row])
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        data = self.encoder.encode(data)
        self.stream.write(data)
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

You will also need to "import types".

What's the difference between Unicode and UTF-8?

most editors support save as ‘Unicode’ encoding actually.

This is an unfortunate misnaming perpetrated by Windows.

Because Windows uses UTF-16LE encoding internally as the memory storage format for Unicode strings, it considers this to be the natural encoding of Unicode text. In the Windows world, there are ANSI strings (the system codepage on the current machine, subject to total unportability) and there are Unicode strings (stored internally as UTF-16LE).

This was all devised in the early days of Unicode, before we realised that UCS-2 wasn't enough, and before UTF-8 was invented. This is why Windows's support for UTF-8 is all-round poor.

This misguided naming scheme became part of the user interface. A text editor that uses Windows's encoding support to provide a range of encodings will automatically and inappropriately describe UTF-16LE as “Unicode”, and UTF-16BE, if provided, as “Unicode big-endian”.

(Other editors that do encodings themselves, like Notepad++, don't have this problem.)

If it makes you feel any better about it, ‘ANSI’ strings aren't based on any ANSI standard, either.

Removing u in list

arr = [str(r) for r in arr]

This basically converts all your elements in string. Hence removes the encoding. Hence the u which represents encoding gets removed Will do the work easily and efficiently

How to check if a string in Python is in ASCII?

def is_ascii(s):
    return all(ord(c) < 128 for c in s)

SSIS Convert Between Unicode and Non-Unicode Error

  1. First, add a data conversion block into your data flow diagram.

  2. Open the data conversion block and tick the column for which the error is showing. Below change its data type to unicode string(DT_WSTR) or whatever datatype is expected and save.

  3. Go to the destination block. Go to mapping in it and map the newly created element to its corresponding address and save.

  4. Right click your project in the solution explorer.select properties. Select configuration properties and select debugging in it. In this, set the Run64BitRunTime option to false (as excel does not handle the 64 bit application very well).

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Python Unicode Encode Error

Try adding the following line at the top of your python script.

# _*_ coding:utf-8 _*_

NameError: global name 'unicode' is not defined - in Python 3

One can replace unicode with u''.__class__ to handle the missing unicode class in Python 3. For both Python 2 and 3, you can use the construct

isinstance(unicode_or_str, u''.__class__)

or

type(unicode_or_str) == type(u'')

Depending on your further processing, consider the different outcome:

Python 3

>>> isinstance('text', u''.__class__)
True
>>> isinstance(u'text', u''.__class__)
True

Python 2

>>> isinstance(u'text', u''.__class__)
True
>>> isinstance('text', u''.__class__)
False

Decode UTF-8 with Javascript

This is a solution with extensive error reporting.

It would take an UTF-8 encoded byte array (where byte array is represented as array of numbers and each number is an integer between 0 and 255 inclusive) and will produce a JavaScript string of Unicode characters.

function getNextByte(value, startByteIndex, startBitsStr, 
                     additional, index) 
{
    if (index >= value.length) {
        var startByte = value[startByteIndex];
        throw new Error("Invalid UTF-8 sequence. Byte " + startByteIndex 
            + " with value " + startByte + " (" + String.fromCharCode(startByte) 
            + "; binary: " + toBinary(startByte)
            + ") starts with " + startBitsStr + " in binary and thus requires " 
            + additional + " bytes after it, but we only have " 
            + (value.length - startByteIndex) + ".");
    }
    var byteValue = value[index];
    checkNextByteFormat(value, startByteIndex, startBitsStr, additional, index);
    return byteValue;
}

function checkNextByteFormat(value, startByteIndex, startBitsStr, 
                             additional, index) 
{
    if ((value[index] & 0xC0) != 0x80) {
        var startByte = value[startByteIndex];
        var wrongByte = value[index];
        throw new Error("Invalid UTF-8 byte sequence. Byte " + startByteIndex 
             + " with value " + startByte + " (" +String.fromCharCode(startByte) 
             + "; binary: " + toBinary(startByte) + ") starts with " 
             + startBitsStr + " in binary and thus requires " + additional 
             + " additional bytes, each of which shouls start with 10 in binary."
             + " However byte " + (index - startByteIndex) 
             + " after it with value " + wrongByte + " (" 
             + String.fromCharCode(wrongByte) + "; binary: " + toBinary(wrongByte)
             +") does not start with 10 in binary.");
    }
}

function fromUtf8 (str) {
        var value = [];
        var destIndex = 0;
        for (var index = 0; index < str.length; index++) {
            var code = str.charCodeAt(index);
            if (code <= 0x7F) {
                value[destIndex++] = code;
            } else if (code <= 0x7FF) {
                value[destIndex++] = ((code >> 6 ) & 0x1F) | 0xC0;
                value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
            } else if (code <= 0xFFFF) {
                value[destIndex++] = ((code >> 12) & 0x0F) | 0xE0;
                value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
            } else if (code <= 0x1FFFFF) {
                value[destIndex++] = ((code >> 18) & 0x07) | 0xF0;
                value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
            } else if (code <= 0x03FFFFFF) {
                value[destIndex++] = ((code >> 24) & 0x03) | 0xF0;
                value[destIndex++] = ((code >> 18) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
            } else if (code <= 0x7FFFFFFF) {
                value[destIndex++] = ((code >> 30) & 0x01) | 0xFC;
                value[destIndex++] = ((code >> 24) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 18) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
            } else {
                throw new Error("Unsupported Unicode character \"" 
                    + str.charAt(index) + "\" with code " + code + " (binary: " 
                    + toBinary(code) + ") at index " + index
                    + ". Cannot represent it as UTF-8 byte sequence.");
            }
        }
        return value;
    }

How do I grep for all non-ASCII characters?

You can use the command:

grep --color='auto' -P -n "[\x80-\xFF]" file.xml

This will give you the line number, and will highlight non-ascii chars in red.

In some systems, depending on your settings, the above will not work, so you can grep by the inverse

grep --color='auto' -P -n "[^\x00-\x7F]" file.xml

Note also, that the important bit is the -P flag which equates to --perl-regexp: so it will interpret your pattern as a Perl regular expression. It also says that

this is highly experimental and grep -P may warn of unimplemented features.

(grep) Regex to match non-ASCII characters?

You can use this regex:

[^\w \xC0-\xFF]

Case ask, the options is Multiline.

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

ASCII isn't in it any more. Using UTF-8 encoding means that you aren't using ASCII encoding. What you should use the escaping mechanism for is what the RFC says:

All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F)

Unicode via CSS :before

At first link fontwaesome CSS file in your HTML file then create an after or before pseudo class like "font-family: "FontAwesome"; content: "\f101";" then save. I hope this work good.

std::wstring VS std::string

So, every reader here now should have a clear understanding about the facts, the situation. If not, then you must read paercebal's outstandingly comprehensive answer [btw: thanks!].

My pragmatical conclusion is shockingly simple: all that C++ (and STL) "character encoding" stuff is substantially broken and useless. Blame it on Microsoft or not, that will not help anyway.

My solution, after in-depth investigation, much frustration and the consequential experiences is the following:

  1. accept, that you have to be responsible on your own for the encoding and conversion stuff (and you will see that much of it is rather trivial)

  2. use std::string for any UTF-8 encoded strings (just a typedef std::string UTF8String)

  3. accept that such an UTF8String object is just a dumb, but cheap container. Do never ever access and/or manipulate characters in it directly (no search, replace, and so on). You could, but you really just really, really do not want to waste your time writing text manipulation algorithms for multi-byte strings! Even if other people already did such stupid things, don't do that! Let it be! (Well, there are scenarios where it makes sense... just use the ICU library for those).

  4. use std::wstring for UCS-2 encoded strings (typedef std::wstring UCS2String) - this is a compromise, and a concession to the mess that the WIN32 API introduced). UCS-2 is sufficient for most of us (more on that later...).

  5. use UCS2String instances whenever a character-by-character access is required (read, manipulate, and so on). Any character-based processing should be done in a NON-multibyte-representation. It is simple, fast, easy.

  6. add two utility functions to convert back & forth between UTF-8 and UCS-2:

    UCS2String ConvertToUCS2( const UTF8String &str );
    UTF8String ConvertToUTF8( const UCS2String &str );
    

The conversions are straightforward, google should help here ...

That's it. Use UTF8String wherever memory is precious and for all UTF-8 I/O. Use UCS2String wherever the string must be parsed and/or manipulated. You can convert between those two representations any time.

Alternatives & Improvements

  • conversions from & to single-byte character encodings (e.g. ISO-8859-1) can be realized with help of plain translation tables, e.g. const wchar_t tt_iso88951[256] = {0,1,2,...}; and appropriate code for conversion to & from UCS2.

  • if UCS-2 is not sufficient, than switch to UCS-4 (typedef std::basic_string<uint32_t> UCS2String)

ICU or other unicode libraries?

For advanced stuff.

How to get string objects instead of Unicode from JSON?

With Python 3.6, sometimes I still run into this problem. For example, when getting response from a REST API and loading the response text to JSON, I still get the unicode strings. Found a simple solution using json.dumps().

response_message = json.loads(json.dumps(response.text))
print(response_message)

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

Best way to reverse a string

"Best" can depend on many things, but here are few more short alternatives ordered from fast to slow:

string s = "z?a"l?g¨o?", pattern = @"(?s).(?<=(?:.(?=.*$(?<=((\P{M}\p{C}?\p{M}*)\1?))))*)";

string s1 = string.Concat(s.Reverse());                          // "???o¨g?l"a?z"  

string s2 = Microsoft.VisualBasic.Strings.StrReverse(s);         // "o?g¨l?a"?z"  

string s3 = string.Concat(StringInfo.ParseCombiningCharacters(s).Reverse()
    .Select(i => StringInfo.GetNextTextElement(s, i)));          // "o?g¨l?a"z?"  

string s4 = Regex.Replace(s, pattern, "$2").Remove(s.Length);    // "o?g¨l?a"z?"  

CSS: how to add white space before element's content?

/* Most Accurate Setting if you only want
   to do this with CSS Pseudo Element */
p:before { 
   content: "\00a0";
   padding-right: 5px; /* If you need more space b/w contents */
}

u'\ufeff' in Python string

The Unicode character U+FEFF is the byte order mark, or BOM, and is used to tell the difference between big- and little-endian UTF-16 encoding. If you decode the web page using the right codec, Python will remove it for you. Examples:

#!python2
#coding: utf8
u = u'ABC'
e8 = u.encode('utf-8')        # encode without BOM
e8s = u.encode('utf-8-sig')   # encode with BOM
e16 = u.encode('utf-16')      # encode with BOM
e16le = u.encode('utf-16le')  # encode without BOM
e16be = u.encode('utf-16be')  # encode without BOM
print 'utf-8     %r' % e8
print 'utf-8-sig %r' % e8s
print 'utf-16    %r' % e16
print 'utf-16le  %r' % e16le
print 'utf-16be  %r' % e16be
print
print 'utf-8  w/ BOM decoded with utf-8     %r' % e8s.decode('utf-8')
print 'utf-8  w/ BOM decoded with utf-8-sig %r' % e8s.decode('utf-8-sig')
print 'utf-16 w/ BOM decoded with utf-16    %r' % e16.decode('utf-16')
print 'utf-16 w/ BOM decoded with utf-16le  %r' % e16.decode('utf-16le')

Note that EF BB BF is a UTF-8-encoded BOM. It is not required for UTF-8, but serves only as a signature (usually on Windows).

Output:

utf-8     'ABC'
utf-8-sig '\xef\xbb\xbfABC'
utf-16    '\xff\xfeA\x00B\x00C\x00'    # Adds BOM and encodes using native processor endian-ness.
utf-16le  'A\x00B\x00C\x00'
utf-16be  '\x00A\x00B\x00C'

utf-8  w/ BOM decoded with utf-8     u'\ufeffABC'    # doesn't remove BOM if present.
utf-8  w/ BOM decoded with utf-8-sig u'ABC'          # removes BOM if present.
utf-16 w/ BOM decoded with utf-16    u'ABC'          # *requires* BOM to be present.
utf-16 w/ BOM decoded with utf-16le  u'\ufeffABC'    # doesn't remove BOM if present.

Note that the utf-16 codec requires BOM to be present, or Python won't know if the data is big- or little-endian.

UTF-8, UTF-16, and UTF-32

Depending on your development environment you may not even have the choice what encoding your string data type will use internally.

But for storing and exchanging data I would always use UTF-8, if you have the choice. If you have mostly ASCII data this will give you the smallest amount of data to transfer, while still being able to encode everything. Optimizing for the least I/O is the way to go on modern machines.

Writing Unicode text to a text file?

The file opened by codecs.open is a file that takes unicode data, encodes it in iso-8859-1 and writes it to the file. However, what you try to write isn't unicode; you take unicode and encode it in iso-8859-1 yourself. That's what the unicode.encode method does, and the result of encoding a unicode string is a bytestring (a str type.)

You should either use normal open() and encode the unicode yourself, or (usually a better idea) use codecs.open() and not encode the data yourself.

What's the difference between ASCII and Unicode?

ASCII defines 128 characters, as Unicode contains a repertoire of more than 120,000 characters.

What's the difference between UTF-8 and UTF-8 without BOM?

When you want to display information encoded in UTF-8 you may not face problems. Declare for example an HTML document as UTF-8 and you will have everything displayed in your browser that is contained in the body of the document.

But this is not the case when we have text, CSV and XML files, either on Windows or Linux.

For example, a text file in Windows or Linux, one of the easiest things imaginable, it is not (usually) UTF-8.

Save it as XML and declare it as UTF-8:

<?xml version="1.0" encoding="UTF-8"?>

It will not display (it will not be be read) correctly, even if it's declared as UTF-8.

I had a string of data containing French letters, that needed to be saved as XML for syndication. Without creating a UTF-8 file from the very beginning (changing options in IDE and "Create New File") or adding the BOM at the beginning of the file

$file="\xEF\xBB\xBF".$string;

I was not able to save the French letters in an XML file.

Unicode, UTF, ASCII, ANSI format differences

Going down your list:

  • "Unicode" isn't an encoding, although unfortunately, a lot of documentation imprecisely uses it to refer to whichever Unicode encoding that particular system uses by default. On Windows and Java, this often means UTF-16; in many other places, it means UTF-8. Properly, Unicode refers to the abstract character set itself, not to any particular encoding.
  • UTF-16: 2 bytes per "code unit". This is the native format of strings in .NET, and generally in Windows and Java. Values outside the Basic Multilingual Plane (BMP) are encoded as surrogate pairs. These used to be relatively rarely used, but now many consumer applications will need to be aware of non-BMP characters in order to support emojis.
  • UTF-8: Variable length encoding, 1-4 bytes per code point. ASCII values are encoded as ASCII using 1 byte.
  • UTF-7: Usually used for mail encoding. Chances are if you think you need it and you're not doing mail, you're wrong. (That's just my experience of people posting in newsgroups etc - outside mail, it's really not widely used at all.)
  • UTF-32: Fixed width encoding using 4 bytes per code point. This isn't very efficient, but makes life easier outside the BMP. I have a .NET Utf32String class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)
  • ASCII: Single byte encoding only using the bottom 7 bits. (Unicode code points 0-127.) No accents etc.
  • ANSI: There's no one fixed ANSI encoding - there are lots of them. Usually when people say "ANSI" they mean "the default locale/codepage for my system" which is obtained via Encoding.Default, and is often Windows-1252 but can be other locales.

There's more on my Unicode page and tips for debugging Unicode problems.

The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.

Insert Unicode character into JavaScript

One option is to put the character literally in your script, e.g.:

const omega = 'O';

This requires that you let the browser know the correct source encoding, see Unicode in JavaScript

However, if you can't or don't want to do this (e.g. because the character is too exotic and can't be expected to be available in the code editor font), the safest option may be to use new-style string escape or String.fromCodePoint:

const omega = '\u{3a9}';

// or:

const omega = String.fromCodePoint(0x3a9);

This is not restricted to UTF-16 but works for all unicode code points. In comparison, the other approaches mentioned here have the following downsides:

  • HTML escapes (const omega = '&#937';): only work when rendered unescaped in an HTML element
  • old style string escapes (const omega = '\u03A9';): restricted to UTF-16
  • String.fromCharCode: restricted to UTF-16

What's the difference between utf8_general_ci and utf8_unicode_ci?

Some details (PL)

As we can read here (Peter Gulutzan) there is difference on sorting/comparing polish letter "L" (L with stroke - html esc: &#321;) (lower case: "l" - html esc: &#322;) - we have following assumption:

utf8_polish_ci      L greater than L and less than M
utf8_unicode_ci     L greater than L and less than M
utf8_unicode_520_ci L equal to L
utf8_general_ci     L greater than Z

In polish language letter L is after letter L and before M. No one of this coding is better or worse - it depends of your needs.

Unicode (UTF-8) reading and writing to files in Python

The \x.. sequence is something that's specific to Python. It's not a universal byte escape sequence.

How you actually enter in UTF-8-encoded non-ASCII depends on your OS and/or your editor. Here's how you do it in Windows. For OS X to enter a with an acute accent you can just hit option + E, then A, and almost all text editors in OS X support UTF-8.

How to print Unicode character in C++?

If you use Windows (note, we are using printf(), not cout):

//Save As UTF8 without signature
#include <stdio.h>
#include<windows.h>
int main (){
    SetConsoleOutputCP(65001); 
    printf("?\n");
}

Not Unicode but working - 1251 instead of UTF8:

//Save As Windows 1251
#include <iostream>
#include<windows.h>
using namespace std;
int main (){
    SetConsoleOutputCP(1251); 
    cout << "?" << endl;
}

How to correct TypeError: Unicode-objects must be encoded before hashing?

encoding this line fixed it for me.

m.update(line.encode('utf-8'))

Replace non-ASCII characters with a single space

As a native and efficient approach, you don't need to use ord or any loop over the characters. Just encode with ascii and ignore the errors.

The following will just remove the non-ascii characters:

new_string = old_string.encode('ascii',errors='ignore')

Now if you want to replace the deleted characters just do the following:

final_string = new_string + b' ' * (len(old_string) - len(new_string))

Convert Unicode to ASCII without errors in Python

I think the answer is there but only in bits and pieces, which makes it difficult to quickly fix the problem such as

UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 2818: ordinal not in range(128)

Let's take an example, Suppose I have file which has some data in the following form ( containing ascii and non-ascii chars )

1/10/17, 21:36 - Land : Welcome ��

and we want to ignore and preserve only ascii characters.

This code will do:

import unicodedata
fp  = open(<FILENAME>)
for line in fp:
    rline = line.strip()
    rline = unicode(rline, "utf-8")
    rline = unicodedata.normalize('NFKD', rline).encode('ascii','ignore')
    if len(rline) != 0:
        print rline

and type(rline) will give you

>type(rline) 
<type 'str'>

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Best way to convert text files between character sets?

PHP iconv()

iconv("UTF-8", "ISO-8859-15", $input);

How do you change the character encoding of a postgres database?

Dumping a database with a specific encoding and try to restore it on another database with a different encoding could result in data corruption. Data encoding must be set BEFORE any data is inserted into the database.

Check this : When copying any other database, the encoding and locale settings cannot be changed from those of the source database, because that might result in corrupt data.

And this : Some locale categories must have their values fixed when the database is created. You can use different settings for different databases, but once a database is created, you cannot change them for that database anymore. LC_COLLATE and LC_CTYPE are these categories. They affect the sort order of indexes, so they must be kept fixed, or indexes on text columns would become corrupt. (But you can alleviate this restriction using collations, as discussed in Section 22.2.) The default values for these categories are determined when initdb is run, and those values are used when new databases are created, unless specified otherwise in the CREATE DATABASE command.


I would rather rebuild everything from the begining properly with a correct local encoding on your debian OS as explained here :

su root

Reconfigure your local settings :

dpkg-reconfigure locales

Choose your locale (like for instance for french in Switzerland : fr_CH.UTF8)

Uninstall and clean properly postgresql :

apt-get --purge remove postgresql\*
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres

Re-install postgresql :

aptitude install postgresql-9.1 postgresql-contrib-9.1 postgresql-doc-9.1

Now any new database will be automatically be created with correct encoding, LC_TYPE (character classification), and LC_COLLATE (string sort order).

FPDF utf-8 encoding (HOW-TO)

None of the above solutions are going to work.

Try this:

function filter_html($value){
    $value = mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8');
    return $value;
}

Character reading from file in Python

This is Pythons way do show you unicode encoded strings. But i think you should be able to print the string on the screen or write it into a new file without any problems.

>>> test = u"I don\u2018t like this"
>>> test
u'I don\u2018t like this'
>>> print test
I don‘t like this

Python str vs unicode types

When you define a as unicode, the chars a and á are equal. Otherwise á counts as two chars. Try len(a) and len(au). In addition to that, you may need to have the encoding when you work with other environments. For example if you use md5, you get different values for a and ua

How do you echo a 4-digit Unicode character in Bash?

Here's a fully internal Bash implementation, no forking, unlimited size of Unicode characters.

fast_chr() {
    local __octal
    local __char
    printf -v __octal '%03o' $1
    printf -v __char \\$__octal
    REPLY=$__char
}

function unichr {
    local c=$1    # Ordinal of char
    local l=0    # Byte ctr
    local o=63    # Ceiling
    local p=128    # Accum. bits
    local s=''    # Output string

    (( c < 0x80 )) && { fast_chr "$c"; echo -n "$REPLY"; return; }

    while (( c > o )); do
        fast_chr $(( t = 0x80 | c & 0x3f ))
        s="$REPLY$s"
        (( c >>= 6, l++, p += o+1, o>>=1 ))
    done

    fast_chr $(( t = p | c ))
    echo -n "$REPLY$s"
}

## test harness
for (( i=0x2500; i<0x2600; i++ )); do
    unichr $i
done

Output was:

-?¦?????????+???
+???+???+???+???
????¦???????-???
????-???????+???
????????????????
-¦++++++++++++¦¦
¦¦¦¦------+++???
????????????????
¯???_???¦???¦???
¦¦¦¦????????????
¦???????????????
????????????????
????????????????
????????????????
????????????????
????????????????

How do I turn off Unicode in a VC++ project?

you can go to project properties --> configuration properties --> General -->Project default and there change the "Character set" from "Unicode" to "Not set".

Representing Directory & File Structure in Markdown Syntax

If you wish to generate it dynamically I recommend using Frontend-md. It is simple to use.

Python os.path.join on Windows

answering to your comment : "the others '//' 'c:', 'c:\\' did not work (C:\\ created two backslashes, C:\ didn't work at all)"

On windows using os.path.join('c:', 'sourcedir') will automatically add two backslashes \\ in front of sourcedir.

To resolve the path, as python works on windows also with forward slashes -> '/', simply add .replace('\\','/') with os.path.join as below:-

os.path.join('c:\\', 'sourcedir').replace('\\','/')

e.g: os.path.join('c:\\', 'temp').replace('\\','/')

output : 'C:/temp'

Reusing output from last command in Bash

Yeah, why type extra lines each time; agreed. You can redirect the returned from a command to input by pipeline, but redirecting printed output to input (1>&0) is nope, at least not for multiple line outputs. Also you won't want to write a function again and again in each file for the same. So let's try something else.

A simple workaround would be to use printf function to store values in a variable.

printf -v myoutput "`cmd`"

such as

printf -v var "`echo ok;
  echo fine;
  echo thankyou`"
echo "$var" # don't forget the backquotes and quotes in either command.

Another customizable general solution (I myself use) for running the desired command only once and getting multi-line printed output of the command in an array variable line-by-line.

If you are not exporting the files anywhere and intend to use it locally only, you can have Terminal set-up the function declaration. You have to add the function in ~/.bashrc file or in ~/.profile file. In second case, you need to enable Run command as login shell from Edit>Preferences>yourProfile>Command.

Make a simple function, say:

get_prev() # preferably pass the commands in quotes. Single commands might still work without.
{
    # option 1: create an executable with the command(s) and run it
    #echo $* > /tmp/exe
    #bash /tmp/exe > /tmp/out
    
    # option 2: if your command is single command (no-pipe, no semi-colons), still it may not run correct in some exceptions.
    #echo `"$*"` > /tmp/out
    
    # option 3: (I actually used below)
    eval "$*" > /tmp/out # or simply "$*" > /tmp/out
    
    # return the command(s) outputs line by line
    IFS=$(echo -en "\n\b")
    arr=()
    exec 3</tmp/out
    while read -u 3 -r line
    do
        arr+=($line)
        echo $line
    done
    exec 3<&-
}

So what we did in option 1 was print the whole command to a temporary file /tmp/exe and run it and save the output to another file /tmp/out and then read the contents of the /tmp/out file line-by-line to an array. Similar in options 2 and 3, except that the commands were exectuted as such, without writing to an executable to be run.

In main script:

#run your command:

cmd="echo hey ya; echo hey hi; printf `expr 10 + 10`'\n' ; printf $((10 + 20))'\n'"
get_prev $cmd

#or simply
get_prev "echo hey ya; echo hey hi; printf `expr 10 + 10`'\n' ; printf $((10 + 20))'\n'"

Now, bash saves the variable even outside previous scope, so the arr variable created in get_prev function is accessible even outside the function in the main script:

#get previous command outputs in arr
for((i=0; i<${#arr[@]}; i++))
do
    echo ${arr[i]}
done
#if you're sure that your output won't have escape sequences you bother about, you may simply print the array
printf "${arr[*]}\n"

Edit:

I use the following code in my implementation:
get_prev()
{
    usage()
    {
        echo "Usage: alphabet [ -h | --help ]
        [ -s | --sep SEP ]
        [ -v | --var VAR ] \"command\""
    }
    
    ARGS=$(getopt -a -n alphabet -o hs:v: --long help,sep:,var: -- "$@")
    if [ $? -ne 0 ]; then usage; return 2; fi
    eval set -- $ARGS
    
    local var="arr"
    IFS=$(echo -en '\n\b')
    for arg in $*
    do
        case $arg in
            -h|--help)
                usage
                echo " -h, --help : opens this help"
                echo " -s, --sep  : specify the separator, newline by default"
                echo " -v, --var  : variable name to put result into, arr by default"
                echo "  command   : command to execute. Enclose in quotes if multiple lines or pipelines are used."
                shift
                return 0
                ;;
            -s|--sep)
                shift
                IFS=$(echo -en $1)
                shift
                ;;
            -v|--var)
                shift
                var=$1
                shift
                ;;
            -|--)
                shift
                ;;
            *)
                cmd=$option
                ;;
        esac
    done
    if [ ${#} -eq 0 ]; then usage; return 1; fi
    
    ERROR=$( { eval "$*" > /tmp/out; } 2>&1 )
    if [ $ERROR ]; then echo $ERROR; return 1; fi
    
    local a=()
    exec 3</tmp/out
    while read -u 3 -r line
    do
        a+=($line)
    done
    exec 3<&-
    
    eval $var=\(\${a[@]}\)
    print_arr $var # comment this to suppress output
}

print()
{
    eval echo \${$1[@]}
}

print_arr()
{
    eval printf "%s\\\n" "\${$1[@]}"
}

Ive been using this to print space-separated outputs of multiple/pipelined/both commands as line separated:

get_prev -s " " -v myarr "cmd1 | cmd2; cmd3 | cmd4"

For example:

get_prev -s ' ' -v myarr whereis python # or "whereis python"
# can also be achieved (in this case) by
whereis python | tr ' ' '\n'

Now tr command is useful at other places as well, such as

echo $PATH | tr ':' '\n'

But for multiple/piped commands... you know now. :)

-Himanshu

How do you convert a C++ string to an int?

I have used something like the following in C++ code before:

#include <sstream>
int main()
{
    char* str = "1234";
    std::stringstream s_str( str );
    int i;
    s_str >> i;
}

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

There is a new library called ipyvolume that may do what you want, the documentation shows live demos. The current version doesn't do meshes and lines, but master from the git repo does (as will version 0.4). (Disclaimer: I'm the author)

Add target="_blank" in CSS

There are a few ways CSS can 'target' navigation. This will style internal and external links using attribute styling, which could help signal visitors to what your links will do.

a[href="#"] { color: forestgreen; font-weight: normal; }
a[href="http"] { color: dodgerblue; font-weight: normal; }  

You can also target the traditional inline HTML 'target=_blank'.

a[target=_blank] { font-weight: bold; } 

Also :target selector to style navigation block and element targets.

nav { display: none; }
nav:target { display: block; }  

CSS :target pseudo-class selector is supported - caniuse, w3schools, MDN.

a[href="http"] { target: new; target-name: new; target-new: tab; }

CSS/CSS3 'target-new' property etc, not supported by any major browsers, 2017 August, though it is part of the W3 spec since 2004 February.

W3Schools 'modal' construction, uses ':target' pseudo-class that could contain WP navigation. You can also add HTML rel="noreferrer and noopener beside target="_blank" to improve 'new tab' performance. CSS will not open links in tabs for now, but this page explains how to do that with jQuery (compatibility may depend for WP coders). MDN has a good review at Using the :target pseudo-class in selectors

How to force Chrome's script debugger to reload javascript?

While you are developing your script, try disabling the Chrome cache.

When you reload the page, the JavaScript should now get refreshed.


Chrome circa 2011

Open settings Disable the cache


Chrome circa 2018

Open settings Disable the cache

You can also access it on the network tab:

Network tab

Aren't promises just callbacks?

Promises overview:

In JS we can wrap asynchronous operations (e.g database calls, AJAX calls) in promises. Usually we want to run some additional logic on the retrieved data. JS promises have handler functions which process the result of the asynchronous operations. The handler functions can even have other asynchronous operations within them which could rely on the value of the previous asynchronous operations.

A promise always has of the 3 following states:

  1. pending: starting state of every promise, neither fulfilled nor rejected.
  2. fulfilled: The operation completed successfully.
  3. rejected: The operation failed.

A pending promise can be resolved/fullfilled or rejected with a value. Then the following handler methods which take callbacks as arguments are called:

  1. Promise.prototype.then() : When the promise is resolved the callback argument of this function will be called.
  2. Promise.prototype.catch() : When the promise is rejected the callback argument of this function will be called.

Although the above methods skill get callback arguments they are far superior than using only callbacks here is an example that will clarify a lot:

Example

_x000D_
_x000D_
function createProm(resolveVal, rejectVal) {_x000D_
    return new Promise((resolve, reject) => {_x000D_
        setTimeout(() => {_x000D_
            if (Math.random() > 0.5) {_x000D_
                console.log("Resolved");_x000D_
                resolve(resolveVal);_x000D_
            } else {_x000D_
                console.log("Rejected");_x000D_
                reject(rejectVal);_x000D_
            }_x000D_
        }, 1000);_x000D_
    });_x000D_
}_x000D_
_x000D_
createProm(1, 2)_x000D_
    .then((resVal) => {_x000D_
        console.log(resVal);_x000D_
        return resVal + 1;_x000D_
    })_x000D_
    .then((resVal) => {_x000D_
        console.log(resVal);_x000D_
        return resVal + 2;_x000D_
    })_x000D_
    .catch((rejectVal) => {_x000D_
        console.log(rejectVal);_x000D_
        return rejectVal + 1;_x000D_
    })_x000D_
    .then((resVal) => {_x000D_
        console.log(resVal);_x000D_
    })_x000D_
    .finally(() => {_x000D_
        console.log("Promise done");_x000D_
    });
_x000D_
_x000D_
_x000D_

  • The createProm function creates a promises which is resolved or rejected based on a random Nr after 1 second
  • If the promise is resolved the first then method is called and the resolved value is passed in as an argument of the callback
  • If the promise is rejected the first catch method is called and the rejected value is passed in as an argument
  • The catch and then methods return promises that's why we can chain them. They wrap any returned value in Promise.resolve and any thrown value (using the throw keyword) in Promise.reject. So any value returned is transformed into a promise and on this promise we can again call a handler function.
  • Promise chains give us more fine tuned control and better overview than nested callbacks. For example the catch method handles all the errors which have occurred before the catch handler.

How to get the data-id attribute?

For those looking to dynamically remove and re-enable the tooltip, you can use the dispose and enable methods. See https://getbootstrap.com/docs/4.0/components/tooltips/#tooltipdispose

increase legend font size ggplot2

You can use theme_get() to display the possible options for theme. You can control the legend font size using:

+ theme(legend.text=element_text(size=X))

replacing X with the desired size.

How to search multiple columns in MySQL?

Here is a query which you can use to search for anything in from your database as a search result ,

SELECT * FROM tbl_customer 
    WHERE CustomerName LIKE '%".$search."%'
    OR Address LIKE '%".$search."%' 
    OR City LIKE '%".$search."%' 
    OR PostalCode LIKE '%".$search."%' 
    OR Country LIKE '%".$search."%'

Using this code will help you search in for multiple columns easily

Determine function name from within that function (without using traceback)

I keep this handy utility nearby:

import inspect
myself = lambda: inspect.stack()[1][3]

Usage:

myself()

Is it ok to use `any?` to check if an array is not empty?

Avoid any? for large arrays.

  • any? is O(n)
  • empty? is O(1)

any? does not check the length but actually scans the whole array for truthy elements.

static VALUE
rb_ary_any_p(VALUE ary)
{
  long i, len = RARRAY_LEN(ary);
  const VALUE *ptr = RARRAY_CONST_PTR(ary);

  if (!len) return Qfalse;
  if (!rb_block_given_p()) {
    for (i = 0; i < len; ++i) if (RTEST(ptr[i])) return Qtrue;
  }
  else {
    for (i = 0; i < RARRAY_LEN(ary); ++i) {
        if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue;
    }
  }
  return Qfalse;
}

empty? on the other hand checks the length of the array only.

static VALUE
rb_ary_empty_p(VALUE ary)
{
  if (RARRAY_LEN(ary) == 0)
    return Qtrue;
  return Qfalse;
}

The difference is relevant if you have "sparse" arrays that start with lots of nil values, like for example an array that was just created.

Java: convert List<String> to a String

Not out of the box, but many libraries have similar:

Commons Lang:

org.apache.commons.lang.StringUtils.join(list, conjunction);

Spring:

org.springframework.util.StringUtils.collectionToDelimitedString(list, conjunction);

Why does my Spring Boot App always shutdown immediately after starting?

In my case I fixed this issue like below:-

  1. First I removed (apache) C:\Users\myuserId\.m2\repository\org\apache

  2. I added below dependencies in my pom.xml file

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
  3. I have changed the default socket by adding below lines in resource file ..\yourprojectfolder\src\main\resourcesand\application.properties(I manually created this file)

     server.port=8099
     [email protected]@
    

    for that I have added below block in my pom.xml under <build> section.

      <build>
      .
      .
     <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
       .
       .    
      </build>
    

My final pom.xml file look like

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bhaiti</groupId>
    <artifactId>spring-boot-rest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-rest</name>
    <description>Welcome project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>       

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>

    </build>


</project>

How to get all files under a specific directory in MATLAB?

I don't know a single-function method for this, but you can use genpath to recurse a list of subdirectories only. This list is returned as a semicolon-delimited string of directories, so you'll have to separate it using strread, i.e.

dirlist = strread(genpath('/path/of/directory'),'%s','delimiter',';')

If you don't want to include the given directory, remove the first entry of dirlist, i.e. dirlist(1)=[]; since it is always the first entry.

Then get the list of files in each directory with a looped dir.

filenamelist=[];
for d=1:length(dirlist)
    % keep only filenames
    filelist=dir(dirlist{d});
    filelist={filelist.name};

    % remove '.' and '..' entries
    filelist([strmatch('.',filelist,'exact');strmatch('..',filelist,'exact'))=[];
    % or to ignore all hidden files, use filelist(strmatch('.',filelist))=[];

    % prepend directory name to each filename entry, separated by filesep*
    for f=1:length(filelist)
        filelist{f}=[dirlist{d} filesep filelist{f}];
    end

    filenamelist=[filenamelist filelist];
end

filesep returns the directory separator for the platform on which MATLAB is running.

This gives you a list of filenames with full paths in the cell array filenamelist. Not the neatest solution, I know.

How to import a SQL Server .bak file into MySQL?

The method I used included part of Richard Harrison's method:

So, install SQL Server 2008 Express edition,

This requires the download of the Web Platform Installer "wpilauncher_n.exe" Once you have this installed click on the database selection ( you are also required to download Frameworks and Runtimes)

After instalation go to the windows command prompt and:

use sqlcmd -S \SQLExpress (whilst logged in as administrator)

then issue the following command.

restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak'; GO This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file.

RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak' WITH MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf'; GO

I fired up Web Platform Installer and from the what's new tab I installed SQL Server Management Studio and browsed the db to make sure the data was there...

At that point i tried the tool included with MSSQL "SQL Import and Export Wizard" but the result of the csv dump only included the column names...

So instead I just exported results of queries like "select * from users" from the SQL Server Management Studio

Bash or KornShell (ksh)?

I don't have experience with ksh, but I have used both bash and zsh. I prefer zsh over bash because of its support for very powerful file globbing, variable expansion modifiers, and faster tab completion.

Here's a quick intro: http://friedcpu.wordpress.com/2007/07/24/zsh-the-last-shell-youll-ever-need/

TypeError : Unhashable type

... and so you should do something like this:

set(tuple ((a,b) for a in range(3)) for b in range(3))

... and if needed convert back to list

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

Removing "bullets" from unordered list <ul>

In my case

li {
  list-style-type : none;
}

It doesn't show the bullet but leaved some space for the bullet.

I use

li {
  list-style-type : '';
}

It works perfectly.

Updating user data - ASP.NET Identity

If you leave any of the fields for ApplicationUser OR IdentityUser null the update will come back as successful but wont save the data in the database.

Example solution:

ApplicationUser model = UserManager.FindById(User.Identity.GetUserId())

Add the newly updated fields:

model.Email = AppUserViewModel.Email;
model.FName = AppUserViewModel.FName;
model.LName = AppUserViewModel.LName;
model.DOB = AppUserViewModel.DOB;
model.Gender = AppUserViewModel.Gender;

Call UpdateAsync

IdentityResult result = await UserManager.UpdateAsync(model);

I have tested this and it works.

Ruby/Rails: converting a Date to a UNIX timestamp

I get the following when I try it:

>> Date.today.to_time.to_i
=> 1259244000
>> Time.now.to_i
=> 1259275709

The difference between these two numbers is due to the fact that Date does not store the hours, minutes or seconds of the current time. Converting a Date to a Time will result in that day, midnight.

Use SELECT inside an UPDATE query

I wrote about some of the limitations of correlated subqueries in Access/JET SQL a while back, and noted the syntax for joining multiple tables for SQL UPDATEs. Based on that info and some quick testing, I don't believe there's any way to do what you want with Access/JET in a single SQL UPDATE statement. If you could, the statement would read something like this:

UPDATE FUNCTIONS A
INNER JOIN (
  SELECT AA.Func_ID, Min(BB.Tax_Code) AS MinOfTax_Code
  FROM TAX BB, FUNCTIONS AA
  WHERE AA.Func_Pure<=BB.Tax_ToPrice AND AA.Func_Year= BB.Tax_Year
  GROUP BY AA.Func_ID
) B 
ON B.Func_ID = A.Func_ID
SET A.Func_TaxRef = B.MinOfTax_Code

Alternatively, Access/JET will sometimes let you get away with saving a subquery as a separate query and then joining it in the UPDATE statement in a more traditional way. So, for instance, if we saved the SELECT subquery above as a separate query named FUNCTIONS_TAX, then the UPDATE statement would be:

UPDATE FUNCTIONS
INNER JOIN FUNCTIONS_TAX
ON FUNCTIONS.Func_ID = FUNCTIONS_TAX.Func_ID
SET FUNCTIONS.Func_TaxRef = FUNCTIONS_TAX.MinOfTax_Code

However, this still doesn't work.

I believe the only way you will make this work is to move the selection and aggregation of the minimum Tax_Code value out-of-band. You could do this with a VBA function, or more easily using the Access DLookup function. Save the GROUP BY subquery above to a separate query named FUNCTIONS_TAX and rewrite the UPDATE statement as:

UPDATE FUNCTIONS
SET Func_TaxRef = DLookup(
  "MinOfTax_Code", 
  "FUNCTIONS_TAX", 
  "Func_ID = '" & Func_ID & "'"
)

Note that the DLookup function prevents this query from being used outside of Access, for instance via JET OLEDB. Also, the performance of this approach can be pretty terrible depending on how many rows you're targeting, as the subquery is being executed for each FUNCTIONS row (because, of course, it is no longer correlated, which is the whole point in order for it to work).

Good luck!

How does HTTP file upload work?

Let's take a look at what happens when you select a file and submit your form (I've truncated the headers for brevity):

POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
... other headers ...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L

------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="MAX_FILE_SIZE"

100000
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object

... contents of file goes here ...
------WebKitFormBoundaryePkpFF7tjBAqx29L--

NOTE: each boundary string must be prefixed with an extra --, just like in the end of the last boundary string. The example above already includes this, but it can be easy to miss. See comment by @Andreas below.

Instead of URL encoding the form parameters, the form parameters (including the file data) are sent as sections in a multipart document in the body of the request.

In the example above, you can see the input MAX_FILE_SIZE with the value set in the form, as well as a section containing the file data. The file name is part of the Content-Disposition header.

The full details are here.

json_decode to array

This will also change it into an array:

<?php
    print_r((array) json_decode($object));
?>

Replace a value in a data frame based on a conditional (`if`) statement

Easier to convert nm to characters and then make the change:

junk$nm <- as.character(junk$nm)
junk$nm[junk$nm == "B"] <- "b"

EDIT: And if indeed you need to maintain nm as factors, add this in the end:

junk$nm <- as.factor(junk$nm)

MySQL's now() +1 day

You can use:

NOW() + INTERVAL 1 DAY

If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW:

CURDATE() + INTERVAL 1 DAY

Make columns of equal width in <table>

Use following property same as table and its fully dynamic:

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed; /* optional, for equal spacing */_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid pink;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz klxjgkldjklg </li>_x000D_
  <li>baz</li>_x000D_
  <li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

May be its solve your issue.

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Using pure Eloquent, implement it like so. This code returns all logged in users whose accounts are active. $users = \App\User::where('status', 'active')->where('logged_in', true)->get();

HTML form with multiple "actions"

this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!

_x000D_
_x000D_
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
_x000D_
_x000D_

How to determine day of week by passing specific date?

You can use below method to get Day of the Week by passing a specific date,

Here for the set method of Calendar class, Tricky part is the index for the month parameter will starts from 0.

public static String getDay(int day, int month, int year) {

        Calendar cal = Calendar.getInstance();

        if(month==1){
            cal.set(year,0,day);
        }else{
            cal.set(year,month-1,day);
        }

        int dow = cal.get(Calendar.DAY_OF_WEEK);

        switch (dow) {
        case 1:
            return "SUNDAY";
        case 2:
            return "MONDAY";
        case 3:
            return "TUESDAY";
        case 4:
            return "WEDNESDAY";
        case 5:
            return "THURSDAY";
        case 6:
            return "FRIDAY";
        case 7:
            return "SATURDAY";
        default:
            System.out.println("GO To Hell....");
        }

        return null;
    }

Download file and automatically save it to folder

My program does exactly what you are after, no prompts or anything, please see the following code.

This code will create all of the necessary directories if they don't already exist:

Directory.CreateDirectory(C:\dir\dira\dirb);  // This code will create all of these directories  

This code will download the given file to the given directory (after it has been created by the previous snippet:

private void install()
    {
        WebClient webClient = new WebClient();                                                          // Creates a webclient
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);                   // Uses the Event Handler to check whether the download is complete
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);  // Uses the Event Handler to check for progress made
        webClient.DownloadFileAsync(new Uri("http://www.com/newfile.zip"), @"C\newfile.zip");           // Defines the URL and destination directory for the downloaded file
    }

So using these two pieces of code you can create all of the directories and then tell the downloader (that doesn't prompt you to download the file to that location.

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

Setup:

My OS windows 8 64bit
Eclipse version Standard/SDK Kepler Service Release 2
My JDK is jdk-8u5-windows-i586
My JRE is jre-8u5-windows-i586

This how I overcome my error.

At the very first my Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") also didn't work. Then I login to this website and downloaded the UCanAccess 2.0.8 zip (as Mr.Gord Thompson said) file and unzip it.

Then you will also able to find these *.jar files in that unzip folder:

ucanaccess-2.0.8.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.0.4.jar

Then what I did was I copied all these 5 files and paste them in these 2 locations:

C:\Program Files (x86)\eclipse\lib
C:\Program Files (x86)\eclipse\lib\ext

(I did that funny thing becoz I was unable to import these libraries to my project)

Then I reopen the eclipse with my project.then I see all that *.jar files in my project's JRE System Library folder.

Finally my code works.

public static void main(String[] args) 
{

    try
    {

        Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\Hasith\\Documents\\JavaDatabase1.mdb");
        Statement stment = conn.createStatement();
        String qry = "SELECT * FROM Table1";

        ResultSet rs = stment.executeQuery(qry);
        while(rs.next())
        {
            String id    = rs.getString("ID") ;
            String fname = rs.getString("Nama");

            System.out.println(id + fname);
        }
    }
    catch(Exception err)
    {
        System.out.println(err);
    }


    //System.out.println("Hasith Sithila");

}

Passing an array as a function parameter in JavaScript

Why don't you pass the entire array and process it as needed inside the function?

var x = [ 'p0', 'p1', 'p2' ]; 
call_me(x);

function call_me(params) {
  for (i=0; i<params.length; i++) {
    alert(params[i])
  }
}

How can I compare time in SQL Server?

Adding to the other answers:

you can create a function for trimming the date from a datetime

CREATE FUNCTION dbo.f_trimdate (@dat datetime) RETURNS DATETIME AS BEGIN
    RETURN CONVERT(DATETIME, CONVERT(FLOAT, @dat) - CONVERT(INT, @dat))
END

So this:

DECLARE @dat DATETIME
SELECT @dat = '20080201 02:25:46.000'
SELECT dbo.f_trimdate(@dat)

Will return 1900-01-01 02:25:46.000

How to _really_ programmatically change primary and accent color in Android Lollipop?

You can use Theme.applyStyle to modify your theme at runtime by applying another style to it.

Let's say you have these style definitions:

<style name="DefaultTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/md_lime_500</item>
    <item name="colorPrimaryDark">@color/md_lime_700</item>
    <item name="colorAccent">@color/md_amber_A400</item>
</style>

<style name="OverlayPrimaryColorRed">
    <item name="colorPrimary">@color/md_red_500</item>
    <item name="colorPrimaryDark">@color/md_red_700</item>
</style>

<style name="OverlayPrimaryColorGreen">
    <item name="colorPrimary">@color/md_green_500</item>
    <item name="colorPrimaryDark">@color/md_green_700</item>
</style>

<style name="OverlayPrimaryColorBlue">
    <item name="colorPrimary">@color/md_blue_500</item>
    <item name="colorPrimaryDark">@color/md_blue_700</item>
</style>

Now you can patch your theme at runtime like so:

getTheme().applyStyle(R.style.OverlayPrimaryColorGreen, true);

The method applyStylehas to be called before the layout gets inflated! So unless you load the view manually you should apply styles to the theme before calling setContentView in your activity.

Of course this cannot be used to specify an arbitrary color, i.e. one out of 16 million (2563) colors. But if you write a small program that generates the style definitions and the Java code for you then something like one out of 512 (83) should be possible.

What makes this interesting is that you can use different style overlays for different aspects of your theme. Just add a few overlay definitions for colorAccent for example. Now you can combine different values for primary color and accent color almost arbitrarily.

You should make sure that your overlay theme definitions don't accidentally inherit a bunch of style definitions from a parent style definition. For example a style called AppTheme.OverlayRed implicitly inherits all styles defined in AppTheme and all these definitions will also be applied when you patch the master theme. So either avoid dots in the overlay theme names or use something like Overlay.Red and define Overlay as an empty style.

How to add header data in XMLHttpRequest when using formdata?

Use: xmlhttp.setRequestHeader(key, value);

How can I check if char* variable points to empty string?

An empty string has one single null byte. So test if (s[0] == (char)0)

How to get text with Selenium WebDriver in Python

This is the correct answer. It worked!!

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome("E:\\Python\\selenium\\webdriver\\chromedriver.exe")
driver.get("https://www.tatacliq.com/global-desi-navy-embroidered-kurta/p-mp000000000876745")
driver.set_page_load_timeout(45)
driver.maximize_window()
driver.implicitly_wait(2)
driver.get_screenshot_as_file("E:\\Python\\Tatacliq.png")
print ("Executed Successfully")
driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").click()
SpecialPrice = driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").text
print(SpecialPrice)

sorting integers in order lowest to highest java

if array.sort doesn't have what your looking for you can try this:

package drawFramePackage;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class QuicksortAlgorithm {
    ArrayList<AffineTransform> affs;
    ListIterator<AffineTransform> li;
    Integer count, count2;
    /**
     * @param args
     */
    public static void main(String[] args) {
        new QuicksortAlgorithm();
    }
    public QuicksortAlgorithm(){
        count = new Integer(0);
        count2 = new Integer(1);
        affs = new ArrayList<AffineTransform>();
        for (int i = 0; i <= 128; i++){
            affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0));
        }
        affs = arrangeNumbers(affs);
        printNumbers();
    }
    public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){
        while (list.size() > 1 && count != list.size() - 1){
            if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){
                list.add(count, list.get(count2));
                list.remove(count2 + 1);
            }
            if (count2 == list.size() - 1){
                count++;
                count2 = count + 1;
            }
            else{
            count2++;
            }
        }
        return list;
    }
    public void printNumbers(){
        li = affs.listIterator();
        while (li.hasNext()){
            System.out.println(li.next());
        }
    }
}

How to read the value of a private field from a different class in Java?

Reflection isn't the only way to resolve your issue (which is to access the private functionality/behaviour of a class/component)

An alternative solution is to extract the class from the .jar, decompile it using (say) Jode or Jad, change the field (or add an accessor), and recompile it against the original .jar. Then put the new .class ahead of the .jar in the classpath, or reinsert it in the .jar. (the jar utility allows you to extract and reinsert to an existing .jar)

As noted below, this resolves the wider issue of accessing/changing private state rather than simply accessing/changing a field.

This requires the .jar not to be signed, of course.

Simple jQuery, PHP and JSONP example?

To make the server respond with a valid JSONP array, wrap the JSON in brackets () and preprend the callback:

echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])";

Using json_encode() will convert a native PHP array into JSON:

$array = array(
    'fullname' => 'Jeff Hansen',
    'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";

Excel: Use a cell value as a parameter for a SQL query

The SQL is somewhat like the syntax of MS SQL.

SELECT * FROM [table$] WHERE *;

It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.

If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:

SELECT Name FROM [Users$] WHERE id = 1;

Hope this helps.

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

I am now using Google Apps (for Email) and Heroku as web server. I am using Google Apps 301 Permanent Redirect feature to redirect the naked domain to WWW.your_domain.com

You can find the step-by-step instructions here https://stackoverflow.com/a/20115583/1440255

How to create a DataTable in C# and how to add rows?

The easiest way is to create a DtaTable as of now

DataTable table = new DataTable
{
    Columns = {
        "Name", // typeof(string) is implied
        {"Marks", typeof(int)}
    },
    TableName = "MarksTable" //optional
};
table.Rows.Add("ravi", 500);

How to convert .pfx file to keystore with private key?

Your PFX file should contain the private key within it. Export the private key and certificate directly from your PFX file (e.g. using OpenSSL) and import them into your Java keystore.

Edit

Further information:

  • Download OpenSSL for Windows here.
  • Export private key: openssl pkcs12 -in filename.pfx -nocerts -out key.pem
  • Export certificate: openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
  • Import private key and certificate into Java keystore using keytool.

How to pass a parameter like title, summary and image in a Facebook sharer URL

This works at the moment (Oct. 2016), but I can't guarantee how long it will last:

https://www.facebook.com/sharer.php?caption=[caption]&description=[description]&u=[website]&picture=[image-url]

Use JAXB to create Object from XML String

If you want to parse using InputStreams

public Object xmlToObject(String xmlDataString) {
        Object converted = null;
        try {
        
            JAXBContext jc = JAXBContext.newInstance(Response.class);
        
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
            
            converted = unmarshaller.unmarshal(stream);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return converted;
    }

What does the "assert" keyword do?

It ensures that the expression returns true. Otherwise, it throws a java.lang.AssertionError.

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.10

$lookup on ObjectId's in an array

Starting with MongoDB v3.4 (released in 2016), the $lookup aggregation pipeline stage can also work directly with an array. There is no need for $unwind any more.

This was tracked in SERVER-22881.

How to add Options Menu to Fragment in Android

Set setHasMenuOptions(true) works if application has a theme with Actionbar such as Theme.MaterialComponents.DayNight.DarkActionBar or Activity has it's own Toolbar, otherwise onCreateOptionsMenu in fragment does not get called.

If you want to use standalone Toolbar you either need to get activity and set your Toolbar as support action bar with

(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)

which lets your fragment onCreateOptionsMenu to be called.

Other alternative is, you can inflate your Toolbar's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU) and item listener with

toolbar.setOnMenuItemClickListener {
   // do something
   true
}

Datetime format Issue: String was not recognized as a valid DateTime

Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
Also, you need to specify H instead of h if you are using 24 hour times:

DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)

See here for more information:

Custom Date and Time Format Strings

Add ArrayList to another ArrayList in java

Then you need a ArrayList of ArrayLists:

ArrayList<ArrayList<String>> nodes = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();
nodes.add(nodeList);

Note that NodeList has been changed to nodeList. In Java Naming Conventions variables start with a lower case. Classes start with an upper case.

How to generate random number in Bash?

A bash function that uses perl to generate a random number of n digits. Specify either the number of digits or a template of n 0s.

rand() {
  perl -E '$ARGV[0]||=""; $ARGV[0]=int($ARGV[0])||length($ARGV[0]); say join "", int(rand(9)+1)*($ARGV[0]?1:0), map { int(rand(10)) } (0..($ARGV[0]||0)-2)' $1
}

Usage:

$ rand 3
381
$ rand 000
728

Demonstration of calling rand n, for n between 0 and 15:

$ for n in {0..15}; do printf "%02d: %s\n" $n $(rand $n); done
00: 0
01: 3
02: 98
03: 139
04: 1712
05: 49296
06: 426697
07: 2431421
08: 82727795
09: 445682186
10: 6368501779
11: 51029574113
12: 602518591108
13: 5839716875073
14: 87572173490132
15: 546889624135868

Demonstration of calling rand n, for n a template of 0s between length 0 and 15

$ for n in {0..15}; do printf "%15s :%02d: %s\n" $(printf "%0${n}d" 0) $n $(rand $(printf "%0${n}d" 0)); done
              0 :00: 0
              0 :01: 0
             00 :02: 70
            000 :03: 201
           0000 :04: 9751
          00000 :05: 62237
         000000 :06: 262860
        0000000 :07: 1365194
       00000000 :08: 83953419
      000000000 :09: 838521776
     0000000000 :10: 2355011586
    00000000000 :11: 95040136057
   000000000000 :12: 511889225898
  0000000000000 :13: 7441263049018
 00000000000000 :14: 11895209107156
000000000000000 :15: 863219624761093

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

To get UserManager in API

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

where AppUserManager is the class that inherits from UserManager.

How to give color to each class in scatter plot in R?

Assuming the class variable is z, you can use:

with(df, plot(x, y, col = z))

however, it's important that z is a factor variable, as R internally stores factors as integers.

This way, 1 is 'black', 2 is 'red', 3 is 'green, ....

Change the value in app.config file dynamically

It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.

Input jQuery get old value before onchange and get value after on change

I have found a solution that works even with "Select2" plugin:

function functionName() {
  $('html').on('change', 'select.some-class', function() {
    var newValue = $(this).val();
    var oldValue = $(this).attr('data-val');
    if ( $.isNumeric(oldValue) ) { // or another condition
      // do something
    }
    $(this).attr('data-val', newValue);
  });
  $('select.some-class').trigger('change');
}

ActiveModel::ForbiddenAttributesError when creating new user

If you are on Rails 4 and you get this error, it could happen if you are using enum on the model if you've defined with symbols like this:

class User
  enum preferred_phone: [:home_phone, :mobile_phone, :work_phone]
end

The form will pass say a radio selector as a string param. That's what happened in my case. The simple fix is to change enum to strings instead of symbols

enum preferred_phone: %w[home_phone mobile_phone work_phone]
# or more verbose
enum preferred_phone: ['home_phone', 'mobile_phone', 'work_phone']

How would I run an async Task<T> method synchronously?

It's much simpler to run the task on the thread pool, rather than trying to trick the scheduler to run it synchronously. That way you can be sure that it won't deadlock. Performance is affected because of the context switch.

Task<MyResult> DoSomethingAsync() { ... }

// Starts the asynchronous task on a thread-pool thread.
// Returns a proxy to the original task.
Task<MyResult> task = Task.Run(() => DoSomethingAsync());

// Will block until the task is completed...
MyResult result = task.Result; 

Check if a string is a palindrome

This C# method will check for even and odd length palindrome string (Recursive Approach):

public static bool IsPalindromeResursive(int rightIndex, int leftIndex, char[] inputString)
{
    if (rightIndex == leftIndex || rightIndex < leftIndex)
        return true;
    if (inputString[rightIndex] == inputString[leftIndex])
        return IsPalindromeResursive(--rightIndex, ++leftIndex, inputString);
    else
        return false;            
}

Why aren't programs written in Assembly more often?

Portability is always an issue -- if not now, at least eventually. The programming industry spends billions every year to port old software which, at the time it was written, had "obviously" no portability issue whatsoever.

What is the difference between RTP or RTSP in a streaming server?

Some basics:

RTSP server can be used for dead source as well as for live source. RTSP protocols provides you commands (Like your VCR Remote), and functionality depends upon your implementation.

RTP is real time protocol used for transporting audio and video in real time. Transport used can be unicast, multicast or broadcast, depending upon transport address and port. Besides transporting RTP does lots of things for you like packetization, reordering, jitter control, QoS, support for Lip sync.....

In your case if you want broadcasting streaming server then you need both RTSP (for control) as well as RTP (broadcasting audio and video)

To start with you can go through sample code provided by live555

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

Python: Figure out local timezone

Here's a slightly more concise version of @vbem's solution:

from datetime import datetime as dt

dt.utcnow().astimezone().tzinfo

The only substantive difference is that I replaced datetime.datetime.now(datetime.timezone.utc) with datetime.datetime.utcnow(). For brevity, I also aliased datetime.datetime as dt.

For my purposes, I want the UTC offset in seconds. Here's what that looks like:

dt.utcnow().astimezone().utcoffset().total_seconds()

How to get relative path from absolute path

If you're sure that your absolute path 2 is always relative to absolute path, just remove the first N characters from path2, where N is the length of path1.

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

you should run standlone.bat or .sh with -c standalone-full.xml switch may be work.

What charset does Microsoft Excel use when saving files?

OOXML files like those that come from Excel 2007 are encoded in UTF-8, according to wikipedia. I don't know about CSV files, but it stands to reason it would use the same format...

How to define an empty object in PHP

You can use new stdClass() (which is recommended):

$obj_a = new stdClass();
$obj_a->name = "John";
print_r($obj_a);

// outputs:
// stdClass Object ( [name] => John ) 

Or you can convert an empty array to an object which produces a new empty instance of the stdClass built-in class:

$obj_b = (object) [];
$obj_b->name = "John";
print_r($obj_b);

// outputs: 
// stdClass Object ( [name] => John )  

Or you can convert the null value to an object which produces a new empty instance of the stdClass built-in class:

$obj_c = (object) null;
$obj_c->name = "John";
print($obj_c);

// outputs:
// stdClass Object ( [name] => John ) 

How to set height property for SPAN

span { display: table-cell; height: (your-height + px); vertical-align: middle; }

For spans to work like a table-cell (or any other element, for that matter), height must be specified. I've given spans a height, and they work just fine--but you must add height to get them to do what you want.

JSON.net: how to deserialize without using the default constructor?

A bit late and not exactly suited here, but I'm gonna add my solution here, because my question had been closed as a duplicate of this one, and because this solution is completely different.

I needed a general way to instruct Json.NET to prefer the most specific constructor for a user defined struct type, so I can omit the JsonConstructor attributes which would add a dependency to the project where each such struct is defined.

I've reverse engineered a bit and implemented a custom contract resolver where I've overridden the CreateObjectContract method to add my custom creation logic.

public class CustomContractResolver : DefaultContractResolver {

    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        var c = base.CreateObjectContract(objectType);
        if (!IsCustomStruct(objectType)) return c;

        IList<ConstructorInfo> list = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).OrderBy(e => e.GetParameters().Length).ToList();
        var mostSpecific = list.LastOrDefault();
        if (mostSpecific != null)
        {
            c.OverrideCreator = CreateParameterizedConstructor(mostSpecific);
            c.CreatorParameters.AddRange(CreateConstructorParameters(mostSpecific, c.Properties));
        }

        return c;
    }

    protected virtual bool IsCustomStruct(Type objectType)
    {
        return objectType.IsValueType && !objectType.IsPrimitive && !objectType.IsEnum && !objectType.Namespace.IsNullOrEmpty() && !objectType.Namespace.StartsWith("System.");
    }

    private ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
    {
        method.ThrowIfNull("method");
        var c = method as ConstructorInfo;
        if (c != null)
            return a => c.Invoke(a);
        return a => method.Invoke(null, a);
    }
}

I'm using it like this.

public struct Test {
  public readonly int A;
  public readonly string B;

  public Test(int a, string b) {
    A = a;
    B = b;
  }
}

var json = JsonConvert.SerializeObject(new Test(1, "Test"), new JsonSerializerSettings {
  ContractResolver = new CustomContractResolver()
});
var t = JsonConvert.DeserializeObject<Test>(json);
t.A.ShouldEqual(1);
t.B.ShouldEqual("Test");

How to get multiline input from user

input(prompt) is basically equivalent to

def input(prompt):
    print(prompt, end='', file=sys.stderr)
    return sys.stdin.readline()

You can read directly from sys.stdin if you like.

lines = sys.stdin.readlines()

lines = [line for line in sys.stdin]

five_lines = list(itertools.islice(sys.stdin, 5))

The first two require that the input end somehow, either by reaching the end of a file or by the user typing Control-D (or Control-Z in Windows) to signal the end. The last one will return after five lines have been read, whether from a file or from the terminal/keyboard.

Example using Hyperlink in WPF

In addition to Fuji's response, we can make the handler reusable turning it into an attached property:

public static class HyperlinkExtensions
{
    public static bool GetIsExternal(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsExternalProperty);
    }

    public static void SetIsExternal(DependencyObject obj, bool value)
    {
        obj.SetValue(IsExternalProperty, value);
    }
    public static readonly DependencyProperty IsExternalProperty =
        DependencyProperty.RegisterAttached("IsExternal", typeof(bool), typeof(HyperlinkExtensions), new UIPropertyMetadata(false, OnIsExternalChanged));

    private static void OnIsExternalChanged(object sender, DependencyPropertyChangedEventArgs args)
    {
        var hyperlink = sender as Hyperlink;

        if ((bool)args.NewValue)
            hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
        else
            hyperlink.RequestNavigate -= Hyperlink_RequestNavigate;
    }

    private static void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
    {
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
        e.Handled = true;
    }
}

And use it like this:

<TextBlock>
    <Hyperlink NavigateUri="https://stackoverflow.com"
               custom:HyperlinkExtensions.IsExternal="true">
        Click here
    </Hyperlink>
</TextBlock>

Removing object properties with Lodash

Lodash unset is suitable for removing a few unwanted keys.

_x000D_
_x000D_
const myObj = {
    keyOne: "hello",
    keyTwo: "world"
}

unset(myObj, "keyTwo");

console.log(myObj); /// myObj = { keyOne: "hello" }
_x000D_
_x000D_
_x000D_

SQL Server equivalent to MySQL enum data type?

IMHO Lookup tables is the way to go, with referential integrity. But only if you avoid "Evil Magic Numbers" by following an example such as this one: Generate enum from a database lookup table using T4

Have Fun!

How to get a pixel's x,y coordinate color from an image?

Building on Jeff's answer, your first step would be to create a canvas representation of your PNG. The following creates an off-screen canvas that is the same width and height as your image and has the image drawn on it.

var img = document.getElementById('my-image');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

After that, when a user clicks, use event.offsetX and event.offsetY to get the position. This can then be used to acquire the pixel:

var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;

Because you are only grabbing one pixel, pixelData is a four entry array containing the pixel's R, G, B, and A values. For alpha, anything less than 255 represents some level of transparency with 0 being fully transparent.

Here is a jsFiddle example: http://jsfiddle.net/thirtydot/9SEMf/869/ I used jQuery for convenience in all of this, but it is by no means required.

Note: getImageData falls under the browser's same-origin policy to prevent data leaks, meaning this technique will fail if you dirty the canvas with an image from another domain or (I believe, but some browsers may have solved this) SVG from any domain. This protects against cases where a site serves up a custom image asset for a logged in user and an attacker wants to read the image to get information. You can solve the problem by either serving the image from the same server or implementing Cross-origin resource sharing.

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

How to copy static files to build directory with Webpack?

Requiring assets using the file-loader module is the way webpack is intended to be used (source). However, if you need greater flexibility or want a cleaner interface, you can also copy static files directly using my copy-webpack-plugin (npm, Github). For your static to build example:

const CopyWebpackPlugin = require('copy-webpack-plugin');
 
module.exports = {
    context: path.join(__dirname, 'your-app'),
    plugins: [
        new CopyWebpackPlugin({
            patterns: [
                { from: 'static' }
            ]
        })
    ]
};

How to convert a time string to seconds?

def time_to_sec(t):
   h, m, s = map(int, t.split(':'))
   return h * 3600 + m * 60 + s

t = '10:40:20'
time_to_sec(t)  # 38420

JSON datetime between Python and JavaScript

I've worked it out.

Let's say you have a Python datetime object, d, created with datetime.now(). Its value is:

datetime.datetime(2011, 5, 25, 13, 34, 5, 787000)

You can serialize it to JSON as an ISO 8601 datetime string:

import json    
json.dumps(d.isoformat())

The example datetime object would be serialized as:

'"2011-05-25T13:34:05.787000"'

This value, once received in the Javascript layer, can construct a Date object:

var d = new Date("2011-05-25T13:34:05.787000");

As of Javascript 1.8.5, Date objects have a toJSON method, which returns a string in a standard format. To serialize the above Javascript object back to JSON, therefore, the command would be:

d.toJSON()

Which would give you:

'2011-05-25T20:34:05.787Z'

This string, once received in Python, could be deserialized back to a datetime object:

datetime.strptime('2011-05-25T20:34:05.787Z', '%Y-%m-%dT%H:%M:%S.%fZ')

This results in the following datetime object, which is the same one you started with and therefore correct:

datetime.datetime(2011, 5, 25, 20, 34, 5, 787000)

No provider for HttpClient

Add HttpModule and HttpClientModule in both imports and providers in app.module.ts solved the issue. imports -> import {HttpModule} from "@angular/http"; import {HttpClientModule} from "@angular/common/http";

GIT vs. Perforce- Two VCS will enter... one will leave

It would take me a lot of convincing to switch from perforce. In the two companies I used it it was more than adequate. Those were both companies with disparate offices, but the offices were set up with plenty of infrastructure so there was no need to have the disjoint/disconnected features.

How many developers are you talking about changing over?

The real question is - what is it about perforce that is not meeting your organization's needs that git can provide? And similarly, what weaknesses does git have compared to perforce? If you can't answer that yourself then asking here won't help. You need to find a business case for your company. (e.g. Perhaps it is with lower overall cost of ownership (that includes loss of productivity for the interim learning stage, higher admin costs (at least initially), etc.)

I think you are in for a tough sell - perforce is a pretty good one to try to replace. It is a no brainer if you are trying to boot out pvcs or ssafe.

WARNING: Can't verify CSRF token authenticity rails

I'm using Rails 4.2.4 and couldn't work out why I was getting:

Can't verify CSRF token authenticity

I have in the layout:

<%= csrf_meta_tags %>

In the controller:

protect_from_forgery with: :exception

Invoking tcpdump -A -s 999 -i lo port 3000 was showing the header being set ( despite not needing to set the headers with ajaxSetup - it was done already):

X-CSRF-Token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
DNT: 1
Content-Length: 125
authenticity_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

In the end it was failing because I had cookies switched off. CSRF doesn't work without cookies being enabled, so this is another possible cause if you're seeing this error.

How to correctly link php-fpm and Nginx Docker containers?

Don't hardcode ip of containers in nginx config, docker link adds the hostname of the linked machine to the hosts file of the container and you should be able to ping by hostname.

EDIT: Docker 1.9 Networking no longer requires you to link containers, when multiple containers are connected to the same network, their hosts file will be updated so they can reach each other by hostname.

Every time a docker container spins up from an image (even stop/start-ing an existing container) the containers get new ip's assigned by the docker host. These ip's are not in the same subnet as your actual machines.

see docker linking docs (this is what compose uses in the background)

but more clearly explained in the docker-compose docs on links & expose

links

links:
 - db
 - db:database
 - redis

An entry with the alias' name will be created in /etc/hosts inside containers for this service, e.g:

172.17.2.186  db
172.17.2.186  database
172.17.2.187  redis

expose

Expose ports without publishing them to the host machine - they'll only be accessible to linked services. Only the internal port can be specified.

and if you set up your project to get the ports + other credentials through environment variables, links automatically set a bunch of system variables:

To see what environment variables are available to a service, run docker-compose run SERVICE env.

name_PORT

Full URL, e.g. DB_PORT=tcp://172.17.0.5:5432

name_PORT_num_protocol

Full URL, e.g. DB_PORT_5432_TCP=tcp://172.17.0.5:5432

name_PORT_num_protocol_ADDR

Container's IP address, e.g. DB_PORT_5432_TCP_ADDR=172.17.0.5

name_PORT_num_protocol_PORT

Exposed port number, e.g. DB_PORT_5432_TCP_PORT=5432

name_PORT_num_protocol_PROTO

Protocol (tcp or udp), e.g. DB_PORT_5432_TCP_PROTO=tcp

name_NAME

Fully qualified container name, e.g. DB_1_NAME=/myapp_web_1/myapp_db_1

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Worked by lowering the spring boot starter parent to 1.5.13

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.13.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

SQL Server - INNER JOIN WITH DISTINCT

select distinct a.FirstName, a.LastName, v.District from AddTbl a inner join ValTbl v on a.LastName = v.LastName order by a.FirstName;

hope this helps

Recursion or Iteration?

If you're just iterating over a list, then sure, iterate away.

A couple of other answers have mentioned (depth-first) tree traversal. It really is such a great example, because it's a very common thing to do to a very common data structure. Recursion is extremely intuitive for this problem.

Check out the "find" methods here: http://penguin.ewu.edu/cscd300/Topic/BSTintro/index.html

How to set background color of a button in Java GUI?

Simple:

btn.setBackground(Color.red);

To use RGB values:

btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));

select2 - hiding the search box

If you have multi attribute in your select, this dirty hack works:

var multipleSelect = $('select[name="list_type"]');
multipleSelect.select2();
multipleSelect.parent().find('.select2-search--inline').remove();
multipleSelect.on('change', function(){
    multipleSelect.parent().find('.select2-search--inline').remove();
});

see docs here https://select2.org/searching#limiting-display-of-the-search-box-to-large-result-sets

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

PHP function to generate v4 UUID

I'm sure there's a more elegant way to do the conversion from binary to decimal for the 4xxx and yxxx portions. But if you want to use openssl_random_pseudo_bytes as your crytographically secure number generator, this is what I use:

return sprintf('%s-%s-%04x-%04x-%s',
    bin2hex(openssl_random_pseudo_bytes(4)),
    bin2hex(openssl_random_pseudo_bytes(2)),
    hexdec(bin2hex(openssl_random_pseudo_bytes(2))) & 0x0fff | 0x4000,
    hexdec(bin2hex(openssl_random_pseudo_bytes(2))) & 0x3fff | 0x8000,
    bin2hex(openssl_random_pseudo_bytes(6))
    );

Iterate through Nested JavaScript Objects

The following code assumes no circular references, and assumes subs is always an array (and not null in leaf nodes):

function find(haystack, needle) {
  if (haystack.label === needle) return haystack;
  for (var i = 0; i < haystack.subs.length; i ++) {
    var result = find(haystack.subs[i], needle);
    if (result) return result;
  }
  return null;
}

Angular ng-class if else

Both John Conde's and ryeballar's answers are correct and will work.

If you want to get too geeky:

  • John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center and it has to decide whether to add/remove left), when clearly only one is needed.

  • Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)


So, you can do the following as an alternative:

ng-class="{true:'center',false:'left'}[page.isSelected(1)]"

How do you stylize a font in Swift?

Add Custom Font in Swift

  1. Drag and drop your font in your project.
  2. Double check that it is added in Copy Bundle Resource. (Build Phase -> Copy Bundle Resource).
  3. In your plist file add "Font Provided by application" and add your fonts with full name.
  4. Now use your font like: myLabel.font = UIFont (name: "GILLSANSCE-ROMAN", size: 20)

What does "select count(1) from table_name" on any database tables mean?

You can test like this:

create table test1(
 id number,
 name varchar2(20)
);

insert into test1 values (1,'abc');
insert into test1 values (1,'abc');

select * from test1;
select count(*) from test1;
select count(1) from test1;
select count(ALL 1) from test1;
select count(DISTINCT 1) from test1;

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

Node.js client for a socket.io server

Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!

const socket = require('socket.io-client')('http://192.168.0.8:5000', {
            reconnection: true,
            reconnectionDelay: 10000
          });
    
        socket.on('connect', (data) => {
            console.log('Connected to Socket');
        });
        
        socket.on('event_name', (data) => {
            console.log("-----------------received event data from the socket io server");
        });
    
        //either 'io server disconnect' or 'io client disconnect'
        socket.on('disconnect', (reason) => {
            console.log("client disconnected");
            if (reason === 'io server disconnect') {
              // the disconnection was initiated by the server, you need to reconnect manually
              console.log("server disconnected the client, trying to reconnect");
              socket.connect();
            }else{
                console.log("trying to reconnect again with server");
            }
            // else the socket will automatically try to reconnect
          });
    
        socket.on('error', (error) => {
            console.log(error);
        });

How to get equal width of input and select fields

Updated answer

Here is how to change the box model used by the input/textarea/select elements so that they all behave the same way. You need to use the box-sizing property which is implemented with a prefix for each browser

-ms-box-sizing:content-box;
-moz-box-sizing:content-box;
-webkit-box-sizing:content-box; 
box-sizing:content-box;

This means that the 2px difference we mentioned earlier does not exist..

example at http://www.jsfiddle.net/gaby/WaxTS/5/

note: On IE it works from version 8 and upwards..


Original

if you reset their borders then the select element will always be 2 pixels less than the input elements..

example: http://www.jsfiddle.net/gaby/WaxTS/2/

How to delete a module in Android Studio

Deleting is such a headache. I am posting the solution for Android Studio 1.0.2.


Step 1: Right click on the "Project Name" selected from the folder hierarchy like shown.
Note: It can also be deleted from the Commander View from right hand side of your window by right clicking the project name and selecting delete from the context menu.

Step 1

Step 2: The project is deleted(seemingly) but gradle seems to keep the record of the project app folder(Check it by clcking on the Gradle View). Now go to File->Close Project.

Step 3: Now you are at the start window. Move the cursor on the in recent project list. Press Delete.

Step 4: Delete the folder from the explorer by moving or deleting it actually. This location is in your_user_name->Android Studio Projects->...

Step 5: Go back to the Android studio window and the project is gone for good. You can start a new project now.

Submit button not working in Bootstrap form

Your problem is this

<button type="button" value=" Send" class="btn btn-success" type="submit" id="submit" />

You've set the type twice. Your browser is only accepting the first, which is "button".

<button type="submit" value=" Send" class="btn btn-success" id="submit" />

ValueError: unconverted data remains: 02:05

  timeobj = datetime.datetime.strptime(my_time, '%Y-%m-%d %I:%M:%S')
  File "/usr/lib/python2.7/_strptime.py", line 335, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains:

In my case, the problem was an extra space in the input date string. So I used strip() and it started to work.

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

This setting useOldUTF8Behavior=true worked fine for me. It gave no incorrect string errors but it converted special characters like à into multiple characters and saved in the database.

To avoid such situations, I removed this property from the JDBC parameter and instead converted the datatype of my column to BLOB. This worked perfect.

What's the difference between a single precision and double precision floating point operation?

Basically single precision floating point arithmetic deals with 32 bit floating point numbers whereas double precision deals with 64 bit.

The number of bits in double precision increases the maximum value that can be stored as well as increasing the precision (ie the number of significant digits).

How can I remove the extension of a filename in a shell script?

As pointed out by Hawker65 in the comment of chepner answer, the most voted solution does neither take care of multiple extensions (such as filename.tar.gz), nor of dots in the rest of the path (such as this.path/with.dots/in.path.name). A possible solution is:

a=this.path/with.dots/in.path.name/filename.tar.gz
echo $(dirname $a)/$(basename $a | cut -d. -f1)

What's the difference between faking, mocking, and stubbing?

Stub, Fakes and Mocks have different meanings across different sources. I suggest you to introduce your team internal terms and agree upon their meaning.

I think it is important to distinguish between two approaches: - behaviour validation (implies behaviour substitution) - end-state validation (implies behaviour emulation)

Consider email sending in case of error. When doing behaviour validation - you check that method Send of IEmailSender was executed once. And you need to emulate return result of this method, return Id of the sent message. So you say: "I expect that Send will be called. And I will just return dummy (or random) Id for any call". This is behaviour validation: emailSender.Expect(es=>es.Send(anyThing)).Return((subject,body) => "dummyId")

When doing state validation you will need to create TestEmailSender that implements IEmailSender. And implement Send method - by saving input to some data structure that will be used for future state verification like array of some objects SentEmails and then it tests you will check that SentEmails contains expected email. This is state validation: Assert.AreEqual(1, emailSender.SentEmails.Count)

From my readings I understood that Behaviour validation usually called Mocks. And State validation usually called Stubs or Fakes.

Alternative to iFrames with HTML5

You should have a look into JSON-P - that was a perfect solution for me when I had that problem:

https://en.wikipedia.org/wiki/JSONP

You basically define a javascript file that loads all your data and another javascript file that processes and displays it. That gets rid of the ugly scrollbar of iframes.

Select Multiple Fields from List in Linq

This is task for which anonymous types are very well suited. You can return objects of a type that is created automatically by the compiler, inferred from usage.

The syntax is of this form:

new { Property1 = value1, Property2 = value2, ... }

For your case, try something like the following:

var listObject = getData();
var catNames = listObject.Select(i =>
    new { CatName = i.category_name, Item1 = i.item1, Item2 = i.item2 })
    .Distinct().OrderByDescending(s => s).ToArray();

jQuery change URL of form submit

Send the data from the form:

$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
  type: "PUT"
  url: url
  dataType: "script"
  data: postData

How to have a default option in Angular.js select box

If you have some thing instead of just init the date part, you can use ng-init() by declare it in your controller, and use it in the top of your HTML. This function will work like a constructor for your controller, and you can initiate your variables there.

angular.module('myApp', [])
 .controller('myController', ['$scope', ($scope) => {
   $scope.allOptions = [
     { name: 'Apple', value: 'apple' }, 
     { name: 'Banana', value: 'banana' }
   ];
   $scope.myInit = () => {
      $scope.userSelected = 'apple'
      // Other initiations can goes here..
   }
}]);


<body ng-app="myApp">
  <div ng-controller="myController" ng-init="init()">
    <select ng-model="userSelected" ng-options="option.value as option.name for option in allOptions"></select>
   </div>
</body>

How to get textLabel of selected row in swift?

Try this:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example

    let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell

    print(currentCell.textLabel!.text)

Convert from java.util.date to JodaTime

http://joda-time.sourceforge.net/quickstart.html

Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:

* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

How do I convert hex to decimal in Python?

>>> int("0xff", 16)
255

or

>>> int("FFFF", 16)
65535

Read the docs.

What does "exited with code 9009" mean during this build?

In my case I had to "CD" (Change Directory) to the proper directory first, before calling the command, since the executable I was calling was in my project directory.

Example:

cd "$(SolutionDir)"
call "$(SolutionDir)build.bat"

Design DFA accepting binary strings divisible by a number 'n'

I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.

Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.

In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.

Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.

For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :

20/2 = 10 
10/2 = 5

Hence our answer is 5 + 1 + 1 = 7. (The 1 + 1 because we divided the number 20 twice).

How to override and extend basic Django admin templates?

With django 1.5 (at least) you can define the template you want to use for a particular modeladmin

see https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#custom-template-options

You can do something like

class Myadmin(admin.ModelAdmin):
    change_form_template = 'change_form.htm'

With change_form.html being a simple html template extending admin/change_form.html (or not if you want to do it from scratch)

jQuery Event : Detect changes to the html/text of a div

Following code works for me.

$("body").on('DOMSubtreeModified', "mydiv", function() {
    alert('changed');
});

Hope it will help someone :)

`ui-router` $stateParams vs. $state.params

An interesting observation I made while passing previous state params from one route to another is that $stateParams gets hoisted and overwrites the previous route's state params that were passed with the current state params, but using $state.params doesn't.

When using $stateParams:

var stateParams        = {};
stateParams.nextParams = $stateParams; //{item_id:123}
stateParams.next       = $state.current.name;

$state.go('app.login', stateParams);
//$stateParams.nextParams on app.login is now:
//{next:'app.details', nextParams:{next:'app.details'}}

When using $state.params:

var stateParams        = {};
stateParams.nextParams = $state.params; //{item_id:123}
stateParams.next       = $state.current.name;

$state.go('app.login', stateParams);
//$stateParams.nextParams on app.login is now:
//{next:'app.details', nextParams:{item_id:123}}

Align div with fixed position on the right side

Here's the real solution (with other cool CSS3 stuff):

#fixed-square {
position: fixed;
top: 0;
right: 0;
z-index: 9500;
cursor: pointer;
width: 24px;
padding: 18px 18px 14px;
opacity: 0.618;
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-transition: all 0.145s ease-out;
-moz-transition: all 0.145s ease-out;
-ms-transition: all 0.145s ease-out;
transition: all 0.145s ease-out;
}

Note the top:0 and right:0. That's what did it for me.

Invalid column name sql error

You should never write code that concatenates SQL and parameters as string - this opens up your code to SQL injection which is a really serious security problem.

Use bind params - for a nice howto see here...

Find and replace in file and overwrite file doesn't work, it empties the file

Warning: this is a dangerous method! It abuses the i/o buffers in linux and with specific options of buffering it manages to work on small files. It is an interesting curiosity. But don't use it for a real situation!

Besides the -i option of sed you can use the tee utility.

From man:

tee - read from standard input and write to standard output and files

So, the solution would be:

sed s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html | tee | tee index.html

-- here the tee is repeated to make sure that the pipeline is buffered. Then all commands in the pipeline are blocked until they get some input to work on. Each command in the pipeline starts when the upstream commands have written 1 buffer of bytes (the size is defined somewhere) to the input of the command. So the last command tee index.html, which opens the file for writing and therefore empties it, runs after the upstream pipeline has finished and the output is in the buffer within the pipeline.

Most likely the following won't work:

sed s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html | tee index.html

-- it will run both commands of the pipeline at the same time without any blocking. (Without blocking the pipeline should pass the bytes line by line instead of buffer by buffer. Same as when you run cat | sed s/bar/GGG/. Without blocking it's more interactive and usually pipelines of just 2 commands run without buffering and blocking. Longer pipelines are buffered.) The tee index.html will open the file for writing and it will be emptied. However, if you turn the buffering always on, the second version will work too.

find filenames NOT ending in specific extensions on Unix?

$ find . -name \*.exe -o -name \*.dll -o -print

The first two -name options have no -print option, so they skipped. Everything else is printed.

Combining CSS Pseudo-elements, ":after" the ":last-child"

This works :) (I hope multi-browser, Firefox likes it)

_x000D_
_x000D_
li { display: inline; list-style-type: none; }_x000D_
li:after { content: ", "; }_x000D_
li:last-child:before { content: "and "; }_x000D_
li:last-child:after { content: "."; }
_x000D_
<html>_x000D_
  <body>_x000D_
    <ul>_x000D_
      <li>One</li>_x000D_
      <li>Two</li>_x000D_
      <li>Three</li>_x000D_
    </ul>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Convert time in HH:MM:SS format to seconds only?

You can use the strtotime function to return the number of seconds from today 00:00:00.

$seconds= strtotime($time) - strtotime('00:00:00');

Scheduling Python Script to run every hour accurately

To run something every 10 minutes past the hour.

from datetime import datetime, timedelta

while 1:
    print 'Run something..'

    dt = datetime.now() + timedelta(hours=1)
    dt = dt.replace(minute=10)

    while datetime.now() < dt:
        time.sleep(1)

How do you detect/avoid Memory leaks in your (Unmanaged) code?

Mtrace appears to be the standard built-in one for linux. The steps are :

  1. set up the environment variable MALLOC_TRACE in bash
    MALLOC_TRACE=/tmp/mtrace.dat
    export MALLOC_TRACE;
  2. Add #include <mcheck.h> to the top of you main source file
  3. Add mtrace(); at the start of main and muntrace(); at the bottom (before the return statement)
  4. compile your program with the -g switch for debug information
  5. run your program
  6. display leak info with
    mtrace your_prog_exe_name /tmp/mtrace.dat
    (I had to install the mtrace perl script first on my fedora system with yum install glibc_utils  )

Foreach in a Foreach in MVC View

You have:

foreach (var category in Model.Categories)

and then

@foreach (var product in Model)

Based on that view and model it seems that Model is of type Product if yes then the second foreach is not valid. Actually the first one could be the one that is invalid if you return a collection of Product.

UPDATE:

You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?

I'm surprised your code compiles when you said you are returning a model of Product type. Here's how you can do it:

@foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>

    <div>
        <ul>    
            @foreach (var product in category.Products)
            {
                <li>
                    put the rest of your code
                </li>
            }
        </ul>
    </div>
}

That suggest that instead of returning a Product, you return a collection of Category with Products. Something like this in EF:

// I am typing it here directly 
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)

Standard deviation of a list

Since Python 3.4 / PEP450 there is a statistics module in the standard library, which has a method stdev for calculating the standard deviation of iterables like yours:

>>> A_rank = [0.8, 0.4, 1.2, 3.7, 2.6, 5.8]
>>> import statistics
>>> statistics.stdev(A_rank)
2.0634114147853952

Malformed String ValueError ast.literal_eval() with String representation of Tuple

Use eval() instead of ast.literal_eval() if the input is trusted (which it is in your case).

raw_data = userfile.read().split('\n')
for a in raw_data : 
    print a
    btc_history.append(eval(a))

This works for me in Python 3.6.0

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

just put #login-box before <h2>Welcome</h2> will be ok.

<div class='container'>
    <div class='hero-unit'>
        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>
        <h2>Welcome</h2>

        <p>Please log in</p>

    </div>
</div>

here is jsfiddle http://jsfiddle.net/SyjjW/4/

Make a div into a link

I pulled in a variable because some values in my link will change depending on what record the user is coming from. This worked for testing :

   <div onclick="location.href='page.html';"  style="cursor:pointer;">...</div> 

and this works too :

   <div onclick="location.href='<%=Webpage%>';"  style="cursor:pointer;">...</div> 

How to change TextBox's Background color?

In WinForms and WebForms you can do:

txtName.BackColor = Color.Aqua;

proper way to logout from a session in PHP

Personally, I do the following:

session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();

That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy).

Differences between strong and weak in Objective-C

Here, Apple Documentation has explained the difference between weak and strong property using various examples :

https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW3

Here, In this blog author has collected all the properties in same place. It will help to compare properties characteristics :

http://rdcworld-iphone.blogspot.in/2012/12/variable-property-attributes-or.html

Circular gradient in android

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <gradient
        android:endColor="@color/color1"
        android:gradientRadius="250dp"
        android:startColor="#8F15DA"
        android:type="radial" />

    <corners
        android:bottomLeftRadius="50dp"
        android:bottomRightRadius="50dp"
        android:radius="3dp"
        android:topLeftRadius="0dp"
        android:topRightRadius="50dp" />
</shape>

CSS - Expand float child DIV height to parent's height

I found a lot of answers, but probably the best solution for me is

.parent { 
  overflow: hidden; 
}
.parent .floatLeft {
  # your other styles
  float: left;
  margin-bottom: -99999px;
  padding-bottom: 99999px;
}

You can check other solutions here http://css-tricks.com/fluid-width-equal-height-columns/

How can I jump to class/method definition in Atom text editor?

As of November 2018 the package autocomplete-python offers this functionality with this key combo:

Ctrl+Alt+G

with mouse cursor on the function call.

Is it valid to replace http:// with // in a <script src="http://...">?

A relative URL without a scheme (http: or https:) is valid, per RFC 3986: "Uniform Resource Identifier (URI): Generic Syntax", Section 4.2. If a client chokes on it, then it's the client's fault because they're not complying with the URI syntax specified in the RFC.

Your example is valid and should work. I've used that relative URL method myself on heavily trafficked sites and have had zero complaints. Also, we test our sites in Firefox, Safari, IE6, IE7 and Opera. These browsers all understand that URL format.

Run PHP Task Asynchronously

I've used the queuing approach, and it works well as you can defer that processing until your server load is idle, letting you manage your load quite effectively if you can partition off "tasks which aren't urgent" easily.

Rolling your own isn't too tricky, here's a few other options to check out:

  • GearMan - this answer was written in 2009, and since then GearMan looks a popular option, see comments below.
  • ActiveMQ if you want a full blown open source message queue.
  • ZeroMQ - this is a pretty cool socket library which makes it easy to write distributed code without having to worry too much about the socket programming itself. You could use it for message queuing on a single host - you would simply have your webapp push something to a queue that a continuously running console app would consume at the next suitable opportunity
  • beanstalkd - only found this one while writing this answer, but looks interesting
  • dropr is a PHP based message queue project, but hasn't been actively maintained since Sep 2010
  • php-enqueue is a recently (2017) maintained wrapper around a variety of queue systems
  • Finally, a blog post about using memcached for message queuing

Another, perhaps simpler, approach is to use ignore_user_abort - once you've sent the page to the user, you can do your final processing without fear of premature termination, though this does have the effect of appearing to prolong the page load from the user perspective.

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

C++ cout hex values?

C++20 std::format

This is now the cleanest method in my opinion, as it does not pollute std::cout state with std::hex:

main.cpp

#include <format>
#include <string>

int main() {
    std::cout << std::format("{:x} {:#x} {}\n", 16, 17, 18);
}

Expected output:

10 0x11 18

Not yet implemented on GCC 10.0.1, Ubuntu 20.04.

But the awesome library that became C++20 and should be the same worked once installed with:

git clone https://github.com/fmtlib/fmt
cd fmt
git checkout 061e364b25b5e5ca7cf50dd25282892922375ddc
mkdir build
cmake ..
sudo make install

main2.cpp

#include <fmt/core.h>
#include <iostream>

int main() {
    std::cout << fmt::format("{:x} {:#x} {}\n", 16, 17, 18);
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main2.out main2.cpp -lfmt
./main2.out

Documented at:

More info at: std::string formatting like sprintf

Pre-C++20: cleanly print and restore std::cout to previous state

main.cpp

#include <iostream>
#include <string>

int main() {
    std::ios oldState(nullptr);
    oldState.copyfmt(std::cout);
    std::cout << std::hex;
    std::cout << 16 << std::endl;
    std::cout.copyfmt(oldState);
    std::cout << 17 << std::endl;
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

Output:

10
17

More details: Restore the state of std::cout after manipulating it

Tested on GCC 10.0.1, Ubuntu 20.04.

Dealing with float precision in Javascript

Check out this link.. It helped me a lot.

http://www.w3schools.com/jsref/jsref_toprecision.asp

The toPrecision(no_of_digits_required) function returns a string so don't forget to use the parseFloat() function to convert to decimal point of required precision.

How do you build a Singleton in Dart?

I use this simple pattern on dart and previously on Swift. I like that it's terse and only one way of using it.

class Singleton {
  static Singleton shared = Singleton._init();
  Singleton._init() {
    // init work here
  }

  void doSomething() {
  }
}

Singleton.shared.doSomething();

What is "406-Not Acceptable Response" in HTTP?

406 Not Acceptable The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

406 happens when the server cannot respond with the accept-header specified in the request. In your case it seems application/json for the response may not be acceptable to the server.

Laravel Check If Related Model Exists

After Php 7.1, The accepted answer won't work for all types of relationships.

Because depending of type the relationship, Eloquent will return a Collection, a Model or Null. And in Php 7.1 count(null) will throw an error.

So, to check if the relation exist you can use:

For relationships single: For example hasOne and belongsTo

if(!is_null($model->relation)) {
   ....
}

For relationships multiple: For Example: hasMany and belongsToMany

if ($model->relation->isNotEmpty()) {
   ....
}

JQuery Datatables : Cannot read property 'aDataSort' of undefined

It's important that your THEAD not be empty in table.As dataTable requires you to specify the number of columns of the expected data . As per your data it should be

<table id="datatable">
    <thead>
        <tr>
            <th>Subscriber ID</th>
            <th>Install Location</th>
            <th>Subscriber Name</th>
            <th>some data</th>
        </tr>
    </thead>
</table>

Count number of occurrences by month

Recommend you use FREQUENCY rather than using COUNTIF.

In your front sheet; enter 01/04/2014 into E5, 01/05/2014 into E6 etc.

Select the range of adjacent cells you want to populate. Enter:

=FREQUENCY(2013!!$A$2:$A$50,'2013 Metrics'!E5:EN)

(where N is the final row reference in your range)

Hit Ctrl + Shift + Enter

Run a Docker image as a container

  • To list the Docker images

    $ docker images
    
  • If your application wants to run in with port 80, and you can expose a different port to bind locally, say 8080:

    $ docker run -d --restart=always -p 8080:80 image_name:version
    

Adding asterisk to required fields in Bootstrap 3

.form-group .required .control-label:after should probably be .form-group.required .control-label:after. The removal of the space between .form-group and .required is the change.

Connection Java-MySql : Public Key Retrieval is not allowed

The above error in my case was actually due to the wrong username and password. Solving the issue: 1. Go to the line DriverManager.getConnection("jdbc:mysql://localhost:3306/?useSSL=false", "username", "password"); The fields username and password might be wrong. Enter the username and password which you use to start your mysql client. The username is generally root and password is the string which you enter when a screen similar to this appears Startup screen of mysql

Note: The portname 3306 might be different in your case.

Changing datagridview cell color based on condition

Without looping it can be achived like below.

private void dgEvents_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {

        FormatRow(dgEvents.Rows[e.RowIndex]);

    }

private void FormatRow(DataGridViewRow myrow)
    {
        try
        {
            if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Error")
            {
                myrow.DefaultCellStyle.BackColor = Color.Red;
            }
            else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Warning")
            {
                myrow.DefaultCellStyle.BackColor = Color.Yellow;
            }
            else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Information")
            {
                myrow.DefaultCellStyle.BackColor = Color.LightGreen;
            }
        }
        catch (Exception exception)
        {
            onLogs?.Invoke(exception.Message, EventArgs.Empty);
        }
    }

The difference between Classes, Objects, and Instances

While the above answers are correct, another way of thinking about Classes and Objects would be to use real world examples: A class named Animal might contain objects like Cat, Dog or Fish. An object with a title of Bible would be of class Book, etc. Classes are general, objects are specific. This thought example helped me when I was learning Java.

Calling the base constructor in C#

Using newer C# features, namely out var, you can get rid of the static factory-method. I just found out (by accident) that out var parameter of methods called inse base-"call" flow to the constructor body.

Example, using this base class you want to derive from:

public abstract class BaseClass
{
    protected BaseClass(int a, int b, int c)
    {
    }
}

The non-compiling pseudo code you want to execute:

public class DerivedClass : BaseClass
{
    private readonly object fatData;

    public DerivedClass(int m)
    {
        var fd = new { A = 1 * m, B = 2 * m, C = 3 * m };
        base(fd.A, fd.B, fd.C); // base-constructor call
        this.fatData = fd;
    }
}

And the solution by using a static private helper method which produces all required base arguments (plus additional data if needed) and without using a static factory method, just plain constructor to the outside:

public class DerivedClass : BaseClass
{
    private readonly object fatData;

    public DerivedClass(int m)
        : base(PrepareBaseParameters(m, out var b, out var c, out var fatData), b, c)
    {
        this.fatData = fatData;
        Console.WriteLine(new { b, c, fatData }.ToString());
    }

    private static int PrepareBaseParameters(int m, out int b, out int c, out object fatData)
    {
        var fd = new { A = 1 * m, B = 2 * m, C = 3 * m };
        (b, c, fatData) = (fd.B, fd.C, fd); // Tuples not required but nice to use
        return fd.A;
    }
}

Pointer to a string in C?

The string is basically bounded from the place where it is pointed to (char *ptrChar;), to the null character (\0).

The char *ptrChar; actually points to the beginning of the string (char array), and thus that is the pointer to that string, so when you do like ptrChar[x] for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).

AES Encryption for an NSString on the iPhone

I waited a bit on @QuinnTaylor to update his answer, but since he didn't, here's the answer a bit more clearly and in a way that it will load on XCode7 (and perhaps greater). I used this in a Cocoa application, but it likely will work okay with an iOS application as well. Has no ARC errors.

Paste before any @implementation section in your AppDelegate.m or AppDelegate.mm file.

#import <CommonCrypto/CommonCryptor.h>

@implementation NSData (AES256)

- (NSData *)AES256EncryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or 
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                     keyPtr, kCCKeySizeAES256,
                                     NULL /* initialization vector (optional) */,
                                     [self bytes], dataLength, /* input */
                                     buffer, bufferSize, /* output */
                                     &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}

- (NSData *)AES256DecryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or 
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                     keyPtr, kCCKeySizeAES256,
                                     NULL /* initialization vector (optional) */,
                                     [self bytes], dataLength, /* input */
                                     buffer, bufferSize, /* output */
                                     &numBytesDecrypted);

    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}

@end

Paste these two functions in the @implementation class you desire. In my case, I chose @implementation AppDelegate in my AppDelegate.mm or AppDelegate.m file.

- (NSString *) encryptString:(NSString*)plaintext withKey:(NSString*)key {
    NSData *data = [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
    return [data base64EncodedStringWithOptions:kNilOptions];
}

- (NSString *) decryptString:(NSString *)ciphertext withKey:(NSString*)key {
    NSData *data = [[NSData alloc] initWithBase64EncodedString:ciphertext options:kNilOptions];
    return [[NSString alloc] initWithData:[data AES256DecryptWithKey:key] encoding:NSUTF8StringEncoding];
}

Write-back vs Write-Through caching?

Let's look at this with the help of an example. Suppose we have a direct mapped cache and the write back policy is used. So we have a valid bit, a dirty bit, a tag and a data field in a cache line. Suppose we have an operation : write A ( where A is mapped to the first line of the cache).

What happens is that the data(A) from the processor gets written to the first line of the cache. The valid bit and tag bits are set. The dirty bit is set to 1.

Dirty bit simply indicates was the cache line ever written since it was last brought into the cache!

Now suppose another operation is performed : read E(where E is also mapped to the first cache line)

Since we have direct mapped cache, the first line can simply be replaced by the E block which will be brought from memory. But since the block last written into the line (block A) is not yet written into the memory(indicated by the dirty bit), so the cache controller will first issue a write back to the memory to transfer the block A to memory, then it will replace the line with block E by issuing a read operation to the memory. dirty bit is now set to 0.

So write back policy doesnot guarantee that the block will be the same in memory and its associated cache line. However whenever the line is about to be replaced, a write back is performed at first.

A write through policy is just the opposite. According to this, the memory will always have a up-to-date data. That is, if the cache block is written, the memory will also be written accordingly. (no use of dirty bits)

Calculating Page Table Size

My explanation uses elementary building blocks that helped me to understand. Note I am leveraging @Deepak Goyal's answer above since he provided clarity:

We were given a logical 32-bit address space (i.e. We have a 32 bit computer)

Consider a system with a 32-bit logical address space

We were also told that

each page size is 4 KB

  • 1 KB (kilobyte) = 1 x 1024 bytes = 2^10 bytes
  • 4 x 1024 bytes = 2^2 x 2^10 bytes => 4 KB (i.e. 2^12 bytes)
  • The size of each page is thus 4 KB (Kilobytes NOT kilobits).

As Depaak said, we calculate the number of pages in the page table with this formula:

Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size 
Num_Pages_in_PgTable =         2^32                           /    2^12
Num_Pages_in_PgTable = 2^20 (i.e. 1 million) 

The authors go on to give the case where each entry in the page table takes 4 bytes. That means that the total size of the page table in physical memory will be 4MB:

Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable
Memory_Required_Per_Page =           4                 x     2^20
Memory_Required_Per_Page =     4 MB (Megabytes)

So yes, each process would require at least 4MB of memory to run, in increments of 4MB.

Example

Now if a professor wanted to make the question a bit more challenging than the explanation from the book, they might ask about a 64-bit computer. Let's say they want memory in bits. To solve the question, we'd follow the same process, only being sure to convert MB to Mbits.

Let's step through this example.

Givens:

  • Logical address space: 64-bit
  • Page Size: 4KB
  • Entry_Size_Per_Page: 4 bytes

Recall: A 64-bit entry can point to one of 2^64 physical page frames - Since Page size is 4 KB, then we still have 2^12 byte page sizes

  • 1 KB (kilobyte) = 1 x 1024 bytes = 2^10 bytes
  • Size of each page = 4 x 1024 bytes = 2^2 x 2^10 bytes = 2^12 bytes

How Many pages In Page Table?

`Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size 
Num_Pages_in_PgTable =         2^64                            /    2^12
Num_Pages_in_PgTable =         2^52 
Num_Pages_in_PgTable =      2^2 x 2^50 
Num_Pages_in_PgTable =       4  x 2^50 `  

How Much Memory in BITS Per Page?

Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable 
Memory_Required_Per_Page =   4 bytes x 8 bits/byte    x     2^52
Memory_Required_Per_Page =     32 bits                x   2^2 x 2^50
Memory_Required_Per_Page =     32 bits                x    4  x 2^50
Memory_Required_Per_Page =     128 Petabits

[2]: Operating System Concepts (9th Ed) - Gagne, Silberschatz, and Galvin

Android: How to Programmatically set the size of a Layout

LinearLayout YOUR_LinearLayout =(LinearLayout)findViewById(R.id.YOUR_LinearLayout)
    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                       /*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
               /*height*/ 100,
               /*weight*/ 1.0f
                );
                YOUR_LinearLayout.setLayoutParams(param);

Bootstrap center heading

Per your comments, to center all headings all you have to do is add text-align:center to all of them at the same time, like so:

CSS

    h1, h2, h3, h4, h5, h6 {
        text-align: center;
    }

Is it possible to use argsort in descending order?

If you negate an array, the lowest elements become the highest elements and vice-versa. Therefore, the indices of the n highest elements are:

(-avgDists).argsort()[:n]

Another way to reason about this, as mentioned in the comments, is to observe that the big elements are coming last in the argsort. So, you can read from the tail of the argsort to find the n highest elements:

avgDists.argsort()[::-1][:n]

Both methods are O(n log n) in time complexity, because the argsort call is the dominant term here. But the second approach has a nice advantage: it replaces an O(n) negation of the array with an O(1) slice. If you're working with small arrays inside loops then you may get some performance gains from avoiding that negation, and if you're working with huge arrays then you can save on memory usage because the negation creates a copy of the entire array.

Note that these methods do not always give equivalent results: if a stable sort implementation is requested to argsort, e.g. by passing the keyword argument kind='mergesort', then the first strategy will preserve the sorting stability, but the second strategy will break stability (i.e. the positions of equal items will get reversed).

Example timings:

Using a small array of 100 floats and a length 30 tail, the view method was about 15% faster

>>> avgDists = np.random.rand(100)
>>> n = 30
>>> timeit (-avgDists).argsort()[:n]
1.93 µs ± 6.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit avgDists.argsort()[::-1][:n]
1.64 µs ± 3.39 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit avgDists.argsort()[-n:][::-1]
1.64 µs ± 3.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

For larger arrays, the argsort is dominant and there is no significant timing difference

>>> avgDists = np.random.rand(1000)
>>> n = 300
>>> timeit (-avgDists).argsort()[:n]
21.9 µs ± 51.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit avgDists.argsort()[::-1][:n]
21.7 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit avgDists.argsort()[-n:][::-1]
21.9 µs ± 37.1 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Please note that the comment from nedim below is incorrect. Whether to truncate before or after reversing makes no difference in efficiency, since both of these operations are only striding a view of the array differently and not actually copying data.

Bootstrap fullscreen layout with 100% height

_x000D_
_x000D_
<section class="min-vh-100 d-flex align-items-center justify-content-center py-3">
  <div class="container">
    <div class="row justify-content-between align-items-center">
    x
    x
    x
    </div>
  </div>
</section>
_x000D_
_x000D_
_x000D_

Downloading MySQL dump from command line

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%.%MM%.%DD%.%HH%.%Min%.%Sec%"
set drive=your backup folder
set databaseName=your databasename
set user="your database user"
set password="your database password"
subst Z: "C:\Program Files\7-Zip" 
subst M: "D:\AppServ\MySQL\bin"
set zipFile="%drive%\%databaseName%-%datestamp%.zip"
set sqlFile="%drive%\%databaseName%-%datestamp%.sql"
M:\mysqldump.exe --user=%user% --password=%password% --result-file="%sqlFile%" --databases %databaseName%
@echo Mysql Backup Created
Z:\7z.exe a -tzip "%zipFile%" "%sqlFile%"
@echo File Compress End
del %sqlFile%
@echo Delete mysql file
pause;

Why is this jQuery click function not working?

You can use $(function(){ // code }); which is executed when the document is ready to execute the code inside that block.

$(function(){
    $('#clicker').click(function(){
        alert('hey');
        $('.hide_div').hide();
    });
});

how to use JSON.stringify and json_decode() properly

When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.

json_decode( html_entity_decode( stripslashes ($jsonString ) ) );

Thanks to @Thisguyhastwothumbs

How do I tell Python to convert integers into words

The inflect package can do this.

https://pypi.python.org/pypi/inflect

$ pip install inflect

and then:

>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(99)
ninety-nine

Using Mockito's generic "any()" method

Since Java 8 you can use the argument-less any method and the type argument will get inferred by the compiler:

verify(bar).doStuff(any());

Explanation

The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).

In this case the parameter type of doStuff will be the target type for any(), and the return value type of any() will get chosen to match that argument type.

This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.


Primitive types

This doesn't work with primitive types, unfortunately:

public interface IBar {
    void doPrimitiveStuff(int i);
}

verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead

The problem is that the compiler will infer Integer as the return value type of any(). Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null. The runtime will try to unbox the return value by calling the intValue method on it before passing it to doStuff, and the exception gets thrown.

Android: keep Service running when app is killed

All the answers seem correct so I'll go ahead and give a complete answer here.

Firstly, the easiest way to do what you are trying to do is launch a Broadcast in Android when the app is killed manually, and define a custom BroadcastReceiver to trigger a service restart following that.

Now lets jump into code.


Create your Service in YourService.java

Note the onCreate() method, where we are starting a foreground service differently for Build versions greater than Android Oreo. This because of the strict notification policies introduced recently where we have to define our own notification channel to display them correctly.

The this.sendBroadcast(broadcastIntent); in the onDestroy() method is the statement which asynchronously sends a broadcast with the action name "restartservice". We'll be using this later as a trigger to restart our service.

Here we have defined a simple Timer task, which prints a counter value every 1 second in the Log while incrementing itself every time it prints.

public class YourService extends Service {
public int counter=0;

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
            startMyOwnForeground();
        else
            startForeground(1, new Notification());
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void startMyOwnForeground()
    {
        String NOTIFICATION_CHANNEL_ID = "example.permanence";
        String channelName = "Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        startTimer();
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stoptimertask();

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, Restarter.class);
        this.sendBroadcast(broadcastIntent);
    }



    private Timer timer;
    private TimerTask timerTask;
    public void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            public void run() {
                Log.i("Count", "=========  "+ (counter++));
            }
        };
        timer.schedule(timerTask, 1000, 1000); //
    }

    public void stoptimertask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Create a Broadcast Receiver to respond to your custom defined broadcasts in Restarter.java

The broadcast with the action name "restartservice" which you just defined in YourService.java is now supposed to trigger a method which will restart your service. This is done using BroadcastReceiver in Android.

We override the built-in onRecieve() method in BroadcastReceiver to add the statement which will restart the service. The startService() will not work as intended in and above Android Oreo 8.1, as strict background policies will soon terminate the service after restart once the app is killed. Therefore we use the startForegroundService() for higher versions and show a continuous notification to keep the service running.

public class Restarter extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Broadcast Listened", "Service tried to stop");
        Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context, YourService.class));
        } else {
            context.startService(new Intent(context, YourService.class));
        }
    }
}

Define your MainActivity.java to call the service on app start.

Here we define a separate isMyServiceRunning() method to check the current status of the background service. If the service is not running, we start it by using startService().

Since the app is already running in foreground, we need not launch the service as a foreground service to prevent itself from being terminated.

Note that in onDestroy() we are dedicatedly calling stopService(), so that our overridden method gets invoked. If this was not done, then the service would have ended automatically after app is killed without invoking our modified onDestroy() method in YourService.java

public class MainActivity extends AppCompatActivity {
    Intent mServiceIntent;
    private YourService mYourService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mYourService = new YourService();
        mServiceIntent = new Intent(this, mYourService.getClass());
        if (!isMyServiceRunning(mYourService.getClass())) {
            startService(mServiceIntent);
        }
    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                Log.i ("Service status", "Running");
                return true;
            }
        }
        Log.i ("Service status", "Not running");
        return false;
    }


    @Override
    protected void onDestroy() {
        //stopService(mServiceIntent);
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, Restarter.class);
        this.sendBroadcast(broadcastIntent);
        super.onDestroy();
    }
}

Finally register them in your AndroidManifest.xml

All of the above three classes need to be separately registered in AndroidManifest.xml.

Note that we define an intent-filter with the action name as "restartservice" where the Restarter.java is registered as a receiver. This ensures that our custom BroadcastReciever is called whenever the system encounters a broadcast with the given action name.

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <receiver
        android:name="Restarter"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="restartservice" />
        </intent-filter>
    </receiver>

    <activity android:name="MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="YourService"
        android:enabled="true" >
    </service>
</application>

This should now restart your service again if the app was killed from the task-manager. This service will keep on running in background as long as the user doesn't Force Stop the app from Application Settings.

UPDATE: Kudos to Dr.jacky for pointing it out. The above mentioned way will only work if the onDestroy() of the service is called, which might not be the case certain times, which I was unaware of. Thanks.

Imitating a blink tag with CSS3 animations

Another variation

_x000D_
_x000D_
.blink {_x000D_
    -webkit-animation: blink 1s step-end infinite;_x000D_
            animation: blink 1s step-end infinite;_x000D_
}_x000D_
@-webkit-keyframes blink { 50% { visibility: hidden; }}_x000D_
        @keyframes blink { 50% { visibility: hidden; }}
_x000D_
This is <span class="blink">blink</span>
_x000D_
_x000D_
_x000D_

Oracle SQL Developer spool output?

Another way simpler than me has worked with SQL Developer 4 in Windows 7

spool "path_to_file\\filename.txt"
query to execute
spool of

You have to execute it as a script, because if not only the query will be saved in the output file In the path name I use the double character "\" as a separator when working with Windows and SQL, The output file will display the query and the result.

How to draw a checkmark / tick using CSS?

Try this // html example

<span>&#10003;</span>

// css example

span {
  content: "\2713";
}

LINQ query to select top five

[Offering a somewhat more descriptive answer than the answer provided by @Ajni.]

This can also be achieved using LINQ fluent syntax:

var list = ctn.Items
    .Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
    .OrderBy(t => t.Delivery.SubmissionDate)
    .Take(5);

Note that each method (Where, OrderBy, Take) that appears in this LINQ statement takes a lambda expression as an argument. Also note that the documentation for Enumerable.Take begins with:

Returns a specified number of contiguous elements from the start of a sequence.

Switch android x86 screen resolution

In VirtualBox you should add custom resolution via the command:

VBoxManage setextradata "VM name" "CustomVideoMode1" "800x480x16"

instead of editing a .vbox file.

This solution works fine for me!

DataTable, How to conditionally delete rows

Here's a one-liner using LINQ and avoiding any run-time evaluation of select strings:

someDataTable.Rows.Cast<DataRow>().Where(
    r => r.ItemArray[0] == someValue).ToList().ForEach(r => r.Delete());

What is the Regular Expression For "Not Whitespace and Not a hyphen"

[^\s-]

should work and so will

[^-\s]
  • [] : The char class
  • ^ : Inside the char class ^ is the negator when it appears in the beginning.
  • \s : short for a white space
  • - : a literal hyphen. A hyphen is a meta char inside a char class but not when it appears in the beginning or at the end.

Laravel 5.1 - Checking a Database Connection

Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!

// Test database connection
try {
    DB::connection()->getPdo();
} catch (\Exception $e) {
    die("Could not connect to the database.  Please check your configuration. error:" . $e );
}

How to copy files from 'assets' folder to sdcard?

Slight modification of above answer to copy a folder recursively and to accommodate custom destination.

public void copyFileOrDir(String path, String destinationDir) {
    AssetManager assetManager = this.getAssets();
    String assets[] = null;
    try {
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(path,destinationDir);
        } else {
            String fullPath = destinationDir + "/" + path;
            File dir = new File(fullPath);
            if (!dir.exists())
                dir.mkdir();
            for (int i = 0; i < assets.length; ++i) {
                copyFileOrDir(path + "/" + assets[i], destinationDir + path + "/" + assets[i]);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
}

private void copyFile(String filename, String destinationDir) {
    AssetManager assetManager = this.getAssets();
    String newFileName = destinationDir + "/" + filename;

    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open(filename);
        out = new FileOutputStream(newFileName);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
    new File(newFileName).setExecutable(true, false);
}

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

This issue can happen not only in but also in any of the .

On systems, in my case, this issue arose when the shift and insert key was pressed in tandem unintentionally which takes the user to the overwrite mode.

To get back to insert mode you need to press shift and insert in tandem again.

Set a Fixed div to 100% width of the parent container

Remove Padding: 10%; or use px instead of percent for .wrap

see the example : http://jsfiddle.net/C93mk/493/

HTML :

<div id="wrapper">
    <div id="wrap">
    Some relative item placed item
    <div id="fixed"></div>
    </div>
</div>

CSS:

body{ height:20000px }
#wrapper {padding:10%;}
#wrap{ 
    float: left;
    position: relative;
    width: 200px; 
    background:#ccc; 
}
#fixed{ 
    position:fixed;
    width:inherit;
    padding:0px;
    height:10px;
    background-color:#333;

}

Return anonymous type results?

You could do something like this:


public System.Collections.IEnumerable GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result.ToList();
}

What does "-ne" mean in bash?

"not equal" So in this case, $RESULT is tested to not be equal to zero.

However, the test is done numerically, not alphabetically:

n1 -ne n2     True if the integers n1 and n2 are not algebraically equal.

compared to:

s1 != s2      True if the strings s1 and s2 are not identical.

How to add form validation pattern in Angular 2?

You could build your form using FormBuilder as it let you more flexible way to configure form.

export class MyComp {
  form: ControlGroup;

  constructor(@Inject()fb: FormBuilder) {  
    this.form = fb.group({  
      foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]  
    });  
  }

Then in your template :

<input type="text" ngControl="foo" />
<div *ngIf="!form.foo.valid">Please correct foo entry !</div> 

You can also customize ng-invalid CSS class.

As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.

export class MyValidators {
  static regex(pattern: string): Function {
    return (control: Control): {[key: string]: any} => {
      return control.value.match(pattern) ? null : {pattern: true};
    };
  }
}

Hope that it help you.

ssh remote host identification has changed

My solution is:

  1. vi ~/.ssh/known_hosts
  2. delete the line that contains your want connected ip.

This is better than delete all of the known_hosts

How to add days to the current date?

From the SQL Server 2017 official documentation:

SELECT DATEADD(day, 360, GETDATE());

If you would like to remove the time part of the GETDATE function, you can do:

SELECT DATEADD(day, 360, CAST(GETDATE() AS DATE));

Facebook API: Get fans of / people who like a page

Facebook's FQL documentation here tells you how to do it. Run the example SELECT name, fan_count FROM page WHERE page_id = 19292868552 and replace the page_id number with your page's id number and it will return the page name and the fan count.

Retrieving a List from a java.util.stream.Stream in Java 8

I like to use a util method that returns a collector for ArrayList when that is what I want.

I think the solution using Collectors.toCollection(ArrayList::new) is a little too noisy for such a common operation.

Example:

ArrayList<Long> result = sourceLongList.stream()
    .filter(l -> l > 100)
    .collect(toArrayList());

public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
    return Collectors.toCollection(ArrayList::new);
}

With this answer I also want to demonstrate how simple it is to create and use custom collectors, which is very useful generally.

How may I reference the script tag that loaded the currently-executing script?

Script are executed sequentially only if they do not have either a "defer" or an "async" attribute. Knowing one of the possible ID/SRC/TITLE attributes of the script tag could work also in those cases. So both Greg and Justin suggestions are correct.

There is already a proposal for a document.currentScript on the WHATWG lists.

EDIT: Firefox > 4 already implement this very useful property but it is not available in IE11 last I checked and only available in Chrome 29 and Safari 8.

EDIT: Nobody mentioned the "document.scripts" collection but I believe that the following may be a good cross browser alternative to get the currently running script:

var me = document.scripts[document.scripts.length -1];

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

I like the Hola Soy method of not using gettimeofday(). It happened to me on a running server the admin changed the timezone. The clock was updated to show the same (correct) local value. This caused the function time() and gettimeofday() to shift 2 hours and all timestamps in some services got stuck.

How can I get the session object if I have the entity-manager?

'entityManager.unwrap(Session.class)' is used to get session from EntityManager.

@Repository
@Transactional
public class EmployeeRepository {

  @PersistenceContext
  private EntityManager entityManager;

  public Session getSession() {
    Session session = entityManager.unwrap(Session.class);
    return session;
  }

  ......
  ......

}

Demo Application link.

How can I create tests in Android Studio?

As of Android Studio 1.1, we've got official (experimental) support for writing Unit Tests (Roboelectric works as well).

Source: https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support

Entity Framework change connection at runtime

A bit late on this answer but I think there's a potential way to do this with a neat little extension method. We can take advantage of the EF convention over configuration plus a few little framework calls.

Anyway, the commented code and example usage:

extension method class:

public static class ConnectionTools
{
    // all params are optional
    public static void ChangeDatabase(
        this DbContext source,
        string initialCatalog = "",
        string dataSource = "",
        string userId = "",
        string password = "",
        bool integratedSecuity = true,
        string configConnectionStringName = "") 
        /* this would be used if the
        *  connectionString name varied from 
        *  the base EF class name */
    {
        try
        {
            // use the const name if it's not null, otherwise
            // using the convention of connection string = EF contextname
            // grab the type name and we're done
            var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
                ? source.GetType().Name 
                : configConnectionStringName;

            // add a reference to System.Configuration
            var entityCnxStringBuilder = new EntityConnectionStringBuilder
                (System.Configuration.ConfigurationManager
                    .ConnectionStrings[configNameEf].ConnectionString);

            // init the sqlbuilder with the full EF connectionstring cargo
            var sqlCnxStringBuilder = new SqlConnectionStringBuilder
                (entityCnxStringBuilder.ProviderConnectionString);

            // only populate parameters with values if added
            if (!string.IsNullOrEmpty(initialCatalog))
                sqlCnxStringBuilder.InitialCatalog = initialCatalog;
            if (!string.IsNullOrEmpty(dataSource))
                sqlCnxStringBuilder.DataSource = dataSource;
            if (!string.IsNullOrEmpty(userId))
                sqlCnxStringBuilder.UserID = userId;
            if (!string.IsNullOrEmpty(password))
                sqlCnxStringBuilder.Password = password;

            // set the integrated security status
            sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;

            // now flip the properties that were changed
            source.Database.Connection.ConnectionString 
                = sqlCnxStringBuilder.ConnectionString;
        }
        catch (Exception ex)
        {
            // set log item if required
        }
    }
}

basic usage:

// assumes a connectionString name in .config of MyDbEntities
var selectedDb = new MyDbEntities();
// so only reference the changed properties
// using the object parameters by name
selectedDb.ChangeDatabase
    (
        initialCatalog: "name-of-another-initialcatalog",
        userId: "jackthelady",
        password: "nomoresecrets",
        dataSource: @".\sqlexpress" // could be ip address 120.273.435.167 etc
    );

I know you already have the basic functionality in place, but thought this would add a little diversity.

How to disable anchor "jump" when loading a page?

Solved my promlem by doing this:

// navbar height 
var navHeigth = $('nav.navbar').height();    

// Scroll to anchor function
var scrollToAnchor = function(hash) {
  // If got a hash
  if (hash) {
    // Scroll to the top (prevention for Chrome)
    window.scrollTo(0, 0);
    // Anchor element
    var term = $(hash);

    // If element with hash id is defined
    if (term) {

      // Get top offset, including header height
      var scrollto = term.offset().top - navHeigth;

      // Capture id value
      var id = term.attr('id');
      // Capture name value
      var name = term.attr('name');

      // Remove attributes for FF scroll prevention
      term.removeAttr('id').removeAttr('name');
      // Scroll to element
      $('html, body').animate({scrollTop:scrollto}, 0);

      // Returning id and name after .5sec for the next scroll
      setTimeout(function() {
        term.attr('id', id).attr('name', name);
      }, 500);
    }
  }
};

// if we are opening the page by url
if (location.hash) {
  scrollToAnchor(location.hash);
}

// preventing default click on links with an anchor
$('a[href*="#"]').click(function(e) {
  e.preventDefault();
  // hash value
  var hash = this.href.substr(this.href.indexOf("#"));
  scrollToAnchor(hash);
});`

Finding the number of days between two dates

Easiest way to find the days difference between two dates

$date1 = strtotime("2019-05-25"); 
$date2 = strtotime("2010-06-23");

$date_difference = $date2 - $date1;

$result =  round( $date_difference / (60 * 60 * 24) );

echo $result;

Facebook how to check if user has liked page and show content?

With Javascript SDK, you can change the code as below, this should be added after FB.init call.

     // Additional initialization code such as adding Event Listeners goes here
FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {
        // the user is logged in and has authenticated your
        // app, and response.authResponse supplies
        // the user's ID, a valid access token, a signed
        // request, and the time the access token 
        // and signed request each expire
        var uid = response.authResponse.userID;
        var accessToken = response.authResponse.accessToken;
        alert('we are fine');
      } else if (response.status === 'not_authorized') {
        // the user is logged in to Facebook, 
        // but has not authenticated your app
        alert('please like us');
         $("#container_notlike").show();
      } else {
        // the user isn't logged in to Facebook.
        alert('please login');
      }
     });

FB.Event.subscribe('edge.create',
function(response) {
    alert('You liked the URL: ' + response);
      $("#container_like").show();
}

Making a DateTime field in a database automatic?

Just right click on that column and select properties and write getdate()in Default value or binding.like image:

enter image description here

If you want do it in CodeFirst in EF you should add this attributes befor of your column definition:

[Databasegenerated(Databaseoption.computed)]

this attributes can found in System.ComponentModel.Dataannotion.Schema.

In my opinion first one is better:))

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You want to simulate n-nested for loops.

Iterating through n-dimmensional array can be seen as increasing the n-digit number.

At each dimmension we have as many digits as the lenght of the dimmension.

Example:

Suppose we had array(matrix)

int[][][] T=new int[3][4][5];

in "for notation" we have:

for(int x=0;x<3;x++)
   for(int y=0;y<4;y++)
       for(int z=0;z<5;z++)
          T[x][y][z]=...

to simulate this you would have to use the "n-digit number notation"

We have 3 digit number, with 3 digits for first, 4 for second and five for third digit

We have to increase the number, so we would get the sequence

0 0 0
0 0 1
0 0 2    
0 0 3
0 0 4
0 1 0
0 1 1
0 1 2
0 1 3
0 1 4
0 2 0
0 2 1
0 2 2
0 2 3
0 2 4
0 3 0
0 3 1
0 3 2
0 3 3
0 3 4
and so on

So you can write the code for increasing such n-digit number. You can do it in such way that you can start with any value of the number and increase/decrease the digits by any numbers. That way you can simulate nested for loops that begin somewhere in the table and finish not at the end.

This is not an easy task though. I can't help with the matlab notation unfortunaly.