Programs & Examples On #Regex

Regular expressions provide a declarative language to match patterns within strings. They are commonly used for string validation, parsing, and transformation. Since regular expressions are not fully standardized, all questions with this tag should also include a tag specifying the applicable programming language or tool. NOTE: Asking for HTML, JSON, etc. regexes tends to be met with negative reactions. If there is a parser for it, use that instead.

Can't escape the backslash with regex?

From http://www.regular-expressions.info/charclass.html :

Note that the only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (\\), the caret (^) and the hyphen (-). The usual metacharacters are normal characters inside a character class, and do not need to be escaped by a backslash. To search for a star or plus, use [+*]. Your regex will work fine if you escape the regular metacharacters inside a character class, but doing so significantly reduces readability.

To include a backslash as a character without any special meaning inside a character class, you have to escape it with another backslash. [\\x] matches a backslash or an x. The closing bracket (]), the caret (^) and the hyphen (-) can be included by escaping them with a backslash, or by placing them in a position where they do not take on their special meaning. I recommend the latter method, since it improves readability. To include a caret, place it anywhere except right after the opening bracket. [x^] matches an x or a caret. You can put the closing bracket right after the opening bracket, or the negating caret. []x] matches a closing bracket or an x. [^]x] matches any character that is not a closing bracket or an x. The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret. Both [-x] and [x-] match an x or a hyphen.

What language are you writing the regex in?

Java string split with "." (dot)

You need to escape the dot if you want to split on a literal dot:

String extensionRemoved = filename.split("\\.")[0];

Otherwise you are splitting on the regex ., which means "any character".
Note the double backslash needed to create a single backslash in the regex.


You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.

To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled:

".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]

ie, when filename is just a dot ".", calling filename.split("\\.", -1)[0] will return a blank, but calling filename.split("\\.")[0] will throw an ArrayIndexOutOfBoundsException.

C++: what regex library should I use?

C++ has a builtin regex library since TR1. AFAIK Boost's regex library is very compatible with it and can be used as a replacement, if your standard library doesn't provide TR1.

Email address validation in C# MVC 4 application: with or without using Regex

It is surprising the question of validating an email address continually comes up on SO!

You can find one often-mentioned practical solution here: How to Find or Validate an Email Address.

Excerpt:

The virtue of my regular expression above is that it matches 99% of the email addresses in use today. All the email address it matches can be handled by 99% of all email software out there. If you're looking for a quick solution, you only need to read the next paragraph. If you want to know all the trade-offs and get plenty of alternatives to choose from, read on.

See this answer on SO for a discussion of the merits of the article at the above link. In particular, the comment dated 2012-04-17 reads:

To all the complainers: after 3 hours experimenting all the solutions offered in this gigantic discussion, this is THE ONLY good java regex solution I can find. None of the rfc5322 stuff works on java regex.

How to use regex in String.contains() method in Java

You can simply use matches method of String class.

boolean result = someString.matches("stores.*store.*product.*");

Regular expression to match standard 10 digit phone number

This code will match a US or Canadian phone number, and will also make sure that it is a valid area code and exchange:

^((\+1)?[\s-]?)?\(?[2-9]\d\d\)?[\s-]?[2-9]\d\d[\s-]?\d\d\d\d

Test on Regex101.com

Escaping special characters in Java Regular Expressions

Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?

If you are looking for a way to create constants that you can use in your regex patterns, then just prepending them with "\\" should work but there is no nice Pattern.escape('.') function to help with this.

So if you are trying to match "\\d" (the string \d instead of a decimal character) then you would do:

// this will match on \d as opposed to a decimal character
String matchBackslashD = "\\\\d";
// as opposed to
String matchDecimalDigit = "\\d";

The 4 slashes in the Java string turn into 2 slashes in the regex pattern. 2 backslashes in a regex pattern matches the backslash itself. Prepending any special character with backslash turns it into a normal character instead of a special one.

matchPeriod = "\\.";
matchPlus = "\\+";
matchParens = "\\(\\)";
... 

In your post you use the Pattern.quote(string) method. This method wraps your pattern between "\\Q" and "\\E" so you can match a string even if it happens to have a special regex character in it (+, ., \\d, etc.)

How to remove all whitespace from a string?

Use [[:blank:]] to match any kind of horizontal white_space characters.

gsub("[[:blank:]]", "", " xx yy 11 22  33 ")
# [1] "xxyy112233"

Minimum 6 characters regex expression

Something along the lines of this?

<asp:TextBox id="txtUsername" runat="server" />

<asp:RegularExpressionValidator
    id="RegularExpressionValidator1"
    runat="server"
    ErrorMessage="Field not valid!"
    ControlToValidate="txtUsername"
    ValidationExpression="[0-9a-zA-Z]{6,}" />

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

Regular expression \p{L} and \p{N}

\p{L} matches a single code point in the category "letter".
\p{N} matches any kind of numeric character in any script.

Source: regular-expressions.info

If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.

Regex to match URL end-of-line or "/" character

/(.+)/(\d{4}-\d{2}-\d{2})-(\d+)(/.*)?$

1st Capturing Group (.+)

.+ matches any character (except for line terminators)

  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Capturing Group (\d{4}-\d{2}-\d{2})

\d{4} matches a digit (equal to [0-9])

  • {4} Quantifier — Matches exactly 4 times

- matches the character - literally (case sensitive)

\d{2} matches a digit (equal to [0-9])

  • {2} Quantifier — Matches exactly 2 times

- matches the character - literally (case sensitive)

\d{2} matches a digit (equal to [0-9])

  • {2} Quantifier — Matches exactly 2 times

- matches the character - literally (case sensitive)

3rd Capturing Group (\d+)

\d+ matches a digit (equal to [0-9])

  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

4th Capturing Group (.*)?

? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)

.* matches any character (except for line terminators)

  • * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

$ asserts position at the end of the string

Javascript replace with reference to matched group?

You can use replace instead of gsub.

"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")

How to escape comma and double quote at same time for CSV file?

Excel has to be able to handle the exact same situation.

Put those things into Excel, save them as CSV, and examine the file with a text editor. Then you'll know the rules Excel is applying to these situations.

Make Java produce the same output.

The formats used by Excel are published, by the way...

****Edit 1:**** Here's what Excel does
****Edit 2:**** Note that php's fputcsv does the same exact thing as excel if you use " as the enclosure.

[email protected]
Richard
"This is what I think"

gets transformed into this:

Email,Fname,Quoted  
[email protected],Richard,"""This is what I think"""

How to replace captured groups only?

A solution is to add captures for the preceding and following text:

