Programs & Examples On #Tinyxpath

Bind TextBox on Enter-key press

This is not an answer to the original question, but rather an extension of the accepted answer by @Samuel Jack. I did the following in my own application, and was in awe of the elegance of Samuel's solution. It is very clean, and very reusable, as it can be used on any control, not just the TextBox. I thought this should be shared with the community.

If you have a Window with a thousand TextBoxes that all require to update the Binding Source on Enter, you can attach this behaviour to all of them by including the XAML below into your Window Resources rather than attaching it to each TextBox. First you must implement the attached behaviour as per Samuel's post, of course.

<Window.Resources>
    <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
        <Style.Setters>
            <Setter Property="b:InputBindingsManager.UpdatePropertySourceWhenEnterPressed" Value="TextBox.Text"/>
        </Style.Setters>
    </Style>
</Window.Resources>

You can always limit the scope, if needed, by putting the Style into the Resources of one of the Window's child elements (i.e. a Grid) that contains the target TextBoxes.

Display text from .txt file in batch file

@echo off
set log=%time% %date%
echo %log%

That is a batch for saving the date and time as a temporary variable, and displaying it. In a hurry, I don't have time to write a script to open a txt, maybe later.

How to implement a queue using two stacks?

With O(1) dequeue(), which is same as pythonquick's answer:

// time: O(n), space: O(n)
enqueue(x):
    if stack.isEmpty():
        stack.push(x)
        return
    temp = stack.pop()
    enqueue(x)
    stack.push(temp)

// time: O(1)
x dequeue():
    return stack.pop()

With O(1) enqueue() (this is not mentioned in this post so this answer), which also uses backtracking to bubble up and return the bottommost item.

// O(1)
enqueue(x):
    stack.push(x)

// time: O(n), space: O(n)
x dequeue():
    temp = stack.pop()
    if stack.isEmpty():
        x = temp
    else:
        x = dequeue()
        stack.push(temp)
    return x

Obviously, it's a good coding exercise as it inefficient but elegant nevertheless.

Extract elements of list at odd positions

You can make use of bitwise AND operator &. Let's see below:

x = [1, 2, 3, 4, 5, 6, 7]
y = [i for i in x if i&1]
>>> 
[1, 3, 5, 7]

Bitwise AND operator is used with 1, and the reason it works because, odd number when written in binary must have its first digit as 1. Let's check

23 = 1 * (2**4) + 0 * (2**3) + 1 * (2**2) + 1 * (2**1) + 1 * (2**0) = 10111
14 = 1 * (2**3) + 1 * (2**2) + 1 * (2**1) + 0 * (2**0) = 1110

AND operation with 1 will only return 1 (1 in binary will also have last digit 1), iff the value is odd.

Check the Python Bitwise Operator page for more.

P.S: You can tactically use this method if you want to select odd and even columns in a dataframe. Let's say x and y coordinates of facial key-points are given as columns x1, y1, x2, etc... To normalize the x and y coordinates with width and height values of each image you can simply perform

for i in range(df.shape[1]):
    if i&1:
        df.iloc[:, i] /= heights
    else:
        df.iloc[:, i] /= widths

This is not exactly related to the question but for data scientists and computer vision engineers this method could be useful.

Cheers!

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Regex match text between tags

Use match instead, and the g flag.

str.match(/<b>(.*?)<\/b>/g);

How does MySQL CASE work?

CASE in MySQL is both a statement and an expression, where each usage is slightly different.

As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN -- Do other stuff
        END;
    END CASE;
  END;
  |

However, as an expression it can be used in clauses:

SELECT *
  FROM employees
  ORDER BY
    CASE title
      WHEN "President" THEN 1
      WHEN "Manager" THEN 2
      ELSE 3
    END, surname

Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

SELECT *
  FROM employees
  ORDER BY
    CASE 
      WHEN title = "President" THEN 1
      WHEN title = "Manager" THEN 2
      ELSE 3
    END, surname

I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

Check play state of AVPlayer

You can tell it's playing using:

AVPlayer *player = ...
if ((player.rate != 0) && (player.error == nil)) {
    // player is playing
}

Swift 3 extension:

extension AVPlayer {
    var isPlaying: Bool {
        return rate != 0 && error == nil
    }
}

Remove header and footer from window.print()

This will be the simplest solution. I tried most of the solutions in the internet but only this helped me.

@print{
    @page :footer {color: #fff }
    @page :header {color: #fff}
}

Send password when using scp to copy files from one server to another

Just pass with sshpass -p "your password" at the beginning of your scp command

sshpass -p "your password" scp ./abc.txt hostname/abc.txt

How to gracefully handle the SIGKILL signal in Java

It is impossible for any program, in any language, to handle a SIGKILL. This is so it is always possible to terminate a program, even if the program is buggy or malicious. But SIGKILL is not the only means for terminating a program. The other is to use a SIGTERM. Programs can handle that signal. The program should handle the signal by doing a controlled, but rapid, shutdown. When a computer shuts down, the final stage of the shutdown process sends every remaining process a SIGTERM, gives those processes a few seconds grace, then sends them a SIGKILL.

The way to handle this for anything other than kill -9 would be to register a shutdown hook. If you can use (SIGTERM) kill -15 the shutdown hook will work. (SIGINT) kill -2 DOES cause the program to gracefully exit and run the shutdown hooks.

Registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

I tried the following test program on OSX 10.6.3 and on kill -9 it did NOT run the shutdown hook, as expected. On a kill -15 it DOES run the shutdown hook every time.

public class TestShutdownHook
{
    public static void main(String[] args) throws InterruptedException
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("Shutdown hook ran!");
            }
        });

        while (true)
        {
            Thread.sleep(1000);
        }
    }
}

There isn't any way to really gracefully handle a kill -9 in any program.

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows.

The only real option to handle a kill -9 is to have another watcher program watch for your main program to go away or use a wrapper script. You could do with this with a shell script that polled the ps command looking for your program in the list and act accordingly when it disappeared.

#!/usr/bin/env bash

java TestShutdownHook
wait
# notify your other app that you quit
echo "TestShutdownHook quit"

Composer: The requested PHP extension ext-intl * is missing from your system

PHP uses a different php.ini for command line php than for the web/apache php. So you see the intl extension in phpinfo() in the browser, but if you run php -m in the command line you might see that the list of extensions there does not include intl.

You can check using php -i on top of the output it should tell you where the ini file is loaded from. Make sure you enable the intl extension in that ini file and you should be good to go.

For php.ini 5.6 version (check version using php -v)

;extension=php_intl.dll 
; remove semicolon
extension=php_intl.dll

For php.ini 7.* version

;extension=intl
; remove semicolon
extension=intl

Installing TensorFlow on Windows (Python 3.6.x)

On 2/22/18, when I tried the official recommendation:

pip3 install --upgrade tensorflow

I got this error

Could not find a version that satisfies the requirement tensorflow

But instead using

pip install --upgrade tensorflow

installed it ok. (I ran it from the ps command prompt.)

I have 64-bit windows 10, 64-bit python 3.6.3, and pip3 version 9.0.1.

Error inflating class android.support.v7.widget.Toolbar?

In the case of Xamarin in VS, you must add

Theme = "@style/MyThemesss"

to youractivity.cs.

I add this and go on.

What is key=lambda

A lambda is an anonymous function:

>>> f = lambda: 'foo'
>>> print f()
foo

It is often used in functions such as sorted() that take a callable as a parameter (often the key keyword parameter). You could provide an existing function instead of a lambda there too, as long as it is a callable object.

Take the sorted() function as an example. It'll return the given iterable in sorted order:

>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']

but that sorts uppercased words before words that are lowercased. Using the key keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:

>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']

We had to create a separate function for that, we could not inline the def lowercased() line into the sorted() expression:

>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
  File "<stdin>", line 1
    sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
                                                           ^
SyntaxError: invalid syntax

A lambda on the other hand, can be specified directly, inline in the sorted() expression:

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']

Lambdas are limited to one expression only, the result of which is the return value.

There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime to UNIX timestamp:

public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
    return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - 
           new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}

adb doesn't show nexus 5 device

In my case:

  • The phone was connected as a media device.
  • Clicked on that message and got a menu. "USB computer connection"
  • In that menu chose to connect it as a camera (for devices that do not support MTP)

And then it worked.

Go to next item in ForEach-Object

I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.

In Powershell 5.1, you want to use continue to move onto the next item in your loop. I tested with 6 items in an array, had a foreach loop through, but put an if statement with:

foreach($i in $array){    
    write-host -fore green "hello $i"
    if($i -like "something"){
        write-host -fore red "$i is bad"
        continue
        write-host -fore red "should not see this"
    }
}

Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i matched, I saw something is bad and then it went on to the next item in the array without saying should not see this. I tested with return and it exited the loop altogether.

How to store Emoji Character in MySQL Database

If you are inserting using PHP, and you have followed the various ALTER database and ALTER table options above, make sure your php connection's charset is utf8mb4.

Example of connection string:

$this->pdo = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8mb4", etc etc

Notice the "charset" is utf8mb4, not just utf8!

Check if SQL Connection is Open or Closed

You should be using SqlConnection.State

e.g,

using System.Data;

if (myConnection != null && myConnection.State == ConnectionState.Closed)
{
   // do something
   // ...
}

Swift Set to Array

In the simplest case, with Swift 3, you can use Array's init(_:) initializer to get an Array from a Set. init(_:) has the following declaration:

init<S>(_ s: S) where S : Sequence, Element == S.Iterator.Element

Creates an array containing the elements of a sequence.

Usage:

let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy")    
let stringArray = Array(stringSet)

print(stringArray)
// may print ["toy", "car", "bike", "boat"]

However, if you also want to perform some operations on each element of your Set while transforming it into an Array, you can use map, flatMap, sort, filter and other functional methods provided by Collection protocol:

let stringSet = Set(["car", "boat", "bike", "toy"])
let stringArray = stringSet.sorted()

print(stringArray)
// will print ["bike", "boat", "car", "toy"]
let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy") 
let stringArray = stringSet.filter { $0.characters.first != "b" }

print(stringArray)
// may print ["car", "toy"]
let intSet = Set([1, 3, 5, 2]) 
let stringArray = intSet.flatMap { String($0) }

print(stringArray)
// may print ["5", "2", "3", "1"]
let intSet = Set([1, 3, 5, 2])
// alternative to `let intArray = Array(intSet)`
let intArray = intSet.map { $0 }

print(intArray)
// may print [5, 2, 3, 1]

Angular2 - Focusing a textbox on component load

See Angular 2: Focus on newly added input element for how to set the focus.

For "on load" use the ngAfterViewInit() lifecycle callback.

laravel compact() and ->with()

I just wanted to hop in here and correct (suggest alternative) to the previous answer....

You can actually use compact in the same way, however a lot neater for example...

return View::make('gameworlds.mygame', compact(array('fixtures', 'teams', 'selections')));

Or if you are using PHP > 5.4

return View::make('gameworlds.mygame', compact(['fixtures', 'teams', 'selections']));

This is far neater, and still allows for readability when reviewing what the application does ;)

Get user profile picture by Id

You can use following urls to obtain different sizes of profile images. Please make sure to add Facebook id to url.

Large size photo https://graph.facebook.com/{facebookId}/picture?type=large

Medium size photo https://graph.facebook.com/{facebookId}/picture?type=normal

Small size photo https://graph.facebook.com/{facebookId}/picture?type=small

Square photo https://graph.facebook.com/{facebookId}/picture?type=square

How to effectively work with multiple files in Vim

I use buffer commands - :bn (next buffer), :bp (previous buffer) :buffers (list open buffers) :b<n> (open buffer n) :bd (delete buffer). :e <filename> will just open into a new buffer.

How to apply CSS page-break to print a table with lots of rows?

Unfortunately the examples above didn't work for me in Chrome.

I came up with the below solution where you can specify the max height in PXs of each page. This will then splits the table into separate tables when the rows equal that height.

$(document).ready(function(){

    var MaxHeight = 200;
    var RunningHeight = 0;
    var PageNo = 1;

    $('table.splitForPrint>tbody>tr').each(function () {

        if (RunningHeight + $(this).height() > MaxHeight) {
            RunningHeight = 0;
            PageNo += 1;
        }

        RunningHeight += $(this).height();

        $(this).attr("data-page-no", PageNo);

    });

    for(i = 1; i <= PageNo; i++){

        $('table.splitForPrint').parent().append("<div class='tablePage'><hr /><table id='Table" + i + "'><tbody></tbody></table><hr /></div>");

        var rows = $('table tr[data-page-no="' + i + '"]');

        $('#Table' + i).find("tbody").append(rows);
    }
    $('table.splitForPrint').remove();

});

You will also need the below in your stylesheet

    div.tablePage {
        page-break-inside:avoid; page-break-after:always;            
    }

How to dynamically add a style for text-align using jQuery

$(this).css("text-align", "center"); should work, make sure 'this' is the element you're actually trying to set the text-align style to.

Proxy with urllib2

proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')

How do I get bit-by-bit data from an integer value in C?

If you want the k-th bit of n, then do

(n & ( 1 << k )) >> k

Here we create a mask, apply the mask to n, and then right shift the masked value to get just the bit we want. We could write it out more fully as:

    int mask =  1 << k;
    int masked_n = n & mask;
    int thebit = masked_n >> k;

You can read more about bit-masking here.

Here is a program:

#include <stdio.h>
#include <stdlib.h>

int *get_bits(int n, int bitswanted){
  int *bits = malloc(sizeof(int) * bitswanted);

  int k;
  for(k=0; k<bitswanted; k++){
    int mask =  1 << k;
    int masked_n = n & mask;
    int thebit = masked_n >> k;
    bits[k] = thebit;
  }

  return bits;
}

int main(){
  int n=7;

  int  bitswanted = 5;

  int *bits = get_bits(n, bitswanted);

  printf("%d = ", n);

  int i;
  for(i=bitswanted-1; i>=0;i--){
    printf("%d ", bits[i]);
  }

  printf("\n");
}

HTML Table different number of columns in different rows

Colspan:

<table>
   <tr>
      <td> Row 1 Col 1</td>
      <td> Row 1 Col 2</td>
</tr>
<tr>
      <td colspan=2> Row 2 Long Col</td>
</tr>
</table>

How can I find a specific element in a List<T>?

public List<DealsCategory> DealCategory { get; set; }
int categoryid = Convert.ToInt16(dealsModel.DealCategory.Select(x => x.Id));

How to remove underline from a link in HTML?

This will remove all underlines from all links:

a {text-decoration: none; }

If you have specific links that you want to apply this to, give them a class name, like nounderline and do this:

a.nounderline {text-decoration: none; }

That will apply only to those links and leave all others unaffected.

This code belongs in the <head> of your document or in a stylesheet:

<head>
    <style type="text/css">
        a.nounderline {text-decoration: none; }
    </style>
</head>

And in the body:

<a href="#" class="nounderline">Link</a>

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

Remove "track by index" from the ng-repeat and it would refresh the DOM

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

Conversion failed when converting date and/or time from character string while inserting datetime

set Culture to english from web.config file

  <globalization uiCulture="en-US" culture="en-US" />

for example if you set the culture to arabic the thime will be

?22?/09?/2017? 02:16:57 ?

and you get the error:Conversion failed when converting date and/or time from character string while inserting datetime

Getting msbuild.exe without installing Visual Studio

The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/

Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)

See this question for additional information.

javax.faces.application.ViewExpiredException: View could not be restored

First what you have to do, before changing web.xml is to make sure your ManagedBean implements Serializable:

@ManagedBean
@ViewScoped
public class Login implements Serializable {
}

Especially if you use MyFaces

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

ImportError: No module named pip

I downloaded pip binaries from here and it resolved the issue.

Converting characters to integers in Java

Character.getNumericValue(c)

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

I couldn't get mvn eclipse:clean etc to work with Kepler.

However I changed creating and extending variables to just using external jars in my eclipse classpath. This was reflected in no var's in my .classpath.

This corrected the problem. I was able to do a Maven update.

Python module for converting PDF to text

Try PDFMiner. It can extract text from PDF files as HTML, SGML or "Tagged PDF" format.

The Tagged PDF format seems to be the cleanest, and stripping out the XML tags leaves just the bare text.

A Python 3 version is available under:

Vue.js getting an element within a component

vuejs 2

v-el:el:uniquename has been replaced by ref="uniqueName". The element is then accessed through this.$refs.uniqueName.

Android: How can I get the current foreground activity (from a service)?

Here's what I suggest and what has worked for me. In your application class, implement an Application.ActivityLifeCycleCallbacks listener and set a variable in your application class. Then query the variable as needed.

class YourApplication: Application.ActivityLifeCycleCallbacks {
    
    var currentActivity: Activity? = null

    fun onCreate() {
        registerActivityLifecycleCallbacks(this)
    }

    ...
    
    override fun onActivityResumed(activity: Activity) {
        currentActivity = activity
    }
}

Decimal or numeric values in regular expression validation

Actually, none of the given answers are fully cover the request.
As the OP didn't provided a specific use case or types of numbers, I will try to cover all possible cases and permutations.

Regular Numbers

Whole Positive

This number is usually called unsigned integer, but you can also call it a positive non-fractional number, include zero. This includes numbers like 0, 1 and 99999.
The Regular Expression that covers this validation is:

/^(0|[1-9]\d*)$/

Test This Regex

Whole Positive and Negative

This number is usually called signed integer, but you can also call it a non-fractional number. This includes numbers like 0, 1, 99999, -99999, -1 and -0.
The Regular Expression that covers this validation is:

/^-?(0|[1-9]\d*)$/

Test This Regex

As you probably noticed, I have also included -0 as a valid number. But, some may argue with this usage, and tell that this is not a real number (you can read more about Signed Zero here). So, if you want to exclude this number from this regex, here's what you should use instead:

/^-?(0|[1-9]\d*)(?<!-0)$/

Test This Regex

All I have added is (?<!-0), which means not to include -0 before this assertion. This (?<!...) assertion called negative lookbehind, which means that any phrase replaces the ... should not appear before this assertion. Lookbehind has limitations, like the phrase cannot include quantifiers. That's why for some cases I'll be using Lookahead instead, which is the same, but in the opposite way.

Many regex flavors, including those used by Perl and Python, only allow fixed-length strings. You can use literal text, character escapes, Unicode escapes other than \X, and character classes. You cannot use quantifiers or backreferences. You can use alternation, but only if all alternatives have the same length. These flavors evaluate lookbehind by first stepping back through the subject string for as many characters as the lookbehind needs, and then attempting the regex inside the lookbehind from left to right.

You can read more bout Lookaround assertions here.

Fractional Numbers

Positive

This number is usually called unsigned float or unsigned double, but you can also call it a positive fractional number, include zero. This includes numbers like 0, 1, 0.0, 0.1, 1.0, 99999.000001, 5.10.
The Regular Expression that covers this validation is:

/^(0|[1-9]\d*)(\.\d+)?$/

Test This Regex

Some may say, that numbers like .1, .0 and .00651 (same as 0.1, 0.0 and 0.00651 respectively) are also valid fractional numbers, and I cannot disagree with them. So here is a regex that is additionally supports this format:

/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/

Test This Regex

Negative and Positive

This number is usually called signed float or signed double, but you can also call it a fractional number. This includes numbers like 0, 1, 0.0, 0.1, 1.0, 99999.000001, 5.10, -0, -1, -0.0, -0.1, -99999.000001, 5.10.
The Regular Expression that covers this validation is:

/^-?(0|[1-9]\d*)(\.\d+)?$/

Test This Regex

For non -0 believers:

/^(?!-0(\.0+)?$)-?(0|[1-9]\d*)(\.\d+)?$/

Test This Regex

For those who want to support also the invisible zero representations, like .1, -.1, use the following regex:

/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/

Test This Regex

The combination of non -0 believers and invisible zero believers, use this regex:

/^(?!-0?(\.0+)?$)-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/

Test This Regex

Numbers with a Scientific Notation (AKA Exponential Notation)

Some may want to support in their validations, numbers with a scientific character e, which is by the way, an absolutely valid number, it is created for shortly represent a very long numbers. You can read more about Scientific Notation here. These numbers are usually looks like 1e3 (which is 1000), 1e-3 (which is 0.001) and are fully supported by many major programming languages (e.g. JavaScript). You can test it by checking if the expression '1e3'==1000 returns true.
I will divide the support for all the above sections, including numbers with scientific notation.

Regular Numbers

Whole positive number regex validation, supports numbers like 6e4, 16e-10, 0e0 but also regular numbers like 0, 11:

/^(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Whole positive and negative number regex validation, supports numbers like -6e4, -16e-10, -0e0 but also regular numbers like -0, -11 and all the whole positive numbers above:

/^-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Whole positive and negative number regex validation for non -0 believers, same as the above, except now it forbids numbers like -0, -0e0, -0e5 and -0e-6:

/^(?!-0)-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Fractional Numbers

Positive number regex validation, supports also the whole numbers above, plus numbers like 0.1e3, 56.0e-3, 0.0e10 and 1.010e0:

/^(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i

Test This Regex

Positive number with invisible zero support regex validation, supports also the above positive numbers, in addition numbers like .1e3, .0e0, .0e-5 and .1e-7:

/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Negative and positive number regex validation, supports the positive numbers above, but also numbers like -0e3, -0.1e0, -56.0e-3 and -0.0e10:

/^-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i

Test This Regex

Negative and positive number regex validation fro non -0 believers, same as the above, except now it forbids numbers like -0, -0.00000, -0.0e0, -0.00000e5 and -0e-6:

/^(?!-0(\.0+)?(e|$))-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i

Test This Regex

Negative and positive number with invisible zero support regex validation, supports also the above positive and negative numbers, in addition numbers like -.1e3, -.0e0, -.0e-5 and -.1e-7:

/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Negative and positive number with the combination of non -0 believers and invisible zero believers, same as the above, but forbids numbers like -.0e0, -.0000e15 and -.0e-19:

/^(?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Numbers with Hexadecimal Representation

In many programming languages, string representation of hexadecimal number like 0x4F7A may be easily cast to decimal number 20346.
Thus, one may want to support it in his validation script.
The following Regular Expression supports only hexadecimal numbers representations:

/^0x[0-9a-f]+$/i

Test This Regex

All Permutations

These final Regular Expressions, support the invisible zero numbers.

Signed Zero Believers

/^(-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i

Test This Regex

Non Signed Zero Believers

/^((?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i

Test This Regex

Hope I covered all number permutations that are supported in many programming languages.
Good luck!


Oh, forgot to mention, that those who want to validate a number includes a thousand separator, you should clean all the commas (,) first, as there may be any type of separator out there, you can't actually cover them all.
But you can remove them first, before the number validation:

//JavaScript
function clearSeparators(number)
{
    return number.replace(/,/g,'');
}

Similar post on my blog.

Install specific branch from github using Npm

you can give git pattern as version, yarn and npm are clever enough to resolve from a git repo.

yarn add any-package@user-name/repo-name#branch-name

or for npm

npm install --save any-package@user-name/repo-name#branch-name

Android - How to regenerate R class?

If you use Intellij IDEA you can click Build - Rebuild Project

Function inside a function.?

(4+3)*(4*2) == 56

Note that PHP doesn't really support "nested functions", as in defined only in the scope of the parent function. All functions are defined globally. See the docs.

Check if all values of array are equal

The accepted answer worked great but I wanted to add a tiny bit. It didn't work for me to use === because I was comparing arrays of arrays of objects, however throughout my app I've been using the fast-deep-equal package which I highly recommend. With that, my code looks like this:

let areAllEqual = arrs.every((val, i, arr) => equal(val, arr[0]) );

and my data looks like this:

[  
  [
    {
      "ID": 28,
      "AuthorID": 121,
      "VisitTypeID": 2
    },
    {
      "ID": 115,
      "AuthorID": 121,
      "VisitTypeID": 1
    },
    {
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
    }
  ],
  [
    {
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
    }
  ],
  [
    {
      "ID": 5,
      "AuthorID": 121,
      "VisitTypeID": 1
    },
    {
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
    }
  ]
]

How to trigger jQuery change event in code

Use the trigger() method

$(selector).trigger("change");

Remove rows not .isin('X')

You have many options. Collating some of the answers above and the accepted answer from this post you can do:
1. df[-df["column"].isin(["value"])]
2. df[~df["column"].isin(["value"])]
3. df[df["column"].isin(["value"]) == False]
4. df[np.logical_not(df["column"].isin(["value"]))]

Note: for option 4 for you'll need to import numpy as np

Update: You can also use the .query method for this too. This allows for method chaining:
5. df.query("column not in @values").
where values is a list of the values that you don't want to include.

Create a temporary table in a SELECT statement without a separate CREATE TABLE

Engine must be before select:

CREATE TEMPORARY TABLE temp1 ENGINE=MEMORY 
as (select * from table1)

Setting the default page for ASP.NET (Visual Studio) server configuration

Right click on the web page you want to use as the default page and choose "Set as Start Page" whenever you run the web application from Visual Studio, it will open the selected page.

How to get the fragment instance from the FragmentActivity?

You can use use findFragmentById in FragmentManager.

Since you are using the Support library (you are extending FragmentActivity) you can use:

getSupportFragmentManager().findFragmentById(R.id.pageview)

If you are not using the support library (so you are on Honeycomb+ and you don't want to use the support library):

getFragmentManager().findFragmentById(R.id.pageview)

Please consider that using the support library is recommended even on Honeycomb+.

Handling very large numbers in Python

The python interpreter will handle it for you, you just have to do your operations (+, -, *, /), and it will work as normal.

The int value is unlimited.

Careful when doing division, by default the quotient is turned into float, but float does not support such large numbers. If you get an error message saying float does not support such large numbers, then it means the quotient is too large to be stored in float you’ll have to use floor division (//).

It ignores any decimal that comes after the decimal point, this way, the result will be int, so you can have a large number result.

>>>10//3
3

>>>10//4
2

Remove insignificant trailing zeros from a number?

After reading all of the answers - and comments - I ended up with this:

function isFloat(n) {
    let number = (Number(n) === n && n % 1 !== 0) ? eval(parseFloat(n)) : n;
    return number;
}

I know using eval can be harmful somehow but this helped me a lot.

So:

isFloat(1.234000);     // = 1.234;
isFloat(1.234001);     // = 1.234001
isFloat(1.2340010000); // = 1.234001

If you want to limit the decimal places, use toFixed() as others pointed out.

let number = (Number(n) === n && n % 1 !== 0) ? eval(parseFloat(n).toFixed(3)) : n;

That's it.

Where is Java's Array indexOf?

There is no direct indexOf function in java arrays.

HttpClient won't import in Android Studio

Try this worked for me Add this dependency to your build.gradle File

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

Url decode UTF-8 in Python

If you are using Python 3, you can use urllib.parse

url = """example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0"""

import urllib.parse
urllib.parse.unquote(url)

gives:

'example.com?title=????????+??????'

Get a file name from a path

If you can use boost,

#include <boost/filesystem.hpp>
path p("C:\\MyDirectory\\MyFile.bat");
string basename = p.filename().string();
//or 
//string basename = path("C:\\MyDirectory\\MyFile.bat").filename().string();

This is all.

I recommend you to use boost library. Boost gives you a lot of conveniences when you work with C++. It supports almost all platforms. If you use Ubuntu, you can install boost library by only one line sudo apt-get install libboost-all-dev (ref. How to Install boost on Ubuntu?)

How can I get the status code from an http error in Axios?

You can put the error into an object and log the object, like this:

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

Hope this help someone out there.

Add a column with a default value to an existing table in SQL Server

The most basic version with two lines only

ALTER TABLE MyTable
ADD MyNewColumn INT NOT NULL DEFAULT 0

Put byte array to JSON and vice versa

The typical way to send binary in json is to base64 encode it.

Java provides different ways to Base64 encode and decode a byte[]. One of these is DatatypeConverter.

Very simply

byte[] originalBytes = new byte[] { 1, 2, 3, 4, 5};
String base64Encoded = DatatypeConverter.printBase64Binary(originalBytes);
byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded);

You'll have to make this conversion depending on the json parser/generator library you use.

How can I include all JavaScript files in a directory via JavaScript file?

You could use something like Grunt Include Source. It gives you a nice syntax that preprocesses your HTML, and then includes whatever you want. This also means, if you set up your build tasks correctly, you can have all these includes in dev mode, but not in prod mode, which is pretty cool.

If you aren't using Grunt for your project, there's probably similar tools for Gulp, or other task runners.

Byte array to image conversion

In one line:

Image.FromStream(new MemoryStream(byteArrayIn));

Detect whether Office is 32bit or 64bit via the registry

Best easy way: Put the ABOUT Icon on your Office 2016 Application. Example Excel

1) Open Excel -> File -> Options -> Customize Ribbon

2) You 'll see 2 panes. Choose Commands From & Customize The Ribbon

3) From Choose Command, Select All Commands

4) From the resulting List Highlight About (Excel)

5) From the Customize The Ribbon Pain, Highlight Any Item (ex. View) where you want to put the About icon

6) Click New group at the bottom

7) Click the add button located between the two pane. DONE

Now when you click the View Tab in excel and click about you'll see 32 bit or 64 bit

Count how many rows have the same value

Try

SELECT NAME, count(*) as NUM FROM tbl GROUP BY NAME

SQL FIDDLE

How do I make a LinearLayout scrollable?

<?xml version="1.0" encoding="utf-8"?>
<ScrollView ...>

    <LinearLayout ...>

        ...
        ...

    </LinearLayout>

</ScrollView>

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

This problem happened to me because I had the hibernate.default_schema set to a different database than the one in the DataSource.

Being strict on my mysql user permissions, when hibernate tried to query a table it queried the one in the hibernate.default_schema database for which the user had no permissions.

Its unfortunate that mysql does not correctly specify the database in this error message, as that would've cleared things up straight away.

Splitting a list into N parts of approximately equal length

this code works for me (Python3-compatible):