str.replace(/(.*name="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3")

RegEx to parse or validate Base64 data

Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com line. In Perl, say, something like

my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;

say decode_base64($sanitized_str);

might be what you want. It produces

This is simple ASCII Base64 for StackOverflow exmaple.

6 digits regular expression

\b\d{1,6}\b

Explanation

\b    # word boundary - start
\d    # any digits between 0 to 9 (inclusive)
{1,6} # length - min 1 digit or max 6 digits
\b    # word boundary - end

How do I extract text that lies between parentheses (round brackets)?

Use a Regular Expression:

string test = "(test)"; 
string word = Regex.Match(test, @"\((\w+)\)").Groups[1].Value;
Console.WriteLine(word);

Remove part of string after "."

You just need to escape the period:

a <- c("NM_020506.1","NM_020519.1","NM_001030297.2","NM_010281.2","NM_011419.3", "NM_053155.2")

gsub("\\..*","",a)
[1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155" 

How to remove special characters from a string?

If you just want to do a literal replace in java, use Pattern.quote(string) to escape any string to a literal.

myString.replaceAll(Pattern.quote(matchingStr), replacementStr)

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

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

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

Out[17]: 0.8106249139964348

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

Out[18]: 0.9240323599951807

Never use regexps if you can avoid them.

javascript regex : only english letters allowed

Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.

var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"

Here's a DEMO on how this regex works with test() and match().

How do I make case-insensitive queries on Mongodb?

To find case-insensitive literals string:

Using regex (recommended)

db.collection.find({
    name: {
        $regex: new RegExp('^' + name.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '$', 'i')
    }
});

Using lower-case index (faster)

db.collection.find({
    name_lower: name.toLowerCase()
});

Regular expressions are slower than literal string matching. However, an additional lowercase field will increase your code complexity. When in doubt, use regular expressions. I would suggest to only use an explicitly lower-case field if it can replace your field, that is, you don't care about the case in the first place.

Note that you will need to escape the name prior to regex. If you want user-input wildcards, prefer appending .replace(/%/g, '.*') after escaping so that you can match "a%" to find all names starting with 'a'.

HTML5 Form Input Pattern Currency Format

Use this pattern "^\d*(\.\d{2}$)?"

Number of regex matches

If you know you will want all the matches, you could use the re.findall function. It will return a list of all the matches. Then you can just do len(result) for the number of matches.

Is there a RegExp.escape function in JavaScript?

There is an ES7 proposal for RegExp.escape at https://github.com/benjamingr/RexExp.escape/, with a polyfill available at https://github.com/ljharb/regexp.escape.

An example based on the rejected ES proposal, includes checks if the property already exists, in the case that TC39 backtracks on their decision.


Code:

if (!Object.prototype.hasOwnProperty.call(RegExp, 'escape')) {
  RegExp.escape = function(string) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
    // https://github.com/benjamingr/RegExp.escape/issues/37
    return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  };
}

Code Minified:

Object.prototype.hasOwnProperty.call(RegExp,"escape")||(RegExp.escape=function(e){return e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")});

// ...
var assert = require('assert');
 
var str = 'hello. how are you?';
var regex = new RegExp(RegExp.escape(str), 'g');
assert.equal(String(regex), '/hello\. how are you\?/g');

There is also an npm module at: https://www.npmjs.com/package/regexp.escape


One can install this and use it as so:


npm install regexp.escape

or

yarn add regexp.escape

var escape = require('regexp.escape');
var assert = require('assert');
 
var str = 'hello. how are you?';
var regex = new RegExp(escape(str), 'g');
assert.equal(String(regex), '/hello\. how are you\?/g');

In the GitHub && NPM page are descriptions of how to use the shim/polyfill for this option, as well. That logic is based on return RegExp.escape || implementation;, where implementation contains the regexp used above.


The NPM module is an extra dependency, but it also make it easier for an external contributor to identify logical parts added to the code. ¯\(?)

Extract substring using regexp in plain bash

    echo "US/Central - 10:26 PM (CST)" | sed -n "s/^.*-\s*\(\S*\).*$/\1/p"

-n      suppress printing
s       substitute
^.*     anything at the beginning
-       up until the dash
\s*     any space characters (any whitespace character)
\(      start capture group
\S*     any non-space characters
\)      end capture group
.*$     anything at the end
\1      substitute 1st capture group for everything on line
p       print it

Remove insignificant trailing zeros from a number?

I needed to solve this problem too when Django was displaying Decimal type values in a text field. E.g. when '1' was the value. It would show '1.00000000'. If '1.23' was the value, it would show '1.23000000' (In the case of a 'decimal_places' setting of 8)

Using parseFloat was not an option for me since it is possible it does not return the exact same value. toFixed was not an option since I did not want to round anything, so I created a function:

function removeTrailingZeros(value) {
    value = value.toString();

    # if not containing a dot, we do not need to do anything
    if (value.indexOf('.') === -1) {
        return value;
    }

    # as long as the last character is a 0 or a dot, remove it
    while((value.slice(-1) === '0' || value.slice(-1) === '.') && value.indexOf('.') !== -1) {
        value = value.substr(0, value.length - 1);
    }
    return value;
}

How to use a variable inside a regular expression?

I agree with all the above unless:

sys.argv[1] was something like Chicken\d{2}-\d{2}An\s*important\s*anchor

sys.argv[1] = "Chicken\d{2}-\d{2}An\s*important\s*anchor"

you would not want to use re.escape, because in that case you would like it to behave like a regex

TEXTO = sys.argv[1]

if re.search(r"\b(?<=\w)" + TEXTO + "\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

Regex to check if valid URL that ends in .jpg, .png, or .gif

Reference: See DecodeConfig section on the official go lang image lib docs here

I believe you could also use DecodeConfig to get the format of an image which you could then validate against const types like jpeg, png, jpg and gif ie

import (
  "encoding/base64"
  "fmt"
  "image"
  "log"
  "strings"
  "net/http"

  // Package image/jpeg is not used explicitly in the code below,
  // but is imported for its initialization side-effect, which allows
  // image.Decode to understand JPEG formatted images. Uncomment these
  // two lines to also understand GIF and PNG images:
  // _ "image/gif"
  // _ "image/png"
  _ "image/jpeg"
   )

func main() {
  resp, err := http.Get("http://i.imgur.com/Peq1U1u.jpg")
  if err != nil {
      log.Fatal(err)
  }
  defer resp.Body.Close()
  data, _, err := image.Decode(resp.Body)
  if err != nil {
      log.Fatal(err)
  }
  reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
  config, format, err := image.DecodeConfig(reader)
  if err != nil {
      log.Fatal(err)
  }
  fmt.Println("Width:", config.Width, "Height:", config.Height, "Format:", format)
}

format here is a string that states the file format eg jpg, png etc

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

Regular expression matching a multiline block of text

Try this:

re.compile(r"^(.+)\n((?:\n.+)+)", re.MULTILINE)

I think your biggest problem is that you're expecting the ^ and $ anchors to match linefeeds, but they don't. In multiline mode, ^ matches the position immediately following a newline and $ matches the position immediately preceding a newline.

Be aware, too, that a newline can consist of a linefeed (\n), a carriage-return (\r), or a carriage-return+linefeed (\r\n). If you aren't certain that your target text uses only linefeeds, you should use this more inclusive version of the regex:

re.compile(r"^(.+)(?:\n|\r\n?)((?:(?:\n|\r\n?).+)+)", re.MULTILINE)

BTW, you don't want to use the DOTALL modifier here; you're relying on the fact that the dot matches everything except newlines.

remove all special characters in java

You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W you will not replace underscores.

Scanner scan = new Scanner(System.in);

while(scan.hasNextLine()){
    System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}

Regular expression to match any character being repeated more than 10 times

The regex you need is /(.)\1{9,}/.

Test:

#!perl
use warnings;
use strict;
my $regex = qr/(.)\1{9,}/;
print "NO" if "abcdefghijklmno" =~ $regex;
print "YES" if "------------------------" =~ $regex;
print "YES" if "========================" =~ $regex;

Here the \1 is called a backreference. It references what is captured by the dot . between the brackets (.) and then the {9,} asks for nine or more of the same character. Thus this matches ten or more of any single character.

Although the above test script is in Perl, this is very standard regex syntax and should work in any language. In some variants you might need to use more backslashes, e.g. Emacs would make you write \(.\)\1\{9,\} here.

If a whole string should consist of 9 or more identical characters, add anchors around the pattern:

my $regex = qr/^(.)\1{9,}$/;

Regular Expression to match string starting with a specific word

If you want to match anything that starts with "stop" including "stop going", "stop" and "stopping" use:

^stop

If you want to match the word stop followed by anything as in "stop going", "stop this", but not "stopped" and not "stopping" use:

^stop\W

javascript - replace dash (hyphen) with a space

var str = "This-is-a-news-item-";
while (str.contains("-")) {
  str = str.replace("-", ' ');
}
alert(str);

I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.

http://jsfiddle.net/LGCYF/

How to extract a floating number from a string

If your float is always expressed in decimal notation something like

>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4 db.")
['13.4']

may suffice.

A more robust version would be:

>>> re.findall(r"[-+]?\d*\.\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")
['-13.2', '14.2', '3']

If you want to validate user input, you could alternatively also check for a float by stepping to it directly:

user_input = "Current Level: 1e100 db"
for token in user_input.split():
    try:
        # if this succeeds, you have your (first) float
        print float(token), "is a float"
    except ValueError:
        print token, "is something else"

# => Would print ...
#
# Current is something else
# Level: is something else
# 1e+100 is a float
# db is something else

Matching strings with wildcard

Using of WildcardPattern from System.Management.Automation may be an option.

pattern = new WildcardPattern(patternString);
pattern.IsMatch(stringToMatch);

Visual Studio UI may not allow you to add System.Management.Automation assembly to References of your project. Feel free to add it manually, as described here.

Get Substring between two characters using javascript

var str = '[basic_salary]+100/[basic_salary]';
var arr = str.split('');
var myArr = [];
for(var i=0;i<arr.length;i++){
    if(arr[i] == '['){
        var a = '';
        for(var j=i+1;j<arr.length;j++){
            if(arr[j] == ']'){
                var i = j-1;
                break;
            }else{
                a += arr[j];
            }
        }
        myArr.push(a);
    }
    var operatorsArr = ['+','-','*','/','%'];
    if(operatorsArr.includes(arr[i])){
        myArr.push(arr[i]);
    }
    var numbArr = ['0','1','2','3','4','5','6','7','8','9'];
    if(numbArr.includes(arr[i])){
        var a = '';
        for(var j=i;j<arr.length;j++){
            if(numbArr.includes(arr[j])){
                a += arr[j];
            }else{
                var i = j-1;
                break;
            }
        }
        myArr.push(a);
    }
}
myArr = ["basic_salary", "+", "100", "/", "basic_salary"]

replace all occurrences in a string

Brighams answer uses literal regexp.

Solution with a Regex object.

var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');

TRY IT HERE : JSFiddle Working Example

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

Using String Format to show decimal up to 2 places or simple integer

If none of the other answers work for you, it may be because you are binding the ContentProperty of a control in the OnLoad function, which means this won't work:

private void UserControl_Load(object sender, RoutedEventArgs e)
{
  Bind.SetBindingElement(labelName, String.Format("{0:0.00}", PropertyName), Label.ContentProperty) 
}

The solution is simple: there is a ContentStringFormat property in the xaml. So when you create the label do this:

//if you want the decimal places definite
<Label Content="0" Name="labelName" ContentStringFormat="0.00"/>

Or

//if you want the decimal places to be optional
<Label Content="0" Name="labelName" ContentStringFormat="0.##"/>

Ruby replace string with captured regex pattern

Try '\1' for the replacement (single quotes are important, otherwise you need to escape the \):

"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"

But since you only seem to be interested in the capture group, note that you can index a string with a regex:

"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"

Escape regex special characters in a Python string

It's not that hard:

def escapeSpecialCharacters ( text, characters ):
    for character in characters:
        text = text.replace( character, '\\' + character )
    return text

>>> escapeSpecialCharacters( 'I\'m "stuck" :\\', '\'"' )
'I\\\'m \\"stuck\\" :\\'
>>> print( _ )
I\'m \"stuck\" :\

Regular expression that doesn't contain certain string

By the power of Google I found a blogpost from 2007 which gives the following regex that matches string which don't contains a certain substring:

^((?!my string).)*$

It works as follows: it looks for zero or more (*) characters (.) which do not begin (?! - negative lookahead) your string and it stipulates that the entire string must be made up of such characters (by using the ^ and $ anchors). Or to put it an other way:

The entire string must be made up of characters which do not begin a given string, which means that the string doesn't contain the given substring.

Extract hostname name from string

2020 answer

You don't need any extra dependencies for this! Depending on whether you need to optimize for performance or not, there are two good solutions:

1. Use URL.hostname for readability

In the Babel era, the cleanest and easiest solution is to use URL.hostname.

_x000D_
_x000D_
const getHostname = (url) => {
  // use URL constructor and return hostname
  return new URL(url).hostname;
}

// tests
console.log(getHostname("https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string/"));
console.log(getHostname("https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname"));
_x000D_
_x000D_
_x000D_

URL.hostname is part of the URL API, supported by all major browsers except IE (caniuse). Use a URL polyfill if you need to support legacy browsers.

Using this solution will also give you access to other URL properties and methods. This will be useful if you also want to extract the URL's pathname or query string params, for example.


2. Use RegEx for performance

URL.hostname is faster than using the anchor solution or parseUri. However it's still much slower than gilly3's regex:

_x000D_
_x000D_
const getHostnameFromRegex = (url) => {
  // run against regex
  const matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
  // extract hostname (will be null if no match is found)
  return matches && matches[1];
}

// tests
console.log(getHostnameFromRegex("https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string/"));
console.log(getHostnameFromRegex("https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname"));
_x000D_
_x000D_
_x000D_

Test it yourself on this jsPerf


TL;DR

If you need to process a very large number of URLs (where performance would be a factor), use RegEx. Otherwise, use URL.hostname.

Invert match with regexp

It's indeed almost a duplicate. I guess the regex you're looking for is

(?!foo).*

Limit length of characters in a regular expression?

Is there a way to limit a regex to 100 characters WITH regex?

Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:

  • one to match the maximum length you'd like to use
  • one which uses the previously extracted value to verify that its own match does not exceed the specified length

If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,

\d{3}-\d{3}-\d{4}

will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.

Likewise, you can set upper or lower limits:

\d{5,10}

means "at least 5, but not more than 10 digits".


Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.

Regular expression to extract text between square brackets

([[][a-z \s]+[]])

Above should work given the following explaination

  • characters within square brackets[] defines characte class which means pattern should match atleast one charcater mentioned within square brackets

  • \s specifies a space

  •  + means atleast one of the character mentioned previously to +.

Match line break with regular expression

By default . (any character) does not match newline characters.

This means you can simply match zero or more of any character then append the end tag.

Find: <li><a href="#">.* Replace: $0</a>

How to extract text from a string using sed?

Try using rextract. It will let you extract text using a regular expression and reformat it.

Example:

$ echo "This is 02G05 a test string 20-Jul-2012" | ./rextract '([\d]+G[\d]+)' '${1}'

2G05

Converting any string into camel case

I just ended up doing this:

String.prototype.toCamelCase = function(str) {
    return str
        .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
        .replace(/\s/g, '')
        .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

I was trying to avoid chaining together multiple replace statements. Something where I'd have $1, $2, $3 in my function. But that type of grouping is hard to understand, and your mention about cross browser problems is something I never thought about as well.

How do you implement a good profanity filter?

Regarding your "trick the system" subquestion, you can handle that by normalizing both the "bad word" list and the user-entered text before doing your search. e.g., Use a series of regexes (or tr if PHP has it) to convert [z$5] to "s", [4@] to "a", etc., then compare the normalized "bad word" list against the normalized text. Note that the normalization could potentially lead to additional false positives, although I can't think of any actual cases at the moment.

The larger challenge is to come up with something that will let people quote "The pen is mightier than the sword" while blocking "p e n i s".

Java: splitting a comma-separated string but ignoring commas in quotes

You're in that annoying boundary area where regexps almost won't do (as has been pointed out by Bart, escaping the quotes would make life hard) , and yet a full-blown parser seems like overkill.

If you are likely to need greater complexity any time soon I would go looking for a parser library. For example this one

Phone Number Validation MVC

Model

[Required(ErrorMessage = "You must provide a phone number")]
[Display(Name = "Home Phone")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string PhoneNumber { get; set; }

View:

@Html.LabelFor(model => model.PhoneNumber)
@Html.EditorFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber)

Check for special characters (/*-+_@&$#%) in a string?

Simple:

function HasSpecialChars(string yourString)
{
    return yourString.Any( ch => ! Char.IsLetterOrDigit( ch ) )
}

How to replace plain URLs with links?

/**
 * Convert URLs in a string to anchor buttons
 * @param {!string} string
 * @returns {!string}
 */

function URLify(string){
  var urls = string.match(/(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)/g);
  if (urls) {
    urls.forEach(function (url) {
      string = string.replace(url, '<a target="_blank" href="' + url + '">' + url + "</a>");
    });
  }
  return string.replace("(", "<br/>(");
}

simple example

Get Filename Without Extension in Python

If I had to do this with a regex, I'd do it like this:

s = re.sub(r'\.jpg$', '', s)

How would I get everything before a : in a string Python

You don't need regex for this

>>> s = "Username: How are you today?"

You can use the split method to split the string on the ':' character

>>> s.split(':')
['Username', ' How are you today?']

And slice out element [0] to get the first part of the string

>>> s.split(':')[0]
'Username'

Only numbers. Input number in React

2019 Answer Late, but hope it helps somebody

This will make sure you won't get null on an empty textfield

  • Textfield value is always 0
  • When backspacing, you will end with 0
  • When value is 0 and you start typing, 0 will be replaced with the actual number
// This will make sure that value never is null when textfield is empty

const minimum = 0;   

export default (props) => {
    const [count, changeCount] = useState(minimum);

    function validate(count) {
        return parseInt(count) | minimum
    }

    function handleChangeCount(count) {
        changeCount(validate(count))
    }

    return (
        <Form>
            <FormGroup>
                <TextInput
                    type="text"
                    value={validate(count)}
                    onChange={handleChangeCount}
                />
            </FormGroup>
            <ActionGroup>
                <Button type="submit">submit form</Button>
            </ActionGroup>
        </Form>
    );
};

Python Regex - How to Get Positions and Values of Matches

note that the span & group are indexed for multi capture groups in a regex

regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
    for idx in range(0, 4):
        print(match.span(idx), match.group(idx))

What is the best regular expression to check if a string is a valid URL?

whats wrong with plain and simple FILTER_VALIDATE_URL ?

 $url = "http://www.example.com";

if(!filter_var($url, FILTER_VALIDATE_URL))
  {
  echo "URL is not valid";
  }
else
  {
  echo "URL is valid";
  }

I know its not the question exactly but it did the job for me when I needed to validate urls so thought it might be useful to others who come across this post looking for the same thing

How to validate numeric values which may contain dots or commas?

\d means a digit in most languages. You can also use [0-9] in all languages. For the "period or comma" use [\.,]. Depending on your language you may need more backslashes based on how you quote the expression. Ultimately, the regular expression engine needs to see a single backslash.

* means "zero-or-more", so \d* and [0-9]* mean "zero or more numbers". ? means "zero-or-one". Neither of those qualifiers means exactly one. Most languages also let you use {m,n} to mean "between m and n" (ie: {1,2} means "between 1 and 2")

Since the dot or comma and additional numbers are optional, you can put them in a group and use the ? quantifier to mean "zero-or-one" of that group.

Putting that all together you can use:

\d{1,2}([\.,][\d{1,2}])?

Meaning, one or two digits \d{1,2}, followed by zero-or-one of a group (...)? consisting of a dot or comma followed by one or two digits [\.,]\d{1,2}

Test if characters are in a string

Just in case you would also like check if a string (or a set of strings) contain(s) multiple sub-strings, you can also use the '|' between two substrings.

>substring="as|at"
>string_vector=c("ass","ear","eye","heat") 
>grepl(substring,string_vector)

You will get

[1]  TRUE FALSE FALSE  TRUE

since the 1st word has substring "as", and the last word contains substring "at"

Python, remove all non-alphabet chars from string

The fastest method is regex

#Try with regex first
t0 = timeit.timeit("""
s = r2.sub('', st)

""", setup = """
import re
r2 = re.compile(r'[^a-zA-Z0-9]', re.MULTILINE)
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""", number = 1000000)
print(t0)

#Try with join method on filter
t0 = timeit.timeit("""
s = ''.join(filter(str.isalnum, st))

""", setup = """
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""",
number = 1000000)
print(t0)

#Try with only join
t0 = timeit.timeit("""
s = ''.join(c for c in st if c.isalnum())

""", setup = """
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""", number = 1000000)
print(t0)


2.6002226710006653 Method 1 Regex
5.739747313000407 Method 2 Filter + Join
6.540099570000166 Method 3 Join

Regular Expression: Any character that is NOT a letter or number

To match anything other than letter or number or letter with diacritics like é you could try this:

[^\wÀ-úÀ-ÿ]

And to replace:

var str = 'dfj,dsf7é@lfsd .sdklfàj1';
str = str.replace(/[^\wÀ-úÀ-ÿ]/g, '_');

Inspired by the top post with support for diacritics

source

How to remove any URL within a string in Python

You could also look at it from the other way around...

from urlparse import urlparse
[el for el in ['text1', 'FTP://somewhere.com', 'text2', 'http://blah.com:8080/foo/bar#header'] if not urlparse(el).scheme]

Java; String replace (using regular expressions)?

Try this, may not be the best way. but it works

String str = "5 * x^3 - 6 * x^1 + 1";
str = str.replaceAll("(?x)(\\d+)(\\s+?\\*?\\s+?)(\\w+?)(\\^+?)(\\d+?)", "$1$3<sup>$5</sup>");
System.out.println(str);

Find a string between 2 known values

For future reference, I found this code snippet at http://www.mycsharpcorner.com/Post.aspx?postID=15 If you need to search for different "tags" it works very well.

    public static string[] GetStringInBetween(string strBegin,
        string strEnd, string strSource,
        bool includeBegin, bool includeEnd)           
    {
        string[] result ={ "", "" };
        int iIndexOfBegin = strSource.IndexOf(strBegin);
        if (iIndexOfBegin != -1)
        {
            // include the Begin string if desired
            if (includeBegin)
                iIndexOfBegin -= strBegin.Length;
            strSource = strSource.Substring(iIndexOfBegin
                + strBegin.Length);
            int iEnd = strSource.IndexOf(strEnd);
            if (iEnd != -1)
            {
                // include the End string if desired
                if (includeEnd)
                    iEnd += strEnd.Length;
                result[0] = strSource.Substring(0, iEnd);
                // advance beyond this segment
                if (iEnd + strEnd.Length < strSource.Length)
                    result[1] = strSource.Substring(iEnd
                        + strEnd.Length);
            }
        }
        else
            // stay where we are
            result[1] = strSource;
        return result;
    }

How can I strip all punctuation from a string in JavaScript using regex?

I ran across the same issue, this solution did the trick and was very readable:

var sentence = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var newSen = sentence.match(/[^_\W]+/g).join(' ');
console.log(newSen);

Result:

"This is an example of a string with punctuation"

The trick was to create a negated set. This means that it matches anything that is not within the set i.e. [^abc] - not a, b or c

\W is any non-word, so [^\W]+ will negate anything that is not a word char.

By adding in the _ (underscore) you can negate that as well.

Make it apply globally /g, then you can run any string through it and clear out the punctuation:

/[^_\W]+/g

Nice and clean ;)

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

Regular expression negative lookahead

Lookarounds can be nested.

So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".

Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"

How can I make my match non greedy in vim?

G'day,

Vim's regexp processing is not too brilliant. I've found that the regexp syntax for sed is about the right match for vim's capabilities.

I usually set the search highlighting on (:set hlsearch) and then play with the regexp after entering a slash to enter search mode.

Edit: Mark, that trick to minimise greedy matching is also covered in Dale Dougherty's excellent book "Sed & Awk" (sanitised Amazon link).

Chapter Three "Understanding Regular Expression Syntax" is an excellent intro to the more primitive regexp capabilities involved with sed and awk. Only a short read and highly recommended.

HTH

cheers,

Matching a space in regex

You can also use the \b for a word boundary. For the name I would use something like this:

[^\b]+\b[^\b]+(\b|$)

EDIT Modifying this to be a regex in Perl example

if( $fullname =~ /([^\b]+)\b[^\b]+([^\b]+)(\b|$)/ ) {
 $first_name = $1;
 $last_name = $2;
}

EDIT AGAIN Based on what you want:

$new_tag = preg_replace("/[\s\t]/","",$tag);

Setting a minimum/maximum character count for any character using a regular expression

If you also want to match newlines, then you might want to use "^[\s\S]{1,35}$" (depending on the regex engine). Otherwise, as others have said, you should used "^.{1,35}$"

Regex for not empty and not whitespace

A little late, but here's a regex I found that returns 0 matches for empty or white spaces:

/^(?!\s*$).+/

You can test this out at regex101

Find the location of a character in string

find the position of the nth occurrence of str2 in str1(same order of parameters as Oracle SQL INSTR), returns 0 if not found

instr <- function(str1,str2,startpos=1,n=1){
    aa=unlist(strsplit(substring(str1,startpos),str2))
    if(length(aa) < n+1 ) return(0);
    return(sum(nchar(aa[1:n])) + startpos+(n-1)*nchar(str2) )
}


instr('xxabcdefabdddfabx','ab')
[1] 3
instr('xxabcdefabdddfabx','ab',1,3)
[1] 15
instr('xxabcdefabdddfabx','xx',2,1)
[1] 0

Check if a string is html or not

Here's a regex-less approach I used for my own project.

If you are trying to detect HTML string among other non-HTML strings, you can convert to HTML parser object and then back and see if the string lengths are different. I.e.:

def isHTML(string):
    string1 = string[:]
    soup = BeautifulSoup(string, 'html.parser')  # Can use other HTML parser like etree
    string2 = soup.text

    if string1 != string2:
        return True
    elif string1 == string2:
        return False

It worked on my sample of 2800 strings.

Javascript string replace with regex to strip off illegal characters

You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

Escaping a forward slash in a regular expression

If you are using C#, you do not need to escape it.

Javascript regular expression password validation having special characters

you can make your own regular expression for javascript validation

    /^            : Start
    (?=.{8,})        : Length
    (?=.*[a-zA-Z])   : Letters
    (?=.*\d)         : Digits
    (?=.*[!#$%&? "]) : Special characters
    $/              : End



        (/^
        (?=.*\d)                //should contain at least one digit
        (?=.*[a-z])             //should contain at least one lower case
        (?=.*[A-Z])             //should contain at least one upper case
        [a-zA-Z0-9]{8,}         //should contain at least 8 from the mentioned characters

        $/)

Example:-   /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{7,}$/

JavaScript Regular Expression Email Validation

I've been using this function for a while. it returns a boolean value.

// Validates email address of course.
function validEmail(e) {
    var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    return String(e).search (filter) != -1;
}

Regex Until But Not Including

Try this

(.*?quick.*?)z

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Python Extension. From the Python Docs:

The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).

Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python

https://docs.python.org/3/howto/regex.html

Fastest way to check if a string matches a regexp in ruby?

This is the benchmark I have run after finding some articles around the net.

With 2.4.0 the winner is re.match?(str) (as suggested by @wiktor-stribizew), on previous versions, re =~ str seems to be fastest, although str =~ re is almost as fast.

#!/usr/bin/env ruby
require 'benchmark'

str = "aacaabc"
re = Regexp.new('a+b').freeze

N = 4_000_000

Benchmark.bm do |b|
    b.report("str.match re\t") { N.times { str.match re } }
    b.report("str =~ re\t")    { N.times { str =~ re } }
    b.report("str[re]  \t")    { N.times { str[re] } }
    b.report("re =~ str\t")    { N.times { re =~ str } }
    b.report("re.match str\t") { N.times { re.match str } }
    if re.respond_to?(:match?)
        b.report("re.match? str\t") { N.times { re.match? str } }
    end
end

Results MRI 1.9.3-o551:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         2.390000   0.000000   2.390000 (  2.397331)
str =~ re         2.450000   0.000000   2.450000 (  2.446893)
str[re]           2.940000   0.010000   2.950000 (  2.941666)
re.match str      3.620000   0.000000   3.620000 (  3.619922)
str.match re      4.180000   0.000000   4.180000 (  4.180083)

Results MRI 2.1.5:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         1.150000   0.000000   1.150000 (  1.144880)
str =~ re         1.160000   0.000000   1.160000 (  1.150691)
str[re]           1.330000   0.000000   1.330000 (  1.337064)
re.match str      2.250000   0.000000   2.250000 (  2.255142)
str.match re      2.270000   0.000000   2.270000 (  2.270948)

Results MRI 2.3.3 (there is a regression in regex matching, it seems):

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         3.540000   0.000000   3.540000 (  3.535881)
str =~ re         3.560000   0.000000   3.560000 (  3.560657)
str[re]           4.300000   0.000000   4.300000 (  4.299403)
re.match str      5.210000   0.010000   5.220000 (  5.213041)
str.match re      6.000000   0.000000   6.000000 (  6.000465)

Results MRI 2.4.0:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re.match? str     0.690000   0.010000   0.700000 (  0.682934)
re =~ str         1.040000   0.000000   1.040000 (  1.035863)
str =~ re         1.040000   0.000000   1.040000 (  1.042963)
str[re]           1.340000   0.000000   1.340000 (  1.339704)
re.match str      2.040000   0.000000   2.040000 (  2.046464)
str.match re      2.180000   0.000000   2.180000 (  2.174691)

Regex for Mobile Number Validation

Satisfies all your requirements if you use the trick told below

Regex: /^(\+\d{1,3}[- ]?)?\d{10}$/

  1. ^ start of line
  2. A + followed by \d+ followed by a or - which are optional.
  3. Whole point two is optional.
  4. Negative lookahead to make sure 0s do not follow.
  5. Match \d+ 10 times.
  6. Line end.

DEMO Added multiline flag in demo to check for all cases

P.S. You really need to specify which language you use so as to use an if condition something like below:

// true if above regex is satisfied and (&&) it does not (`!`) match `0`s `5` or more times

if(number.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && ! (number.match(/0{5,}/)) )

Regular Expressions: Search in list

Full Example (Python 3):
For Python 2.x look into Note below

import re

mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note
print(newlist)

Prints:

['cat', 'wildcat', 'thundercat']

Note:

For Python 2.x developers, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).

Python 3 code example
Python 2.x code example

How to download an entire directory and subdirectories using wget?

This works:

wget -m -np -c --no-check-certificate -R "index.html*" "https://the-eye.eu/public/AudioBooks/Edgar%20Allan%20Poe%20-%2"

How to capture multiple repeated groups?

I think you need something like this....

b="HELLO,THERE,WORLD"
re.findall('[\w]+',b)

Which in Python3 will return

['HELLO', 'THERE', 'WORLD']

How can I parse a CSV string with JavaScript, which contains comma in data?

My answer presumes your input is a reflection of code/content from web sources where single and double quote characters are fully interchangeable provided they occur as an non-escaped matching set.

You cannot use regex for this. You actually have to write a micro parser to analyze the string you wish to split. I will, for the sake of this answer, call the quoted parts of your strings as sub-strings. You need to specifically walk across the string. Consider the following case:

var a = "some sample string with \"double quotes\" and 'single quotes' and some craziness like this: \\\" or \\'",
    b = "sample of code from JavaScript with a regex containing a comma /\,/ that should probably be ignored.";

In this case you have absolutely no idea where a sub-string starts or ends by simply analyzing the input for a character pattern. Instead you have to write logic to make decisions on whether a quote character is used a quote character, is itself unquoted, and that the quote character is not following an escape.

I am not going to write that level of complexity of code for you, but you can look at something I recently wrote that has the pattern you need. This code has nothing to do with commas, but is otherwise a valid enough micro-parser for you to follow in writing your own code. Look into the asifix function of the following application:

https://github.com/austincheney/Pretty-Diff/blob/master/fulljsmin.js

Replace only some groups with Regex

If you don't want to change your pattern you can use the Group Index and Length properties of a matched group.

var text = "example-123-example";
var pattern = @"-(\d+)-";
var regex = new RegEx(pattern);
var match = regex.Match(text);

var firstPart = text.Substring(0,match.Groups[1].Index);    
var secondPart = text.Substring(match.Groups[1].Index + match.Groups[1].Length);
var fullReplace = firstPart + "AA" + secondPart;

Regular expression to allow spaces between words

Just add a space to end of your regex pattern as follows:

[a-zA-Z0-9_ ]

Java Regex to Validate Full Name allow only Spaces and Letters

My personal choice is: ^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$, Where:

^\p{L}+ - It should start with 1 or more letters.

[\p{Pd}\p{Zs}'\p{L}]* - It can have letters, space character (including invisible), dash or hyphen characters and ' in any order 0 or more times.

\p{L}+$ - It should finish with 1 or more letters.

|^\p{L}+$ - Or it just should contain 1 or more letters (It is done to support single letter names).

Support for dots (full stops) was dropped, as in British English it can be dropped in Mr or Mrs, for example.

Remove part of a string

Here's the strsplit solution if s is a vector:

> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

UPDATE 9 July 2012 - Looks like this is fixed in RTM.

  1. We already imply ^ and $ so you don't need to add them. (It doesn't appear to be a problem to include them, but you don't need them)
  2. This appears to be a bug in ASP.NET MVC 4/Preview/Beta. I've opened a bug

View source shows the following:

data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)"                  <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9&#32;.&amp;amp;&amp;#39;-]+)"      <-- MVC 4/Beta

It looks like we're double encoding.

Match everything except for specified strings

I had the same question, the solutions proposed were almost working but they had some issue. In the end the regex I used is:

^(?!red|green|blue).*

I tested it in Javascript and .NET.

.* should't be placed inside the negative lookahead like this: ^(?!.*red|green|blue) or it would make the first element behave different from the rest (i.e. "anotherred" wouldn't be matched while "anothergreen" would)

How to count number of unique values of a field in a tab-delimited text file?

You can make use of cut, sort and uniq commands as follows:

cat input_file | cut -f 1 | sort | uniq

gets unique values in field 1, replacing 1 by 2 will give you unique values in field 2.

Avoiding UUOC :)

cut -f 1 input_file | sort | uniq

EDIT:

To count the number of unique occurences you can make use of wc command in the chain as:

cut -f 1 input_file | sort | uniq | wc -l

Traits vs. interfaces

Public Service Announcement:

I want to state for the record that I believe traits are almost always a code smell and should be avoided in favor of composition. It's my opinion that single inheritance is frequently abused to the point of being an anti-pattern and multiple inheritance only compounds this problem. You'll be much better served in most cases by favoring composition over inheritance (be it single or multiple). If you're still interested in traits and their relationship to interfaces, read on ...


Let's start by saying this:

Object-Oriented Programming (OOP) can be a difficult paradigm to grasp. Just because you're using classes doesn't mean your code is Object-Oriented (OO).

To write OO code you need to understand that OOP is really about the capabilities of your objects. You've got to think about classes in terms of what they can do instead of what they actually do. This is in stark contrast to traditional procedural programming where the focus is on making a bit of code "do something."

If OOP code is about planning and design, an interface is the blueprint and an object is the fully constructed house. Meanwhile, traits are simply a way to help build the house laid out by the blueprint (the interface).

Interfaces

So, why should we use interfaces? Quite simply, interfaces make our code less brittle. If you doubt this statement, ask anyone who's been forced to maintain legacy code that wasn't written against interfaces.

The interface is a contract between the programmer and his/her code. The interface says, "As long as you play by my rules you can implement me however you like and I promise I won't break your other code."

So as an example, consider a real-world scenario (no cars or widgets):

You want to implement a caching system for a web application to cut down on server load

You start out by writing a class to cache request responses using APC:

class ApcCacher
{
  public function fetch($key) {
    return apc_fetch($key);
  }
  public function store($key, $data) {
    return apc_store($key, $data);
  }
  public function delete($key) {
    return apc_delete($key);
  }
}

Then, in your HTTP response object, you check for a cache hit before doing all the work to generate the actual response:

class Controller
{
  protected $req;
  protected $resp;
  protected $cacher;

  public function __construct(Request $req, Response $resp, ApcCacher $cacher=NULL) {
    $this->req    = $req;
    $this->resp   = $resp;
    $this->cacher = $cacher;

    $this->buildResponse();
  }

  public function buildResponse() {
    if (NULL !== $this->cacher && $response = $this->cacher->fetch($this->req->uri()) {
      $this->resp = $response;
    } else {
      // Build the response manually
    }
  }

  public function getResponse() {
    return $this->resp;
  }
}

This approach works great. But maybe a few weeks later you decide you want to use a file-based cache system instead of APC. Now you have to change your controller code because you've programmed your controller to work with the functionality of the ApcCacher class rather than to an interface that expresses the capabilities of the ApcCacher class. Let's say instead of the above you had made the Controller class reliant on a CacherInterface instead of the concrete ApcCacher like so:

// Your controller's constructor using the interface as a dependency
public function __construct(Request $req, Response $resp, CacherInterface $cacher=NULL)

To go along with that you define your interface like so:

interface CacherInterface
{
  public function fetch($key);
  public function store($key, $data);
  public function delete($key);
}

In turn you have both your ApcCacher and your new FileCacher classes implement the CacherInterface and you program your Controller class to use the capabilities required by the interface.

This example (hopefully) demonstrates how programming to an interface allows you to change the internal implementation of your classes without worrying if the changes will break your other code.

Traits

Traits, on the other hand, are simply a method for re-using code. Interfaces should not be thought of as a mutually exclusive alternative to traits. In fact, creating traits that fulfill the capabilities required by an interface is the ideal use case.

You should only use traits when multiple classes share the same functionality (likely dictated by the same interface). There's no sense in using a trait to provide functionality for a single class: that only obfuscates what the class does and a better design would move the trait's functionality into the relevant class.

Consider the following trait implementation:

interface Person
{
    public function greet();
    public function eat($food);
}

trait EatingTrait
{
    public function eat($food)
    {
        $this->putInMouth($food);
    }

    private function putInMouth($food)
    {
        // Digest delicious food
    }
}

class NicePerson implements Person
{
    use EatingTrait;

    public function greet()
    {
        echo 'Good day, good sir!';
    }
}

class MeanPerson implements Person
{
    use EatingTrait;

    public function greet()
    {
        echo 'Your mother was a hamster!';
    }
}

A more concrete example: imagine both your FileCacher and your ApcCacher from the interface discussion use the same method to determine whether a cache entry is stale and should be deleted (obviously this isn't the case in real life, but go with it). You could write a trait and allow both classes to use it to for the common interface requirement.

One final word of caution: be careful not to go overboard with traits. Often traits are used as a crutch for poor design when unique class implementations would suffice. You should limit traits to fulfilling interface requirements for best code design.

How to create composite primary key in SQL Server 2008

I know I'm late to this party, but for an existing table, try:

ALTER table TABLE_NAME
ADD CONSTRAINT [name of your PK, e.g. PK_TableName] PRIMARY KEY CLUSTERED (column1, column2, etc.)

Getting individual colors from a color map in matplotlib

For completeness these are the cmap choices I encountered so far:

Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r

How do you add a JToken to an JObject?

TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

  • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
  • JValue = any Json value type (string, int, boolean).
  • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
  • JContainer = The mother of all types which contain other types (JObject, JValue).
  • JObject = a JContainer type that holds a collection of JProperties
  • JArray = a JContainer type that holds a collection JValue or JContainer.

Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

This is the code I modified.

public class Program
{
  public static void Main()
  {
    try
    {
      string jsonText = @"
      {
        ""food"": {
          ""fruit"": {
            ""apple"": {
              ""colour"": ""red"",
              ""size"": ""small""
            },
            ""orange"": {
              ""colour"": ""orange"",
              ""size"": ""large""
            }
          }
        }
      }";

      var foodJsonObj = JObject.Parse(jsonText);
      var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");

      var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
      fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));

      Console.WriteLine(foodJsonObj.ToString());
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
  }
}

How can I compare two lists in python and return matches

A quick performance test showing Lutz's solution is the best:

import time

def speed_test(func):
    def wrapper(*args, **kwargs):
        t1 = time.time()
        for x in xrange(5000):
            results = func(*args, **kwargs)
        t2 = time.time()
        print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0)
        return results
    return wrapper

@speed_test
def compare_bitwise(x, y):
    set_x = frozenset(x)
    set_y = frozenset(y)
    return set_x & set_y

@speed_test
def compare_listcomp(x, y):
    return [i for i, j in zip(x, y) if i == j]

@speed_test
def compare_intersect(x, y):
    return frozenset(x).intersection(y)

# Comparing short lists
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)

# Comparing longer lists
import random
a = random.sample(xrange(100000), 10000)
b = random.sample(xrange(100000), 10000)
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)

These are the results on my machine:

# Short list:
compare_bitwise took 10.145 ms
compare_listcomp took 11.157 ms
compare_intersect took 7.461 ms

# Long list:
compare_bitwise took 11203.709 ms
compare_listcomp took 17361.736 ms
compare_intersect took 6833.768 ms

Obviously, any artificial performance test should be taken with a grain of salt, but since the set().intersection() answer is at least as fast as the other solutions, and also the most readable, it should be the standard solution for this common problem.

How to select rows in a DataFrame between two values, in Python Pandas?

you can also use .between() method

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")

emp[emp["Salary"].between(60000, 61000)]

Output

enter image description here

how to always round up to the next integer

I think the easiest way is to divide two integers and increase by one :

int r = list.Count() / 10;
r += (list.Count() % 10 == 0 ? 0 : 1);

No need of libraries or functions.

edited with the right code.

How to use "/" (directory separator) in both Linux and Windows in Python?

Use os.path.join(). Example: os.path.join(pathfile,"output","log.txt").

In your code that would be: rootTree.write(os.path.join(pathfile,"output","log.txt"))

What's the best way to add a full screen background image in React Native

I've heard about having to use BackgroundImage because in future you are supposed to not be able to nest the Image tag. But I could not get BackgroudImage to properly display my background. What I did was nest my Image inside a View tag and style both the outer View as well as the image. Keys were setting width to null, and setting resizeMode to 'stretch'. Below is my code:

_x000D_
_x000D_
import React, {Component} from 'react';_x000D_
import { View, Text, StyleSheet, Image} from 'react-native';_x000D_
_x000D_
export default class BasicImage extends Component {_x000D_
 constructor(props) {_x000D_
   super(props);_x000D_
_x000D_
   this.state = {};_x000D_
 }_x000D_
_x000D_
 render() {_x000D_
  return (_x000D_
   <View style={styles.container}>_x000D_
       <Image _x000D_
         source={this.props.source}_x000D_
         style={styles.backgroundImage}_x000D_
       />_x000D_
      </View>_x000D_
  )_x000D_
 }_x000D_
}_x000D_
_x000D_
const styles = StyleSheet.create({   _x000D_
  container: {_x000D_
   flex: 1,_x000D_
   width: null,_x000D_
   height: null,_x000D_
   marginBottom: 50_x000D_
  },_x000D_
    text: {_x000D_
      marginLeft: 5,_x000D_
      marginTop: 22,_x000D_
      fontFamily: 'fontawesome',_x000D_
        color: 'black',_x000D_
        fontSize: 25,_x000D_
        backgroundColor: 'rgba(0,0,0,0)',_x000D_
    },_x000D_
  backgroundImage: {_x000D_
   flex: 1,_x000D_
   width: null,_x000D_
   height: null,_x000D_
   resizeMode: 'stretch',_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

How can I find the number of arguments of a Python function?

func.__code__.co_argcount gives you number of any arguments BEFORE *args

func.__kwdefaults__ gives you a dict of the keyword arguments AFTER *args

func.__code__.co_kwonlyargcount is equal to len(func.__kwdefaults__)

func.__defaults__ gives you the values of optional arguments that appear before *args

Here is the simple illustration:

the illustration

>>> def a(b, c, d, e, f=1, g=3, h=None, *i, j=2, k=3, **L):
    pass

>>> a.__code__.co_argcount
7
>>> a.__defaults__
(1, 3, None)
>>> len(a.__defaults__)
3
>>> 
>>> 
>>> a.__kwdefaults__
{'j': 2, 'k': 3}
>>> len(a.__kwdefaults__)
2
>>> a.__code__.co_kwonlyargcount
2

Classpath including JAR within a JAR

After some research I have found method that doesn't require maven or any 3rd party extension/program.

You can use "Class-Path" in your manifest file.

For example:

Create manifest file MANIFEST.MF

Manifest-Version: 1.0
Created-By: Bundle
Class-Path: ./custom_lib.jar
Main-Class: YourMainClass

Compile all your classes and run jar cfm Testing.jar MANIFEST.MF *.class custom_lib.jar

c stands for create archive f indicates that you want to specify file v is for verbose input m means that we will pass custom manifest file

Be sure that you included lib in jar package. You should be able to run jar in the normal way.

based on: http://www.ibm.com/developerworks/library/j-5things6/

all other information you need about the class-path do you find here

SQL Error with Order By in Subquery

You don't need order by in your sub query. Move it out into the main query, and include the column you want to order by in the subquery.

however, your query is just returning a count, so I don't see the point of the order by.

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

So, rather return the whole object first, just wrap it to json_encode and then return it. This will return a proper and valid object.

public function id($id){
    $promotion = Promotion::find($id);
    return json_encode($promotion);
}

Or, For DB this will be just like,

public function id($id){
    $promotion = DB::table('promotions')->first();
    return json_encode($promotion);
}

I think it may help someone else.

CSS3 equivalent to jQuery slideUp and slideDown?

You could do something like this:

#youritem .fade.in {
    animation-name: fadeIn;
}

#youritem .fade.out {
    animation-name: fadeOut;
}

@keyframes fadeIn {
    0% {
        opacity: 0;
        transform: translateY(startYposition);
    } 
    100% {
        opacity: 1;
        transform: translateY(endYposition);
    }
}

@keyframes fadeOut {
    0% {
        opacity: 1;
        transform: translateY(startYposition);
    } 
    100% {
        opacity: 0;
        transform: translateY(endYposition);
    }
}

Example - Slide and Fade:

This slides and animates the opacity - not based on height of the container, but on the top/coordinate. View example

Example - Auto-height/No Javascript: Here is a live sample, not needing height - dealing with automatic height and no javascript.
View example

jQuery selector regular expressions

If you just want to select elements that contain given string then you can use following selector:

$(':contains("search string")')

How to serialize an object into a string

How about persisting the object as a blob

Subset data to contain only columns whose names match a condition

Just in case for data.table users, the following works for me:

df[, grep("ABC", names(df)), with = FALSE]

Order data frame rows according to vector with specific order

I prefer to use ***_join in dplyr whenever I need to match data. One possible try for this

left_join(data.frame(name=target),df,by="name")

Note that the input for ***_join require tbls or data.frame

LaTeX source code listing like in professional books

I am happy with the listings package:

Listing example

Here is how I configure it:

\lstset{
language=C,
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
columns=fullflexible,
showstringspaces=false
}

I use it like this:

\begin{lstlisting}[caption=Caption example.,
  label=a_label,
  float=t]
// Insert the code here
\end{lstlisting}

Playing a MP3 file in a WinForm application

Refactoring:

new WindowsMediaPlayer() { URL = "MyMusic.mp3" }.controls.play();

How to determine if a number is odd in JavaScript

Use my extensions :

Number.prototype.isEven=function(){
     return this % 2===0;
};

Number.prototype.isOdd=function(){
     return !this.isEven();
}

then

var a=5; 
 a.isEven();

==False

 a.isOdd();

==True

if you are not sure if it is a Number , test it by the following branching :

if(a.isOdd){
    a.isOdd();
}

UPDATE :

if you would not use variable :

(5).isOdd()

Performance :

It turns out that Procedural paradigm is better than OOP paradigm . By the way , i performed profiling in this FIDDLE . However , OOP way is still prettiest .

enter image description here

Jackson enum Serializing and DeSerializer

I did it like this :

// Your JSON
{"event":"forgot password"}

// Your class to map 
public class LoggingDto {
    @JsonProperty(value = "event")
    private FooEnum logType;
}

//Your enum
public enum FooEnum {

    DATA_LOG ("Dummy 1"),
    DATA2_LOG ("Dummy 2"),
    DATA3_LOG ("forgot password"),
    DATA4_LOG ("Dummy 4"),
    DATA5_LOG ("Dummy 5"),
    UNKNOWN ("");

    private String fullName;

    FooEnum(String fullName) {
        this.fullName = fullName;
    }

    public String getFullName() {
        return fullName;
    }

    @JsonCreator
    public static FooEnum getLogTypeFromFullName(String fullName) {
        for (FooEnum logType : FooEnum.values()) {
            if (logType.fullName.equals(fullName)) {
                return logType;
            }
        }
        return UNKNOWN;
    }


}

So the value of the property "logType" for class LoggingDto will be DATA3_LOG

Vim and Ctags tips and tricks

Another useful plugin for C development is cscope Just as Ctags lets you jump to definitions, Cscope jumps to the calling functions.

If you have cscope in your ~/bin/ directory, add the following to your .vimrc and use g^] to go to the calling function (see :help cscope).

if has("cscope")
    set csprg=~/bin/cscope
    set csto=0
    set cst
    set nocsverb
    " add any database in current directory
    if filereadable("cscope.out")
        cs add cscope.out
        " else add database pointed to by environment
    elseif $CSCOPE_DB != ""
        cs add $CSCOPE_DB
    endif
endif

Almost forgot... Just as ctags - you have to generate (and periodically update) the database. I use the following script

select_files > cscope.files
ctags -L cscope.files
ctags -e -L cscope.files
cscope -ub -i cscope.files

Where 'select_files' is another script that extracts the list of C and header files from the Makefile. This way I index only the files actually used by the project.

Read file from resources folder in Spring Boot

The simplest method to bring a resource from the classpath in the resources directory parsed into a String is the following one liner.

As a String(Using Spring Libraries):

         String resource = StreamUtils.copyToString(
                new ClassPathResource("resource.json").getInputStream(), defaultCharset());

This method uses the StreamUtils utility and streams the file as an input stream into a String in a concise compact way.

If you want the file as a byte array you can use basic Java File I/O libraries:

As a byte array(Using Java Libraries):

byte[] resource = Files.readAllBytes(Paths.get("/src/test/resources/resource.json"));

How to hash some string with sha256 in Java?

Another alternative is Guava which has an easy-to-use suite of Hashing utilities. For example, to hash a string using SHA256 as a hex-string you would simply do:

final String hashed = Hashing.sha256()
        .hashString("your input", StandardCharsets.UTF_8)
        .toString();

How can I convert a VBScript to an executable (EXE) file?

Here are a couple possible solutions...

I have not tried all of these myself yet, but I will be trying them all soon.

Note: I do not have any personal or financial connection to any of these tools.

1) VB Script to EXE Converter (NOT Compiler): (Free)
vbs2exe.com.

The exe produced appears to be a true EXE.

From their website:

VBS to EXE is a free online converter that doesn't only convert your vbs files into exe but it also:

1- Encrypt your vbs file source code using 128 bit key.
2- Allows you to call win32 API
3- If you have troubles with windows vista especially when UAC is enabled then you may give VBS to EXE a try.
4- No need for wscript.exe to run your vbs anymore.
5- Your script is never saved to the hard disk like some others converters. it is a TRUE exe not an extractor.

This solution should work even if wscript/cscript is not installed on the computer.

Basically, this creates a true .EXE file. Inside the created .EXE is an "engine" that replaces wscript/cscript, and an encrypted copy of your VB Script code. This replacement engine executes your code IN MEMORY without calling wscript/cscript to do it.


2) Compile and Convert VBS to EXE...:
ExeScript

The current version is 3.5.

This is NOT a Free solution. They have a 15 day trial. After that, you need to buy a license for a hefty $44.96 (Home License/noncommercial), or $89.95 (Business License/commercial usage).

It seems to work in a similar way to the previous solution.

According to a forum post there:
Post: "A Exe file still need Windows Scripting Host (WSH) ??"

WSH is not required if "Compile" option was used, since ExeScript
implements it's own scripting host. ...


3) Encrypt the script with Microsoft's ".vbs to .vbe" encryption tool.