def chunkify(tab, num):
    return [tab[i*num: i*num+num] for i in range(len(tab)//num+(1 if len(tab)%num else 0))]

example (for bytearray type, but it works for lists as well):

b = bytearray(b'\x01\x02\x03\x04\x05\x06\x07\x08')
>>> chunkify(b,3)
[bytearray(b'\x01\x02\x03'), bytearray(b'\x04\x05\x06'), bytearray(b'\x07\x08')]
>>> chunkify(b,4)
[bytearray(b'\x01\x02\x03\x04'), bytearray(b'\x05\x06\x07\x08')]

Firebug-like debugger for Google Chrome

This doesn't answer your question but, in case you missed it, Chris Pederick's Web Developer is now available for Chrome: https://chrome.google.com/extensions/detail/bfbameneiokkgbdmiekhjnmfkcnldhhm.

Setting JDK in Eclipse

Eclipse's compiler can assure that your java sources conform to a given JDK version even if you don't have that version installed. This feature is useful for ensuring backwards compatibility of your code.

Your code will still be compiled and run by the JDK you've selected.

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

getResources().getColor() is deprecated

well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor function. You can get current theme with getTheme().

This will do the trick in fragment, you can replace getActivity() with getBaseContext(), yourContext, etc which hold your current context

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}

*p.s : color is deprecated in M, but drawable is deprecated in L

How can I disable HREF if onclick is executed?

Simply disable default browser behaviour using preventDefault and pass the event within your HTML.

<a href=/foo onclick= yes_js_login(event)>Lorem ipsum</a>

yes_js_login = function(e) {
  e.preventDefault();
}

How do I check what version of Python is running my script?

Check Python version: python -V or python --version or apt-cache policy python

you can also run whereis python to see how many versions are installed.

Developing C# on Linux

Mono Develop is what you want, if you have used visual studio you should find it simple enough to get started.

If I recall correctly you should be able to install with sudo apt-get install monodevelop

How to create batch file in Windows using "start" with a path and command with spaces

Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.

Try something like this:

start "Dummy Title" "c:\path with spaces\app.exe" param1 "param with spaces"

Make a dictionary with duplicate keys in Python

If you want to have lists only when they are necessary, and values in any other cases, then you can do this:

class DictList(dict):
    def __setitem__(self, key, value):
        try:
            # Assumes there is a list on the key
            self[key].append(value)
        except KeyError: # If it fails, because there is no key
            super(DictList, self).__setitem__(key, value)
        except AttributeError: # If it fails because it is not a list
            super(DictList, self).__setitem__(key, [self[key], value])

You can then do the following:

dl = DictList()
dl['a']  = 1
dl['b']  = 2
dl['b'] = 3

Which will store the following {'a': 1, 'b': [2, 3]}.


I tend to use this implementation when I want to have reverse/inverse dictionaries, in which case I simply do:

my_dict = {1: 'a', 2: 'b', 3: 'b'}
rev = DictList()
for k, v in my_dict.items():
    rev_med[v] = k

Which will generate the same output as above: {'a': 1, 'b': [2, 3]}.


CAVEAT: This implementation relies on the non-existence of the append method (in the values you are storing). This might produce unexpected results if the values you are storing are lists. For example,

dl = DictList()
dl['a']  = 1
dl['b']  = [2]
dl['b'] = 3

would produce the same result as before {'a': 1, 'b': [2, 3]}, but one might expected the following: {'a': 1, 'b': [[2], 3]}.

Best way to show a loading/progress indicator?

This is how I did this so that only one progress dialog can be open at a time. Based off of the answer from Suraj Bajaj

private ProgressDialog progress;



public void showLoadingDialog() {

    if (progress == null) {
        progress = new ProgressDialog(this);
        progress.setTitle(getString(R.string.loading_title));
        progress.setMessage(getString(R.string.loading_message));
    }
    progress.show();
}

public void dismissLoadingDialog() {

    if (progress != null && progress.isShowing()) {
        progress.dismiss();
    }
}

I also had to use

protected void onResume() {
    dismissLoadingDialog();
    super.onResume();
}

Can you use CSS to mirror/flip text?

You can user either

.your-class{ 
      position:absolute; 
      -moz-transform: scaleX(-1); 
      -o-transform: scaleX(-1); 
      -webkit-transform: scaleX(-1); 
      transform: scaleX(-1); 
      filter: FlipH;  
}

or

 .your-class{ 
  position:absolute;
  transform: rotate(360deg) scaleX(-1);
}

Notice that setting position to absolute is very important! If you won't set it, you will need to set display: inline-block;

mysqldump Error 1045 Access denied despite correct passwords etc

Putting -p as the first option worked for me on Windows Server 2012R2 (in cmd.exe as Admin).

mysqldump.exe –p --user=root  --databases DBname --result-file=C:\DBname.sql

SVN Repository on Google Drive or DropBox

While possible, it's potentially very risky - if you attempt to commit changes to the repository from 2 different locations simultaneously, you'll get a giant mess due to the file conflicts. Get a free private SVN host somewhere, or set up a repository on a server you have access to.

Edit based on a recent experience: If you have files open that are managed by Dropbox and your computer crashes, your files may be truncated to 0 bytes. If this happens to the files which manage your repository, your repository will be corrupted. If you discover this soon enough, you can use Dropbox's "recover old version" feature but you're still taking a risk.

Android change SDK version in Eclipse? Unable to resolve target android-x

Goto project -->properties --> (in the dialog box that opens goto Java build path), and in order and export select android 4.1 (your new version) and select dependencies.

How to read a single character from the user?

Answered here: raw_input in python without pressing enter

Use this code-

from tkinter import Tk, Frame


def __set_key(e, root):
    """
    e - event with attribute 'char', the released key
    """
    global key_pressed
    if e.char:
        key_pressed = e.char
        root.destroy()


def get_key(msg="Press any key ...", time_to_sleep=3):
    """
    msg - set to empty string if you don't want to print anything
    time_to_sleep - default 3 seconds
    """
    global key_pressed
    if msg:
        print(msg)
    key_pressed = None
    root = Tk()
    root.overrideredirect(True)
    frame = Frame(root, width=0, height=0)
    frame.bind("<KeyRelease>", lambda f: __set_key(f, root))
    frame.pack()
    root.focus_set()
    frame.focus_set()
    frame.focus_force()  # doesn't work in a while loop without it
    root.after(time_to_sleep * 1000, func=root.destroy)
    root.mainloop()
    root = None  # just in case
    return key_pressed


def __main():
        c = None
        while not c:
                c = get_key("Choose your weapon ... ", 2)
        print(c)

if __name__ == "__main__":
    __main()

Reference: https://github.com/unfor19/mg-tools/blob/master/mgtools/get_key_pressed.py

Best way to get value from Collection by index

use for each loop...

ArrayList<Character> al = new ArrayList<>();    
String input="hello";

for (int i = 0; i < input.length(); i++){
    al.add(input.charAt(i));
}

for (Character ch : al) {               
    System.Out.println(ch);             
}

What is token-based authentication?

It's just hash which is associated with user in database or some other way. That token can be used to authenticate and then authorize a user access related contents of the application. To retrieve this token on client side login is required. After first time login you need to save retrieved token not any other data like session, session id because here everything is token to access other resources of application.

Token is used to assure the authenticity of the user.

UPDATES: In current time, We have more advanced token based technology called JWT (Json Web Token). This technology helps to use same token in multiple systems and we call it single sign-on.

Basically JSON Based Token contains information about user details and token expiry details. So that information can be used to further authenticate or reject the request if token is invalid or expired based on details.

List supported SSL/TLS versions for a specific OpenSSL build

It's clumsy, but you can get this from the usage messages for s_client or s_server, which are #ifed at compile time to match the supported protocol versions. Use something like

 openssl s_client -help 2>&1 | awk '/-ssl[0-9]|-tls[0-9]/{print $1}' 
 # in older releases any unknown -option will work; in 1.1.0 must be exactly -help

What is the format specifier for unsigned short int?

Try using the "%h" modifier:

scanf("%hu", &length);
        ^

ISO/IEC 9899:201x - 7.21.6.1-7

Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.

What's the reason I can't create generic array types in Java?

Arrays Are Covariant

Arrays are said to be covariant which basically means that, given the subtyping rules of Java, an array of type T[] may contain elements of type T or any subtype of T. For instance

Number[] numbers = new Number[3];
numbers[0] = newInteger(10);
numbers[1] = newDouble(3.14);
numbers[2] = newByte(0);

But not only that, the subtyping rules of Java also state that an array S[] is a subtype of the array T[] if S is a subtype of T, therefore, something like this is also valid:

Integer[] myInts = {1,2,3,4};
Number[] myNumber = myInts;

Because according to the subtyping rules in Java, an array Integer[] is a subtype of an array Number[] because Integer is a subtype of Number.

But this subtyping rule can lead to an interesting question: what would happen if we try to do this?

myNumber[0] = 3.14; //attempt of heap pollution

This last line would compile just fine, but if we run this code, we would get an ArrayStoreException because we’re trying to put a double into an integer array. The fact that we are accessing the array through a Number reference is irrelevant here, what matters is that the array is an array of integers.

This means that we can fool the compiler, but we cannot fool the run-time type system. And this is so because arrays are what we call a reifiable type. This means that at run-time Java knows that this array was actually instantiated as an array of integers which simply happens to be accessed through a reference of type Number[].

So, as we can see, one thing is the actual type of the object, an another thing is the type of the reference that we use to access it, right?

The Problem with Java Generics

Now, the problem with generic types in Java is that the type information for type parameters is discarded by the compiler after the compilation of code is done; therefore this type information is not available at run time. This process is called type erasure. There are good reasons for implementing generics like this in Java, but that’s a long story, and it has to do with binary compatibility with pre-existing code.

The important point here is that since at run-time there is no type information, there is no way to ensure that we are not committing heap pollution.

Let’s consider now the following unsafe code:

List<Integer> myInts = newArrayList<Integer>();
myInts.add(1);
myInts.add(2);
List<Number> myNums = myInts; //compiler error
myNums.add(3.14); //heap polution

If the Java compiler does not stop us from doing this, the run-time type system cannot stop us either, because there is no way, at run time, to determine that this list was supposed to be a list of integers only. The Java run-time would let us put whatever we want into this list, when it should only contain integers, because when it was created, it was declared as a list of integers. That’s why the compiler rejects line number 4 because it is unsafe and if allowed could break the assumptions of the type system.

As such, the designers of Java made sure that we cannot fool the compiler. If we cannot fool the compiler (as we can do with arrays) then we cannot fool the run-time type system either.

As such, we say that generic types are non-reifiable, since at run time we cannot determine the true nature of the generic type.

I skipped some parts of this answers you can read full article here: https://dzone.com/articles/covariance-and-contravariance

How to parse data in JSON format?

Following is simple example that may help you:

json_string = """
{
    "pk": 1, 
    "fa": "cc.ee", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)

The output for the above code will be:

{"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345", 
 "fc": ""}, "fa": "cc.ee"}

Note that you can set the ident argument of dump to print it like so (for example,when using print json.dumps(data , indent=4)):

{
    "pk": 1, 
    "fb": {
        "new_key": "cc.ee was present!", 
        "fd_id": "12345", 
        "fc": ""
    }, 
    "fa": "cc.ee"
}

link button property to open in new tab?

It throws error.

Microsoft JScript runtime error: 'aspnetForm' is undefined

Counting the number of non-NaN elements in a numpy ndarray in Python

An alternative, but a bit slower alternative is to do it over indexing.

np.isnan(data)[np.isnan(data) == False].size

In [30]: %timeit np.isnan(data)[np.isnan(data) == False].size
1 loops, best of 3: 498 ms per loop 

The double use of np.isnan(data) and the == operator might be a bit overkill and so I posted the answer only for completeness.

How to "pretty" format JSON output in Ruby on Rails

Using <pre> HTML code and pretty_generate is good trick:

<%
  require 'json'

  hash = JSON[{hey: "test", num: [{one: 1, two: 2, threes: [{three: 3, tthree: 33}]}]}.to_json] 
%>

<pre>
  <%=  JSON.pretty_generate(hash) %>
</pre>

Generating a drop down list of timezones with PHP

If you don't want to be dependent on static timezone list, or want to display the offset along with timezone.

Here is what I came up with

function timezones()
{
    $timezones = \DateTimeZone::listIdentifiers();
    $items = array();
    foreach($timezones as $timezoneId) {
        $timezone = new \DateTimeZone($timezoneId);
        $offsetInSeconds = $timezone->getOffset(new \DateTime());
        $items[$timezoneId] = $offsetInSeconds;
    }
    asort($items);
    array_walk ($items, function (&$offsetInSeconds, &$timezoneId) { 
        $offsetPrefix = $offsetInSeconds < 0 ? '-' : '+';
        $offset = gmdate('H:i', abs($offsetInSeconds));
        $offset = "(GMT${offsetPrefix}${offset}) ".$timezoneId;
        $offsetInSeconds = $offset;
    });
    return $items;
}

Which gives me the following result

Array
(
    [Pacific/Midway] => (GMT-11:00) Pacific/Midway
    [Pacific/Pago_Pago] => (GMT-11:00) Pacific/Pago_Pago
    [Pacific/Niue] => (GMT-11:00) Pacific/Niue
    [America/Adak] => (GMT-10:00) America/Adak
    [Pacific/Tahiti] => (GMT-10:00) Pacific/Tahiti
    [Pacific/Rarotonga] => (GMT-10:00) Pacific/Rarotonga
    [Pacific/Honolulu] => (GMT-10:00) Pacific/Honolulu
    [Pacific/Marquesas] => (GMT-09:30) Pacific/Marquesas
    [America/Sitka] => (GMT-09:00) America/Sitka
    [Pacific/Gambier] => (GMT-09:00) Pacific/Gambier
    [America/Yakutat] => (GMT-09:00) America/Yakutat
    [America/Juneau] => (GMT-09:00) America/Juneau
    [America/Nome] => (GMT-09:00) America/Nome
    [America/Anchorage] => (GMT-09:00) America/Anchorage
    [America/Metlakatla] => (GMT-09:00) America/Metlakatla
    [America/Los_Angeles] => (GMT-08:00) America/Los_Angeles
    [America/Tijuana] => (GMT-08:00) America/Tijuana
    [America/Whitehorse] => (GMT-08:00) America/Whitehorse
    [America/Vancouver] => (GMT-08:00) America/Vancouver
    [America/Dawson] => (GMT-08:00) America/Dawson
    [Pacific/Pitcairn] => (GMT-08:00) Pacific/Pitcairn
    [America/Mazatlan] => (GMT-07:00) America/Mazatlan
    [America/Fort_Nelson] => (GMT-07:00) America/Fort_Nelson
    [America/Yellowknife] => (GMT-07:00) America/Yellowknife
    [America/Inuvik] => (GMT-07:00) America/Inuvik
    [America/Edmonton] => (GMT-07:00) America/Edmonton
    [America/Denver] => (GMT-07:00) America/Denver
    [America/Chihuahua] => (GMT-07:00) America/Chihuahua
    [America/Boise] => (GMT-07:00) America/Boise
    [America/Ojinaga] => (GMT-07:00) America/Ojinaga
    [America/Cambridge_Bay] => (GMT-07:00) America/Cambridge_Bay
    [America/Dawson_Creek] => (GMT-07:00) America/Dawson_Creek
    [America/Phoenix] => (GMT-07:00) America/Phoenix
    [America/Hermosillo] => (GMT-07:00) America/Hermosillo
    [America/Creston] => (GMT-07:00) America/Creston
    [America/Matamoros] => (GMT-06:00) America/Matamoros
    [America/Menominee] => (GMT-06:00) America/Menominee
    [America/Indiana/Knox] => (GMT-06:00) America/Indiana/Knox
    [America/Managua] => (GMT-06:00) America/Managua
    [America/Bahia_Banderas] => (GMT-06:00) America/Bahia_Banderas
    [America/Indiana/Tell_City] => (GMT-06:00) America/Indiana/Tell_City
    [America/Belize] => (GMT-06:00) America/Belize
    [America/Chicago] => (GMT-06:00) America/Chicago
    [America/Guatemala] => (GMT-06:00) America/Guatemala
    [America/El_Salvador] => (GMT-06:00) America/El_Salvador
    [America/Merida] => (GMT-06:00) America/Merida
    [America/Costa_Rica] => (GMT-06:00) America/Costa_Rica
    [America/Mexico_City] => (GMT-06:00) America/Mexico_City
    [America/Winnipeg] => (GMT-06:00) America/Winnipeg
    [Pacific/Galapagos] => (GMT-06:00) Pacific/Galapagos
    [America/Resolute] => (GMT-06:00) America/Resolute
    [America/Regina] => (GMT-06:00) America/Regina
    [America/Rankin_Inlet] => (GMT-06:00) America/Rankin_Inlet
    [America/Rainy_River] => (GMT-06:00) America/Rainy_River
    [America/North_Dakota/New_Salem] => (GMT-06:00) America/North_Dakota/New_Salem
    [America/North_Dakota/Beulah] => (GMT-06:00) America/North_Dakota/Beulah
    [America/North_Dakota/Center] => (GMT-06:00) America/North_Dakota/Center
    [America/Tegucigalpa] => (GMT-06:00) America/Tegucigalpa
    [America/Swift_Current] => (GMT-06:00) America/Swift_Current
    [America/Monterrey] => (GMT-06:00) America/Monterrey
    [America/Pangnirtung] => (GMT-05:00) America/Pangnirtung
    [America/Indiana/Petersburg] => (GMT-05:00) America/Indiana/Petersburg
    [America/Indiana/Marengo] => (GMT-05:00) America/Indiana/Marengo
    [America/Bogota] => (GMT-05:00) America/Bogota
    [America/Toronto] => (GMT-05:00) America/Toronto
    [America/Detroit] => (GMT-05:00) America/Detroit
    [America/Panama] => (GMT-05:00) America/Panama
    [America/Cancun] => (GMT-05:00) America/Cancun
    [America/Rio_Branco] => (GMT-05:00) America/Rio_Branco
    [America/Port-au-Prince] => (GMT-05:00) America/Port-au-Prince
    [America/Cayman] => (GMT-05:00) America/Cayman
    [America/Grand_Turk] => (GMT-05:00) America/Grand_Turk
    [America/Havana] => (GMT-05:00) America/Havana
    [America/Indiana/Indianapolis] => (GMT-05:00) America/Indiana/Indianapolis
    [America/Indiana/Vevay] => (GMT-05:00) America/Indiana/Vevay
    [America/Guayaquil] => (GMT-05:00) America/Guayaquil
    [America/Nipigon] => (GMT-05:00) America/Nipigon
    [America/Indiana/Vincennes] => (GMT-05:00) America/Indiana/Vincennes
    [America/Atikokan] => (GMT-05:00) America/Atikokan
    [America/Indiana/Winamac] => (GMT-05:00) America/Indiana/Winamac
    [America/New_York] => (GMT-05:00) America/New_York
    [America/Iqaluit] => (GMT-05:00) America/Iqaluit
    [America/Jamaica] => (GMT-05:00) America/Jamaica
    [America/Nassau] => (GMT-05:00) America/Nassau
    [America/Kentucky/Louisville] => (GMT-05:00) America/Kentucky/Louisville
    [America/Kentucky/Monticello] => (GMT-05:00) America/Kentucky/Monticello
    [America/Eirunepe] => (GMT-05:00) America/Eirunepe
    [Pacific/Easter] => (GMT-05:00) Pacific/Easter
    [America/Lima] => (GMT-05:00) America/Lima
    [America/Thunder_Bay] => (GMT-05:00) America/Thunder_Bay
    [America/Guadeloupe] => (GMT-04:00) America/Guadeloupe
    [America/Manaus] => (GMT-04:00) America/Manaus
    [America/Guyana] => (GMT-04:00) America/Guyana
    [America/Halifax] => (GMT-04:00) America/Halifax
    [America/Puerto_Rico] => (GMT-04:00) America/Puerto_Rico
    [America/Porto_Velho] => (GMT-04:00) America/Porto_Velho
    [America/Port_of_Spain] => (GMT-04:00) America/Port_of_Spain
    [America/Montserrat] => (GMT-04:00) America/Montserrat
    [America/Moncton] => (GMT-04:00) America/Moncton
    [America/Martinique] => (GMT-04:00) America/Martinique
    [America/Kralendijk] => (GMT-04:00) America/Kralendijk
    [America/La_Paz] => (GMT-04:00) America/La_Paz
    [America/Marigot] => (GMT-04:00) America/Marigot
    [America/Lower_Princes] => (GMT-04:00) America/Lower_Princes
    [America/Grenada] => (GMT-04:00) America/Grenada
    [America/Santo_Domingo] => (GMT-04:00) America/Santo_Domingo
    [America/Goose_Bay] => (GMT-04:00) America/Goose_Bay
    [America/Caracas] => (GMT-04:00) America/Caracas
    [America/Anguilla] => (GMT-04:00) America/Anguilla
    [America/St_Barthelemy] => (GMT-04:00) America/St_Barthelemy
    [America/Barbados] => (GMT-04:00) America/Barbados
    [America/St_Kitts] => (GMT-04:00) America/St_Kitts
    [America/Blanc-Sablon] => (GMT-04:00) America/Blanc-Sablon
    [America/Boa_Vista] => (GMT-04:00) America/Boa_Vista
    [America/St_Lucia] => (GMT-04:00) America/St_Lucia
    [America/St_Thomas] => (GMT-04:00) America/St_Thomas
    [America/Antigua] => (GMT-04:00) America/Antigua
    [America/St_Vincent] => (GMT-04:00) America/St_Vincent
    [America/Thule] => (GMT-04:00) America/Thule
    [America/Curacao] => (GMT-04:00) America/Curacao
    [America/Tortola] => (GMT-04:00) America/Tortola
    [America/Dominica] => (GMT-04:00) America/Dominica
    [Atlantic/Bermuda] => (GMT-04:00) Atlantic/Bermuda
    [America/Glace_Bay] => (GMT-04:00) America/Glace_Bay
    [America/Aruba] => (GMT-04:00) America/Aruba
    [America/St_Johns] => (GMT-03:30) America/St_Johns
    [America/Argentina/Tucuman] => (GMT-03:00) America/Argentina/Tucuman
    [America/Belem] => (GMT-03:00) America/Belem
    [America/Santiago] => (GMT-03:00) America/Santiago
    [America/Santarem] => (GMT-03:00) America/Santarem
    [America/Recife] => (GMT-03:00) America/Recife
    [America/Punta_Arenas] => (GMT-03:00) America/Punta_Arenas
    [Atlantic/Stanley] => (GMT-03:00) Atlantic/Stanley
    [America/Paramaribo] => (GMT-03:00) America/Paramaribo
    [America/Fortaleza] => (GMT-03:00) America/Fortaleza
    [America/Argentina/San_Luis] => (GMT-03:00) America/Argentina/San_Luis
    [Antarctica/Palmer] => (GMT-03:00) Antarctica/Palmer
    [America/Montevideo] => (GMT-03:00) America/Montevideo
    [America/Cuiaba] => (GMT-03:00) America/Cuiaba
    [America/Miquelon] => (GMT-03:00) America/Miquelon
    [America/Cayenne] => (GMT-03:00) America/Cayenne
    [America/Campo_Grande] => (GMT-03:00) America/Campo_Grande
    [Antarctica/Rothera] => (GMT-03:00) Antarctica/Rothera
    [America/Godthab] => (GMT-03:00) America/Godthab
    [America/Bahia] => (GMT-03:00) America/Bahia
    [America/Asuncion] => (GMT-03:00) America/Asuncion
    [America/Argentina/Ushuaia] => (GMT-03:00) America/Argentina/Ushuaia
    [America/Argentina/La_Rioja] => (GMT-03:00) America/Argentina/La_Rioja
    [America/Araguaina] => (GMT-03:00) America/Araguaina
    [America/Argentina/Buenos_Aires] => (GMT-03:00) America/Argentina/Buenos_Aires
    [America/Argentina/Rio_Gallegos] => (GMT-03:00) America/Argentina/Rio_Gallegos
    [America/Argentina/Catamarca] => (GMT-03:00) America/Argentina/Catamarca
    [America/Maceio] => (GMT-03:00) America/Maceio
    [America/Argentina/San_Juan] => (GMT-03:00) America/Argentina/San_Juan
    [America/Argentina/Salta] => (GMT-03:00) America/Argentina/Salta
    [America/Argentina/Mendoza] => (GMT-03:00) America/Argentina/Mendoza
    [America/Argentina/Cordoba] => (GMT-03:00) America/Argentina/Cordoba
    [America/Argentina/Jujuy] => (GMT-03:00) America/Argentina/Jujuy
    [Atlantic/South_Georgia] => (GMT-02:00) Atlantic/South_Georgia
    [America/Noronha] => (GMT-02:00) America/Noronha
    [America/Sao_Paulo] => (GMT-02:00) America/Sao_Paulo
    [Atlantic/Cape_Verde] => (GMT-01:00) Atlantic/Cape_Verde
    [Atlantic/Azores] => (GMT-01:00) Atlantic/Azores
    [America/Scoresbysund] => (GMT-01:00) America/Scoresbysund
    [Europe/Lisbon] => (GMT+00:00) Europe/Lisbon
    [Europe/London] => (GMT+00:00) Europe/London
    [Europe/Jersey] => (GMT+00:00) Europe/Jersey
    [Europe/Isle_of_Man] => (GMT+00:00) Europe/Isle_of_Man
    [Atlantic/Faroe] => (GMT+00:00) Atlantic/Faroe
    [Europe/Guernsey] => (GMT+00:00) Europe/Guernsey
    [Europe/Dublin] => (GMT+00:00) Europe/Dublin
    [Atlantic/St_Helena] => (GMT+00:00) Atlantic/St_Helena
    [Atlantic/Reykjavik] => (GMT+00:00) Atlantic/Reykjavik
    [Atlantic/Madeira] => (GMT+00:00) Atlantic/Madeira
    [Atlantic/Canary] => (GMT+00:00) Atlantic/Canary
    [Africa/Accra] => (GMT+00:00) Africa/Accra
    [Antarctica/Troll] => (GMT+00:00) Antarctica/Troll
    [Africa/Abidjan] => (GMT+00:00) Africa/Abidjan
    [UTC] => (GMT+00:00) UTC
    [America/Danmarkshavn] => (GMT+00:00) America/Danmarkshavn
    [Africa/Monrovia] => (GMT+00:00) Africa/Monrovia
    [Africa/Dakar] => (GMT+00:00) Africa/Dakar
    [Africa/Conakry] => (GMT+00:00) Africa/Conakry
    [Africa/Casablanca] => (GMT+00:00) Africa/Casablanca
    [Africa/Lome] => (GMT+00:00) Africa/Lome
    [Africa/Freetown] => (GMT+00:00) Africa/Freetown
    [Africa/El_Aaiun] => (GMT+00:00) Africa/El_Aaiun
    [Africa/Bissau] => (GMT+00:00) Africa/Bissau
    [Africa/Nouakchott] => (GMT+00:00) Africa/Nouakchott
    [Africa/Banjul] => (GMT+00:00) Africa/Banjul
    [Africa/Ouagadougou] => (GMT+00:00) Africa/Ouagadougou
    [Africa/Bamako] => (GMT+00:00) Africa/Bamako
    [Europe/Gibraltar] => (GMT+01:00) Europe/Gibraltar
    [Africa/Bangui] => (GMT+01:00) Africa/Bangui
    [Europe/Ljubljana] => (GMT+01:00) Europe/Ljubljana
    [Africa/Ceuta] => (GMT+01:00) Africa/Ceuta
    [Africa/Algiers] => (GMT+01:00) Africa/Algiers
    [Europe/Busingen] => (GMT+01:00) Europe/Busingen
    [Europe/Copenhagen] => (GMT+01:00) Europe/Copenhagen
    [Europe/Madrid] => (GMT+01:00) Europe/Madrid
    [Europe/Budapest] => (GMT+01:00) Europe/Budapest
    [Europe/Brussels] => (GMT+01:00) Europe/Brussels
    [Europe/Bratislava] => (GMT+01:00) Europe/Bratislava
    [Europe/Berlin] => (GMT+01:00) Europe/Berlin
    [Europe/Belgrade] => (GMT+01:00) Europe/Belgrade
    [Europe/Andorra] => (GMT+01:00) Europe/Andorra
    [Europe/Amsterdam] => (GMT+01:00) Europe/Amsterdam
    [Europe/Luxembourg] => (GMT+01:00) Europe/Luxembourg
    [Europe/Monaco] => (GMT+01:00) Europe/Monaco
    [Europe/Malta] => (GMT+01:00) Europe/Malta
    [Europe/Tirane] => (GMT+01:00) Europe/Tirane
    [Europe/Zurich] => (GMT+01:00) Europe/Zurich
    [Europe/Zagreb] => (GMT+01:00) Europe/Zagreb
    [Europe/Warsaw] => (GMT+01:00) Europe/Warsaw
    [Europe/Vienna] => (GMT+01:00) Europe/Vienna
    [Europe/Vatican] => (GMT+01:00) Europe/Vatican
    [Europe/Vaduz] => (GMT+01:00) Europe/Vaduz
    [Europe/Stockholm] => (GMT+01:00) Europe/Stockholm
    [Africa/Brazzaville] => (GMT+01:00) Africa/Brazzaville
    [Europe/Skopje] => (GMT+01:00) Europe/Skopje
    [Europe/Sarajevo] => (GMT+01:00) Europe/Sarajevo
    [Europe/San_Marino] => (GMT+01:00) Europe/San_Marino
    [Europe/Rome] => (GMT+01:00) Europe/Rome
    [Europe/Prague] => (GMT+01:00) Europe/Prague
    [Europe/Paris] => (GMT+01:00) Europe/Paris
    [Europe/Oslo] => (GMT+01:00) Europe/Oslo
    [Europe/Podgorica] => (GMT+01:00) Europe/Podgorica
    [Africa/Douala] => (GMT+01:00) Africa/Douala
    [Arctic/Longyearbyen] => (GMT+01:00) Arctic/Longyearbyen
    [Africa/Malabo] => (GMT+01:00) Africa/Malabo
    [Africa/Kinshasa] => (GMT+01:00) Africa/Kinshasa
    [Africa/Libreville] => (GMT+01:00) Africa/Libreville
    [Africa/Ndjamena] => (GMT+01:00) Africa/Ndjamena
    [Africa/Lagos] => (GMT+01:00) Africa/Lagos
    [Africa/Niamey] => (GMT+01:00) Africa/Niamey
    [Africa/Porto-Novo] => (GMT+01:00) Africa/Porto-Novo
    [Africa/Sao_Tome] => (GMT+01:00) Africa/Sao_Tome
    [Africa/Luanda] => (GMT+01:00) Africa/Luanda
    [Africa/Tunis] => (GMT+01:00) Africa/Tunis
    [Europe/Uzhgorod] => (GMT+02:00) Europe/Uzhgorod
    [Africa/Harare] => (GMT+02:00) Africa/Harare
    [Europe/Mariehamn] => (GMT+02:00) Europe/Mariehamn
    [Africa/Lubumbashi] => (GMT+02:00) Africa/Lubumbashi
    [Asia/Nicosia] => (GMT+02:00) Asia/Nicosia
    [Africa/Windhoek] => (GMT+02:00) Africa/Windhoek
    [Europe/Tallinn] => (GMT+02:00) Europe/Tallinn
    [Europe/Zaporozhye] => (GMT+02:00) Europe/Zaporozhye
    [Africa/Gaborone] => (GMT+02:00) Africa/Gaborone
    [Africa/Mbabane] => (GMT+02:00) Africa/Mbabane
    [Africa/Khartoum] => (GMT+02:00) Africa/Khartoum
    [Africa/Johannesburg] => (GMT+02:00) Africa/Johannesburg
    [Europe/Vilnius] => (GMT+02:00) Europe/Vilnius
    [Africa/Maseru] => (GMT+02:00) Africa/Maseru
    [Africa/Lusaka] => (GMT+02:00) Africa/Lusaka
    [Europe/Riga] => (GMT+02:00) Europe/Riga
    [Africa/Kigali] => (GMT+02:00) Africa/Kigali
    [Europe/Helsinki] => (GMT+02:00) Europe/Helsinki
    [Africa/Maputo] => (GMT+02:00) Africa/Maputo
    [Europe/Chisinau] => (GMT+02:00) Europe/Chisinau
    [Europe/Sofia] => (GMT+02:00) Europe/Sofia
    [Asia/Beirut] => (GMT+02:00) Asia/Beirut
    [Africa/Blantyre] => (GMT+02:00) Africa/Blantyre
    [Asia/Jerusalem] => (GMT+02:00) Asia/Jerusalem
    [Asia/Gaza] => (GMT+02:00) Asia/Gaza
    [Asia/Amman] => (GMT+02:00) Asia/Amman
    [Asia/Famagusta] => (GMT+02:00) Asia/Famagusta
    [Europe/Athens] => (GMT+02:00) Europe/Athens
    [Africa/Bujumbura] => (GMT+02:00) Africa/Bujumbura
    [Asia/Hebron] => (GMT+02:00) Asia/Hebron
    [Europe/Kaliningrad] => (GMT+02:00) Europe/Kaliningrad
    [Africa/Cairo] => (GMT+02:00) Africa/Cairo
    [Europe/Kiev] => (GMT+02:00) Europe/Kiev
    [Europe/Bucharest] => (GMT+02:00) Europe/Bucharest
    [Asia/Damascus] => (GMT+02:00) Asia/Damascus
    [Africa/Tripoli] => (GMT+02:00) Africa/Tripoli
    [Asia/Baghdad] => (GMT+03:00) Asia/Baghdad
    [Africa/Djibouti] => (GMT+03:00) Africa/Djibouti
    [Asia/Aden] => (GMT+03:00) Asia/Aden
    [Asia/Bahrain] => (GMT+03:00) Asia/Bahrain
    [Europe/Istanbul] => (GMT+03:00) Europe/Istanbul
    [Africa/Juba] => (GMT+03:00) Africa/Juba
    [Europe/Kirov] => (GMT+03:00) Europe/Kirov
    [Europe/Moscow] => (GMT+03:00) Europe/Moscow
    [Antarctica/Syowa] => (GMT+03:00) Antarctica/Syowa
    [Europe/Minsk] => (GMT+03:00) Europe/Minsk
    [Africa/Kampala] => (GMT+03:00) Africa/Kampala
    [Africa/Dar_es_Salaam] => (GMT+03:00) Africa/Dar_es_Salaam
    [Europe/Simferopol] => (GMT+03:00) Europe/Simferopol
    [Asia/Riyadh] => (GMT+03:00) Asia/Riyadh
    [Indian/Antananarivo] => (GMT+03:00) Indian/Antananarivo
    [Asia/Kuwait] => (GMT+03:00) Asia/Kuwait
    [Africa/Nairobi] => (GMT+03:00) Africa/Nairobi
    [Indian/Mayotte] => (GMT+03:00) Indian/Mayotte
    [Africa/Mogadishu] => (GMT+03:00) Africa/Mogadishu
    [Asia/Qatar] => (GMT+03:00) Asia/Qatar
    [Europe/Volgograd] => (GMT+03:00) Europe/Volgograd
    [Africa/Asmara] => (GMT+03:00) Africa/Asmara
    [Africa/Addis_Ababa] => (GMT+03:00) Africa/Addis_Ababa
    [Indian/Comoro] => (GMT+03:00) Indian/Comoro
    [Asia/Tehran] => (GMT+03:30) Asia/Tehran
    [Europe/Saratov] => (GMT+04:00) Europe/Saratov
    [Indian/Reunion] => (GMT+04:00) Indian/Reunion
    [Europe/Astrakhan] => (GMT+04:00) Europe/Astrakhan
    [Asia/Baku] => (GMT+04:00) Asia/Baku
    [Asia/Dubai] => (GMT+04:00) Asia/Dubai
    [Indian/Mauritius] => (GMT+04:00) Indian/Mauritius
    [Indian/Mahe] => (GMT+04:00) Indian/Mahe
    [Asia/Tbilisi] => (GMT+04:00) Asia/Tbilisi
    [Asia/Yerevan] => (GMT+04:00) Asia/Yerevan
    [Asia/Muscat] => (GMT+04:00) Asia/Muscat
    [Europe/Samara] => (GMT+04:00) Europe/Samara
    [Europe/Ulyanovsk] => (GMT+04:00) Europe/Ulyanovsk
    [Asia/Kabul] => (GMT+04:30) Asia/Kabul
    [Antarctica/Mawson] => (GMT+05:00) Antarctica/Mawson
    [Asia/Samarkand] => (GMT+05:00) Asia/Samarkand
    [Asia/Aqtobe] => (GMT+05:00) Asia/Aqtobe
    [Indian/Maldives] => (GMT+05:00) Indian/Maldives
    [Asia/Ashgabat] => (GMT+05:00) Asia/Ashgabat
    [Asia/Atyrau] => (GMT+05:00) Asia/Atyrau
    [Asia/Dushanbe] => (GMT+05:00) Asia/Dushanbe
    [Asia/Yekaterinburg] => (GMT+05:00) Asia/Yekaterinburg
    [Asia/Oral] => (GMT+05:00) Asia/Oral
    [Asia/Aqtau] => (GMT+05:00) Asia/Aqtau
    [Asia/Karachi] => (GMT+05:00) Asia/Karachi
    [Asia/Tashkent] => (GMT+05:00) Asia/Tashkent
    [Indian/Kerguelen] => (GMT+05:00) Indian/Kerguelen
    [Asia/Colombo] => (GMT+05:30) Asia/Colombo
    [Asia/Kolkata] => (GMT+05:30) Asia/Kolkata
    [Asia/Kathmandu] => (GMT+05:45) Asia/Kathmandu
    [Antarctica/Vostok] => (GMT+06:00) Antarctica/Vostok
    [Indian/Chagos] => (GMT+06:00) Indian/Chagos
    [Asia/Almaty] => (GMT+06:00) Asia/Almaty
    [Asia/Omsk] => (GMT+06:00) Asia/Omsk
    [Asia/Dhaka] => (GMT+06:00) Asia/Dhaka
    [Asia/Bishkek] => (GMT+06:00) Asia/Bishkek
    [Asia/Urumqi] => (GMT+06:00) Asia/Urumqi
    [Asia/Thimphu] => (GMT+06:00) Asia/Thimphu
    [Asia/Qyzylorda] => (GMT+06:00) Asia/Qyzylorda
    [Indian/Cocos] => (GMT+06:30) Indian/Cocos
    [Asia/Yangon] => (GMT+06:30) Asia/Yangon
    [Asia/Novokuznetsk] => (GMT+07:00) Asia/Novokuznetsk
    [Asia/Barnaul] => (GMT+07:00) Asia/Barnaul
    [Antarctica/Davis] => (GMT+07:00) Antarctica/Davis
    [Asia/Novosibirsk] => (GMT+07:00) Asia/Novosibirsk
    [Asia/Krasnoyarsk] => (GMT+07:00) Asia/Krasnoyarsk
    [Asia/Phnom_Penh] => (GMT+07:00) Asia/Phnom_Penh
    [Asia/Pontianak] => (GMT+07:00) Asia/Pontianak
    [Asia/Jakarta] => (GMT+07:00) Asia/Jakarta
    [Asia/Hovd] => (GMT+07:00) Asia/Hovd
    [Asia/Tomsk] => (GMT+07:00) Asia/Tomsk
    [Asia/Ho_Chi_Minh] => (GMT+07:00) Asia/Ho_Chi_Minh
    [Asia/Vientiane] => (GMT+07:00) Asia/Vientiane
    [Indian/Christmas] => (GMT+07:00) Indian/Christmas
    [Asia/Bangkok] => (GMT+07:00) Asia/Bangkok
    [Asia/Choibalsan] => (GMT+08:00) Asia/Choibalsan
    [Asia/Taipei] => (GMT+08:00) Asia/Taipei
    [Asia/Makassar] => (GMT+08:00) Asia/Makassar
    [Asia/Macau] => (GMT+08:00) Asia/Macau
    [Asia/Kuching] => (GMT+08:00) Asia/Kuching
    [Asia/Kuala_Lumpur] => (GMT+08:00) Asia/Kuala_Lumpur
    [Asia/Shanghai] => (GMT+08:00) Asia/Shanghai
    [Asia/Singapore] => (GMT+08:00) Asia/Singapore
    [Asia/Brunei] => (GMT+08:00) Asia/Brunei
    [Asia/Irkutsk] => (GMT+08:00) Asia/Irkutsk
    [Asia/Ulaanbaatar] => (GMT+08:00) Asia/Ulaanbaatar
    [Australia/Perth] => (GMT+08:00) Australia/Perth
    [Asia/Hong_Kong] => (GMT+08:00) Asia/Hong_Kong
    [Antarctica/Casey] => (GMT+08:00) Antarctica/Casey
    [Asia/Manila] => (GMT+08:00) Asia/Manila
    [Australia/Eucla] => (GMT+08:45) Australia/Eucla
    [Asia/Jayapura] => (GMT+09:00) Asia/Jayapura
    [Asia/Khandyga] => (GMT+09:00) Asia/Khandyga
    [Pacific/Palau] => (GMT+09:00) Pacific/Palau
    [Asia/Dili] => (GMT+09:00) Asia/Dili
    [Asia/Yakutsk] => (GMT+09:00) Asia/Yakutsk
    [Asia/Tokyo] => (GMT+09:00) Asia/Tokyo
    [Asia/Seoul] => (GMT+09:00) Asia/Seoul
    [Asia/Chita] => (GMT+09:00) Asia/Chita
    [Asia/Pyongyang] => (GMT+09:00) Asia/Pyongyang
    [Australia/Darwin] => (GMT+09:30) Australia/Darwin
    [Asia/Ust-Nera] => (GMT+10:00) Asia/Ust-Nera
    [Pacific/Chuuk] => (GMT+10:00) Pacific/Chuuk
    [Antarctica/DumontDUrville] => (GMT+10:00) Antarctica/DumontDUrville
    [Pacific/Guam] => (GMT+10:00) Pacific/Guam
    [Pacific/Port_Moresby] => (GMT+10:00) Pacific/Port_Moresby
    [Asia/Vladivostok] => (GMT+10:00) Asia/Vladivostok
    [Australia/Brisbane] => (GMT+10:00) Australia/Brisbane
    [Australia/Lindeman] => (GMT+10:00) Australia/Lindeman
    [Pacific/Saipan] => (GMT+10:00) Pacific/Saipan
    [Australia/Adelaide] => (GMT+10:30) Australia/Adelaide
    [Australia/Broken_Hill] => (GMT+10:30) Australia/Broken_Hill
    [Australia/Sydney] => (GMT+11:00) Australia/Sydney
    [Antarctica/Macquarie] => (GMT+11:00) Antarctica/Macquarie
    [Pacific/Noumea] => (GMT+11:00) Pacific/Noumea
    [Pacific/Norfolk] => (GMT+11:00) Pacific/Norfolk
    [Australia/Melbourne] => (GMT+11:00) Australia/Melbourne
    [Pacific/Kosrae] => (GMT+11:00) Pacific/Kosrae
    [Pacific/Pohnpei] => (GMT+11:00) Pacific/Pohnpei
    [Australia/Currie] => (GMT+11:00) Australia/Currie
    [Pacific/Guadalcanal] => (GMT+11:00) Pacific/Guadalcanal
    [Pacific/Efate] => (GMT+11:00) Pacific/Efate
    [Australia/Hobart] => (GMT+11:00) Australia/Hobart
    [Asia/Magadan] => (GMT+11:00) Asia/Magadan
    [Asia/Sakhalin] => (GMT+11:00) Asia/Sakhalin
    [Pacific/Bougainville] => (GMT+11:00) Pacific/Bougainville
    [Australia/Lord_Howe] => (GMT+11:00) Australia/Lord_Howe
    [Asia/Srednekolymsk] => (GMT+11:00) Asia/Srednekolymsk
    [Pacific/Fiji] => (GMT+12:00) Pacific/Fiji
    [Pacific/Wake] => (GMT+12:00) Pacific/Wake
    [Pacific/Nauru] => (GMT+12:00) Pacific/Nauru
    [Pacific/Majuro] => (GMT+12:00) Pacific/Majuro
    [Asia/Kamchatka] => (GMT+12:00) Asia/Kamchatka
    [Pacific/Kwajalein] => (GMT+12:00) Pacific/Kwajalein
    [Pacific/Funafuti] => (GMT+12:00) Pacific/Funafuti
    [Pacific/Wallis] => (GMT+12:00) Pacific/Wallis
    [Asia/Anadyr] => (GMT+12:00) Asia/Anadyr
    [Pacific/Tarawa] => (GMT+12:00) Pacific/Tarawa
    [Pacific/Fakaofo] => (GMT+13:00) Pacific/Fakaofo
    [Pacific/Enderbury] => (GMT+13:00) Pacific/Enderbury
    [Pacific/Auckland] => (GMT+13:00) Pacific/Auckland
    [Antarctica/McMurdo] => (GMT+13:00) Antarctica/McMurdo
    [Pacific/Tongatapu] => (GMT+13:00) Pacific/Tongatapu
    [Pacific/Chatham] => (GMT+13:45) Pacific/Chatham
    [Pacific/Kiritimati] => (GMT+14:00) Pacific/Kiritimati
    [Pacific/Apia] => (GMT+14:00) Pacific/Apia
)

What difference does .AsNoTracking() make?

The difference is that in the first case the retrieved user is not tracked by the context so when you are going to save the user back to database you must attach it and set correctly state of the user so that EF knows that it should update existing user instead of inserting a new one. In the second case you don't need to do that if you load and save the user with the same context instance because the tracking mechanism handles that for you.

How to install numpy on windows using pip install?

First go through this link https://www.python.org/downloads/ to download python 3.6.1 or 2.7.13 either of your choice.I preferred to use python 2.7 or 3.4.4 .now after installation go to the folder name python27/python34 then click on script now here open the command prompt by left click ad run as administration. After the command prompt appear write their "pip install numpy" this will install the numpy latest version and installing it will show success comment that's all. Similarly matplotlib can be install by just typing "pip install matplotlip". And now if you want to download scipy then just write "pip install scipy" and if it doesn't work then you need to download python scipy from the link https://sourceforge.net/projects/scipy/ and install it.

Django values_list vs values

values()

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

values_list()

Returns a QuerySet that returns list of tuples, rather than model instances, when used as an iterable.

distinct()

distinct are used to eliminate the duplicate elements.

Example:

>>> list(Article.objects.values_list('id', flat=True)) # flat=True will remove the tuples and return the list   
[1, 2, 3, 4, 5, 6]

>>> list(Article.objects.values('id'))
[{'id':1}, {'id':2}, {'id':3}, {'id':4}, {'id':5}, {'id':6}]

Getting a slice of keys from a map

A nicer way to do this would be to use append:

keys = []int{}
for k := range mymap {
    keys = append(keys, k)
}

Other than that, you’re out of luck—Go isn’t a very expressive language.

Find the number of employees in each department - SQL Oracle

select count(e.empno), d.deptno, d.dname 
from emp e, dep d
where e.DEPTNO = d.DEPTNO 
group by d.deptno, d.dname;

Cast to generic type in C#

You can't do that. You could try telling your problem from a more high level point of view (i.e. what exactly do you want to accomplish with the casted variable) for a different solution.

You could go with something like this:

 public abstract class Message { 
     // ...
 }
 public class Message<T> : Message {
 }

 public abstract class MessageProcessor {
     public abstract void ProcessMessage(Message msg);
 }
 public class SayMessageProcessor : MessageProcessor {
     public override void ProcessMessage(Message msg) {
         ProcessMessage((Message<Say>)msg);
     }
     public void ProcessMessage(Message<Say> msg) {
         // do the actual processing
     }
 }

 // Dispatcher logic:
 Dictionary<Type, MessageProcessor> messageProcessors = {
    { typeof(Say), new SayMessageProcessor() },
    { typeof(string), new StringMessageProcessor() }
 }; // properly initialized

 messageProcessors[msg.GetType().GetGenericArguments()[0]].ProcessMessage(msg);

Date only from TextBoxFor()

Keep in mind that display will depend on culture. And while in most cases all other answers are correct, it did not work for me. Culture issue will also cause different problems with jQuery datepicker, if attached.

If you wish to force the format escape / in the following manner:

@Html.TextBoxFor(model => model.dtArrivalDate, "{0:MM\\/dd\\/yyyy}")

If not escaped for me it show 08-01-2010 vs. expected 08/01/2010.

Also if not escaped jQuery datepicker will select different defaultDate, in my instance it was May 10, 2012.

SQL DELETE with INNER JOIN

If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.

For this example however I don't think you need the first s:

DELETE s 
FROM spawnlist AS s 
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate 
WHERE n.type = "monster";

It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:

SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";

You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html

Makefile: How to correctly include header file and its directory?

The preprocessor is looking for StdCUtil/split.h in

and in

  • $INC_DIR (i.e. ../StdCUtil/ = /root/Core/../StdCUtil/ = /root/StdCUtil/). So ../StdCUtil/ + StdCUtil/split.h = ../StdCUtil/StdCUtil/split.h and the file is missing

You can fix the error changing the $INC_DIR variable (best solution):

$INC_DIR = ../

or the include directive:

#include "split.h"

but in this way you lost the "path syntax" that makes it very clear what namespace or module the header file belongs to.

Reference:

EDIT/UPDATE

It should also be

CXX = g++
CXXFLAGS = -c -Wall -I$(INC_DIR)

...

%.o: %.cpp $(DEPS)
    $(CXX) -o $@ $< $(CXXFLAGS)

'Syntax Error: invalid syntax' for no apparent reason

For problems where it seems to be an error on a line you think is correct, you can often remove/comment the line where the error appears to be and, if the error moves to the next line, there are two possibilities.

Either both lines have a problem or the previous line has a problem which is being carried forward. The most likely case is the second option (even more so if you remove another line and it moves again).

For example, the following Python program twisty_passages.py:

xyzzy = (1 +
plugh = 7

generates the error:

  File "twisty_passages.py", line 2
    plugh = 7
          ^
SyntaxError: invalid syntax

despite the problem clearly being on line 1.


In your particular case, that is the problem. The parentheses in the line before your error line is unmatched, as per the following snippet:

# open parentheses: 1  2             3
#                   v  v             v
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
#                               ^             ^
# close parentheses:            1             2

Depending on what you're trying to achieve, the solution may be as simple as just adding another closing parenthesis at the end, to close off the sqrt function.

I can't say for certain since I don't recognise the expression off the top of my head. Hardly surprising if (assuming PSAT is the enzyme, and the use of the typeMolecule identifier) it's to do with molecular biology - I seem to recall failing Biology consistently in my youth :-)

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

If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:

  1. Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(https://github.com/charlesw/tesseract).
  2. Go to the Downloads section of the official Tesseract project (https://code.google.com/p/tesseract-ocr/ EDIT: It's now located here: https://github.com/tesseract-ocr/langdata).
  3. Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. Create tessdata directory in your project and place the language data files in it.
  5. Go to Properties of the newly added files and set them to copy on build.
  6. Add a reference to System.Drawing.
  7. From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
  8. Create the following two files in your project (just to get started):

Program.cs

using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
            {
                testImagePath = args[0];
            }

            try
            {
                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using (var img = Pix.LoadFromFile(testImagePath))
                    {
                        using (logger.Begin("Process image"))
                        {
                            var i = 1;
                            using (var page = engine.Process(img))
                            {
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                {
                                    iter.Begin();
                                    do
                                    {
                                        if (i % 2 == 0)
                                        {
                                            using (logger.Begin("Line {0}", i))
                                            {
                                                do
                                                {
                                                    using (logger.Begin("Word Iteration"))
                                                    {
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                        {
                                                            logger.Log("New block");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                        {
                                                            logger.Log("New paragraph");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                        {
                                                            logger.Log("New line");
                                                        }
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                    }
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                            }
                                        }
                                        i++;
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }



        private class ResultPrinter
        {
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
            {
                this.logger = logger;
            }

            public void Print(ResultIterator iter)
            {
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
            }
        }
    }
}

FormattedConsoleLogger.cs

using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
{
    public class FormattedConsoleLogger
    {
        const string Tab = "    ";
        private class Scope : DisposableBase
        {
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
            {
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                {
                    indent.Append(Tab);
                }
                this.indent = indent.ToString();
            }

            public void Log(string format, object[] args)
            {
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                {
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i += 2;
                    }
                    else if (message[i] == '\r' || message[i] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i++;
                    }
                    else
                    {
                        if (isNewLine)
                        {
                            indentedMessage.Append(indent);
                            isNewLine = false;
                        }
                        indentedMessage.Append(message[i]);
                        i++;
                    }
                }

                Console.WriteLine(indentedMessage.ToString());

            }

            public Scope Begin()
            {
                return new Scope(container, indentLevel + 1);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    var scope = container.scopes.Pop();
                    if (scope != this)
                    {
                        throw new InvalidOperationException("Format scope removed out of order.");
                    }
                }
            }
        }

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
        {
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
            {
                scope = new Scope(this, 1);
            }
            else
            {
                scope = ActiveScope.Begin();
            }
            scopes.Push(scope);
            return scope;
        }

        public void Log(string format, params object[] args)
        {
            if (scopes.Count > 0)
            {
                ActiveScope.Log(format, args);
            }
            else
            {
                Console.WriteLine(String.Format(format, args));
            }
        }

        private Scope ActiveScope
        {
            get
            {
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;
            }
        }
    }
}

What is a good game engine that uses Lua?

World of Warcraft's engine seems all right, and it uses Lua. :)

Run Python script at startup in Ubuntu

In similar situations, I've done well by putting something like the following into /etc/rc.local:

cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local  # check that rc.local ran

This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.

filtering NSArray into a new NSArray in Objective-C

Checkout this library

https://github.com/BadChoice/Collection

It comes with lots of easy array functions to never write a loop again

So you can just do:

NSArray* youngHeroes = [self.heroes filter:^BOOL(Hero *object) {
    return object.age.intValue < 20;
}];

or

NSArray* oldHeroes = [self.heroes reject:^BOOL(Hero *object) {
    return object.age.intValue < 20;
}];

'uint32_t' identifier not found error

There is an implementation available at the msinttypes project page - "This project fills the absence of stdint.h and inttypes.h in Microsoft Visual Studio".

I don't have experience with this implementation, but I've seen it recommended by others on SO.

Property '...' has no initializer and is not definitely assigned in the constructor

We may get the message Property has no initializer and is not definitely assigned in the constructor when adding some configuration in the tsconfig.json file so as to have an Angular project compiled in strict mode:

"compilerOptions": {
  "strict": true,
  "noImplicitAny": true,
  "noImplicitThis": true,
  "alwaysStrict": true,
  "strictNullChecks": true,
  "strictFunctionTypes": true,
  "strictPropertyInitialization": true,

Indeed the compiler then complains that a member variable is not defined before being used.

For an example of a member variable that is not defined at compile time, a member variable having an @Input directive:

@Input() userId: string;

We could silence the compiler by stating the variable may be optional:

@Input() userId?: string;

But then, we would have to deal with the case of the variable not being defined, and clutter the source code with some such statements:

if (this.userId) {
} else {
}

Instead, knowing the value of this member variable would be defined in time, that is, it would be defined before being used, we can tell the compiler not to worry about it not being defined.

The way to tell this to the compiler is to add the ! definite assignment assertion operator, as in:

@Input() userId!: string;

Now, the compiler understands that this variable, although not defined at compile time, shall be defined at run-time, and in time, before it is being used.

It is now up to the application to ensure this variable is defined before being used.

As an an added protection, we can assert the variable is being defined, before we use it.

We can assert the variable is defined, that is, the required input binding was actually provided by the calling context:

private assertInputsProvided(): void {
  if (!this.userId) {
    throw (new Error("The required input [userId] was not provided"));
  }
}

public ngOnInit(): void {
  // Ensure the input bindings are actually provided at run-time
  this.assertInputsProvided();
}

Knowing the variable was defined, the variable can now be used:

ngOnChanges() {
  this.userService.get(this.userId)
    .subscribe(user => {
      this.update(user.confirmedEmail);
    });
}

Note that the ngOnInit method is called after the input bindings attempt, this, even if no actual input was provided to the bindings.

Whereas the ngOnChanges method is called after the input bindings attempt, and only if there was actual input provided to the bindings.

How can I specify a display?

I through vnc to understand the X11 more. To specify the display to get a many-displayed program, export DISPLAY=IP:DisplayNum.ScreenNum

For example,

vncserver :2
vncserver -list
echo '$DISPLAY'=$DISPLAY 
export DISPLAY=:2  # export DISPLAY=IP:DisplayNum or export DISPLAY=:DisplayNum for localhost; So that can vnc connect and see the vnc desktop :2 if $DISPLAY is not :2.
echo '$DISPLAY'=$DISPLAY

How to add style from code behind?

If no file available for download, I needed to disable the asp:linkButton, change it to grey and eliminate the underline on the hover. This worked:

.disabled {
    color: grey;
    text-decoration: none !important;
}

LinkButton button = item.FindControl("lnkFileDownload") as LinkButton;
button.Enabled = false;
button.CssClass = "disabled";

How do I center content in a div using CSS?

To align horizontally it's pretty straight forward:

    <style type="text/css"> 
body  {
    margin: 0; 
    padding: 0;
    text-align: center;
}
.bodyclass #container { 
    width: ???px; /*SET your width here*/
    margin: 0 auto;
    text-align: left;
} 
</style>
<body class="bodyclass ">
<div id="container">type your content here</div>
</body>

and for vertical align, it's a bit tricky: here's the source

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>Universal vertical center with CSS</title>
  <style>
    .greenBorder {border: 1px solid green;} /* just borders to see it */
  </style>
</head>

<body>
  <div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;">
    <div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
      <div class="greenBorder" style=" #position: relative; #top: -50%">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
      </div>
    </div>
  </div>
</body>
</html>

How to execute an Oracle stored procedure via a database link

The syntax is

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

Convert Unix timestamp into human readable date using MySQL

Need a unix timestamp in a specific timezone?

Here's a one liner if you have quick access to the mysql cli:

mysql> select convert_tz(from_unixtime(1467095851), 'UTC', 'MST') as 'local time';

+---------------------+
| local time          |
+---------------------+
| 2016-06-27 23:37:31 |
+---------------------+

Replace 'MST' with your desired timezone. I live in Arizona thus the conversion from UTC to MST.

Ruby value of a hash key?

This question seems to be ambiguous.

I'll try with my interpretation of the request.

def do_something(data)
   puts "Found! #{data}"
end

a = { 'x' => 'test', 'y' => 'foo', 'z' => 'bar' }
a.each { |key,value| do_something(value) if key == 'x' }

This will loop over all the key,value pairs and do something only if the key is 'x'.

How to apply shell command to each line of a command output?

i like to use gawk for running multiple commands on a list, for instance

ls -l | gawk '{system("/path/to/cmd.sh "$1)}'

however the escaping of the escapable characters can get a little hairy.

SQLite3 database or disk is full / the database disk image is malformed

I use the following script for repairing malformed sqlite files:

#!/bin/bash

cat <( sqlite3 "$1" .dump | grep "^ROLLBACK" -v ) <( echo "COMMIT;" ) | sqlite3 "fix_$1"

Most of the time when a sqlite database is malformed it is still possible to make a dump. This dump is basically a lot of SQL statements that rebuild the database.

Some rows might be missing from the dump (probably becasue they are corrupted). If this is the case the INSERT statements of the missing rows will be replaced with some comments and the script will end with a ROLLBACK TRANSACTION.

So what we do here is we make the dump (malformed rows are excluded) and we replace the ROLLBACK with a COMMIT so that the entire dump script will be committed in stead of rolled back.

This method saved my life a couple of 100 times already \o/

Jquery Hide table rows

You just need to traverse up the DOM tree to the nearest <tr> like so...

$("#ID_OF_ELEMENT").parents("tr").hide();

jQuery API Reference

java.util.NoSuchElementException - Scanner reading user input

This has really puzzled me for a while but this is what I found in the end.

When you call, sc.close() in first method, it not only closes your scanner but closes your System.in input stream as well. You can verify it by printing its status at very top of the second method as :

    System.out.println(System.in.available());

So, now when you re-instantiate, Scanner in second method, it doesn't find any open System.in stream and hence the exception.

I doubt if there is any way out to reopen System.in because:

public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**

The only good solution for your problem is to initiate the Scanner in your main method, pass that as argument in your two methods, and close it again in your main method e.g.:

main method related code block:

Scanner scanner = new Scanner(System.in);  

// Ask users for quantities 
PromptCustomerQty(customer, ProductList, scanner );

// Ask user for payment method
PromptCustomerPayment(customer, scanner );

//close the scanner 
scanner.close();

Your Methods:

 public static void PromptCustomerQty(Customer customer, 
                             ArrayList<Product> ProductList, Scanner scanner) {

    // no more scanner instantiation
    ...
    // no more scanner close
 }


 public static void PromptCustomerPayment (Customer customer, Scanner sc) {

    // no more scanner instantiation
    ...
    // no more scanner close
 }

Hope this gives you some insight about the failure and possible resolution.

Video streaming over websockets using JavaScript

The Media Source Extensions has been proposed which would allow for Adaptive Bitrate Streaming implementations.

How to check if a column exists in a SQL Server table?

if exists (
  select * 
  from INFORMATION_SCHEMA.COLUMNS 
  where TABLE_NAME = '<table_name>' 
  and COLUMN_NAME = '<column_name>'
) begin
  print 'Column you have specified exists'
end else begin
  print 'Column does not exist'
end

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

@bogatron has it right, you can use where, it's worth noting that you can do this natively in pandas:

df1 = df.where(pd.notnull(df), None)

Note: this changes the dtype of all columns to object.

Example:

In [1]: df = pd.DataFrame([1, np.nan])

In [2]: df
Out[2]: 
    0
0   1
1 NaN

In [3]: df1 = df.where(pd.notnull(df), None)

In [4]: df1
Out[4]: 
      0
0     1
1  None

Note: what you cannot do recast the DataFrames dtype to allow all datatypes types, using astype, and then the DataFrame fillna method:

df1 = df.astype(object).replace(np.nan, 'None')

Unfortunately neither this, nor using replace, works with None see this (closed) issue.


As an aside, it's worth noting that for most use cases you don't need to replace NaN with None, see this question about the difference between NaN and None in pandas.

However, in this specific case it seems you do (at least at the time of this answer).

Which .NET Dependency Injection frameworks are worth looking into?

Spring.Net is quite solid, but the documentation took some time to wade through. Autofac is good, and while .Net 2.0 is supported, you need VS 2008 to compile it, or else use the command line to build your app.

How can I implement rate limiting with Apache? (requests per second)

In Apache 2.4, there's a new stock module called mod_ratelimit. For emulating modem speeds, you can use mod_dialup. Though I don't see why you just couldn't use mod_ratelimit for everything.

How to call a Python function from Node.js

Example for people who are from Python background and want to integrate their machine learning model in the Node.js application:

It uses the child_process core module:

const express = require('express')
const app = express()

app.get('/', (req, res) => {

    const { spawn } = require('child_process');
    const pyProg = spawn('python', ['./../pypy.py']);

    pyProg.stdout.on('data', function(data) {

        console.log(data.toString());
        res.write(data);
        res.end('end');
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

It doesn't require sys module in your Python script.

Below is a more modular way of performing the task using Promise:

const express = require('express')
const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./../pypy.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(fromRunpy) {
        console.log(fromRunpy.toString());
        res.end(fromRunpy);
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

Scanning Java annotations at runtime

There's a wonderful comment by zapp that sinks in all those answers:

new Reflections("my.package").getTypesAnnotatedWith(MyAnnotation.class)

How to handle checkboxes in ASP.NET MVC forms?

Same as nautic20's answer, just simply use MVC default model binding checkbox list with same name as a collection property of string/int/enum in ViewModel. That is it.

But one issue need to point out. In each checkbox component, you should not put "Id" in it which will affect MVC model binding.

Following code will work for model binding:

 <% foreach (var item in Model.SampleObjectList)
       { %>
        <tr>
            <td><input type="checkbox" name="SelectedObjectIds" value="<%= item.Id%>" /></td>
            <td><%= Html.Encode(item.Name)%></td>
        </tr>
 <% } %>

Following codes will not binding to model (difference here is it assigned id for each checkbox)

<% foreach (var item in Model.SampleObjectList)
       { %>
        <tr>
            <td><input type="checkbox" name="SelectedObjectIds" id="[some unique key]" value="<%= item.Id%>" /></td>
            <td><%= Html.Encode(item.Name)%></td>
        </tr>
<% } %>

Passing references to pointers in C++

The problem is that you're trying to bind a temporary to the reference, which C++ doesn't allow unless the reference is const.

So you can do one of either the following:

void myfunc(string*& val)
{
    // Do stuff to the string pointer
}


void myfunc2(string* const& val)
{
    // Do stuff to the string pointer
}

int main()
// sometime later 
{
    // ...
    string s;
    string* ps = &s;

    myfunc( ps);   // OK because ps is not a temporary
    myfunc2( &s);  // OK because the parameter is a const&
    // ...

    return 0;
}

How do I tell a Python script to use a particular version

Perhaps not exactly what you asked, but I find this to be useful to put at the start of my programs:

import sys

if sys.version_info[0] < 3:
    raise Exception("Python 3 or a more recent version is required.")

How do you properly use WideCharToMultiByte

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

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

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

int main() 
{

    size_t wcsChars = wcslen( wcsString);

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

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

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

And the output:

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

How do I add an active class to a Link from React Router?

You can actually replicate what is inside NavLink something like this

const NavLink = ( {
  to,
  exact,
  children
} ) => {

  const navLink = ({match}) => {

    return (
      <li class={{active: match}}>
        <Link to={to}>
          {children}
        </Link>
      </li>
    )

  }

  return (
    <Route
      path={typeof to === 'object' ? to.pathname : to}
      exact={exact}
      strict={false}
      children={navLink}
    />
  )
}

just look into NavLink source code and remove parts you don't need ;)

Fatal error: Call to undefined function mb_detect_encoding()

I had the same problem with Ubuntu 17, Ispconfig was not processing the operations queued of any kind and also the server.sh command was not working. I checked and the running PHP version after the OS upgrade was 7.1 so the solution was to type:

apt-get install php7.1-mbstring

and now is everything ok

Django: Redirect to previous page after login

This may not be a "best practice", but I've successfully used this before:

return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))

android: how to use getApplication and getApplicationContext from non activity / service class

Sending your activity context to other classes could cause memoryleaks because holding that context alive is the reason that the GC can't dispose the object

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

batch/bat to copy folder and content at once

I suspect that the xcopy command is the magic bullet you're looking for.

It can copy files, directories, and even entire drives while preserving the original directory hierarchy. There are also a handful of additional options available, compared to the basic copy command.

Check out the documentation here.

If your batch file only needs to run on Windows Vista or later, you can use robocopy instead, which is an even more powerful tool than xcopy, and is now built into the operating system. It's documentation is available here.

Vertical and horizontal align (middle and center) with CSS

This isn't as easy to do as one might expect -- you can really only do vertical alignment if you know the height of your container. IF this is the case, you can do it with absolute positioning.

The concept is to set the top / left positions at 50%, and then use negative margins (set to half the height / width) to pull the container back to being centered.

Example: http://jsbin.com/ipawe/edit

Basic CSS:

#mydiv { 
    position: absolute;
    top: 50%;
    left: 50%;
    height: 400px;
    width: 700px;
    margin-top: -200px; /* -(1/2 height) */
    margin-left: -350px; /* -(1/2 width) */
  }

Change background image opacity

You can create several divs and do that:

<div style="width:100px; height:100px;">
   <div style="position:relative; top:0px; left:0px; width:100px; height:100px; opacity:0.3;"><img src="urltoimage" alt=" " /></div>
   <div style="position:relative; top:0px; left:0px; width:100px; height:100px;"> DIV with no opacity </div>
</div>

I did that couple times... Simple, yet effective...

Make a table fill the entire window

you can see the solution on http://jsfiddle.net/CBQCA/1/

OR

<table style="height:100%;width:100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0;border:1px solid">
     <tr style="height: 25%;">
        <td>Region</td>
    </tr>
    <tr style="height: 75%;">
        <td>100.00%</td>
    </tr>
</table>?

I removed the font size, to show that columns are expanded. I added border:1px solid just to make sure table is expanded. you can remove it.

Building and running app via Gradle and Android Studio is slower than via Eclipse

Just try this first. It is my personal experience.

I had the same problem. What i had done is just permanently disable the antivirus (Mine was Avast Security 2015). Just after disabling the antivirus , thing gone well. the gradle finished successfully. From now within seconds the gradle is finishing ( Only taking 5-10 secs).

How to expire a cookie in 30 minutes using jQuery?

30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.

 var date = new Date();
 var minutes = 30;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie("example", "foo", { expires: date });

cannot connect to pc-name\SQLEXPRESS

Use (LocalDB)\MSSQLLocalDB as the server name

push multiple elements to array

You can push multiple elements into an array in the following way

_x000D_
_x000D_
var a = [];_x000D_
    _x000D_
a.push(1, 2, 3);_x000D_
_x000D_
console.log(a);
_x000D_
_x000D_
_x000D_

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

Submit form using AJAX and jQuery

First give your form an id attribute, then use code like this:

$(document).ready( function() {
  var form = $('#my_awesome_form');

  form.find('select:first').change( function() {
    $.ajax( {
      type: "POST",
      url: form.attr( 'action' ),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );
  } );

} );

So this code uses .serialize() to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.

For future reference, the jQuery docs are very, very good.

Python Dictionary Comprehension

Use dict() on a list of tuples, this solution will allow you to have arbitrary values in each list, so long as they are the same length

i_s = range(1, 11)
x_s = range(1, 11)
# x_s = range(11, 1, -1) # Also works
d = dict([(i_s[index], x_s[index], ) for index in range(len(i_s))])

Saving a Excel File into .txt format without quotes

Try this code. This does what you want.

LOGIC

  1. Save the File as a TAB delimited File in the user temp directory
  2. Read the text file in 1 go
  3. Replace "" with blanks and write to the new file at the same time.

CODE (TRIED AND TESTED)

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long

Private Const MAX_PATH As Long = 260

'~~> Change this where and how you want to save the file
Const FlName = "C:\Users\Siddharth Rout\Desktop\MyWorkbook.txt"

Sub Sample()
    Dim tmpFile As String
    Dim MyData As String, strData() As String
    Dim entireline As String
    Dim filesize As Integer

    '~~> Create a Temp File
    tmpFile = TempPath & Format(Now, "ddmmyyyyhhmmss") & ".txt"

    ActiveWorkbook.SaveAs Filename:=tmpFile _
    , FileFormat:=xlText, CreateBackup:=False

    '~~> Read the entire file in 1 Go!
    Open tmpFile For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)

    '~~> Get a free file handle
    filesize = FreeFile()

    '~~> Open your file
    Open FlName For Output As #filesize

    For i = LBound(strData) To UBound(strData)
        entireline = Replace(strData(i), """", "")
        '~~> Export Text
        Print #filesize, entireline
    Next i

    Close #filesize

    MsgBox "Done"
End Sub

Function TempPath() As String
    TempPath = String$(MAX_PATH, Chr$(0))
    GetTempPath MAX_PATH, TempPath
    TempPath = Replace(TempPath, Chr$(0), "")
End Function

SNAPSHOTS

Actual Workbook

enter image description here

After Saving

enter image description here

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

On top of @unutbu answer, you could coerce pandas numpy object array to native (float64) type, something along the line

import pandas as pd
pd.to_numeric(df['tester'], errors='coerce')

Specify errors='coerce' to force strings that can't be parsed to a numeric value to become NaN. Column type would be dtype: float64, and then isnan check should work

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

PHP validation/regex for URL

    function validateURL($URL) {
      $pattern_1 = "/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";
      $pattern_2 = "/^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";       
      if(preg_match($pattern_1, $URL) || preg_match($pattern_2, $URL)){
        return true;
      } else{
        return false;
      }
    }

Get form data in ReactJS

Adding on to Michael Schock's answer:

class MyForm extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.target);

    console.log(data.get('email')); // reference by form input's `name` tag

    fetch('/api/form-submit-url', {
      method: 'POST',
      body: data,
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="username">Enter username</label>
        <input id="username" name="username" type="text" />

        <label htmlFor="email">Enter your email</label>
        <input id="email" name="email" type="email" />

        <label htmlFor="birthdate">Enter your birth date</label>
        <input id="birthdate" name="birthdate" type="text" />

        <button>Send data!</button>
      </form>
    );
  }
}