Apparently, this does not work for Windows 7/8, and it is possible there are ways to "decrypt" the .vbe file. At the time of writing this, I could not find a working link to download this. If I find one, I will add it to this answer.

Open a selected file (image, pdf, ...) programmatically from my Android Application?

To Open a File in Android Programatically,you can use this code :- We use File Provider for internal file access .You can also see details about File Provider here in this linkfileprovidr1,file provider2,file provider3. Create a File Provider and defined in Manifest File .

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.packagename.app.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">

    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths">
    </meta-data>

</provider>

Define file_path in resources file.

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="my_images"
        path="Android/data/com.packagename.app/files/Pictures" />

    <external-files-path name="vivalinkComProp" path="Android/data/com.vivalink.app/vivalinkComProp/docs"/>
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />

</paths>

Define Intent For View

String directory_path = Environment.getExternalStorageDirectory().getPath() + "/MyFile/";
String targetPdf = directory_path + fileName + ".pdf";
File filePath = new File(targetPdf);

Intent intentShareFile = new Intent(Intent.ACTION_VIEW);
File fileWithinMyDir = new File(targetPdf);
Uri bmpUri = FileProvider.getUriForFile(activity, "com.packagename.app.fileprovider", filePath);
if (fileWithinMyDir.exists()) {
    intentShareFile.setDataAndType(bmpUri,"application/pdf");
    intentShareFile.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intentShareFile.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(Intent.createChooser(intentShareFile, "Open File Using..."));

}

You can use different way to create a file provider in android . Hope this will help you.

Can an Option in a Select tag carry multiple values?

put values for each options like

<SELECT NAME="val">
   <OPTION VALUE="1" value="1:2:3:4"> 1-4  
   <OPTION VALUE="2" value="5:6:7:8"> 5-8  
   <OPTION VALUE="3" value="9:10:11:12"> 9-12
</SELECT>

at server side in case of php, use functions like explode [array] = explode([delimeter],[posted value]);

$values = explode(':',$_POST['val']

the above code return an array have only the numbers and the ':' get removed

Open file dialog box in JavaScript

What if javascript is Turned Off on clients machine? Use following solution for all scenarios. You dont even need javascript/jQuery. :

HTML

<label for="fileInput"><img src="File_upload_Img"><label>
<input type="file" id="fileInput"></label>

CSS

#fileInput{opacity:0}  
body{
    background:cadetblue;
}

Explanation : for="Your input Id" . Triggers click event by default by HTML. So it by default triggers click event, no need of jQuery/javascript. If its simply done by HTML why use jQuery/jScript? And you cant tell if client disabled JS. Your feature should work even though JS is turned off.

Working jsFiddle (You dont need JS , jquery)

What is the difference between an abstract function and a virtual function?

Abstract function cannot have a body and MUST be overridden by child classes

Virtual Function will have a body and may or may not be overridden by child classes

Changing image size in Markdown

Combining two answers I came out with a solution, that might not look that pretty,
but It works!

It creates a thumbnail with a specific size that might be clicked to brings you to the max resolutions image.

[<img src="image.png" width="250"/>](image.png)

Here's an example! I tested it on Visual Code and Github. Example markdown

Database, Table and Column Naming Conventions?

I'm also in favour of a ISO/IEC 11179 style naming convention, noting they are guidelines rather than being prescriptive.

See Data element name on Wikipedia:

"Tables are Collections of Entities, and follow Collection naming guidelines. Ideally, a collective name is used: eg., Personnel. Plural is also correct: Employees. Incorrect names include: Employee, tblEmployee, and EmployeeTable."

As always, there are exceptions to rules e.g. a table which always has exactly one row may be better with a singular name e.g. a config table. And consistency is of utmost importance: check whether you shop has a convention and, if so, follow it; if you don't like it then do a business case to have it changed rather than being the lone ranger.

How to install iPhone application in iPhone Simulator

If you're looking to do this XCode 5+, I found this is the easiest method:

Install ios-sim:

npm install -g ios-sim

Then simply execute:

ios-sim launch ./mySample.app --devicetypeid com.apple.CoreSimulator.SimDeviceType.iPhone-6

In which you can switch up your device type. Simple, fast, and it actually works.

Not an enclosing class error Android Studio

startActivity(new Intent(this, Katra_home.class));

try this one it will be work

How to select last child element in jQuery?

For perfomance:

$('#example').children().last()

or if you want a last children with a certain class as commented above.

$('#example').children('.test').last()

or a specific child element with a specific class

$('#example').children('li.test').last()

How to access Session variables and set them in javascript?

i used my .php file to put required into sessions

$_SESSION['name'] = $phparray["name"]; $ajaxoutput['name'] =$phparray["name"];

in my .js file i used

sessionStorage.setItem("name", ajaxreturnedarray["name"]);

and i retrieved this using

var myName= sessionStorage.getItem("name");

in other .js files or in same .js files

if i keep it as it is , it will return same at all times even you loggedout. so while logging out i made

sessionStorage.setItem("name", "");

using this i emptied local variable. i used this process in single page website login/logout sessions. i hope this way will work for you because it worked for me. plz let me know your experiences.

calling Jquery function from javascript

    <script>

        // Instantiate your javascript function
        niceJavascriptRoutine = null;

        // Begin jQuery
        $(document).ready(function() {

            // Your jQuery function
            function niceJqueryRoutine() {
                // some code
            }
            // Point the javascript function to the jQuery function
            niceJavaScriptRoutine = niceJueryRoutine;

        });

    </script>

Simple example for Intent and Bundle

Try this: if you need pass values between the activities you use this...

This is code for Main_Activity put the values to intent

 String name="aaaa";
 Intent intent=new Intent(Main_Activity.this,Other_Activity.class);
 intent.putExtra("name", name);
 startActivity(intent);

This code for Other_Activity and get the values form intent

    Bundle b = new Bundle();
    b = getIntent().getExtras();
    String name = b.getString("name");

Why is a "GRANT USAGE" created the first time I grant a user privileges?

In addition mysql passwords when not using the IDENTIFIED BY clause, may be blank values, if non-blank, they may be encrypted. But yes USAGE is used to modify an account by granting simple resource limiters such as MAX_QUERIES_PER_HOUR, again this can be specified by also using the WITH clause, in conjuction with GRANT USAGE(no privileges added) or GRANT ALL, you can also specify GRANT USAGE at the global level, database level, table level,etc....

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

Is it possible to Turn page programmatically in UIPageViewController?

Yes it is possible with the method:

- (void)setViewControllers:(NSArray *)viewControllers 
                 direction:(UIPageViewControllerNavigationDirection)direction 
                  animated:(BOOL)animated 
                completion:(void (^)(BOOL finished))completion;`

That is the same method used for setting up the first view controller on the page. Similar, you can use it to go to other pages.

Wonder why viewControllers is an array, and not a single view controller?

That's because a page view controller could have a "spine" (like in iBooks), displaying 2 pages of content at a time. If you display 1 page of content at a time, then just pass in a 1-element array.

An example in Swift:

pageContainer.setViewControllers([displayThisViewController], direction: .Forward, animated: true, completion: nil)

What is a non-capturing group in regular expressions?

Let me try this with an example:

Regex Code: (?:animal)(?:=)(\w+)(,)\1\2

Search String:

Line 1 - animal=cat,dog,cat,tiger,dog

Line 2 - animal=cat,cat,dog,dog,tiger

Line 3 - animal=dog,dog,cat,cat,tiger

(?:animal) --> Non-Captured Group 1

(?:=)--> Non-Captured Group 2

(\w+)--> Captured Group 1

(,)--> Captured Group 2

\1 --> result of captured group 1 i.e In Line 1 is cat, In Line 2 is cat, In Line 3 is dog.

\2 --> result of captured group 2 i.e comma (,)

So in this code by giving \1 and \2 we recall or repeat the result of captured group 1 and 2 respectively later in the code.

As per the order of code (?:animal) should be group 1 and (?:=) should be group 2 and continues..

but by giving the ?: we make the match-group non captured (which do not count off in matched group, so the grouping number starts from the first captured group and not the non captured), so that the repetition of the result of match-group (?:animal) can't be called later in code.

Hope this explains the use of non capturing group.

enter image description here

How to connect to local instance of SQL Server 2008 Express

Please check the ServerName which you provided. It should match with the below shown Name in the UserName textbox, and that name should followed with \SQLEXPRESS:

Connect dialog

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I was having the same problem with requests (the python library). It happened to be the accept-encoding header.

It was set this way: 'accept-encoding': 'gzip, deflate, br'

I simply removed it from the request and stopped getting the error.

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

For GMT, here is the easiest way:

Select dateadd(s, @UnixTime+DATEDIFF (S, GETUTCDATE(), GETDATE()), '1970-01-01')

Excel formula to get week number in month (having Monday)

Jonathan from the ExcelCentral forums suggests:

=WEEKNUM(A1,2)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),2)+1 

This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:

=WEEKNUM(A1,1)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),1)+1

For weeks beginning on Tuesday, use:

=WEEKNUM(A1,12)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),12)+1

etc.

I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).

What are the best PHP input sanitizing functions?

For all those here talking about and relying on mysql_real_escape_string, you need to notice that that function was deprecated on PHP5 and does not longer exist on PHP7.

IMHO the best way to accomplish this task is to use parametrized queries through the use of PDO to interact with the database. Check this: https://phpdelusions.net/pdo_examples/select

Always use filters to process user input. See http://php.net/manual/es/function.filter-input.php

How to increase apache timeout directive in .htaccess?

Just in case this helps anyone else:

If you're going to be adding the TimeOut directive, and your website uses multiple vhosts (eg. one for port 80, one for port 443), then don't forget to add the directive to all of them!

New Line Issue when copying data from SQL Server 2012 to Excel

@AHiggins's suggestion worked well for me:

REPLACE(REPLACE(REPLACE(B.Address, CHAR(10), ' '), CHAR(13), ' '), CHAR(9), ' ')

Android Studio: Module won't show up in "Edit Configuration"

If all the above doesn't work. Try to update your Android studio version. Steps: 1. In Android Studio, select File > Settings (or Android Studio > Preference on Mac). 2. In the left pane, select Appearance & Behavior > System Settings > Updates. 3. Be sure that Automatically check for updates is checked, and then select a channel from the drop-down list. 4. Click OK.

Xcode 6 iPhone Simulator Application Support location

This worked for me in swift:

let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
println("App Path: \(dirPaths)")

How to find text in a column and saving the row number where it is first found - Excel VBA

Check for "projtemp" and then check if the previous one is a number entry (like 19,18..etc..) if that is so then get the row no of that proj temp ....

and if that is not so ..then re-check that the previous entry is projtemp or a number entry ...

How to run JUnit test cases from the command line

Actually you can also make the Junit test a runnable Jar and call the runnable jar as java -jar

Evaluate list.contains string in JSTL

Sadly, I think that JSTL doesn't support anything but an iteration through all elements to figure this out. In the past, I've used the forEach method in the core tag library:

<c:set var="contains" value="false" />
<c:forEach var="item" items="${myList}">
  <c:if test="${item eq myValue}">
    <c:set var="contains" value="true" />
  </c:if>
</c:forEach>

After this runs, ${contains} will be equal to "true" if myList contained myValue.

Is it possible to use jQuery .on and hover?

$("#MyTableData").on({

 mouseenter: function(){

    //stuff to do on mouse enter
    $(this).css({'color':'red'});

},
mouseleave: function () {
    //stuff to do on mouse leave
    $(this).css({'color':'blue'});

}},'tr');

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

Supplement to Iman Mahmoudinasab's answer

For SQL Server 2016, this is where to find the files:

https://www.microsoft.com/en-us/download/details.aspx?id=52676

Note that the files are in the list but you may need to scroll down to see/select it.

From SQL Server 2017 onwards, things change:

"Beginning with SQL Server 2017 SMO is distributed as the Microsoft.SqlServer.SqlManagementObjects NuGet package to allow users to develop applications with SMO."

Source: https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/installing-smo?view=sql-server-2017

Index of Currently Selected Row in DataGridView

dataGridView1.SelectedRows[0].Index;

Or if you wanted to use LINQ and get the index of all selected rows, you could do:

dataGridView1.SelectedRows.Select(r => r.Index);

adding 30 minutes to datetime php/mysql

Use DATE_ADD function

DATE_ADD(datecolumn, INTERVAL 30 MINUTE);

What are the dark corners of Vim your mom never told you about?

:setlocal autoread

Auto reloads the current buffer..especially useful while viewing log files and it almost serves the functionality of "tail" program in unix from within vim.

Checking for compile errors from within vim. set the makeprg variable depending on the language let's say for perl

:setlocal makeprg = perl\ -c \ %

For PHP

set makeprg=php\ -l\ %
set errorformat=%m\ in\ %f\ on\ line\ %l

Issuing ":make" runs the associated makeprg and displays the compilation errors/warnings in quickfix window and can easily navigate to the corresponding line numbers.

How to delete from a text file, all lines that contain a specific string?

Just in case someone wants to do it for exact matches of strings, you can use the -w flag in grep - w for whole. That is, for example if you want to delete the lines that have number 11, but keep the lines with number 111:

-bash-4.1$ head file
1
11
111

-bash-4.1$ grep -v "11" file
1

-bash-4.1$ grep -w -v "11" file
1
111

It also works with the -f flag if you want to exclude several exact patterns at once. If "blacklist" is a file with several patterns on each line that you want to delete from "file":

grep -w -v -f blacklist file

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

In my case, I was inserting the values in the Child Table in the wrong order

For Table with 2 columns- Column1 and Column2, i got this error when I mistakenly entered:

Insert into Table values('value for column2''value for column1')

Error resolved when I used below format :-

Insert into Table (column1, column2) values('value for column2''value for column1')

How do you UDP multicast in Python?

Just another answer to explain some subtle points in the code of the other answers:

  • socket.INADDR_ANY - (Edited) In the context of IP_ADD_MEMBERSHIP, this doesn't really bind the socket to all interfaces but just choose the default interface where multicast is up (according to routing table)
  • Joining a multicast group isn't the same as binding a socket to a local interface address

see What does it mean to bind a multicast (UDP) socket? for more on how multicast works

Multicast receiver:

import socket
import struct
import argparse


def run(groups, port, iface=None, bind_group=None):
    # generally speaking you want to bind to one of the groups you joined in
    # this script,
    # but it is also possible to bind to group which is added by some other
    # programs (like another python program instance of this)

    # assert bind_group in groups + [None], \
    #     'bind group not in groups to join'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

    # allow reuse of socket (to allow another instance of python running this
    # script binding to the same ip/port)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.bind(('' if bind_group is None else bind_group, port))
    for group in groups:
        mreq = struct.pack(
            '4sl' if iface is None else '4s4s',
            socket.inet_aton(group),
            socket.INADDR_ANY if iface is None else socket.inet_aton(iface))

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    while True:
        print(sock.recv(10240))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=19900)
    parser.add_argument('--join-mcast-groups', default=[], nargs='*',
                        help='multicast groups (ip addrs) to listen to join')
    parser.add_argument(
        '--iface', default=None,
        help='local interface to use for listening to multicast data; '
        'if unspecified, any interface would be chosen')
    parser.add_argument(
        '--bind-group', default=None,
        help='multicast groups (ip addrs) to bind to for the udp socket; '
        'should be one of the multicast groups joined globally '
        '(not necessarily joined in this python program) '
        'in the interface specified by --iface. '
        'If unspecified, bind to 0.0.0.0 '
        '(all addresses (all multicast addresses) of that interface)')
    args = parser.parse_args()
    run(args.join_mcast_groups, args.port, args.iface, args.bind_group)

sample usage: (run the below in two consoles and choose your own --iface (must be same as the interface that receives the multicast data))

python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '224.1.1.1' '224.1.1.2' '224.1.1.3' --bind-group '224.1.1.2'

python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '224.1.1.4'

Multicast sender:

import socket
import argparse


def run(group, port):
    MULTICAST_TTL = 20
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
    sock.sendto(b'from multicast_send.py: ' +
                f'group: {group}, port: {port}'.encode(), (group, port))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--mcast-group', default='224.1.1.1')
    parser.add_argument('--port', default=19900)
    args = parser.parse_args()
    run(args.mcast_group, args.port)

sample usage: # assume the receiver binds to the below multicast group address and that some program requests to join that group. And to simplify the case, assume the receiver and the sender are under the same subnet

python3 multicast_send.py --mcast-group '224.1.1.2'

python3 multicast_send.py --mcast-group '224.1.1.4'

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

Display all post meta keys and meta values of the same post ID in wordpress

As of Jan 2020 and WordPress v5.3.2, I confirm the following works fine.

It will include the field keys with their equivalent underscore keys as well, but I guess if you properly "enum" your keys in your code, that should be no problem:

$meta_values   = get_post_meta( get_the_ID() );
$example_field = meta_values['example_field_key'][0];

//OR if you do enum style 
//(emulation of a class with a list of *const* as enum does not exist in PHP per se)
$example_field = meta_values[PostTypeEnum::FIELD_EXAMPLE_KEY][0]; 

As the print_r(meta_values); gives:

Array
(
    [_edit_lock] => Array
        (
            [0] => 1579542560:1
        )

    [_edit_last] => Array
        (
            [0] => 1
        )

    [example_field] => Array
        (
            [0] => 13
        )
)

Hope that helps someone, go make a ruckus!

Folder is locked and I can't unlock it

Right click on your Subversion working directory folder, and select TortoiseSVN->Clean Up from the Context Menu. This will recurse it's way through your working directory and cleanup any incomplete actions, remove the local locks (which is different from using Subversion locking of a file in the repository which lets everyone know about the lock).

If that doesn't work, see if you can find the names of the files that were changed, but not yet committed, save them, and redo the checkout.

What is the main difference between PATCH and PUT request?

put:
If I want to update my first name, then I send a put request:

{ "first": "Nazmul", "last": "hasan" } 

But here is a problem with using put request: When I want to send put request I have to send all two parameters that is first and last (whereas I only need to update first) so it is mandatory to send them all again with put request.

patch:
patch request, on the other hand, says: only specify the data which you need to update and it won't be affecting or changing other data.
So no need to send all values again. Do I only need to change first name? Well, It only suffices to specify first in patch request.

What is the meaning of "__attribute__((packed, aligned(4))) "

Before answering, I would like to give you some data from Wiki


Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.


gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.

If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)

How to display raw JSON data on a HTML page

I think all you need to display the data on an HTML page is JSON.stringify.

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

Of course you will probably want to replace body with some other element via getElementById.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

How can I access and process nested objects, arrays or JSON?

jQuery's grep function lets you filter through an array:

_x000D_
_x000D_
var data = {_x000D_
    code: 42,_x000D_
    items: [{_x000D_
        id: 1,_x000D_
        name: 'foo'_x000D_
    }, {_x000D_
        id: 2,_x000D_
        name: 'bar'_x000D_
    }]_x000D_
};_x000D_
_x000D_
$.grep(data.items, function(item) {_x000D_
    if (item.id === 2) {_x000D_
        console.log(item.id); //console id of item_x000D_
        console.log(item.name); //console name of item_x000D_
        console.log(item); //console item object_x000D_
        return item; //returns item object_x000D_
    }_x000D_
_x000D_
});_x000D_
// Object {id: 2, name: "bar"}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

Using Accept header is really easy to get the format json or xml from the REST service.

This is my Controller, take a look produces section.

@RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
    public UIProperty getProperties() {
        return uiProperty;
    }

In order to consume the REST service we can use the code below where header can be MediaType.APPLICATION_JSON_VALUE or MediaType.APPLICATION_XML_VALUE

HttpHeaders headers = new HttpHeaders();
headers.add("Accept", header);

HttpEntity entity = new HttpEntity(headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);
return response.getBody();

Edit 01:

In order to work with application/xml, add this dependency

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

An error when I add a variable to a string

You're missing your database name:

$sql = "SELECT ID, ListStID, ListEmail, Title FROM ".$entry_database." WHERE ID = ". $ReqBookID .";

And make sure that $entry_database isn't null or empty:

var_dump($entry_database);

Also notice that you don't need to have $ReqBookID in '' as if it's an Int.

Pass connection string to code-first DbContext

Thought I'd add this bit for people who come looking for "How to pass a connection string to a DbContext": You can construct a connection string for your underlying datastore and pass the entire connection string to the constructor of your type derived from DbContext.

(Re-using Code from @Lol Coder) Model & Context

public class Dinner
{
    public int DinnerId { get; set; }
    public string Title { get; set; }
}

public class NerdDinners : DbContext
{
    public NerdDinners(string connString)
        : base(connString)
    {
    }
    public DbSet<Dinner> Dinners { get; set; }
}

Then, say you construct a Sql Connection string using the SqlConnectioStringBuilder like so:

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(GetConnectionString());

Where the GetConnectionString method constructs the appropriate connection string and the SqlConnectionStringBuilder ensures the connection string is syntactically correct; you may then instantiate your db conetxt like so:

var myContext = new NerdDinners(builder.ToString());

How do I URl encode something in Node.js?

encodeURIComponent(string) will do it:

encodeURIComponent("Robert'); DROP TABLE Students;--")
//>> "Robert')%3B%20DROP%20TABLE%20Students%3B--"

Passing SQL around in a query string might not be a good plan though,

see this one

Getting list of files in documents folder

This code prints out all the directories and files in my documents directory:

Some modification of your function:

func listFilesFromDocumentsFolder() -> [String]
{
    let dirs = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
    if dirs != [] {
        let dir = dirs[0]
        let fileList = try! FileManager.default.contentsOfDirectory(atPath: dir)
        return fileList
    }else{
        let fileList = [""]
        return fileList
    }
}

Which gets called by:

    let fileManager:FileManager = FileManager.default
    let fileList = listFilesFromDocumentsFolder()

    let count = fileList.count

    for i in 0..<count
    {
        if fileManager.fileExists(atPath: fileList[i]) != true
        {
            print("File is \(fileList[i])")
        }
    }

how to change directory using Windows command line

cd has a parameter /d, which will change drive and path with one command:

cd /d d:\temp

( see cd /?)

What is the difference between Builder Design pattern and Factory Design pattern?

Factory pattern let you create an object at once at once while builder pattern let you break the creation process of an object. In this way, you can add different functionality during the creation of an object.

Split string into individual words Java

As a more general solution (but ASCII only!), to include any other separators between words (like commas and semicolons), I suggest:

String s = "I want to walk my dog, cat, and tarantula; maybe even my tortoise.";
String[] words = s.split("\\W+");

The regex means that the delimiters will be anything that is not a word [\W], in groups of at least one [+]. Because [+] is greedy, it will take for instance ';' and ' ' together as one delimiter.

Flushing footer to bottom of the page, twitter bootstrap

In the latest version of bootstrap 4.3, this can be done using .fixed-bottom class.

<div class="fixed-bottom"></div>

Here's how I use it with the footer:

<footer class="footer fixed-bottom container">
        <hr>
        <p>&copy; 2017 Company, Inc.</p>
</footer>

You can find more information in the position documentation here.

Laravel Eloquent get results grouped by days

Like most database problems, they should be solved by using the database.

Storing the data you want to group by and using indexes you can achieve an efficient and clear method to solve this problem.

Create the migration

    $table->tinyInteger('activity_year')->unsigned()->index();
    $table->smallInteger('activity_day_of_year')->unsigned()->index();

Update the Model

<?php

namespace App\Models;

  use DB;
  use Carbon\Carbon;
  use Illuminate\Database\Eloquent\Model;

  class PageView extends Model
  {
  public function scopePerDay($query){

     $query->groupBy('activity_year');
     $query->groupBy('activity_day_of_year');

     return $query;

  }

  public function setUpdatedAt($value)
  {   
    $date = Carbon::now();

    $this->activity_year = (int)$date->format('y');
    $this->activity_day_of_year = $date->dayOfYear;

    return parent::setUpdatedAt($value);
 }

Usage

   $viewsPerDay = PageView::perDay()->get();

Using wget to recursively fetch a directory with arbitrary files in it

Recursive wget ignoring robots (for websites)

wget -e robots=off -r -np --page-requisites --convert-links 'http://example.com/folder/'

-e robots=off causes it to ignore robots.txt for that domain

-r makes it recursive

-np = no parents, so it doesn't follow links up to the parent folder

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

Yes, the moment jQuery sees the URL belongs to a different domain, it assumes that call as a cross domain call, thus crossdomain:true is not required here.

Also, important to note that you cannot make a synchronous call with $.ajax if your URL belongs to a different domain (cross domain) or you are using JSONP. Only async calls are allowed.

Note: you can call the service synchronously if you specify the async:false with your request.

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Another great option is the free V-Tools addin for Microsoft Access. Among other helpful tools it has a form to edit and save the Import/Export specifications.

enter image description here

enter image description here

Note: As of version 1.83, there is a bug in enumerating the code pages on Windows 10. (Apparently due to a missing/changed API function in Windows 10) The tools still works great, you just need to comment out a few lines of code or step past it in the debug window.

This has been a real life-saver for me in editing a complex import spec for our online orders.

Importing CSV File to Google Maps

The easiest way to do this is generate a KML file (see http://code.google.com/apis/kml/articles/csvtokml.html for a possible solution). You can then open that up in Google Maps by storing it online and linking to it from Google Maps as described at http://code.google.com/apis/kml/documentation/whatiskml.html

EDIT: http://www.gpsbabel.org/ may let you do it without coding.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

In my case, even though Target Framework of Project was 4.7.1, I was still getting same Error, Solution was to change httpRuntime in web.config under system.web to 4.7.1!

Best way to combine two or more byte arrays in C#

    public static bool MyConcat<T>(ref T[] base_arr, ref T[] add_arr)
    {
        try
        {
            int base_size = base_arr.Length;
            int size_T = System.Runtime.InteropServices.Marshal.SizeOf(base_arr[0]);
            Array.Resize(ref base_arr, base_size + add_arr.Length);
            Buffer.BlockCopy(add_arr, 0, base_arr, base_size * size_T, add_arr.Length * size_T);
        }
        catch (IndexOutOfRangeException ioor)
        {
            MessageBox.Show(ioor.Message);
            return false;
        }
        return true;
    }

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

If you are using bootstrap that will be the problem. If you want to use same bootstrap file in two locations use it below the header section .(example - inside body)

Note : "specially when you use html editors. "

Thank you.

Getting attribute of element in ng-click function in angularjs

Addition to the answer of Brett DeWoody: (which is updated now)

var dataValue = obj.srcElement.attributes.data.nodeValue;

Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:

var dataValue = obj.currentTarget.attributes.data.nodeValue;

Works in IE, Chrome and FF, I did not test Safari.

How can I switch views programmatically in a view controller? (Xcode, iPhone)

I think the OP is asking how to swap a VIEW without changing viewCONTROLLERs. Am I misunderstanding his question?

In pseudocode, he wants to do:

let myController = instantiate(someParentController)

let view1 = Bundle.main.loadNib(....) as... blah
myController.setThisViewTo( view1 )

let view2 = Bundle.main.loadNib(....) as... blah
myController.setThisViewTo( view2 )

Am I getting his question wrong?

Sql query to insert datetime in SQL Server

No need to use convert. Simply list it as a quoted date in ISO 8601 format.
Like so:

select * from table1 where somedate between '2000/01/01' and '2099/12/31'

The separator needs to be a / and it needs to be surrounded by single ' quotes.

from unix timestamp to datetime

Looks like you might want the ISO format so that you can retain the timezone.

var dateTime = new Date(1370001284000);
dateTime.toISOString(); // Returns "2013-05-31T11:54:44.000Z"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

Rails raw SQL example

You can do this:

sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)

records_array would then be the result of your sql query in an array which you can iterate through.

ld cannot find -l<library>

you can add the Path to coinhsl lib to LD_LIBRARY_PATH variable. May be that will help.

export LD_LIBRARY_PATH=/xx/yy/zz:$LD_LIBRARY_PATH

where /xx/yy/zz represent the path to coinhsl lib.

iPhone - Get Position of UIView within entire UIWindow

That's an easy one:

[aView convertPoint:localPosition toView:nil];

... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:

[aView.superview convertPoint:aView.frame.origin toView:nil];

2014 Edit: Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...

  1. don't change when rotating the device.
  2. always have their origin in the top left corner of the unrotated screen.
  3. are window coordinates: The coordinate system ist defined by the bounds of the window. The screen's and device coordinate systems are different and should not be mixed up with window coordinates.

how to convert numeric to nvarchar in sql command

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.

However, if the result must match a specific culture, FORMAT might be the function to go:

DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value)        -->  1505.5698
SELECT FORMAT(@value, 'N2', 'en-us')    --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de')    --> 1.505,57

For more information on FORMAT see here.

Of course, formatting the result should be a matter of the UI layer of the software.

http://localhost/phpMyAdmin/ unable to connect

XAMPP by default uses http://localhost/phpmyadmin

It also requires you start both Apache and MySQL from the control panel (or as a service).

In the XAMPP Control Panel, clicking [ Admin ] on the MySQL line will open your default browser at the configured URL for the phpMyAdmin application.

If you get a phpMyAdmin error stating "Cannot connect: invalid settings." You will need to make sure your MySQL config file has a matching port for server and client. If it is not the standard 3306 port, you will also need to change your phpMyAdmin config file under apache (config.inc.php) to meet the new port settings. (127.0.0.1 becomes 127.0.0.1:<port>)

Sorting hashmap based on keys

Use sorted TreeMap:

Map<String, Float> map = new TreeMap<>(yourMap);

It will automatically put entries sorted by keys. I think natural String ordering will be fine in your case.

Note that HashMap due to lookup optimizations does not preserve order.

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

Setting the MySQL root user password on OS X

To reference MySQL 8.0.15 + , the password() function is not available. Use the command below.

Kindly use

UPDATE mysql.user SET authentication_string='password' WHERE User='root';

Create a new cmd.exe window from within another cmd.exe prompt

I also tried executing batch file that run daemon process/server at the end of CCNET task; The only way to make CruiseControl spawn an independent asynchronous process WITHOUT waiting for the end of process is:

  1. create a batch file to run the daemon process (server application)
  2. use task scheduler to run the batch file as CCNET task (using schtasks.exe)

    schtasks.exe /create /F /SC once /ST 08:50 /TN TaskName /TR "c:/path/to/batchFileName.bat"
    
    • 08:50 is the HH:MM time format

you might need to kill the process at the start of ccnet

PS: the selected answer using "start cmd.exe" does not work; a new command prompt is indeed spawned, but CCNET will wait for the spawned cmd to finish.

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

"location" directive should be inside a 'server' directive, e.g.

server {
    listen       8765;

    location / {
        resolver 8.8.8.8;
        proxy_pass http://$http_host$uri$is_args$args;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Bulk create model objects in django

Here is how to bulk-create entities from column-separated file, leaving aside all unquoting and un-escaping routines:

SomeModel(Model):
    @classmethod
    def from_file(model, file_obj, headers, delimiter):
        model.objects.bulk_create([
            model(**dict(zip(headers, line.split(delimiter))))
            for line in file_obj],
            batch_size=None)

HTML <select> selected option background-color CSS style

You may not be able to do this using pure CSS. But, a little javascript can do it nicely.

A crude way to do it -

var sel = document.getElementById('select_id');
sel.addEventListener('click', function(el){
    var options = this.children;
    for(var i=0; i < this.childElementCount; i++){
        options[i].style.color = 'white';
    }
    var selected = this.children[this.selectedIndex];
        selected.style.color = 'red';
    }, false);

If...Then...Else with multiple statements after Then

This works with multiple statements:

if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6

Or you can split it over multiple lines:

if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6

reactjs - how to set inline style of backgroundcolor?

https://facebook.github.io/react/tips/inline-styles.html

You don't need the quotes.

<a style={{backgroundColor: bgColors.Yellow}}>yellow</a>

Dynamically creating keys in a JavaScript associative array

Use the first example. If the key doesn't exist it will be added.

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

Will pop up a message box containing 'oscar'.

Try:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );

Easy way to export multiple data.frame to multiple Excel worksheets

I do this all the time, all I do is

WriteXLS::WriteXLS(
    all.dataframes,
    ExcelFileName = xl.filename,
    AdjWidth = T,
    AutoFilter = T,
    FreezeRow = 1,
    FreezeCol = 2,
    BoldHeaderRow = T,
    verbose = F,
    na = '0'
  )

and all those data frames come from here

all.dataframes <- vector()
for (obj.iter in all.objects) {
  obj.name <- obj.iter
  obj.iter <- get(obj.iter)
  if (class(obj.iter) == 'data.frame') {
      all.dataframes <- c(all.dataframes, obj.name)
}

obviously sapply routine would be better here

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

The thing that tripped me up on this problem was that I thought that the need for a key applied to what looks like 'real' or DOM HTML elements as opposed to JSX elements that I have defined.

Of course with React we are working with a virtual DOM so the React JSX elements we define <MyElement> are just as important to it as the elements that look like real DOM HTML elements like <div>.

Does that make sense?

how to sort order of LEFT JOIN in SQL query?

This will get you the most expensive car for the user:

SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName

However, this statement makes me think that you want all of the cars prices sorted, descending:

So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?

So you could try this:

SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC

Proper way to restrict text input values (e.g. only numbers)

A few of the answers did not work for me so I took the best bits from some of the answers (thanks guys) and created an Angular 5 Directive that should do the job (and more) for you. It maybe not perfect but it offers flexibility.

import { Directive, HostListener, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
selector: '[appInputMask]'
})
export class InputMaskDirective {
@Input('appInputMask') inputType: string;

showMsg = false;
pattern: RegExp;

private regexMap = { // add your own
integer: /^[0-9 ]*$/g,
float: /^[+-]?([0-9]*[.])?[0-9]+$/g,
words: /([A-z]*\\s)*/g,
point25: /^\-?[0-9]*(?:\\.25|\\.50|\\.75|)$/g,
badBoys: /^[^{}*+£$%\\^-_]+$/g
};

constructor(public el: ElementRef, public renderer: Renderer2) { };

@HostListener('keypress', ['$event']) onInput(e) {
this.pattern = this.regexMap[this.inputType]
const inputChar = e.key;
this.pattern.lastIndex = 0; // dont know why but had to add this

if (this.pattern.test(inputChar)) {
   // success
  this.renderer.setStyle(this.el.nativeElement, 'color', 'green'); 
  this.badBoyAlert('black');
} else {

  this.badBoyAlert('black');
   //do something her to indicate invalid character
  this.renderer.setStyle(this.el.nativeElement, 'color', 'red');
  e.preventDefault();

}

  }
  badBoyAlert(color: string) {
    setTimeout(() => {
      this.showMsg = true;
      this.renderer.setStyle(this.el.nativeElement, 'color', color);
    }, 2000)
  }

  }

HTML <input class="form-control" appInputMask="badBoys">

find difference between two text files with one item per line

I successfully used

diff "${file1}" "${file2}" | grep "<" | sed 's/^<//g' > "${diff_file}"

Outputting the difference to a file.

Track a new remote branch created on GitHub

First of all you have to fetch the remote repository:

git fetch remoteName

Than you can create the new branch and set it up to track the remote branch you want:

git checkout -b newLocalBranch remoteName/remoteBranch

You can also use "git branch --track" instead of "git checkout -b" as max specified.

git branch --track newLocalBranch remoteName/remoteBranch

SQL Server check case-sensitivity?

Collation can be set at various levels:

  1. Server
  2. Database
  3. Column

So you could have a Case Sensitive Column in a Case Insensitive database. I have not yet come across a situation where a business case could be made for case sensitivity of a single column of data, but I suppose there could be.

Check Server Collation

SELECT SERVERPROPERTY('COLLATION')

Check Database Collation

SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;

Check Column Collation

select table_name, column_name, collation_name
from INFORMATION_SCHEMA.COLUMNS
where table_name = @table_name

Detect Windows version in .net

The above answers would give me Major version 6 on Windows 10.

The solution that I have found to work without adding extra VB libraries was following:

var versionString = (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion")?.GetValue("productName");

I wouldn't consider this the best way to get the version, but the upside this is oneliner no extra libraries, and in my case checking if it contains "10" was good enough.

curl error 18 - transfer closed with outstanding read data remaining

I had the same problem, but managed to fix it by suppressing the 'Expect: 100-continue' header that cURL usually sends (the following is PHP code, but should work similarly with other cURL APIs):

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));

By the way, I am sending calls to the HTTP server that is included in the JDK 6 REST stuff, which has all kinds of problems. In this case, it first sends a 100 response, and then with some requests doesn't send the subsequent 200 response correctly.

Getting visitors country from their IP

Use following services

1) http://api.hostip.info/get_html.php?ip=12.215.42.19

2)

$json = file_get_contents('http://freegeoip.appspot.com/json/66.102.13.106');
$expression = json_decode($json);
print_r($expression);

3) http://ipinfodb.com/ip_location_api.php

How do I call a function twice or more times consecutively?

You may try while loop as shown below;

def do1():
    # Do something

def do2(x):
    while x > 0:
        do1()
        x -= 1

do2(5)

Thus make call the do1 function 5 times.

Javascript to set hidden form value on drop down change

Just to be different, changed my answer so that this question doesn't have 5 answers with the same code.

<html>
<head>
   <title>Page</title>  
   <script src="jquery-1.3.2.min.js"></script>
   <script>
       $(function() {
           var select = $("body").append('<form></form>').children('form')
                .append('<input type="hidden" value="" />').children('input[type=hidden]')
                .attr('id', 'hiddenValue').end()
                .append('<select></select>').children('select')
                .attr('id', 'dropdown')
                .change(function() {
                    alert($(this).val());
                });

           $.each({ one: 1, two: 2, three: 3, four: 4, five: 5 }, function(txt, val) {
               select.append('<option value="' + val + '">' + txt + '</option>');
           });
       });
</script>
</head>
   <body></body>
</html>

Programmatically open new pages on Tabs

<a href="http://www.google.com/" target="_self">New Tab Example</a>

Works in IE7.

Regards,

Glenn

convert iso date to milliseconds in javascript

Yes, you can do this in a single line

let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

I faced this issue once and was able to resolve it by fixing of my /etc/hosts. It just was unable to resolve localhost name... Details are here: http://itvictories.com/node/6

In fact, there is 99% that error related to /etc/hosts file

X server just unable to resolve localhost and all consequent actions just fails.

Please be sure that you have a record like

127.0.0.1 localhost

in your /etc/hosts file.

How to get form values in Symfony2 controller

If you have extra fields in the form that not defined in Entity , $form->getData() doesn't work , one way could be this :

$request->get("form")["foo"] 

Or :

$form->get('foo')->getData();

Finding the length of an integer in C

Yes, using sprintf.

int num;
scanf("%d",&num);
char testing[100];
sprintf(testing,"%d",num);
int length = strlen(testing);

Alternatively, you can do this mathematically using the log10 function.

int num;
scanf("%d",&num);
int length;
if (num == 0) {
  length = 1;
} else {    
  length = log10(fabs(num)) + 1;
  if (num < 0) length++;
}

How to get error information when HttpWebRequest.GetResponse() fails

I came across this question when trying to check if a file existed on an FTP site or not. If the file doesn't exist there will be an error when trying to check its timestamp. But I want to make sure the error is not something else, by checking its type.

The Response property on WebException will be of type FtpWebResponse on which you can check its StatusCode property to see which FTP error you have.

Here's the code I ended up with:

    public static bool FileExists(string host, string username, string password, string filename)
    {
        // create FTP request
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
        request.Credentials = new NetworkCredential(username, password);

        // we want to get date stamp - to see if the file exists
        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        try
        {
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            var lastModified = response.LastModified;

            // if we get the last modified date then the file exists
            return true;
        }
        catch (WebException ex)
        {
            var ftpResponse = (FtpWebResponse)ex.Response;

            // if the status code is 'file unavailable' then the file doesn't exist
            // may be different depending upon FTP server software
            if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                return false;
            }

            // some other error - like maybe internet is down
            throw;
        }
    }

How to remove element from ArrayList by checking its value?

One-liner (java8):

list.removeIf(s -> s.equals("acbd")); // removes all instances, not just the 1st one

(does all the iterating implicitly)

How can I make a ComboBox non-editable in .NET?

To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this:

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

Link to the documentation for the ComboBox DropDownStyle property on MSDN.

How to remove provisioning profiles from Xcode

Provisioning profiles are stored under settings > accounts. Just press the "View details..." for the developer account you want and the provisioning profiles will be listed there.

What should be the values of GOPATH and GOROOT?

Starting with go 1.8 (Q2 2017), GOPATH will be set for you by default to $HOME/go

See issue 17262 and Rob Pike's comment:

$HOME/go it will be.
There is no single best answer but this is short and sweet, and it can only be a problem to choose that name if $HOME/go already exists, which will only happy for experts who already have go installed and will understand GOPATH.

How to get data from Magento System Configuration

$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName');

sectionName, groupName and fieldName are present in etc/system.xml file of your module.

The above code will automatically fetch config value of currently viewed store.

If you want to fetch config value of any other store than the currently viewed store then you can specify store ID as the second parameter to the getStoreConfig function as below:

$store = Mage::app()->getStore(); // store info
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName', $store);

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

There are a few misunderstandings in the discussion above.

First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.

As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:

 IF @@TRANCOUNT > 0
      ROLLBACK TRANSACTION @transaction

Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)

This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.

As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.

how to get yesterday's date in C#

You will get yesterday date by this following code snippet.

DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

The -jar option is mutually exclusive of -classpath. See an old description here

-jar

Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.

See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

A quick and dirty hack is to append your classpath to the bootstrap classpath:

-Xbootclasspath/a:path

Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.

However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.

ffmpeg usage to encode a video to H264 codec format

I used these options to convert to the H.264/AAC .mp4 format for HTML5 playback (I think it may help other guys with this problem in some way):

ffmpeg -i input.flv -vcodec mpeg4 -acodec aac output.mp4

UPDATE

As @LordNeckbeard mentioned, the previous line will produce MPEG-4 Part 2 (back in 2012 that worked somehow, I don't remember/understand why). Use the libx264 encoder to produce the proper video with H.264/AAC. To test the output file you can just drag it to a browser window and it should playback just fine.

ffmpeg -i input.flv -vcodec libx264 -acodec aac output.mp4

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

How do I find the current directory of a batch file, and then use it for the path?

Try in yourbatch

set "batchisin=%~dp0"

which should set the variable to your batch's location.

How to restart kubernetes nodes?

If a node is so unhealthy that the master can't get status from it -- Kubernetes may not be able to restart the node. And if health checks aren't working, what hope do you have of accessing the node by SSH?

In this case, you may have to hard-reboot -- or, if your hardware is in the cloud, let your provider do it.

For example, the AWS EC2 Dashboard allows you to right-click an instance to pull up an "Instance State" menu -- from which you can reboot/terminate an unresponsive node.

Before doing this, you might choose to kubectl cordon node for good measure. And you may find kubectl delete node to be an important part of the process for getting things back to normal -- if the node doesn't automatically rejoin the cluster after a reboot.


Why would a node become unresponsive? Probably some resource has been exhausted in a way that prevents the host operating system from handling new requests in a timely manner. This could be disk, or network -- but the more insidious case is out-of-memory (OOM), which Linux handles poorly.

To help Kubernetes manage node memory safely, it's a good idea to do both of the following:

  • Reserve some memory for the system.
  • Be very careful with (avoid) opportunistic memory specifications for your pods. In other words, don't allow different values of requests and limits for memory.

The idea here is to avoid the complications associated with memory overcommit, because memory is incompressible, and both Linux and Kubernetes' OOM killers may not trigger before the node has already become unhealthy and unreachable.

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

Given sheet 2:

ColumnA
-------
apple
orange

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

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

The resulting data looks like this:

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

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

How do I return a char array from a function?

With Boost:

boost::array<char, 10> testfunc()
{
    boost::array<char, 10> str;

    return str;
}

A normal char[10] (or any other array) can't be returned from a function.

How to Sort Date in descending order From Arraylist Date in android?

If date in string format convert it to date format for each object :

String argmodifiledDate = "2014-04-06 22:26:15";
SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            try
            {
                this.modifiledDate = format.parse(argmodifiledDate);
            }
            catch (ParseException e)
            {

                e.printStackTrace();
            }

Then sort the arraylist in descending order :

ArrayList<Document> lstDocument= this.objDocument.getArlstDocuments();
        Collections.sort(lstDocument, new Comparator<Document>() {
              public int compare(Document o1, Document o2) {
                  if (o1.getModifiledDate() == null || o2.getModifiledDate() == null)
                    return 0;     
                  return o2.getModifiledDate().compareTo(o1.getModifiledDate());
              }
            });

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

As this post gets a bit of popularity I edited it a bit. Spring Boot 2.x.x changed default JDBC connection pool from Tomcat to faster and better HikariCP. Here comes incompatibility, because HikariCP uses different property of jdbc url. There are two ways how to handle it:

OPTION ONE

There is very good explanation and workaround in spring docs:

Also, if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari has no url property (but does have a jdbcUrl property). In that case, you must rewrite your configuration as follows:

app.datasource.jdbc-url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass

OPTION TWO

There is also how-to in the docs how to get it working from "both worlds". It would look like below. ConfigurationProperties bean would do "conversion" for jdbcUrl from app.datasource.url

@Configuration
public class DatabaseConfig {
    @Bean
    @ConfigurationProperties("app.datasource")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("app.datasource")
    public HikariDataSource dataSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
                .build();
    }
}

How to select/get drop down option in Selenium 2

Take a look at the section about filling in forms using webdriver in the selenium documentation and the javadoc for the Select class.

To select an option based on the label:

Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down")));
select.deselectAll();
select.selectByVisibleText("Value1");

To get the first selected value:

WebElement option = select.getFirstSelectedOption()

How to change target build on Android project?

as per 2018, the targetSdkVersion can be set up in your app/build.gradle the following way:

android {
    compileSdkVersion 26
    buildToolsVersion '27.0.3'

    defaultConfig {
       ...
       targetSdkVersion 26
    }
    ...
}

if you choose 26 as SDK target, be sure to follow https://developer.android.com/about/versions/oreo/android-8.0-migration

MySQL date formats - difficulty Inserting a date

When using a string-typed variable in PHP containing a date, the variable must be enclosed in single quotes:

$NEW_DATE = '1997-07-15';
$sql = "INSERT INTO tbl (NEW_DATE, ...) VALUES ('$NEW_DATE', ...)";

What's the best way to parse command line arguments?

The new hip way is argparse for these reasons. argparse > optparse > getopt

update: As of py2.7 argparse is part of the standard library and optparse is deprecated.

What is the best way to seed a database in Rails?

The best way is to use fixtures.

Note: Keep in mind that fixtures do direct inserts and don't use your model so if you have callbacks that populate data you will need to find a workaround.

How should I pass an int into stringWithFormat?

And for comedic value:

label.text = [NSString stringWithFormat:@"%@", [NSNumber numberWithInt:count]];

(Though it could be useful if one day you're dealing with NSNumber's)

Extracting text from a PDF file using PDFMiner in python?

this code is tested with pdfminer for python 3 (pdfminer-20191125)

from pdfminer.layout import LAParams
from pdfminer.converter import PDFPageAggregator
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.layout import LTTextBoxHorizontal

def parsedocument(document):
    # convert all horizontal text into a lines list (one entry per line)
    # document is a file stream
    lines = []
    rsrcmgr = PDFResourceManager()
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    for page in PDFPage.get_pages(document):
            interpreter.process_page(page)
            layout = device.get_result()
            for element in layout:
                if isinstance(element, LTTextBoxHorizontal):
                    lines.extend(element.get_text().splitlines())
    return lines

How to check file input size with jQuery?

<form id="uploadForm" class="disp-inline" role="form" action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
</form>
<button onclick="checkSize();"></button>
<script>
    function checkSize(){
        var size = $('#uploadForm')["0"].firstChild.files["0"].size;
        console.log(size);
    }
</script>

I found this to be the easiest if you don't plan on submitted the form through standard ajax / html5 methods, but of course it works with anything.

NOTES:

var size = $('#uploadForm')["0"]["0"].files["0"].size;

This used to work, but it doesn't in chrome anymore, i just tested the code above and it worked in both ff and chrome (lastest). The second ["0"] is now firstChild.

How to check visibility of software keyboard in Android?

This is probably not suitable for production because it will open the keyboard. Note that the boolean returned by similar functions is not specified in the API and are therefore unreliable. Refer to the documentation here...

https://developer.android.com/reference/android/view/inputmethod/InputMethodManager#showSoftInput(android.view.View,%20int,%20android.os.ResultReceiver)

public boolean showSoftInput (View view, 
            int flags, 
            ResultReceiver resultReceiver)

Note that this method takes a ResultReceiver. It can get the results: RESULT_UNCHANGED_SHOWN, RESULT_UNCHANGED_HIDDEN, RESULT_SHOWN, or RESULT_HIDDEN. If you get RESULT_UNCHANGED_SHOWN, the keyboard was visible. If you need it to stay closed if it was closed, you will need to close it.

Generate a random date between two other dates

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Create random datetime object."""

from datetime import datetime
import random


def create_random_datetime(from_date, to_date, rand_type='uniform'):
    """
    Create random date within timeframe.

    Parameters
    ----------
    from_date : datetime object
    to_date : datetime object
    rand_type : {'uniform'}

    Examples
    --------
    >>> random.seed(28041990)
    >>> create_random_datetime(datetime(1990, 4, 28), datetime(2000, 12, 31))
    datetime.datetime(1998, 12, 13, 23, 38, 0, 121628)
    >>> create_random_datetime(datetime(1990, 4, 28), datetime(2000, 12, 31))
    datetime.datetime(2000, 3, 19, 19, 24, 31, 193940)
    """
    delta = to_date - from_date
    if rand_type == 'uniform':
        rand = random.random()
    else:
        raise NotImplementedError('Unknown random mode \'{}\''
                                  .format(rand_type))
    return from_date + rand * delta


if __name__ == '__main__':
    import doctest
    doctest.testmod()

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

ReferenceError: describe is not defined NodeJs

if you are using vscode, want to debug your files

I used tdd before, it throw ReferenceError: describe is not defined

But, when I use bdd, it works!

waste half day to solve it....

    {
      "type": "node",
      "request": "launch",
      "name": "Mocha Tests",
      "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
      "args": [
        "-u",
        "bdd",// set to bdd, not tdd
        "--timeout",
        "999999",
        "--colors",
        "${workspaceFolder}/test/**/*.js"
      ],
      "internalConsoleOptions": "openOnSessionStart"
},

Responsive font size in CSS

One way to solve the problem of the text to look good on both desktop and mobile/tablet is in fixing the text size to physical units like physical centimeters or inches, which don't depend on the screen PPI (points per inch).

Based on this answer, below is the code I use at the end of the HTML document for a responsive font size:

<div id='testdiv' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>
<script type='text/javascript'>
  var devicePixelRatio = window.devicePixelRatio || 1;
  dpi_x = document.getElementById('testdiv').offsetWidth * devicePixelRatio;
  dpi_y = document.getElementById('testdiv').offsetHeight * devicePixelRatio;

  function setFontSizeForClass(className, fontSize) {
      var elms = document.getElementsByClassName(className);
      for(var i=0; i<elms.length; i++) {
          elms[i].style.fontSize = String(fontSize * dpi_y / 96) + "px";
      }
  }

  setFontSizeForClass('h1-font-size', 30);
  setFontSizeForClass('action-font-size', 20);
  setFontSizeForClass('guideline-font-size', 25);
  // etc for your different classes
</script>

In the code above the items of a different class are assigned font sizes in physical units, as long as the browser/OS is configured correctly for the PPI of its screen.

A physical-unit font is always not too large and not too small, so long as the distance to the screen is usual (book-reading distance).

Commenting out a set of lines in a shell script

You can also put multi-line comments using:

: '
comment1comment1
comment2comment2
comment3comment3
comment4comment4
'

As per the Bash Reference for Bourne Shell builtins

: (a colon)

: [arguments]

Do nothing beyond expanding arguments and performing redirections. The return status is zero.

Thanks to Ikram for pointing this out in the post Shell script put multiple line comment

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

The order of precedence for resolving TNS names in ODP.NET, Managed Driver is this (see here):

  1. data source alias in the 'dataSources' section under section in the .NET config file.
  2. data source alias in the tnsnames.ora file at the location specified by 'TNS_ADMIN' in the .NET config file.
  3. data source alias in the tnsnames.ora file present in the same directory as the .exe.
  4. data source alias in the tnsnames.ora file present at %TNS_ADMIN% (where %TNS_ADMIN% is an environment variable setting).
  5. data source alias in the tnsnames.ora file present at %ORACLE_HOME%\network\admin (where %ORACLE_HOME% is an environment variable setting).

I believe the reason your sample works with Oracle.DataAccess but not with Oracle.ManagedDataAccess is that Windows registry based configuration is not supported for the latter (see documentation) - the ODP.NET installation sets an ORACLE_HOME registry key (HLKM\SOFTWARE\Oracle\Key_NAME\ORACLE_HOME) which is recognized only by the unmanaged part.

How to find out the server IP address (using JavaScript) that the browser is connected to?

Try this as a shortcut, not as a definitive solution (see comments):

<script type="text/javascript">
    var ip = location.host;
    alert(ip);
</script>

This solution cannot work in some scenarios but it can help for quick testing. Regards

How do I diff the same file between two different commits on the same branch?

If you want to see all changes to the file between the two commits on a commit-by-commit basis, you can also do

git log -u $start_commit..$end_commit -- path/to/file

Get and Set Screen Resolution

If you want to collect screen resolution you can run the following code within a WPF window (the window is what the this would refer to):

System.Windows.Media.Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
Double dpiX = m.M11 * 96;
Double dpiY = m.M22 * 96;

Frame Buster Buster ... buster code needed

All the proposed solutions directly force a change in the location of the top window. What if a user wants the frame to be there? For example the top frame in the image results of search engines.

I wrote a prototype where by default all inputs (links, forms and input elements) are disabled and/or do nothing when activated.

If a containing frame is detected, the inputs are left disabled and a warning message is shown at the top of the page. The warning message contains a link that will open a safe version of the page in a new window. This prevents the page from being used for clickjacking, while still allowing the user to view the contents in other situations.

If no containing frame is detected, the inputs are enabled.

Here is the code. You need to set the standard HTML attributes to safe values and add additonal attributes that contain the actual values. It probably is incomplete and for full safety additional attributes (I am thinking about event handlers) will probably have to be treated in the same way:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
  <head>
    <title></title>
    <script><!--
      function replaceAttributeValuesWithActualOnes( array, attributeName, actualValueAttributeName, additionalProcessor ) {
        for ( var elementIndex = 0; elementIndex < array.length; elementIndex += 1 ) {
          var element = array[ elementIndex ];
          var actualValue = element.getAttribute( actualValueAttributeName );
          if ( actualValue != null ) {
            element[ attributeName ] = actualValue;
          }

          if ( additionalProcessor != null ) {
            additionalProcessor( element );
          }
        }
      }

      function detectFraming() {
        if ( top != self ) {
          document.getElementById( "framingWarning" ).style.display = "block";
        } else {
          replaceAttributeValuesWithActualOnes( document.links, "href", "acme:href" );

          replaceAttributeValuesWithActualOnes( document.forms, "action", "acme:action", function ( form ) {
            replaceAttributeValuesWithActualOnes( form.elements, "disabled", "acme:disabled" );
          });
        }
      }
      // -->
    </script>
  </head>
  <body onload="detectFraming()">
    <div id="framingWarning" style="display: none; border-style: solid; border-width: 4px; border-color: #F00; padding: 6px; background-color: #FFF; color: #F00;">
      <div>
        <b>SECURITY WARNING</b>: Acme App is displayed inside another page.
        To make sure your data is safe this page has been disabled.<br>
        <a href="framing-detection.html" target="_blank" style="color: #090">Continue working safely in a new tab/window</a>
      </div>
    </div>
    <p>
      Content. <a href="#" acme:href="javascript:window.alert( 'Action performed' );">Do something</a>
    </p>
    <form name="acmeForm" action="#" acme:action="real-action.html">
      <p>Name: <input type="text" name="name" value="" disabled="disabled" acme:disabled=""></p>
      <p><input type="submit" name="save" value="Save" disabled="disabled" acme:disabled=""></p>
    </form>
  </body>
</html>

Is there any way to show a countdown on the lockscreen of iphone?

There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.

I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.

How to split a string and assign it to variables

The IPv6 addresses for fields like RemoteAddr from http.Request are formatted as "[::1]:53343"

So net.SplitHostPort works great:

package main

    import (
        "fmt"
        "net"
    )

    func main() {
        host1, port, err := net.SplitHostPort("127.0.0.1:5432")
        fmt.Println(host1, port, err)

        host2, port, err := net.SplitHostPort("[::1]:2345")
        fmt.Println(host2, port, err)

        host3, port, err := net.SplitHostPort("localhost:1234")
        fmt.Println(host3, port, err)
    }

Output is:

127.0.0.1 5432 <nil>
::1 2345 <nil>
localhost 1234 <nil>

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

A more hacky way is to add eg., in boot.tsx the line

import './path/declare_modules.d.ts';

with

declare module 'react-materialize';
declare module 'react-router';
declare module 'flux';

in declare_modules.d.ts

It works but other solutions are better IMO.

How to select first and last TD in a row?

You can use the following snippet:

  tr td:first-child {text-decoration: underline;}
  tr td:last-child {color: red;}

Using the following pseudo classes:

:first-child means "select this element if it is the first child of its parent".

:last-child means "select this element if it is the last child of its parent".

Only element nodes (HTML tags) are affected, these pseudo-classes ignore text nodes.

Service located in another namespace

It is so simple to do it

if you want to use it as host and want to resolve it

If you are using ambassador to any other API gateway for service located in another namespace it's always suggested to use :

            Use : <service name>
            Use : <service.name>.<namespace name>
            Not : <service.name>.<namespace name>.svc.cluster.local

it will be like : servicename.namespacename.svc.cluster.local

this will send request to a particular service inside the namespace you have mention.

example:

kind: Service
apiVersion: v1
metadata:
  name: service
spec:
  type: ExternalName
  externalName: <servicename>.<namespace>.svc.cluster.local

Here replace the <servicename> and <namespace> with the appropriate value.

In Kubernetes, namespaces are used to create virtual environment but all are connect with each other.

Nodemailer with Gmail and NodeJS

I found the simplest method, described in this article mentioned in Greg T's answer, was to create an App Password which is available after turning on 2FA for the account.

myaccount.google.com > Sign-in & security > Signing in to Google > App Passwords

This gives you an alternative password for the account, then you just configure nodemailer as a normal SMTP service.

var smtpTransport = nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 587,
    auth: {
        user: "[email protected]",
        pass: "app password"
    }
});

While Google recommend Oauth2 as the best option, this method is easy and hasn't been mentioned in this question yet.

Extra tip: I also found you can add your app name to the "from" address and GMail does not replace it with just the account email like it does if you try to use another address. ie.

from: 'My Pro App Name <[email protected]>'

"The given path's format is not supported."

If the value is a file url like file://C:/whatever, use the Uri class to translate to a regular filename:

var localPath = (new Uri(urlStylePath)).AbsolutePath

In general, using the provided API is best practice.

Wildcards in a Windows hosts file

I could not find a prohibition in writing, but by convention, the Windows hosts file closely follows the UNIX hosts file, and you cannot put wildcard hostname references into that file.

If you read the man page, it says:

DESCRIPTION
     The hosts file contains information regarding the known hosts on the net-
     work.  For each host a single line should be present with the following
     information:

           Internet address
           Official host name
           Aliases

Although it does say,

     Host names may contain any printable character other than a field delim-
     iter, newline, or comment character.

that is not true from a practical level.

Basically, the code that looks at the /etc/hosts file does not support a wildcard entry.

The workaround is to create all the entries in advance, maybe use a script to put a couple hundred entries at once.

Stashing only staged changes in git - is it possible?

Out of your comments to Mike Monkiewicz answer I suggest to use a simpler model: Use regular development branches, but use the squash option of the merge to get a single commit in your master branch:

git checkout -b bug1    # create the development branch
* hack hack hack *      # do some work
git commit
* hack hack hack *
git commit
* hack hack hack *
git commit
* hack hack hack *
git commit
git checkout master     # go back to the master branch
git merge --squash bug1 # merge the work back
git commit              # commit the merge (don't forget
                        #    to change the default commit message)
git branch -D bug1      # remove the development branch

The advantage of this procedure is that you can use the normal git work flow.

What is the difference between Views and Materialized Views in Oracle?

Materialized views are disk based and are updated periodically based upon the query definition.

Views are virtual only and run the query definition each time they are accessed.

How can I represent an infinite number in Python?

Also if you use SymPy you can use sympy.oo

>>> from sympy import oo
>>> oo + 1
oo
>>> oo - oo
nan

etc.

C++ Dynamic Shared Library on Linux

Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library

Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.

If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.

Drop multiple tables in one shot in MySQL

SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;

Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.

N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.

How to add display:inline-block in a jQuery show() function?

The best .let it's parent display :inline-block or add a parent div what CSS only have display :inline-block.

tmux set -g mouse-mode on doesn't work

As @Graham42 noted, mouse option has changed in version 2.1. Scrolling now requires for you to enter copy mode first. To enable scrolling almost identical to how it was before 2.1 add following to your .tmux.conf.

set-option -g mouse on

# make scrolling with wheels work
bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'select-pane -t=; copy-mode -e; send-keys -M'"
bind -n WheelDownPane select-pane -t= \; send-keys -M

This will enable scrolling on hover over a pane and you will be able to scroll that pane line by line.

Source: https://groups.google.com/d/msg/tmux-users/TRwPgEOVqho/Ck_oth_SDgAJ

How to store Emoji Character in MySQL Database

For Rails, next to the accepted answer, don't forget to add:

encoding: utf8mb4
collation: utf8mb4_bin

to your database.yml

Of Countries and their Cities

Check this out:

Cities of the world database donated by MaxMind.com

The company MaxMind.com1 has agreed to release their cities of the world database under the GPL. The database contains locations by country, city, latitude and longitude. There are over 3,047,000 records in the database. For those of you who have tried the location.module with the zipcodes database from CivicSpace, you will recognize how cool it is and how well this fits with that project and therefore Drupal.

Here's another free one that might help you get started.

Creating and maintaining such a database is quite a bit of work - so anyone who's done it is likely keeping it to themselves, or offering it for a fee.

Close application and launch home screen on Android

It's actually quiet easy.

The way I do this is by saving a flag in a static variable available to all. Then, when I exit, I set this flag and all my activities check this flag onResume. If the flag is set then I issue the System.exit on that activity.

That way all activities will check for the flag and will close gracefully if the flag is set.

How to convert int to NSString?

Primitives can be converted to objects with @() expression. So the shortest way is to transform int to NSNumber and pick up string representation with stringValue method:

NSString *strValue = [@(myInt) stringValue];

or

NSString *strValue = @(myInt).stringValue;

jQuery autocomplete with callback ajax json

$(document).on('keyup','#search_product',function(){
    $( "#search_product" ).autocomplete({
      source:function(request,response){
                  $.post("<?= base_url('ecommerce/autocomplete') ?>",{'name':$( "#search_product" ).val()}).done(function(data, status){

                    response(JSON.parse(data));
        });
      }
    });
});

PHP code :

public function autocomplete(){
    $name=$_POST['name'];
    $result=$this->db->select('product_name,sku_code')->like('product_name',$name)->get('product_list')->result_array();
    $names=array();
    foreach($result as $row){
        $names[]=$row['product_name'];
    }
    echo json_encode($names);
}

Rails select helper - Default selected value, how?

Alternatively, you could set the :project_id attribute in the controller, since the first argument of f.select pulls that particular attribute.

How do you redirect HTTPS to HTTP?

If you are looking for an answer where you can redirect specific url/s to http then please update your htaccess like below

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/(home/panel/videos|user/profile) [NC] # Multiple urls
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /(home/panel/videos|user/profile) [NC] # Multiple urls
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

It worked for me :)

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

You should install node.js with nvm, because that way you do not have to provide superuser privileges when installing global packages (you can simply execute "npm install -g packagename" without prepending 'sudo').

Brew is fantastic for other things, however. I tend to be biased towards Bower whenever I have the option to install something with Bower.

Does PHP have threading?

From the PHP manual for the pthreads extension:

pthreads is an Object Orientated API that allows user-land multi-threading in PHP. It includes all the tools you need to create multi-threaded applications targeted at the Web or the Console. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Stackables.

As unbelievable as this sounds, it's entirely true. Today, PHP can multi-thread for those wishing to try it.

The first release of PHP4, 22 May 2000, PHP was shipped with a thread safe architecture - a way for it to execute multiple instances of it's interpreter in separate threads in multi-threaded SAPI ( Server API ) environments. Over the last 13 years, the design of this architecture has been maintained and advanced: It has been in production use on the worlds largest websites ever since.

Threading in user land was never a concern for the PHP team, and it remains as such today. You should understand that in the world where PHP does it's business, there's already a defined method of scaling - add hardware. Over the many years PHP has existed, hardware has got cheaper and cheaper and so this became less and less of a concern for the PHP team. While it was getting cheaper, it also got much more powerful; today, our mobile phones and tablets have dual and quad core architectures and plenty of RAM to go with it, our desktops and servers commonly have 8 or 16 cores, 16 and 32 gigabytes of RAM, though we may not always be able to have two within budget and having two desktops is rarely useful for most of us.

Additionally, PHP was written for the non-programmer, it is many hobbyists native tongue. The reason PHP is so easily adopted is because it is an easy language to learn and write. The reason PHP is so reliable today is because of the vast amount of work that goes into it's design, and every single decision made by the PHP group. It's reliability and sheer greatness keep it in the spot light, after all these years; where it's rivals have fallen to time or pressure.

Multi-threaded programming is not easy for most, even with the most coherent and reliable API, there are different things to think about, and many misconceptions. The PHP group do not wish for user land multi-threading to be a core feature, it has never been given serious attention - and rightly so. PHP should not be complex, for everyone.

All things considered, there are still benefits to be had from allowing PHP to utilize it's production ready and tested features to allow a means of making the most out of what we have, when adding more isn't always an option, and for a lot of tasks is never really needed.

pthreads achieves, for those wishing to explore it, an API that does allow a user to multi-thread PHP applications. It's API is very much a work in progress, and designated a beta level of stability and completeness.

It is common knowledge that some of the libraries PHP uses are not thread safe, it should be clear to the programmer that pthreads cannot change this, and does not attempt to try. However, any library that is thread safe is useable, as in any other thread safe setup of the interpreter.

pthreads utilizes Posix Threads ( even in Windows ), what the programmer creates are real threads of execution, but for those threads to be useful, they must be aware of PHP - able to execute user code, share variables and allow a useful means of communication ( synchronization ). So every thread is created with an instance of the interpreter, but by design, it's interpreter is isolated from all other instances of the interpreter - just like multi-threaded Server API environments. pthreads attempts to bridge the gap in a sane and safe way. Many of the concerns of the programmer of threads in C just aren't there for the programmer of pthreads, by design, pthreads is copy on read and copy on write ( RAM is cheap ), so no two instances ever manipulate the same physical data, but they can both affect data in another thread. The fact that PHP may use thread unsafe features in it's core programming is entirely irrelevant, user threads, and it's operations are completely safe.

Why copy on read and copy on write:

public function run() {
    ...
    (1) $this->data = $data;
    ...
    (2) $this->other = someOperation($this->data);
    ...
}

(3) echo preg_match($pattern, $replace, $thread->data);

(1) While a read, and write lock are held on the pthreads object data store, data is copied from its original location in memory to the object store. pthreads does not adjust the refcount of the variable, Zend is able to free the original data if there are no further references to it.

(2) The argument to someOperation references the object store, the original data stored, which it itself a copy of the result of (1), is copied again for the engine into a zval container, while this occurs a read lock is held on the object store, the lock is released and the engine can execute the function. When the zval is created, it has a refcount of 0, enabling the engine to free the copy on completion of the operation, because no other references to it exist.

(3) The last argument to preg_match references the data store, a read lock is obtained, the data set in (1) is copied to a zval, again with a refcount of 0. The lock is released, The call to preg_match operates on a copy of data, that is itself a copy of the original data.

Things to know:

  • The object store's hash table where data is stored, thread safe, is
    based on the TsHashTable shipped with PHP, by Zend.

  • The object store has a read and write lock, an additional access lock is provided for the TsHashTable such that if requires ( and it does, var_dump/print_r, direct access to properties as the PHP engine wants to reference them ) pthreads can manipulate the TsHashTable outside of the defined API.

  • The locks are only held while the copying operations occur, when the copies have been made the locks are released, in a sensible order.

This means:

  • When a write occurs, not only are a read and write lock held, but an additional access lock. The table itself is locked down, there is no possible way another context can lock, read, write or affect it.

  • When a read occurs, not only is the read lock held, but the additional access lock too, again the table is locked down.

No two contexts can physically nor concurrently access the same data from the object store, but writes made in any context with a reference will affect the data read in any context with a reference.

This is shared nothing architecture and the only way to exist is co-exist. Those a bit savvy will see that, there's a lot of copying going on here, and they will wonder if that is a good thing. Quite a lot of copying goes on within a dynamic runtime, that's the dynamics of a dynamic language. pthreads is implemented at the level of the object, because good control can be gained over one object, but methods - the code the programmer executes - have another context, free of locking and copies - the local method scope. The object scope in the case of a pthreads object should be treated as a way to share data among contexts, that is it's purpose. With this in mind you can adopt techniques to avoid locking the object store unless it's necessary, such as passing local scope variables to other methods in a threaded object rather than having them copy from the object store upon execution.

Most of the libraries and extensions available for PHP are thin wrappers around 3rd parties, PHP core functionality to a degree is the same thing. pthreads is not a thin wrapper around Posix Threads; it is a threading API based on Posix Threads. There is no point in implementing Threads in PHP that it's users do not understand or cannot use. There's no reason that a person with no knowledge of what a mutex is or does should not be able to take advantage of all that they have, both in terms of skill, and resources. An object functions like an object, but wherever two contexts would otherwise collide, pthreads provides stability and safety.

Anyone who has worked in java will see the similarities between a pthreads object and threading in java, those same people will have no doubt seen an error called ConcurrentModificationException - as it sounds an error raised by the java runtime if two threads write the same physical data concurrently. I understand why it exists, but it baffles me that with resources as cheap as they are, coupled with the fact the runtime is able to detect the concurrency at the exact and only time that safety could be achieved for the user, that it chooses to throw a possibly fatal error at runtime rather than manage the execution and access to the data.

No such stupid errors will be emitted by pthreads, the API is written to make threading as stable, and compatible as is possible, I believe.

Multi-threading isn't like using a new database, close attention should be paid to every word in the manual and examples shipped with pthreads.

Lastly, from the PHP manual:

pthreads was, and is, an experiment with pretty good results. Any of its limitations or features may change at any time; that is the nature of experimentation. It's limitations - often imposed by the implementation - exist for good reason; the aim of pthreads is to provide a useable solution to multi-tasking in PHP at any level. In the environment which pthreads executes, some restrictions and limitations are necessary in order to provide a stable environment.

How to programmatically set the ForeColor of a label to its default?

For example summer :

lblSummer.foreColor = color.Yellow;

getContext is not a function

Your value:

this.element = $(id);

is a jQuery object, not a pure Canvas element.

To turn it back so you can call getContext(), call this.element.get(0), or better yet store the real element and not the jQuery object:

function canvasLayer(location, id) {

    this.width = $(window).width();
    this.height = $(window).height();
    this.element = document.createElement('canvas');

    $(this.element)
       .attr('id', id)
       .text('unsupported browser')
       .attr('width', this.width)       // for pixels
       .attr('height', this.height)
       .width(this.width)               // for CSS scaling
       .height(this.height)
       .appendTo(location);

    this.context = this.element.getContext("2d");
}

See running code at http://jsfiddle.net/alnitak/zbaMh/, ideally using the Chrome Javascript Console so you can see the resulting object in the debug output.

Regex: Specify "space or start of string" and "space or end of string"

\b matches at word boundaries (without actually matching any characters), so the following should do what you want:

\bstackoverflow\b

Bootstrap Responsive Text Size

Well, my solution is sort of hack, but it works and I am using it.

1vw = 1% of viewport width

1vh = 1% of viewport height

1vmin = 1vw or 1vh, whichever is smaller

1vmax = 1vw or 1vh, whichever is larger

h1 {
  font-size: 5.9vw;
}
h2 {
  font-size: 3.0vh;
}
p {
  font-size: 2vmin;
}

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.


This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

How to Convert a Text File into a List in Python

This looks like a CSV file, so you could use the python csv module to read it. For example:

import csv

crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]

Using the csv module allows you to specify how things like quotes and newlines are handled. See the documentation I linked to above.

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

How do I write a custom init for a UIView subclass in Swift?

Here is how I do it on iOS 9 in Swift -

import UIKit

class CustomView : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        //for debug validation
        self.backgroundColor = UIColor.blueColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Here is a full project with example:

How can I show line numbers in Eclipse?

Eclipse has a search feature in the top left box of the Preferences. Type in 'line numbers' in that search box, and presto...

In case you're tired of googling each time you forget...

ggplot2 plot without axes, legends, etc

xy <- data.frame(x=1:10, y=10:1)
plot <- ggplot(data = xy)+geom_point(aes(x = x, y = y))
plot
panel = grid.get("panel-3-3")

grid.newpage()
pushViewport(viewport(w=1, h=1, name="layout"))
pushViewport(viewport(w=1, h=1, name="panel-3-3"))
upViewport(1)
upViewport(1)
grid.draw(panel)

Programmatically navigate using React router

Warning: this answer covers only ReactRouter versions before 1.0

I will update this answer with 1.0.0-rc1 use cases after!

You can do this without mixins too.

let Authentication = React.createClass({
  contextTypes: {
    router: React.PropTypes.func
  },
  handleClick(e) {
    e.preventDefault();
    this.context.router.transitionTo('/');
  },
  render(){
    return (<div onClick={this.handleClick}>Click me!</div>);
  }
});

The gotcha with contexts is that it is not accessible unless you define the contextTypes on the class.

As for what is context, it is an object, like props, that are passed down from parent to child, but it is passed down implicitly, without having to redeclare props each time. See https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html