See this Medium article: How to Handle Forms with Just React

This method gets form data only when Submit button is pressed. Much cleaner IMO!

Python: Making a beep noise

The cross-platform way:

import time
import sys
for i in range(1,6):
    sys.stdout.write('\r\a{i}'.format(i=i))
    sys.stdout.flush()
    time.sleep(1)
sys.stdout.write('\n')

How to check how many letters are in a string in java?

If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:

String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e

The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc

sample.codePointCount(0, sample.length()) // returns 5

http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

How to decode a QR-code image in (preferably pure) Python?

The following code works fine with me:

brew install zbar
pip install pyqrcode
pip install pyzbar

For QR code image creation:

import pyqrcode
qr = pyqrcode.create("test1")
qr.png("test1.png", scale=6)

For QR code decoding:

from PIL import Image
from pyzbar.pyzbar import decode
data = decode(Image.open('test1.png'))
print(data)

that prints the result:

[Decoded(data=b'test1', type='QRCODE', rect=Rect(left=24, top=24, width=126, height=126), polygon=[Point(x=24, y=24), Point(x=24, y=150), Point(x=150, y=150), Point(x=150, y=24)])]

Correct way to initialize empty slice

As an addition to @ANisus' answer...

below is some information from the "Go in action" book, which I think is worth mentioning:

Difference between nil & empty slices

If we think of a slice like this:

[pointer] [length] [capacity]

then:

nil slice:   [nil][0][0]
empty slice: [addr][0][0] // points to an address

nil slice

They’re useful when you want to represent a slice that doesn’t exist, such as when an exception occurs in a function that returns a slice.

// Create a nil slice of integers.
var slice []int

empty slice

Empty slices are useful when you want to represent an empty collection, such as when a database query returns zero results.

// Use make to create an empty slice of integers.
slice := make([]int, 0)

// Use a slice literal to create an empty slice of integers.
slice := []int{}

Regardless of whether you’re using a nil slice or an empty slice, the built-in functions append, len, and cap work the same.


Go playground example:

package main

import (
    "fmt"
)

func main() {

    var nil_slice []int
    var empty_slice = []int{}

    fmt.Println(nil_slice == nil, len(nil_slice), cap(nil_slice))
    fmt.Println(empty_slice == nil, len(empty_slice), cap(empty_slice))

}

prints:

true 0 0
false 0 0

Redirecting a request using servlets and the "setHeader" method not working

Another way of doing this if you want to redirect to any url source after the specified point of time

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

public class MyServlet extends HttpServlet


{

public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException

{

response.setContentType("text/html");

PrintWriter pw=response.getWriter();

pw.println("<b><centre>Redirecting to Google<br>");


response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url  after 5 seconds


pw.close();
}

}

Spring cannot find bean xml configuration file when it does exist

I have stuck in this issue for a while and I have came to the following solution

  1. Create an ApplicationContextAware class (which is a class that implements the ApplicationContextAware)
  2. In ApplicationContextAware we have to implement the one method only

    public void setApplicationContext(ApplicationContext context) throws BeansException

  3. Tell the spring context about this new bean (I call it SpringContext)

    bean id="springContext" class="packe.of.SpringContext" />
    

Here is the code snippet

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContext implements ApplicationContextAware {
  private static ApplicationContext context;

  @Override
  public void setApplicationContext(ApplicationContext context) throws BeansException {
    this.context = context;
  }
  public static ApplicationContext getApplicationContext() {
    return context;
  }
}
  1. Then you can call any method of application context outside the spring context for example

    
    SomeServiceClassOrComponent utilityService SpringContext.getApplicationContext().getBean(SomeServiceClassOrComponent .class);
    

I hope this will solve the problem for many users

How to escape a single quote inside awk

A single quote is represented using \x27

Like in

awk 'BEGIN {FS=" ";} {printf "\x27%s\x27 ", $1}'

Source

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

Is it possible to decrypt SHA1

Since SHA-1 maps several byte sequences to one, you can't "decrypt" a hash, but in theory you can find collisions: strings that have the same hash.

It seems that breaking a single hash would cost about 2.7 million dollars worth of computer time currently, so your efforts are probably better spent somewhere else.

ReactJS: setTimeout() not working?

Anytime we create a timeout we should s clear it on componentWillUnmount, if it hasn't fired yet.

      let myVar;
         const Component = React.createClass({

            getInitialState: function () {
                return {position: 0};    
            },

            componentDidMount: function () {
                 myVar = setTimeout(()=> this.setState({position: 1}), 3000)
            },

            componentWillUnmount: () => {
              clearTimeout(myVar);
             };
            render: function () {
                 return (
                    <div className="component">
                        {this.state.position}
                    </div>
                 ); 
            }

        });

ReactDOM.render(
    <Component />,
    document.getElementById('main')
);

When to use in vs ref vs out

You need to use ref if you plan to read and write to the parameter. You need to use out if you only plan to write. In effect, out is for when you'd need more than one return value, or when you don't want to use the normal return mechanism for output (but this should be rare).

There are language mechanics that assist these use cases. Ref parameters must have been initialized before they are passed to a method (putting emphasis on the fact that they are read-write), and out parameters cannot be read before they are assigned a value, and are guaranteed to have been written to at the end of the method (putting emphasis on the fact that they are write only). Contravening to these principles results in a compile-time error.

int x;
Foo(ref x); // error: x is uninitialized

void Bar(out int x) {}  // error: x was not written to

For instance, int.TryParse returns a bool and accepts an out int parameter:

int value;
if (int.TryParse(numericString, out value))
{
    /* numericString was parsed into value, now do stuff */
}
else
{
    /* numericString couldn't be parsed */
}

This is a clear example of a situation where you need to output two values: the numeric result and whether the conversion was successful or not. The authors of the CLR decided to opt for out here since they don't care about what the int could have been before.

For ref, you can look at Interlocked.Increment:

int x = 4;
Interlocked.Increment(ref x);

Interlocked.Increment atomically increments the value of x. Since you need to read x to increment it, this is a situation where ref is more appropriate. You totally care about what x was before it was passed to Increment.

In the next version of C#, it will even be possible to declare variable in out parameters, adding even more emphasis on their output-only nature:

if (int.TryParse(numericString, out int value))
{
    // 'value' exists and was declared in the `if` statement
}
else
{
    // conversion didn't work, 'value' doesn't exist here
}

Template not provided using create-react-app

For Linux this worked for me

sudo npm uninstall -g create-react-app
npx create-react-app my-test-app

Storing image in database directly or as base64 data?

  • Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.

  • Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.

Redirecting from cshtml page

You can go to method of same controller..using this line , and if you want to pass some parameters to that action it can be done by writing inside ( new { } ).. Note:- you can add as many parameter as required.

@Html.ActionLink("MethodName", new { parameter = Model.parameter })

Omitting all xsi and xsd namespaces when serializing an object in .NET?

...
XmlSerializer s = new XmlSerializer(objectToSerialize.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
s.Serialize(xmlWriter, objectToSerialize, ns);

How should I use Outlook to send code snippets?

When I paste code into Outlook or have sentences containing code or technical syntax I get annoyed by all of the red squiggles that identify spelling errors. If you want Outlook to clear all of the red spellcheck squiggles you can add a button to the Quick Access Toolbar that calls a VBA macro and removes all squiggles from the current document.

I prefer to run this macro separate from my style choice because I often use it on a selection of text that has mixed content.

For syntax highlighting I use the Notepad++ technique already listed by @srujanreddy, though I discovered that the right-click context menu option a bit handier than navigating the Plugins menu.

Image showing you can right-click on selected text and choose to copy text with syntax highlighting

If you get annoyed by spell check while you are preparing your email you can add a button to your quick access toolbar that will remove the red squiggles from the message body.
See this article: https://stackoverflow.com/a/49865743/1898524

Remove Spell Check Squiggles

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

When an Amazon RDS instance is blocked because the value of max_connect_errors has been exceeded, you cannot use the host that generated the connection errors to issue the "flush hosts" command, as the MySQL Server running on the instance is at that point blocking connections from that host.

You therefore need to issue the "flush hosts" command from another EC2 instance or remote server that has access to that RDS instance.

mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts

If this involved launching a new instance, or creating/modifying security groups to permit external access, it may be quicker to simply login to the RDS user interface and reboot the RDS instance that is blocked.

how to check for datatype in node js- specifically for integer

you can try this one isNaN(Number(x)) where x is any thing like string or number

Trying to embed newline in a variable in bash

Try echo $'a\nb'.

If you want to store it in a variable and then use it with the newlines intact, you will have to quote your usage correctly:

var=$'a\nb\nc'
echo "$var"

Or, to fix your example program literally:

var="a b c"
for i in $var; do
    p="`echo -e "$p\\n$i"`"
done
echo "$p"

How do I print part of a rendered HTML page in JavaScript?

Along the same lines as some of the suggestions you would need to do at least the following:

  • Load some CSS dynamically through JavaScript
  • Craft some print-specific CSS rules
  • Apply your fancy CSS rules through JavaScript

An example CSS could be as simple as this:

@media print {
  body * {
    display:none;
  }

  body .printable {
    display:block;
  }
}

Your JavaScript would then only need to apply the "printable" class to your target div and it will be the only thing visible (as long as there are no other conflicting CSS rules -- a separate exercise) when printing happens.

<script type="text/javascript">
  function divPrint() {
    // Some logic determines which div should be printed...
    // This example uses div3.
    $("#div3").addClass("printable");
    window.print();
  }
</script>

You may want to optionally remove the class from the target after printing has occurred, and / or remove the dynamically-added CSS after printing has occurred.

Below is a full working example, the only difference is that the print CSS is not loaded dynamically. If you want it to really be unobtrusive then you will need to load the CSS dynamically like in this answer.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Print Portion Example</title>
    <style type="text/css">
      @media print {
        body * {
          display:none;
        }

        body .printable {
          display:block;
        }
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  </head>

  <body>
    <h1>Print Section Example</h1>
    <div id="div1">Div 1</div>
    <div id="div2">Div 2</div>
    <div id="div3">Div 3</div>
    <div id="div4">Div 4</div>
    <div id="div5">Div 5</div>
    <div id="div6">Div 6</div>
    <p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
    <script type="text/javascript">
      function divPrint() {
        // Some logic determines which div should be printed...
        // This example uses div3.
        $("#div3").addClass("printable");
        window.print();
      }
    </script>
  </body>
</html>

Java math function to convert positive int to negative and negative to positive?

What about x *= -1; ? Do you really want a library function for this?

How to search text using php if ($text contains "World")

The best solution is my method:

In my method, only full words are detected,But in other ways it is not.

for example:

$text='hello world!'; 

if(strpos($text, 'wor') === FALSE) { 
   echo '"wor" not found in string'; 
}

Result: strpos returned true!!! but in my method return false.

My method:

public function searchInLine($txt,$word){

    $txt=strtolower($txt);
    $word=strtolower($word);
    $word_length=strlen($word);
    $string_length=strlen($txt);
    if(strpos($txt,$word)!==false){
        $indx=strpos($txt,$word);
        $last_word=$indx+$word_length;
        if($indx==0){
            if(strpos($txt,$word." ")!==false){
                return true;
            }
            if(strpos($txt,$word.".")!==false){
                return true;
            }
            if(strpos($txt,$word.",")!==false){
                return true;
            }
            if(strpos($txt,$word."?")!==false){
                return true;
            }
            if(strpos($txt,$word."!")!==false){
                return true;
            }
        }else if($last_word==$string_length){
            if(strpos($txt," ".$word)!==false){
                return true;
            }
            if(strpos($txt,".".$word)!==false){
                return true;
            }
            if(strpos($txt,",".$word)!==false){
                return true;
            }
            if(strpos($txt,"?".$word)!==false){
                return true;
            }
            if(strpos($txt,"!".$word)!==false){
                return true;
            }

        }else{
            if(strpos($txt," ".$word." ")!==false){
                return true;
            }
            if(strpos($txt," ".$word.".")!==false){
                return true;
            }
            if(strpos($txt," ".$word.",")!==false){
                return true;
            }
            if(strpos($txt," ".$word."!")!==false){
                return true;
            }
            if(strpos($txt," ".$word."?")!==false){
                return true;
            }
        }
        }

    return false;
}

Does Java have an exponential operator?

To do this with user input:

public static void getPow(){
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first integer: ");    // 3
    int first = sc.nextInt();
    System.out.println("Enter second integer: ");    // 2
    int second = sc.nextInt();
    System.out.println(first + " to the power of " + second + " is " + 
        (int) Math.pow(first, second));    // outputs 9

Mock MVC - Add Request Parameter to test

@ModelAttribute is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username and userClient.firstName, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient object.

(i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)

Using two CSS classes on one element

Another option is to use Descendant selectors

HTML:

<div class="social">
<p class="first">burrito</p>
<p class="last">chimichanga</p>
</div>

Reference first one in CSS: .social .first { color: blue; }

Reference last one in CSS: .social .last { color: green; }

Jsfiddle: https://jsfiddle.net/covbtpaq/153/

How do I read text from the clipboard?

I've seen many suggestions to use the win32 module, but Tkinter provides the shortest and easiest method I've seen, as in this post: How do I copy a string to the clipboard on Windows using Python?

Plus, Tkinter is in the python standard library.

Syntax error on print with Python 3

Because in Python 3, print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as

print("Hello World")

But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:

from __future__ import print_function

Now your code works on both 2.x & 3.x.

Check out below examples also to get familiar with print() function.

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

Source: What’s New In Python 3.0?

fstream won't create a file

You need to add some arguments. Also, instancing and opening can be put in one line:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

YYYY-MM-DD format date in shell script

Try to use this command :

date | cut -d " " -f2-4 | tr " " "-" 

The output would be like: 21-Feb-2021

Changing file permission in Python

os.chmod(path, 0444) is the Python command for changing file permissions in Python 2.x. For a combined Python 2 and Python 3 solution, change 0444 to 0o444.

You could always use Python to call the chmod command using subprocess. I think this will only work on Linux though.

import subprocess

subprocess.call(['chmod', '0444', 'path'])

How do I remove time part from JavaScript date?

The previous answers are fine, just adding my preferred way of handling this:

var timePortion = myDate.getTime() % (3600 * 1000 * 24);
var dateOnly = new Date(myDate - timePortion);

If you start with a string, you first need to parse it like so:

var myDate = new Date(dateString);

And if you come across timezone related problems as I have, this should fix it:

var timePortion = (myDate.getTime() - myDate.getTimezoneOffset() * 60 * 1000) % (3600 * 1000 * 24);

How to check if an element does NOT have a specific class?

Select element (or group of elements) having class "abc", not having class "xyz":

    $('.abc:not(".xyz")')

When selecting regular CSS you can use .abc:not(.xyz).

Unnamed/anonymous namespaces vs. static functions

Putting methods in an anonymous namespace prevents you from accidentally violating the One Definition Rule, allowing you to never worry about naming your helper methods the same as some other method you may link in.

And, as pointed out by luke, anonymous namespaces are preferred by the standard over static members.

Common xlabel/ylabel for matplotlib subplots

I ran into a similar problem while plotting a grid of graphs. The graphs consisted of two parts (top and bottom). The y-label was supposed to be centered over both parts.

I did not want to use a solution that depends on knowing the position in the outer figure (like fig.text()), so I manipulated the y-position of the set_ylabel() function. It is usually 0.5, the middle of the plot it is added to. As the padding between the parts (hspace) in my code was zero, I could calculate the middle of the two parts relative to the upper part.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# Create outer and inner grid
outerGrid = gridspec.GridSpec(2, 3, width_ratios=[1,1,1], height_ratios=[1,1])
somePlot = gridspec.GridSpecFromSubplotSpec(2, 1,
               subplot_spec=outerGrid[3], height_ratios=[1,3], hspace = 0)

# Add two partial plots
partA = plt.subplot(somePlot[0])
partB = plt.subplot(somePlot[1])

# No x-ticks for the upper plot
plt.setp(partA.get_xticklabels(), visible=False)

# The center is (height(top)-height(bottom))/(2*height(top))
# Simplified to 0.5 - height(bottom)/(2*height(top))
mid = 0.5-somePlot.get_height_ratios()[1]/(2.*somePlot.get_height_ratios()[0])
# Place the y-label
partA.set_ylabel('shared label', y = mid)

plt.show()

picture

Downsides:

  • The horizontal distance to the plot is based on the top part, the bottom ticks might extend into the label.

  • The formula does not take space between the parts into account.

  • Throws an exception when the height of the top part is 0.

There is probably a general solution that takes padding between figures into account.

Concatenate two PySpark dataframes

This should do it for you ...

from pyspark.sql.types import FloatType
from pyspark.sql.functions import randn, rand, lit, coalesce, col
import pyspark.sql.functions as F

df_1 = sqlContext.range(0, 6)
df_2 = sqlContext.range(3, 10)
df_1 = df_1.select("id", lit("old").alias("source"))
df_2 = df_2.select("id")

df_1.show()
df_2.show()
df_3 = df_1.alias("df_1").join(df_2.alias("df_2"), df_1.id == df_2.id, "outer")\
  .select(\
    [coalesce(df_1.id, df_2.id).alias("id")] +\
    [col("df_1." + c) for c in df_1.columns if c != "id"])\
  .sort("id")
df_3.show()

How to add/update child entities when updating a parent entity in EF

public async Task<IHttpActionResult> PutParent(int id, Parent parent)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != parent.Id)
            {
                return BadRequest();
            }

            db.Entry(parent).State = EntityState.Modified;

            foreach (Child child in parent.Children)
            {
                db.Entry(child).State = child.Id == 0 ? EntityState.Added : EntityState.Modified;
            }

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ParentExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Ok(db.Parents.Find(id));
        }

This is how I solved this problem. This way, EF knows which to add which to update.

How to include bootstrap css and js in reactjs app?

Full answer to give you jquery and bootstrap since jquery is a requirement for bootstrap.js:

Install jquery and bootstrap into node_modules:

npm install bootstrap
npm install jquery

Import in your components using this exact filepath:

import 'jquery/src/jquery'; //for bootstrap.min.js
//bootstrap-theme file for bootstrap 3 only
import 'bootstrap/dist/css/bootstrap-theme.min.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';

No module named Image

Did you setup PIL module? Link

You can try to reinstall it on your computer.

Dependency Injection vs Factory Pattern

Dependency Injection

Instead of instantiating the parts itself a car asks for the parts it needs to function.

class Car
{
    private Engine engine;
    private SteeringWheel wheel;
    private Tires tires;

    public Car(Engine engine, SteeringWheel wheel, Tires tires)
    {
        this.engine = engine;
        this.wheel = wheel;
        this.tires = tires;
    }
}

Factory

Puts the pieces together to make a complete object and hides the concrete type from the caller.

static class CarFactory
{
    public ICar BuildCar()
    {
        Engine engine = new Engine();
        SteeringWheel steeringWheel = new SteeringWheel();
        Tires tires = new Tires();
        ICar car = new RaceCar(engine, steeringWheel, tires);
        return car;
    }   
}

Result

As you can see, Factories and DI complement each other.

static void Main()
{
     ICar car = CarFactory.BuildCar();
     // use car
}

Do you remember goldilocks and the three bears? Well, dependency injection is kind of like that. Here are three ways to do the same thing.

void RaceCar() // example #1
{
    ICar car = CarFactory.BuildCar();
    car.Race();
}

void RaceCar(ICarFactory carFactory) // example #2
{
    ICar car = carFactory.BuildCar();
    car.Race();
}

void RaceCar(ICar car) // example #3
{
    car.Race();
}

Example #1 - This is the worst because it completely hides the dependency. If you looked at the method as a black box you would have no idea it required a car.

Example #2 - This is a little better because now we know we need a car since we pass in a car factory. But this time we are passing too much since all the method actually needs is a car. We are passing in a factory just to build the car when the car could be built outside the method and passed in.

Example #3 - This is ideal because the method asks for exactly what it needs. Not too much or too little. I don't have to write a MockCarFactory just to create MockCars, I can pass the mock straight in. It is direct and the interface doesn't lie.

This Google Tech Talk by Misko Hevery is amazing and is the basis of what I derived my example from. http://www.youtube.com/watch?v=XcT4yYu_TTs

How to install latest version of git on CentOS 7.x/6.x

Rackspace maintains the ius repository, which contains a reasonably up-to-date git, but the stock git has to first be removed.

CentOS 6 or 7 instructions (run as root or with sudo):

# retrieve and check CENTOS_MAIN_VERSION (6 or 7):
CENTOS_MAIN_VERSION=$(cat /etc/centos-release | awk -F 'release[ ]*' '{print $2}' | awk -F '.' '{print $1}')
echo $CENTOS_MAIN_VERSION
# output should be "6" or "7"

# Install IUS Repo and Epel-Release:
yum install -y https://repo.ius.io/ius-release-el${CENTOS_MAIN_VERSION}.rpm
yum install -y epel-release 

# re-install git:
yum erase -y git*
yum install -y git-core

# check version:
git --version
# output: git version 2.24.3

Note: git-all instead of git-core often installs an old version. Try e.g. git224-all instead.

The script is tested on a CentOS 7 docker image (7e6257c9f8d8) and on a CentOS 6 docker image (d0957ffdf8a2).

ruby 1.9: invalid byte sequence in UTF-8

I recommend you to use a HTML parser. Just find the fastest one.

Parsing HTML is not as easy as it may seem.

Browsers parse invalid UTF-8 sequences, in UTF-8 HTML documents, just putting the "?" symbol. So once the invalid UTF-8 sequence in the HTML gets parsed the resulting text is a valid string.

Even inside attribute values you have to decode HTML entities like amp

Here is a great question that sums up why you can not reliably parse HTML with a regular expression: RegEx match open tags except XHTML self-contained tags

What is the argument for printf that formats a long?

On most platforms, long and int are the same size (32 bits). Still, it does have its own format specifier:

long n;
unsigned long un;
printf("%ld", n); // signed
printf("%lu", un); // unsigned

For 64 bits, you'd want a long long:

long long n;
unsigned long long un;
printf("%lld", n); // signed
printf("%llu", un); // unsigned

Oh, and of course, it's different in Windows:

printf("%l64d", n); // signed
printf("%l64u", un); // unsigned

Frequently, when I'm printing 64-bit values, I find it helpful to print them in hex (usually with numbers that big, they are pointers or bit fields).

unsigned long long n;
printf("0x%016llX", n); // "0x" followed by "0-padded", "16 char wide", "long long", "HEX with 0-9A-F"

will print:

0x00000000DEADBEEF

Btw, "long" doesn't mean that much anymore (on mainstream x64). "int" is the platform default int size, typically 32 bits. "long" is usually the same size. However, they have different portability semantics on older platforms (and modern embedded platforms!). "long long" is a 64-bit number and usually what people meant to use unless they really really knew what they were doing editing a piece of x-platform portable code. Even then, they probably would have used a macro instead to capture the semantic meaning of the type (eg uint64_t).

char c;       // 8 bits
short s;      // 16 bits
int i;        // 32 bits (on modern platforms)
long l;       // 32 bits
long long ll; // 64 bits 

Back in the day, "int" was 16 bits. You'd think it would now be 64 bits, but no, that would have caused insane portability issues. Of course, even this is a simplification of the arcane and history-rich truth. See wiki:Integer