Programs & Examples On #Conditional statements

In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch prediction, this is always achieved by selectively altering the control flow based on some condition.

MySQL "Or" Condition

try this

    AND date='$Date_Today'
    OR date='$Date_Yesterday', '$Date_TwoDaysAgo', '$Date_ThreeDaysAgo', '$Date_FourDaysAgo', '$Date_FiveDaysAgo', '$Date_SixDaysAgo', '$Date_SevenDaysAgo'"     

my be like this

 OR date='$Date_Yesterday' oR '$Date_TwoDaysAgo'.........

How to have multiple conditions for one if statement in python

Darian Moody has a nice solution to this challenge in his blog post:

a = 1
b = 2
c = True

rules = [a == 1,
         b == 2,
         c == True]

if all(rules):

The all() method returns True when all elements in the given iterable are true. If not, it returns False.

You can read a little more about it in the python docs here and more information and examples here.

(I also answered the similar question with this info here - How to have multiple conditions for one if statement in python)

How to check whether a str(variable) is empty or not?

How do i make an: if str(variable) == [contains text]: condition?

Perhaps the most direct way is:

if str(variable) != '':
  # ...

Note that the if not ... solutions test the opposite condition.

How to write a switch statement in Ruby

Since switch case always returns a single object, we can directly print its result:

puts case a
     when 0
        "It's zero"
     when 1
        "It's one"

querying WHERE condition to character length?

   FROM   my_table
   WHERE  substr(my_field,1,5) = "abcde";

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

Try negation operator ! before $(this):

if (!$(this).parent().next().is('ul')){


In a more general case:

N( A union B) = N(A) + N(B) - N(A intersect B) 
= COUNTIFS(A1:A196,"Yes",J1:J196,"Agree")+COUNTIFS(A1:A196,"No",J1:J196,"Agree")-A1:A196,"Yes",A1:A196,"No")

What is the purpose of using WHERE 1=1 in SQL statements?

The 1=1 is ignored by always all rdbms. There is no tradeoff executing a query with WHERE 1=1.

Building dynamic WHERE conditions, like ORM frameworks or other do very often, it is easier to append the real where conditions because you avoid checking for prepending an AND to the current condition.

stmt += "WHERE 1=1";
if (v != null) {
   stmt += (" AND col = " + v.ToString());

This is how it looks like without 1=1.

var firstCondition = true;
if (v != null) {
   if (!firstCondition) {
      stmt += " AND ";
   else {
       stmt += " WHERE ";
       firstCondition = false;
   stmt += "col = " + v.ToString());

Conditional Count on a field

Using COUNT instead of SUM removes the requirement for an ELSE statement:

SELECT jobId, jobName,
    COUNT(CASE WHEN Priority=1 THEN 1 END) AS Priority1,
    COUNT(CASE WHEN Priority=2 THEN 1 END) AS Priority2,
    COUNT(CASE WHEN Priority=3 THEN 1 END) AS Priority3,
    COUNT(CASE WHEN Priority=4 THEN 1 END) AS Priority4,
    COUNT(CASE WHEN Priority=5 THEN 1 END) AS Priority5
FROM TableName
GROUP BY jobId, jobName

Simpler way to check if variable is not equal to multiple string values?

You need to multi value check. Try using the following code :

    if(count(array_intersect($illstack,$val))===count($val)){ // all of $val is in $illstack}

Weird behavior of the != XPath operator

The problem is that the 'and' is being treated as an 'or'.

No, the problem is that you are using the XPath != operator and you aren't aware of its "weird" semantics.


Just replace the any x != y expressions with a not(x = y) expression.

In your specific case:


<xsl:when test="$AccountNumber != '12345' and $Balance != '0'">


<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')">


By definition whenever one of the operands of the != operator is a nodeset, then the result of evaluating this operator is true if there is a node in the node-set, whose value isn't equal to the other operand.


 $someNodeSet != $someValue

generally doesn't produce the same result as:

 not($someNodeSet = $someValue)

The latter (by definition) is true exactly when there isn't a node in $someNodeSet whose string value is equal to $someValue.

Lesson to learn:

Never use the != operator, unless you are absolutely sure you know what you are doing.

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;

(6.7) init-declarator-list:
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator = initializer

(6.8) statement:

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

javascript: using a condition in switch case

If that's what you want to do, it would be better to use if statements. For example:

if(liCount == 0){
if(liCount<=5 && liCount>0){
if(liCount<=10 && liCount>5){
var api = $('#UploadList').data('jsp');

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

Replace all elements of Python NumPy Array that are greater than some value

You can also use &, | (and/or) for more flexibility:

values between 5 and 10: A[(A>5)&(A<10)]

values greater than 10 or smaller than 5: A[(A<5)|(A>10)]

If statement for strings in python?

Even once you fixed the mis-cased if and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in. Here's how you'd do it (and note that if is all lowercase and that the code within the if block is indented one level).

One approach:

if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:
    print("this will do the calculation")


if answer.lower() in ['y', 'yes']:
    print("this will do the calculation")

Can I use conditional statements with EJS templates (in JMVC)?

You can also use else if syntax:

<% if (x === 1) { %>
    <p>Hello world!</p>
<% } else if (x === 2) { %>
    <p>Hi earth!</p>
<% } else { %>
    <p>Hey terra!</p>
<% } %>

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

Multiple statements are to be separated by a new line:

If SkyIsBlue Then
ElseIf SkyIsRed Then
ElseIf SkyIsYellow Then
  If Sunset Then
  ElseIf Sunrise or IsMorning Then
  End If
End If

Can you use if/else conditions in CSS?

You can use javascript for this purpose, this way:

  1. first you set the CSS for the 'normal' class and for the 'active' class
  2. then you give to your element the id 'MyElement'
  3. and now you make your condition in JavaScript, something like the example below... (you can run it, change the value of myVar to 5 and you will see how it works)

var myVar = 4;_x000D_
if(myVar == 5){_x000D_
  document.getElementById("MyElement").className = "active";_x000D_
  document.getElementById("MyElement").className = "normal";_x000D_
  background-position : 150px 8px;_x000D_
  background-color: black;_x000D_
  background-position : 4px 8px; _x000D_
  background-color: green;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
<div id="MyElement">_x000D_

Conditional Replace Pandas

.ix indexer works okay for pandas version prior to 0.20.0, but since pandas 0.20.0, the .ix indexer is deprecated, so you should avoid using it. Instead, you can use .loc or iloc indexers. You can solve this problem by:

mask = df.my_channel > 20000
column_name = 'my_channel'
df.loc[mask, column_name] = 0

Or, in one line,

df.loc[df.my_channel > 20000, 'my_channel'] = 0

mask helps you to select the rows in which df.my_channel > 20000 is True, while df.loc[mask, column_name] = 0 sets the value 0 to the selected rows where maskholds in the column which name is column_name.

Update: In this case, you should use loc because if you use iloc, you will get a NotImplementedError telling you that iLocation based boolean indexing on an integer type is not available.

Excel - programm cells to change colour based on another cell

  1. Select cell B3 and click the Conditional Formatting button in the ribbon and choose "New Rule".
  2. Select "Use a formula to determine which cells to format"
  3. Enter the formula: =IF(B2="X",IF(B3="Y", TRUE, FALSE),FALSE), and choose to fill green when this is true
  4. Create another rule and enter the formula =IF(B2="X",IF(B3="W", TRUE, FALSE),FALSE) and choose to fill red when this is true.

More details - conditional formatting with a formula applies the format when the formula evaluates to TRUE. You can use a compound IF formula to return true or false based on the values of any cells.

IN Clause with NULL or IS NULL

The question as answered by Daniel is perfctly fine. I wanted to leave a note regarding NULLS. We should be carefull about using NOT IN operator when a column contains NULL values. You won't get any output if your column contains NULL values and you are using the NOT IN operator. This is how it's explained over here , a very good article which I came across and thought of sharing it.

MySQL select with CONCAT condition

Try this:

  FROM  (
        SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
        FROM users 
    ) a
WHERE firstlast = "Bob Michael Jones"

How do I test if a variable does not equal either of two values?

I do that using jQuery

if ( 0 > $.inArray( test, [a,b] ) ) { ... }

SELECT query with CASE condition and SUM()

To get each sum in a separate column:

Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
       SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash') 
and CStatus='Active';

Replacing values from a column using a condition in R

# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0

(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:

levels(df$species) <- c(levels(df$species), "unknown") 
df$species[df$depth<10]  <- "unknown" 

Check if year is leap year in javascript

You can use the following code to check if it's a leap year:

ily = function(yr) {
    return (yr % 400) ? ((yr % 100) ? ((yr % 4) ? false : true) : false) : true;

How to convert NUM to INT in R?

Use as.integer:

x <- runif(5, 0, 100)
[1] 26.55087 37.21239 57.28534 90.82078 20.16819

[1] 26 37 57 90 20

Test for class:

xx <- as.integer(x)
 int [1:5] 26 37 57 90 20

Fastest way to check if a file exist using standard C++/C++11/C?

I need a fast function that can check if a file is exist or not and PherricOxide's answer is almost what I need except it does not compare the performance of boost::filesystem::exists and open functions. From the benchmark results we can easily see that :

  • Using stat function is the fastest way to check if a file is exist. Note that my results are consistent with that of PherricOxide's answer.

  • The performance of boost::filesystem::exists function is very close to that of stat function and it is also portable. I would recommend this solution if boost libraries is accessible from your code.

Benchmark results obtained with Linux kernel 4.17.0 and gcc-7.3:

2018-05-05 00:35:35
Running ./filesystem
Run on (8 X 2661 MHz CPU s)
CPU Caches:
  L1 Data 32K (x4)
  L1 Instruction 32K (x4)
  L2 Unified 256K (x4)
  L3 Unified 8192K (x1)
Benchmark           Time           CPU Iterations
use_stat          815 ns        813 ns     861291
use_open         2007 ns       1919 ns     346273
use_access       1186 ns       1006 ns     683024
use_boost         831 ns        830 ns     831233

Below is my benchmark code:

#include <string.h>                                                                                                                                                                                                                                           
#include <stdlib.h>                                                                                                                                                                                                                                           
#include <sys/types.h>                                                                                                                                                                                                                                        
#include <sys/stat.h>                                                                                                                                                                                                                                         
#include <unistd.h>                                                                                                                                                                                                                                           
#include <dirent.h>                                                                                                                                                                                                                                           
#include <fcntl.h>                                                                                                                                                                                                                                            
#include <unistd.h>                                                                                                                                                                                                                                           

#include "boost/filesystem.hpp"                                                                                                                                                                                                                               

#include <benchmark/benchmark.h>                                                                                                                                                                                                                              

const std::string fname("filesystem.cpp");                                                                                                                                                                                                                    
struct stat buf;                                                                                                                                                                                                                                              

// Use stat function                                                                                                                                                                                                                                          
void use_stat(benchmark::State &state) {                                                                                                                                                                                                                      
    for (auto _ : state) {                                                                                                                                                                                                                                    
        benchmark::DoNotOptimize(stat(, &buf));                                                                                                                                                                                                   

// Use open function                                                                                                                                                                                                                                          
void use_open(benchmark::State &state) {                                                                                                                                                                                                                      
    for (auto _ : state) {                                                                                                                                                                                                                                    
        int fd = open(, O_RDONLY);                                                                                                                                                                                                                
        if (fd > -1) close(fd);                                                                                                                                                                                                                               
// Use access function                                                                                                                                                                                                                                        
void use_access(benchmark::State &state) {                                                                                                                                                                                                                    
    for (auto _ : state) {                                                                                                                                                                                                                                    
        benchmark::DoNotOptimize(access(, R_OK));                                                                                                                                                                                                 

// Use boost                                                                                                                                                                                                                                                  
void use_boost(benchmark::State &state) {                                                                                                                                                                                                                     
    for (auto _ : state) {                                                                                                                                                                                                                                    
        boost::filesystem::path p(fname);                                                                                                                                                                                                                     


Call a python function from jinja2

If you are doing it with Django, you can just pass the function with the context:

context = {
    'title':'My title',
    'str': str,
return render(request, 'index.html', context)

Now you will be able to use the str function in jinja2 template

Dealing with multiple Python versions and PIP?

I had python 2.6 installed by default (Amazon EC2 AMI), but needed python2.7 plus some external packages for my application. Assuming you already installed python2.7 alongside with default python (2.6 in my case). Here is how to install pip and packages for non-default python2.7

Install pip for your python version:

curl -O

Use specific pip version to install packages:

pip2.7 install mysql-connector-python --allow-external mysql-connector-python

I want to use CASE statement to update some records in sql server 2005

This is also an alternate use of case-when...

UPDATE [dbo].[JobTemplates]
SET [CycleId] = 
    CASE [Id]
        WHEN 1376 THEN 44   --ACE1 FX1
        WHEN 1385 THEN 44   --ACE1 FX2
        WHEN 1574 THEN 43   --ACE1 ELEM1
        WHEN 1576 THEN 43   --ACE1 ELEM2
        WHEN 1581 THEN 41   --ACE1 FS1
        WHEN 1585 THEN 42   --ACE1 HS1
        WHEN 1588 THEN 43   --ACE1 RS1
        WHEN 1589 THEN 44   --ACE1 RM1
        WHEN 1590 THEN 43   --ACE1 ELEM3
        WHEN 1591 THEN 43   --ACE1 ELEM4
        WHEN 1595 THEN 44   --ACE1 SSTn     
        ELSE 0  
    [Id] IN (1376,1385,1574,1576,1581,1585,1588,1589,1590,1591,1595)

I like the use of the temporary tables in cases where duplicate values are not permitted and your update may create them. For example:

    ,CASE [CycleId]
        WHEN  29 THEN 44
        WHEN  30 THEN 43
        WHEN  31 THEN 43
        WHEN 101 THEN 41
        WHEN 102 THEN 43
        WHEN 116 THEN 42
        WHEN 120 THEN 44
        WHEN 127 THEN 44
        WHEN 129 THEN 44
        ELSE    0
     END                AS [CycleId]
    [QueueId] = 3
    [BaseDimensionId], [ElastomerTypeId], [Id];
---- (403 row(s) affected)

UPDATE [dbo].[ProductionQueueProcessAutoclaveNominals]
    [CycleId] = X.[CycleId]
        MIN([Id]) AS [Id],[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId] 
    GROUP BY    
) AS X
    [dbo].[ProductionQueueProcessAutoclaveNominals].[Id] = X.[Id];
----(375 row(s) affected)

SQL like search string starts with

You need to use the wildcard % :

SELECT * from games WHERE (lower(title) LIKE 'age of empires III%');

ThreadStart with parameters

One of the 2 overloads of the Thread constructor takse a ParameterizedThreadStart delegate which allows you to pass a single parameter to the start method. Unfortunately though it only allows for a single parameter and it does so in an unsafe way because it passes it as object. I find it's much easier to use a lambda expression to capture the relevant parameters and pass them in a strongly typed fashion.

Try the following

public Thread StartTheThread(SomeType param1, SomeOtherType param2) {
  var t = new Thread(() => RealStart(param1, param2));
  return t;

private static void RealStart(SomeType param1, SomeOtherType param2) {

Install specific version using laravel installer

The direct way as mentioned in the documentation:

composer create-project --prefer-dist laravel/laravel blog "6.*"

Why do we use Base64?

Here is a summary of my understanding after reading what others have posted:


Base64 encoding is not meant to provide security

Base64 encoding is not meant to compress data

Why do we use Base64

Base64 is a text representation of data that consists of only 64 characters which are the alphanumeric characters (lowercase and uppercase), +, / and =. These 64 characters are considered ‘safe’, that is, they can not be misinterpreted by legacy computers and programs unlike characters such as <, > \n and many others.

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

You can also use this code to extend ObservableCollection:

public static class ObservableCollectionExtend
    public static void AddRange<TSource>(this ObservableCollection<TSource> source, IEnumerable<TSource> items)
        foreach (var item in items)

Then you don't need to change class in existing code.

How to store a datetime in MySQL with timezone info

I once also faced such an issue where i needed to save data which was used by different collaborators and i ended up storing the time in unix timestamp form which represents the number of seconds since january 1970 which is an integer format. Example todays date and time in tanzania is Friday, September 13, 2019 9:44:01 PM which when store in unix timestamp would be 1568400241

Now when reading the data simply use something like php or any other language and extract the date from the unix timestamp. An example with php will be

echo date('m/d/Y', 1568400241);

This makes it easier even to store data with other collaborators in different locations. They can simply convert the date to unix timestamp with their own gmt offset and store it in a integer format and when outputting this simply convert with a

Automatically plot different colored lines

Actually, a decent shortcut method for getting the colors to cycle is to use hold all; in place of hold on;. Each successive plot will rotate (automatically for you) through MATLAB's default colormap.

From the MATLAB site on hold:

hold all holds the plot and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and LineStyleOrder property values to the beginning of the list. Plotting commands continue cycling through the predefined colors and linestyles from where the last plot stopped in the list.

How to return a dictionary | Python

What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:

def query(id):
    for line in file:
        table = {}
        (table["ID"],table["name"],table["city"]) = line.split(";")
        if id == int(table["ID"]):
             return table
    # ID not found; close file and return empty dict
    return {}

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

Define a fixed-size list in Java


Commons library provides a built-in FixedSizeList which does not support the add, remove and clear methods (but the set method is allowed because it does not modify the List's size). In other words, if you try to call one of these methods, your list still retain the same size.

To create your fixed size list, just call

List<YourType> fixed = FixedSizeList.decorate(Arrays.asList(new YourType[100]));

You can use unmodifiableList if you want an unmodifiable view of the specified list, or read-only access to internal lists.

List<YourType> unmodifiable = java.util.Collections.unmodifiableList(internalList);

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.

The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

How to create a scrollable Div Tag Vertically?

Well, your code worked for me (running Chrome 5.0.307.9 and Firefox 3.5.8 on Ubuntu 9.10), though I switched

overflow-y: scroll;


overflow-y: auto;

Demo page over at:

xhtml below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">

<html xmlns="" xml:lang="en" lang="en">

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

    <title>Div in table</title>
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css" />

        <style type="text/css" media="all">

        th      {border-bottom: 2px solid #ccc; }

        th,td       {padding: 0.5em 1em; 
                margin: 0;
                border-collapse: collapse;

        tr td:first-child
                {border-right: 2px solid #ccc; } 

        td > div    {width: 249px;
                height: 299px;
                overflow-y: auto;

    <script type="text/javascript" src="js/jquery.js"></script>

    <script type="text/javascript">






            <tr><th>This is column one</th><th>This is column two</th><th>This is column three</th>

            <tr><td>This is row one</td><td>data point 2.1</td><td>data point 3.1</td>
            <tr><td>This is row two</td><td>data point 2.2</td><td>data point 3.2</td>
            <tr><td>This is row three</td><td>data point 2.3</td><td>data point 3.3</td>
            <tr><td>This is row four</td><td><div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies mattis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum a accumsan purus. Vivamus semper tempus nisi et convallis. Aliquam pretium rutrum lacus sed auctor. Phasellus viverra elit vel neque lacinia ut dictum mauris aliquet. Etiam elementum iaculis lectus, laoreet tempor ligula aliquet non. Mauris ornare adipiscing feugiat. Vivamus condimentum luctus tortor venenatis fermentum. Maecenas eu risus nec leo vehicula mattis. In nisi nibh, fermentum vitae tincidunt non, mattis eu metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc vel est purus. Ut accumsan, elit non lacinia porta, nibh magna pretium ligula, sed iaculis metus tortor aliquam urna. Duis commodo tincidunt aliquam. Maecenas in augue ut ligula sodales elementum quis vitae risus. Vivamus mollis blandit magna, eu fringilla velit auctor sed.</p></div></td><td>data point 3.4</td>
            <tr><td>This is row five</td><td>data point 2.5</td><td>data point 3.5</td>
            <tr><td>This is row six</td><td>data point 2.6</td><td>data point 3.6</td>
            <tr><td>This is row seven</td><td>data point 2.7</td><td>data point 3.7</td>





Converting date between DD/MM/YYYY and YYYY-MM-DD?

In case you need to convert an entire column of data (from pandas DataFrame), then first convert it (pandas Series) to the datetime format using to_datetime and finally use .dt.strftime:

def conv_dates_series(df, col, old_date_format, new_date_format):

    df[col] = pd.to_datetime(df[col], format=old_date_format).dt.strftime(new_date_format)


Sample usage:

import pandas as pd

test_df = pd.DataFrame({"Dates": ["1900-01-01", "1999-12-31"]})


conv_dates_series(test_df, "Dates", old_date_format, new_date_format)

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

How to determine if .NET Core is installed

It's possible that .NET Core is installed but not added to the PATH variable for your operating system or user profile. Running the dotnet commands may not work. As an alternative, you can check that the .NET Core install folders exist.

It's installed to a standard folder if you didn't change it during the instillation

  • dotnet executable C:\program files\dotnet\dotnet.exe

  • .NET SDK C:\program files\dotnet\sdk\{version}\

  • .NET Runtime C:\program files\dotnet\shared\{runtime-type}\{version}\

For more details check How to check that .NET Core is already installed page at .NET documentation

Python: For each list element apply a function across the list

If I'm correct in thinking that you want to find the minimum value of a function for all possible pairs of 2 elements from a list...

l = [1,2,3,4,5]

def f(i,j):
   return i+j 

# Prints min value of f(i,j) along with i and j
print min( (f(i,j),i,j) for i in l for j in l)

What is the best/simplest way to read in an XML file in Java application?

Depending on your application and the scope of the cfg file, a properties file might be the easiest. Sure it isn't as elegant as xml but it certainly easier.

Java enum - why use toString instead of name

name() is a "built-in" method of enum. It is final and you cannot change its implementation. It returns the name of enum constant as it is written, e.g. in upper case, without spaces etc.

Compare MOBILE_PHONE_NUMBER and Mobile phone number. Which version is more readable? I believe the second one. This is the difference: name() always returns MOBILE_PHONE_NUMBER, toString() may be overriden to return Mobile phone number.

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

I've been having the same issue for days now with an integration that also just "used to work before".

Out of sheer depression, I just tried

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

This solved it for me..even though the integration strictly only makes use of SSLv3.

I came to the realization that something if off since Fiddler reported saying that there is an "empty TLS negotiation cipher" or something of the like.

Hopefully it works!

Setting up a git remote origin

You can include the branch to track when setting up remotes, to keep things working as you might expect:

git remote add --track master origin [email protected]:group/project.git   # git
git remote add --track master origin [email protected]:group/project.git   # git w/IP
git remote add --track master origin   # http
git remote add --track master origin # http w/IP
git remote add --track master origin /Volumes/Git/group/project/           # local
git remote add --track master origin G:/group/project/                     # local, Win

This keeps you from having to manually edit your git config or specify branch tracking manually.

powershell is missing the terminator: "

In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 


1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

How can I make my string property nullable?

string type is a reference type, therefore it is nullable by default. You can only use Nullable<T> with value types.

public struct Nullable<T> where T : struct

Which means that whatever type is replaced for the generic parameter, it must be a value type.

How to get the current time in milliseconds from C in Linux?

Use gettimeofday() to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.

Arithmetic operation resulted in an overflow. (Adding integers)

The result integer value is out of the range which an integer data type can hold.

Try using Int64

Using a BOOL property

Apple recommends for stylistic purposes.If you write this code:

@property (nonatomic,assign) BOOL working;

Then you can not use [object isWorking].
It will show an error. But if you use below code means

@property (assign,getter=isWorking) BOOL working;

So you can use [object isWorking] .

Laravel 5 - redirect to HTTPS

Similar to manix's answer but in one place. Middleware to force HTTPS

namespace App\Http\Middleware;

use Closure;

use Illuminate\Http\Request;

class ForceHttps
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
    public function handle($request, Closure $next)
        if (!app()->environment('local')) {
            // for Proxies

            if (!$request->isSecure()) {
                return redirect()->secure($request->getRequestUri());

        return $next($request);

Python Pandas Replacing Header with Top Row

header = table_df.iloc[0]
table_df.drop([0], axis =0, inplace=True)
table_df.columns = header

How do I comment out a block of tags in XML?

If you ask, because you got errors with the <!-- --> syntax, it's most likely the CDATA section (and there the ]]> part), that then lies in the middle of the comment. It should not make a difference, but ideal and real world can be quite a bit apart, sometimes (especially when it comes to XML processing).

Try to change the ]]>, too:

    <band height="20">
        <reportElement x="180" y="0" width="200" height="20"/>
        <text><![CDATA[Hello World!]--><!--]></text>

Another thing, that comes to mind: If the content of your XML somewhere contains two hyphens, the comment immediately ends there:

<!-- <a> This is strange -- but true!</a> -->
--------------------------^ comment ends here

That's quite a common pitfall. It's inherited from the way SGML handles comments. (Read the XML spec on this topic)

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

for me it worked the approach that I used in eclipselink as well. Just call the size() of the collection that should be loaded before using it as parameter to pages.

for (Entity e : entityListKeeper.getEntityList()) {

Here entityListKeeper has List of Entity that has list of LazyLoadedEntity. If you have just therelation Entity has list of LazyLoadedEntity then the solution is:


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

I used the code mentioned in this great answer and expanded it to support 2 additional parameters which I needed in my case. The parameters are file extensions to filter on and a flag indicating whether to concatenate the full path to the name of the file or not.

I hope it is clear enough and someone will finds it beneficial.

function fileList = getAllFiles(dirName, fileExtension, appendFullPath)

  dirData = dir([dirName '/' fileExtension]);      %# Get the data for the current directory
  dirWithSubFolders = dir(dirName);
  dirIndex = [dirWithSubFolders.isdir];  %# Find the index for directories
  fileList = {}';  %'# Get a list of the files
  if ~isempty(fileList)
    if appendFullPath
      fileList = cellfun(@(x) fullfile(dirName,x),...  %# Prepend path to files
  subDirs = {dirWithSubFolders(dirIndex).name};  %# Get a list of the subdirectories
  validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
                                               %#   that are not '.' or '..'
  for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dirName,subDirs{iDir});    %# Get the subdirectory path
    fileList = [fileList; getAllFiles(nextDir, fileExtension, appendFullPath)];  %# Recursively call getAllFiles


Example for running the code:

fileList = getAllFiles(dirName, '*.xml', 0); %#0 is false obviously

Adding subscribers to a list using Mailchimp's API v3

If you Want to run Batch Subscribe on a List using Mailchimp API . Then you can use the below function.

     * Mailchimp API- List Batch Subscribe added function
     * @param array  $data   Passed you data as an array format.
     * @param string $apikey your mailchimp api key.
     * @return mixed
    function batchSubscribe(array $data, $apikey)
        $auth          = base64_encode('user:' . $apikey);
        $json_postData = json_encode($data);
        $ch            = curl_init();
        $dataCenter    = substr($apikey, strpos($apikey, '-') + 1);
        $curlopt_url   = 'https://' . $dataCenter . '';
        curl_setopt($ch, CURLOPT_URL, $curlopt_url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
            'Authorization: Basic ' . $auth));
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_postData);
        $result = curl_exec($ch);
        return $result;

Function Use And Data format for Batch Operations:

$apikey  = 'Your MailChimp Api Key';
$list_id = 'Your list ID';
$servername = 'localhost';
$username   = 'Youre DB username';
$password   = 'Your DB password';
$dbname     = 'Your DB Name';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
$sql       = 'SELECT * FROM emails';// your SQL Query goes here
$result    = $conn->query($sql);
$finalData = [];
if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {
        $individulData = array(
            'apikey'        => $apikey,
            'email_address' => $row['email'],
            'status'        => 'subscribed',
            'merge_fields'  => array(
                'FNAME' => 'eastwest',
                'LNAME' => 'rehab',
        $json_individulData        = json_encode($individulData);
        $finalData['operations'][] =
                "method" => "POST",
                "path"   => "/lists/$list_id/members/",
                "body"   => $json_individulData
$api_response = batchSubscribe($finalData, $apikey);

Also, You can found this code in my Github gist. GithubGist Link

Reference Documentation: Official

What is the difference between json.dumps and json.load?

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

How can I make an svg scale with its parent container?

To specify the coordinates within the SVG image independently of the scaled size of the image, use the viewBox attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use the width and height attributes to define what the width or height are with respect to the containing page.

For instance, if you have the following:

    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />

It will render as a 10px by 20px triangle:

10x20 triangle

Now, if you set only the width and height, that will change the size of the SVG element, but not scale the triangle:

<svg width=100 height=50>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />

10x20 triangle

If you set the view box, that causes it to transform the image such that the given box (in the coordinate system of the image) is scaled up to fit within the given width and height (in the coordinate system of the page). For instance, to scale up the triangle to be 100px by 50px:

<svg width=100 height=50 viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />

100x50 triangle

If you want to scale it up to the width of the HTML viewport:

<svg width="100%" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />

300x150 triangle

Note that by default, the aspect ratio is preserved. So if you specify that the element should have a width of 100%, but a height of 50px, it will actually only scale up to the height of 50px (unless you have a very narrow window):

<svg width="100%" height="50px" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />

100x50 triangle

If you actually want it to stretch horizontally, disable aspect ratio preservation with preserveAspectRatio=none:

<svg width="100%" height="50px" viewBox="0 0 20 10" preserveAspectRatio="none">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />

300x50 triangle

(note that while in my examples I use syntax that works for HTML embedding, to include the examples as an image in StackOverflow I am instead embedding within another SVG, so I need to use valid XML syntax)

Android studio takes too much memory

Open below mention path on your system and delete all your avd's (Virtual devices: Emulator)


Note: - Deleting Emulator only from android studio will not delete all the spaces grab by their avd's. So delete all avd's from above given path and then create new emulator, if you needed.

"import datetime" v.s. "from datetime import datetime"

from datetime import datetime,timedelta
print("Todays Date:",today)
print("Yesterday date:",yesterday)
print("Tommorrow Date:",tommorrow)

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Using this HTML:

<div id="myElement" style="position: absolute">This stays at the top</div>

This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.

$(window).scroll(function() {
    $('#myElement').css('top', $(this).scrollTop() + "px");

As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's debounce/throttle plugin to reduce overhead.

HTTP Error 404 when running Tomcat from Eclipse

It is because there is no default ROOT web application. When you create some web app and deploy it to Tomcat using Eclipse, then you will be able to access it with the URL in the form of


where YourWebAppName is some name you give to your web app (the so called application context path).

Quote from Jetty Documentation Wiki (emphasis mine):

The context path is the prefix of a URL path that is used to select the web application to which an incoming request is routed. Typically a URL in a Java servlet server is of the format, where each of the path elements may be zero or more / separated elements. If there is no context path, the context is referred to as the root context.

If you still want the default app which is accessed with the URL of the form


or if you change the default 8080 port to 80, then just


i.e. without application context path read the following (quote from Tutorial: Installing Tomcat 7 and Using it with Eclipse, emphasis mine):

Copy the ROOT (default) Web app into Eclipse. Eclipse forgets to copy the default apps (ROOT, examples, docs, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.34\webapps and copy the ROOT folder. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like C:\your-eclipse-workspace-location\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or .../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

What's the difference between HEAD^ and HEAD~ in Git?

  • HEAD~ specifies the first parent on a "branch"

  • HEAD^ allows you to select a specific parent of the commit

An Example:

If you want to follow a side branch, you have to specify something like


how to draw directed graphs using networkx in python?

You need to use a directed graph instead of a graph, i.e.

G = nx.DiGraph()

Then, create a list of the edge colors you want to use and pass those to nx.draw (as shown by @Marius).

Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.

enter image description here

Selection with .loc in python

  1. Whenever slicing (a:n) can be used, it can be replaced by fancy indexing (e.g. [a,b,c,...,n]). Fancy indexing is nothing more than listing explicitly all the index values instead of specifying only the limits.

  2. Whenever fancy indexing can be used, it can be replaced by a list of Boolean values (a mask) the same size than the index. The value will be True for index values that would have been included in the fancy index, and False for the values that would have been excluded. It's another way of listing some index values, but which can be easily automated in NumPy and Pandas, e.g by a logical comparison (like in your case).

The second replacement possibility is the one used in your example. In:

iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'

the mask

iris_data['class'] == 'versicolor'

is a replacement for a long and silly fancy index which would be list of row numbers where class column (a Series) has the value versicolor.

Whether a Boolean mask appears within a .iloc or .loc (e.g. df.loc[mask]) indexer or directly as the index (e.g. df[mask]) depends on wether a slice is allowed as a direct index. Such cases are shown in the following indexer cheat-sheet:

Pandas indexers loc and iloc cheat-sheet
Pandas indexers loc and iloc cheat-sheet

Write values in app.config file

string filePath = System.IO.Path.GetFullPath("");

var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
    // Open App.Config of executable
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

    // Add an Application Setting if not exist

        config.AppSettings.Settings.Add("key1", "value1");
        config.AppSettings.Settings.Add("key2", "value2");

    // Save the changes in App.config file.

    // Force a reload of a changed section.
catch (ConfigurationErrorsException ex)
    if (ex.BareMessage == "Root element is missing.")

How can I stop a While loop?

The is operator in Python probably doesn't do what you expect. Instead of this:

    if numpy.array_equal(tmp,universe_array) is True:

I would write it like this:

    if numpy.array_equal(tmp,universe_array):

The is operator tests object identity, which is something quite different from equality.

Enabling/installing GD extension? --without-gd

I've PHP 7.3 and Nginx 1.14 on Ubuntu 18.

# it installs php7.3-gd for the moment
# and restarts PHP 7.3 FastCGI Process Manager: php-fpm7.3.
sudo apt-get install php-gd

# after I've restarted Nginx
sudo /etc/init.d/nginx restart


Ignoring new fields on JSON objects using Jackson

Up to date and complete answer with Jackson 2

Using Annotation

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyMappingClass {


See JsonIgnoreProperties on Jackson online documentation.

Using Configuration

Less intrusive than annotation.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

ObjectReader objectReader = objectMapper.reader(MyMappingClass.class);
MyMappingClass myMappingClass = objectReader.readValue(json);

See FAIL_ON_UNKNOWN_PROPERTIES on Jackson online documentation.

Handling onchange event in HTML.DropDownList Razor MVC

The way of dknaack does not work for me, I found this solution as well:

@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList, 
                    "Select chapter", new { @onchange = "location = this.value;" })


@Html.DropDownList(controlName, + cast, "Default value", @onchange event)

In the controller you can add:

DbModel db = new DbModel();    //entity model of Entity Framework

ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");

How to Decrease Image Brightness in CSS

You could use:

filter: brightness(50%);
-webkit-filter: brightness(50%);
-moz-filter: brightness(50%);
-o-filter: brightness(50%);
-ms-filter: brightness(50%);

Execute CMD command from code

Using Process.Start:

using System.Diagnostics;

class Program
    static void Main()

Difference between an API and SDK

Application Programming Interface is a set of routines/data structures/classes which specifies a way to interact with the target platform/software like OS X, Android, project management application, virtualization software etc.

While Software Development Kit is a wrapper around API/s that makes the job easy for developers.

For example, Android SDK facilitates developers to interact with the Android platform as a whole while the platform itself is built by composite software components communicating via APIs.

Also, sometimes SDKs are built to facilitate development in a specific programming language. For example, Selenium web driver (built in Java) provides APIs to drive any browser natively, while capybara can be considered an an SDK that facilitates Ruby developers to use Selenium web driver. However, Selenium web driver is also an SDK by itself as it combines interaction with various native browser drivers into one package.

Cassandra cqlsh - connection refused

I was trying to run it on a network drive. So I increased the client_timeout in cqlsh and it worked.

What is time_t ultimately a typedef to?

time_t is of type long int on 64 bit machines, else it is long long int.

You could verify this in these header files:

time.h: /usr/include
types.h and typesizes.h: /usr/include/x86_64-linux-gnu/bits

(The statements below are not one after another. They could be found in the resp. header file using Ctrl+f search.)

1)In time.h

typedef __time_t time_t;

2)In types.h

# define __STD_TYPE     typedef  
__STD_TYPE __TIME_T_TYPE __time_t;  

3)In typesizes.h

#define __TIME_T_TYPE       __SYSCALL_SLONG_TYPE  
#if defined __x86_64__ && defined __ILP32__  

4) Again in types.h

#define __SLONGWORD_TYPE    long int
#if __WORDSIZE == 32
# define __SQUAD_TYPE       __quad_t
#elif __WORDSIZE == 64
# define __SQUAD_TYPE       long int  

#if __WORDSIZE == 64
typedef long int __quad_t;  
__extension__ typedef long long int __quad_t;

Does List<T> guarantee insertion order?

Here are 4 items, with their index

0  1  2  3
K  C  A  E

You want to move K to between A and E -- you might think position 3. You have be careful about your indexing here, because after the remove, all the indexes get updated.

So you remove item 0 first, leaving

0  1  2
C  A  E

Then you insert at 3

0  1  2  3
C  A  E  K

To get the correct result, you should have used index 2. To make things consistent, you will need to send to (indexToMoveTo-1) if indexToMoveTo > indexToMove, e.g.

bool moveUp = (listInstance.IndexOf(itemToMoveTo) > indexToMove);
listInstance.Insert(indexToMoveTo, moveUp ? (itemToMoveTo - 1) : itemToMoveTo);

This may be related to your problem. Note my code is untested!

EDIT: Alternatively, you could Sort with a custom comparer (IComparer) if that's applicable to your situation.

Javascript-Setting background image of a DIV via a function and function parameter

From what I know, the correct syntax is:

function ChangeBackgroungImageOfTab(tabName, imagePrefix)
    document.getElementById(tabName).style.backgroundImage = "url('buttons/" + imagePrefix + ".png')";

So basically, getElementById(tabName).backgroundImage and split the string like:

"cssInHere('and" + javascriptOutHere + "/cssAgain')";

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.


    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.


    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.


    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).


    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.


Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

Can't install any packages in Node.js using "npm install"

If you happened to run npm install command on Windows, first make sure you open your command prompt with Administration Privileges. That's what solved the issue for me.

How to move the cursor word by word in the OS X Terminal

I have Alt+/ working: open Preferences » Settings » Keyboard, set the entry for option cursor left to send string to shell: \033b, and set option cursor right to send string to shell: \033f. You can also use this for other Control key combinations.

Open new Terminal Tab from command line (Mac OS X)

If you are using iTerm this command will open a new tab:

osascript -e 'tell application "iTerm" to activate' -e 'tell application "System Events" to tell process "iTerm" to keystroke "t" using command down'

What is the easiest way to initialize a std::vector with hardcoded elements?

One method would be to use the array to initialize the vector

static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

HTML to PDF with Node.js

Phantom.js is an headless webkit server and it will load any web page and render it in memory, although you might not be able to see it, there is a Screen Capture feature, in which you can export the current view as PNG, PDF, JPEG and GIF. Have a look at this example from phantom.js documentation

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

Try resetting your password for the email used. Had similar issue, and got it fixed only after changing password.

How to connect to remote Redis server?

One thing that confused me a little bit with this command is that if redis-cli fails to connect using the passed connection string it will still put you in the redis-cli shell, i.e:

Could not connect to Redis at Connection refused
not connected> 

You'll then need to exit to get yourself out of the shell. I wasn't paying much attention here and kept passing in new redis-cli commands wondering why the command wasn't using my passed connection string.

Align Bootstrap Navigation to Center

Try this css

.clearfix:before, .clearfix:after, .container:before, .container:after, .container-fluid:before, .container-fluid:after, .row:before, .row:after, .form-horizontal .form-group:before, .form-horizontal .form-group:after, .btn-toolbar:before, .btn-toolbar:after, .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after, .nav:before, .nav:after, .navbar:before, .navbar:after, .navbar-header:before, .navbar-header:after, .navbar-collapse:before, .navbar-collapse:after, .pager:before, .pager:after, .panel-body:before, .panel-body:after, .modal-footer:before, .modal-footer:after {
    content: " ";
    display: table-cell;

ul.nav {
    float: none;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    width: 240px;

How to install bcmath module?

When using the official PHP images of Docker, use docker-php-ext-install bcmath.


Is Tomcat running?

I always do

tail -f logs/catalina.out

When I see there

INFO: Server startup in 77037 ms

then I know the server is up.

Gem Command not found

I had the same problem. What I did was:

sudo apt-get update

And then reinstall ruby-full

sudo apt-get install ruby-full

heroku - how to see all the logs

For cedar stack see:

you need to run:

heroku run bash ...

RegExp matching string not starting with my

Wouldn't it be significantly more readable to do a positive match and reject those strings - rather than match the negative to find strings to accept?


How to get all of the IDs with jQuery?

My suggestion?

var arr = $.map($("#mydiv [id]"), function(n, i) {

you could also do this as:

var arr = $.map($("#mydiv span"), function(n, i) {


var arr = $.map($("#mydiv span[id]"), function(n, i) {

or even just:

var arr = $("#mydiv [id]").map(function() {

Lots of ways basically.

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

Upping the directive in the virtualhost for KeepAliveTimeout to 60 solved this for me.

Get last n lines of a file, similar to tail

Assumes a unix-like system on Python 2 you can do:

import os
def tail(f, n, offset=0):
  stdin,stdout = os.popen2("tail -n "+n+offset+" "+f)
  lines = stdout.readlines(); stdout.close()
  return lines[:,-offset]

For python 3 you may do:

import subprocess
def tail(f, n, offset=0):
    proc = subprocess.Popen(['tail', '-n', n + offset, f], stdout=subprocess.PIPE)
    lines = proc.stdout.readlines()
    return lines[:, -offset]

Size-limited queue that holds last N elements in Java

You can use a MinMaxPriorityQueue from Google Guava, from the javadoc:

A min-max priority queue can be configured with a maximum size. If so, each time the size of the queue exceeds that value, the queue automatically removes its greatest element according to its comparator (which might be the element that was just added). This is different from conventional bounded queues, which either block or reject new elements when full.

Add or change a value of JSON key with jquery or javascript

Once you have decoded the JSON, the result is a JavaScript object. Just manipulate it as you would any other object. For example:

data.busNum = 12345;

What is The difference between ListBox and ListView

Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

How to throw an exception in C?

If you write code with Happy path design pattern (i.e. for embedded device) you may simulate exception error processing (aka deffering or finally emulation) with operator "goto".

int process(int port)
    int rc;
    int fd1;
    int fd2;

    fd1 = open("/dev/...", ...);
    if (fd1 == -1) {
      rc = -1;
      goto out;

    fd2 = open("/dev/...", ...);
    if (fd2 == -1) {
      rc = -1;
      goto out;

    // Do some with fd1 and fd2 for example write(f2, read(fd1))

    rc = 0;


    //if (rc != 0) {

    return rc;

It does not actually exception handler but it take you a way to handle error at fucntion exit.

P.S. You should be careful use goto only from same or more deep scopes and never jump variable declaration.

Objective-C ARC: strong vs retain and weak vs assign

Clang's document on Objective-C Automatic Reference Counting (ARC) explains the ownership qualifiers and modifiers clearly:

There are four ownership qualifiers:

  • __autoreleasing
  • __strong
  • __*unsafe_unretained*
  • __weak

A type is nontrivially ownership-qualified if it is qualified with __autoreleasing, __strong, or __weak.

Then there are six ownership modifiers for declared property:

  • assign implies __*unsafe_unretained* ownership.
  • copy implies __strong ownership, as well as the usual behavior of copy semantics on the setter.
  • retain implies __strong ownership.
  • strong implies __strong ownership.
  • *unsafe_unretained* implies __*unsafe_unretained* ownership.
  • weak implies __weak ownership.

With the exception of weak, these modifiers are available in non-ARC modes.

Semantics wise, the ownership qualifiers have different meaning in the five managed operations: Reading, Assignment, Initialization, Destruction and Moving, in which most of times we only care about the difference in Assignment operation.

Assignment occurs when evaluating an assignment operator. The semantics vary based on the qualification:

  • For __strong objects, the new pointee is first retained; second, the lvalue is loaded with primitive semantics; third, the new pointee is stored into the lvalue with primitive semantics; and finally, the old pointee is released. This is not performed atomically; external synchronization must be used to make this safe in the face of concurrent loads and stores.
  • For __weak objects, the lvalue is updated to point to the new pointee, unless the new pointee is an object currently undergoing deallocation, in which case the lvalue is updated to a null pointer. This must execute atomically with respect to other assignments to the object, to reads from the object, and to the final release of the new pointee.
  • For __*unsafe_unretained* objects, the new pointee is stored into the lvalue using primitive semantics.
  • For __autoreleasing objects, the new pointee is retained, autoreleased, and stored into the lvalue using primitive semantics.

The other difference in Reading, Init, Destruction and Moving, please refer to Section 4.2 Semantics in the document.

string sanitizer for filename

What about using rawurlencode() ?

Here is a function that sanitize even Chinese Chars:

public static function normalizeString ($str = '')
    $str = strip_tags($str); 
    $str = preg_replace('/[\r\n\t ]+/', ' ', $str);
    $str = preg_replace('/[\"\*\/\:\<\>\?\'\|]+/', ' ', $str);
    $str = strtolower($str);
    $str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );
    $str = htmlentities($str, ENT_QUOTES, "utf-8");
    $str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
    $str = str_replace(' ', '-', $str);
    $str = rawurlencode($str);
    $str = str_replace('%', '-', $str);
    return $str;

Here is the explaination

  1. Strip HTML Tags
  2. Remove Break/Tabs/Return Carriage
  3. Remove Illegal Chars for folder and filename
  4. Put the string in lower case
  5. Remove foreign accents such as Éàû by convert it into html entities and then remove the code and keep the letter.
  6. Replace Spaces with dashes
  7. Encode special chars that could pass the previous steps and enter in conflict filename on server. ex. "?????"
  8. Replace "%" with dashes to make sure the link of the file will not be rewritten by the browser when querying th file.

OK, some filename will not be releavant but in most case it will work.

ex. Original Name: "???????-??-????????????.jpg"

Output Name: "-E1-83-A1-E1-83-90-E1-83-91-E1-83-94-E1-83-AD-E1-83-93-E1-83-98--E1-83-93-E1-83-90--E1-83-A2-E1-83-98-E1-83-9E-E1-83-9D-E1-83-92-E1-83-A0-E1-83-90-E1-83-A4-E1-83-98-E1-83-A3-E1-83-9A-E1-83-98.jpg"

It's better like that than an 404 error.

Hope that was helpful.


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

XmlSerializer sr = new XmlSerializer(objectToSerialize.GetType());
TextWriter xmlWriter = new StreamWriter(filename);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
sr.Serialize(xmlWriter, objectToSerialize, namespaces);

Psql could not connect to server: No such file or directory, 5432 error?

FATAL:  could not load server certificate file "/etc/ssl/certs/ssl-cert-snakeoil.pem": No such file or directory
LOG:  database system is shut down
pg_ctl: could not start server

I have a missing ssl-cert-snakeoil.pem file so i created it using make-ssl-cert generate-default-snakeoil --force-overwrite And it worked fine.

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Typical Java programs compile into .jar files, which can be executed like .exe files provided the target machine has Java installed and that Java is in its PATH. From Eclipse you use the Export menu item from the File menu.

Project vs Repository in GitHub

GitHub recently introduced a new feature called Projects. This provides a visual board that is typical of many Project Management tools:


A Repository as documented on GitHub:

A repository is the most basic element of GitHub. They're easiest to imagine as a project's folder. A repository contains all of the project files (including documentation), and stores each file's revision history. Repositories can have multiple collaborators and can be either public or private.

A Project as documented on GitHub:

Project boards on GitHub help you organize and prioritize your work. You can create project boards for specific feature work, comprehensive roadmaps, or even release checklists. With project boards, you have the flexibility to create customized workflows that suit your needs.

Part of the confusion is that the new feature, Projects, conflicts with the overloaded usage of the term project in the documentation above.

How do I import the javax.servlet API in my Eclipse project?

Little bit difference from Hari:

Right click on project ---> Properties ---> Java Build Path ---> Add Library... ---> Server Runtime ---> Apache Tomcat ----> Finish.

Split a String into an array in Swift?

Swift 4 makes it much easier to split characters, just use the new split function for Strings.

Example: let s = "hi, hello" let a = s.split(separator: ",") print(a)

Now you got an array with 'hi' and ' hello'.

How do I center an SVG in a div?

You can also do this:

<div style="width: 40px; height: 40px;">
    <svg class="sqs-svg-icon--social" viewBox="0 0 64 64">
        <use class="sqs-use--icon" xmlns:xlink="" xlink:href="#twitter-icon">
            <svg id="twitter-icon" viewBox="0 0 64 64" width="100%" height="100%">
                    d="M48,22.1c-1.2,0.5-2.4,0.9-3.8,1c1.4-0.8,2.4-2.1,2.9-3.6c-1.3,0.8-2.7,1.3-4.2,1.6 C41.7,19.8,40,19,38.2,19c-3.6,0-6.6,2.9-6.6,6.6c0,0.5,0.1,1,0.2,1.5c-5.5-0.3-10.3-2.9-13.5-6.9c-0.6,1-0.9,2.1-0.9,3.3 c0,2.3,1.2,4.3,2.9,5.5c-1.1,0-2.1-0.3-3-0.8c0,0,0,0.1,0,0.1c0,3.2,2.3,5.8,5.3,6.4c-0.6,0.1-1.1,0.2-1.7,0.2c-0.4,0-0.8,0-1.2-0.1 c0.8,2.6,3.3,4.5,6.1,4.6c-2.2,1.8-5.1,2.8-8.2,2.8c-0.5,0-1.1,0-1.6-0.1c2.9,1.9,6.4,2.9,10.1,2.9c12.1,0,18.7-10,18.7-18.7 c0-0.3,0-0.6,0-0.8C46,24.5,47.1,23.4,48,22.1z"

Visual Studio Code always asking for git credentials

Use an SSH key without a passphrase.

Maybe this is obvious to some (wasn't to me). It also doesn't solve the issue if you absolutely require a passphrase, but this was a decent compromise in my situation on Mac.

How to make PyCharm always show line numbers

Version 2.6 and above:
PyCharm (far left menu) -> Preferences... -> Editor (bottom left section) -> General -> Appearance -> Show line numbers checkbox

enter image description here

Version 2.5 and below:
Settings -> Editor -> General -> Appearance -> Show line numbers checkbox

How to generate random number in Bash?

I wrote several articles on this.

$ RANDOM=$(date +%s%N | cut -b10-19)
$ echo $(( $RANDOM % 113 + 13 ))

The above will give a number between 13 and 113, with reasonable random entropy.

How to download image from url

For anyone who wants to download an image WITHOUT saving it to a file:

Image DownloadImage(string fromUrl)
    using (System.Net.WebClient webClient = new System.Net.WebClient())
        using (Stream stream = webClient.OpenRead(fromUrl))
            return Image.FromStream(stream);

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {

create a white rgba / CSS3

The code you have is a white with low opacity.

If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.

Here is a simple demo.

If you want it to look 'more white', make it less opaque:

background:rgba(255,255,255, 0.9);


How to link a folder with an existing Heroku app

heroku login 

git init

heroku git:remote -a app-name123

then check the remote repo :

git remote -v

Moment JS start and end of given month

When you use .endOf() you are mutating the object it's called on, so startDate becomes Sep 30

You should use .clone() to make a copy of it instead of changing it

var startDate = moment(year + '-' + month + '-' + 01 + ' 00:00:00');
            var endDate = startDate.clone().endOf('month');

Mon Sep 01 2014 00:00:00 GMT+0700 (ICT) 
Tue Sep 30 2014 23:59:59 GMT+0700 (ICT) 

Way to insert text having ' (apostrophe) into a SQL table

$value = "he doesn't work for me";

$new_value = str_replace("'", "''", "$value"); // it looks like  " ' "  , " ' ' " 

INSERT INTO exampleTbl (`column`) VALUES('$new_value')

ReferenceError: fetch is not defined

It seems fetch support URL scheme with "http" or "https" for CORS request.

Install node fetch library npm install node-fetch, read the file and parse to json.

const fs = require('fs')
const readJson = filename => {
  return new Promise((resolve, reject) => {
    if (filename.toLowerCase().endsWith(".json")) {
      fs.readFile(filename, (err, data) => {
        if (err) {
    else {
      reject(new Error("Invalid filetype, <*.json> required."))

// usage
const filename = "../data.json"
readJson(filename).then(data => console.log(data)).catch(err => console.log(err.message))

Checking password match while typing

The problem in this case is that onchange-event does not fire until the input looses focus, so you will probably want to listen for the keyup-event instead, which is fired on every keystroke.

Also, I would prefer not using inline-javascript, but rather catch the event using jQuery instead.


How to get a list column names and datatypes of a table in PostgreSQL?

Below will list all the distinct data types of all the table in the provided schema name.

\copy (select distinct data_type, column_name from information_schema.columns where table_name in (SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema' and schemaname = '<Your schema name>')) to 'datatypes.csv'  delimiter as ',' CSV header

How to Split Image Into Multiple Pieces in Python

I tried the solutions above, but sometimes you just gotta do it yourself. Might be off by a pixel in some cases but works fine in general.

import matplotlib.pyplot as plt
import numpy as np
def image_to_tiles(im, number_of_tiles = 4, plot=False):
    Function that splits SINGLE channel images into tiles
    :param im: image: single channel image (NxN matrix)
    :param number_of_tiles: squared number
    :param plot:
    :return tiles:
    n_slices = np.sqrt(number_of_tiles)
    assert int(n_slices + 0.5) ** 2 == number_of_tiles, "Number of tiles is not a perfect square"

    n_slices = n_slices.astype(
    [w, h] = cropped_npy.shape

    r = np.linspace(0, w, n_slices+1)
    r_tuples = [([i]),[i+1])) for i in range(0, len(r)-1)]
    q = np.linspace(0, h, n_slices+1)
    q_tuples = [([i]),[i+1])) for i in range(0, len(q)-1)]

    tiles = []
    for row in range(n_slices):
        for column in range(n_slices):
            [x1, y1, x2, y2] = *r_tuples[row], *q_tuples[column] 
            tiles.append(im[x1:y1, x2:y2])

    if plot:
        fig, axes = plt.subplots(n_slices, n_slices, figsize=(10,10))
        c = 0
        for row in range(n_slices):
            for column in range(n_slices):

    return tiles

Hope it helps.

Using sessions & session variables in a PHP Login Script

Hope this helps :)

begins the session, you need to say this at the top of a page or before you call session code


put a user id in the session to track who is logged in

 $_SESSION['user'] = $user_id;

Check if someone is logged in

 if (isset($_SESSION['user'])) {
   // logged in
 } else {
   // not logged in

Find the logged in user ID


So on your page


 if (isset($_SESSION['user'])) {
   logged in HTML and code here

 } else {
   Not logged in HTML and code here

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;;
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());"File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        System.out.println("sftp Channel exited.");
        System.out.println("Channel disconnected.");
        System.out.println("Host Session disconnected.");

Install IPA with iTunes 12

Since iTunes 12.7 doesn't have "Application" section so it can't be done. As a workaround I've found this answer.

I simply installed "Apple Configurator 2". Than:

  1. Run application
  2. Connect device
  3. Unlock device
  4. Drag IPA file to visualisation of device in "Apple Configurator 2"
  5. Confirm action

I didn't had to "sign in" as described in on linked question answers

How to keep environment variables when using sudo

A simple wrapper function (or in-line for loop)

I came up with a unique solution because:

  • sudo -E "$@" was leaking variables that was causing problems for my command
  • sudo VAR1="$VAR1" ... VAR42="$VAR42" "$@" was long and ugly in my case


function sudo_exports(){
    eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) "$@"

# create a test script to call as sudo
echo 'echo Forty-Two is $VAR42' >
chmod +x

export VAR42="The Answer to the Ultimate Question of Life, The Universe, and Everything."


# clean function style
sudo_exports ./

# or just use the content of the function
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) ./


$ ./
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.


This is made possible by a feature of the bash builtin printf. The %q produces a shell quoted string. Unlike the parameter expansion in bash 4.4, this works in bash versions < 4.0

Run certain code every n seconds

Save yourself a schizophrenic episode and use the Advanced Python scheduler:

The code is so simple:

from apscheduler.scheduler import Scheduler

sched = Scheduler()

def some_job():
    print "Every 10 seconds"

sched.add_interval_job(some_job, seconds = 10)


AngularJS open modal on button click

Hope this will help you .

Here is Html code:-

    <div ng-controller="MyController" class="container">
      <h1>Modal example</h1>
      <button ng-click="open()" class="btn btn-primary">Test Modal</button>

      <modal title="Login form" visible="showModal">
        <form role="form">


AngularJs code:-

var mymodal = angular.module('mymodal', []);

mymodal.controller('MyController', function ($scope) {
    $scope.showModal = false;
    $ = function(){
    $scope.showModal = !$scope.showModal;

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ title }}</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
      restrict: 'E',
      transclude: true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)

        $(element).on('', function(){
            scope.$parent[attrs.visible] = true;

        $(element).on('', function(){
            scope.$parent[attrs.visible] = false;

Check this--jsfiddle

How to calculate combination and permutation in R?

It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.

Emulator error: This AVD's configuration is missing a kernel file

A singular intelligent thought occurred to me after a long day of repair/rebuild/upgrades of the SDK/NDK & JDK. The environment vars need examined, as the fix for my AVD 'GalaxyS3' missing kernel file was to expand the system-images reference to absolute.


Adding the "C:....sdk\" to the 'image.sysdir.1=' entry in the 'workspace'.android\avd\GalaxyS3.avd\config.ini file solved the problem (for now).

Difference between const reference and normal parameter

The first method passes n by value, i.e. a copy of n is sent to the function. The second one passes n by reference which basically means that a pointer to the n with which the function is called is sent to the function.

For integral types like int it doesn't make much sense to pass as a const reference since the size of the reference is usually the same as the size of the reference (the pointer). In the cases where making a copy is expensive it's usually best to pass by const reference.

Why are Python's 'private' methods not actually private?

When I first came from Java to Python I hated this. It scared me to death.

Today it might just be the one thing I love most about Python.

I love being on a platform, where people trust each other and don't feel like they need to build impenetrable walls around their code. In strongly encapsulated languages, if an API has a bug, and you have figured out what goes wrong, you may still be unable to work around it because the needed method is private. In Python the attitude is: "sure". If you think you understand the situation, perhaps you have even read it, then all we can say is "good luck!".

Remember, encapsulation is not even weakly related to "security", or keeping the kids off the lawn. It is just another pattern that should be used to make a code base easier to understand.

How to merge many PDF files into a single one?

You can also use Ghostscript to merge different PDFs. You can even use it to merge a mix of PDFs, PostScript (PS) and EPS into one single output PDF file:

gs \
  -o merged.pdf \
  -sDEVICE=pdfwrite \
  -dPDFSETTINGS=/prepress \
   input_1.pdf \
   input_2.pdf \
   input_3.eps \ \

However, I agree with other answers: for your use case of merging PDF file types only, pdftk may be the best (and certainly fastest) option.

If processing time is not the main concern, but if the main concern is file size (or a fine-grained control over certain features of the output file), then the Ghostscript way certainly offers more power to you. To highlight a few of the differences:

  • Ghostscript can 'consolidate' the fonts of the input files which leads to a smaller file size of the output. It also can re-sample images, or scale all pages to a different size, or achieve a controlled color conversion from RGB to CMYK (or vice versa) should you need this (but that will require more CLI options than outlined in above command).
  • pdftk will just concatenate each file, and will not convert any colors. If each of your 16 input PDFs contains 5 subsetted fonts, the resulting output will contain 80 subsetted fonts. The resulting PDF's size is (nearly exactly) the sum of the input file bytes.

Multiprocessing a for loop?

You can use multiprocessing.Pool:

from multiprocessing import Pool
class Engine(object):
    def __init__(self, parameters):
        self.parameters = parameters
    def __call__(self, filename):
        sci = + '.fits')
        manipulated = manipulate_image(sci, self.parameters)
        return manipulated

    pool = Pool(8) # on 8 processors
    engine = Engine(my_parameters)
    data_outputs =, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen

Interfaces — What's the point?

Therese are ask really great examples.

Another, in the case of a switch statement, you no longer have the need to maintain and switch every time you want rio perform a task in a specific way.

In your pizza example, if want to make a pizza, the interface is all you need, from there each pizza takes care of it's own logic.

This helps to reduce coupling and cyclomatic complexity. You have to still implement the logic but there will be less you have to keep track of in the broader picture.

For each pizza you can then keep track of information specific to that pizza. What other pizzas have doesn't matter because only the other pizzas need to know.

Find a string between 2 known values

string input = "Exemple of value between two string FirstString text I want to keep SecondString end of my string";
var match = Regex.Match(input, @"FirstString (.+?) SecondString ").Groups[1].Value;

How to reset selected file with input tag file type in Angular 2?

In my case I did it as below:

 <input #fileInput hidden (change)="uploadFile($" type="file" />
 <button mat-button color="warn" (click)="fileInput.value='';"> Upload File</button>

I am resetting it using #fileInput in HTML rather than creating a ViewChild in component.ts . Whenever the "Upload File" button is being clicked, first it resets the #fileInput and then triggers function. If any separate button needed to reset then on click #fileInput.value='' can be executed.

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

A typical situation where you cannot use [[ is in an autotools script, there brackets has a special and different meaning, so you will have to use test instead of [ or [[ -- Note that test and [ are the same program.

How to remove backslash on json_encode() function?

You do not want to delete it. Because JSON uses double quotes " " for strings, and your one returns

This is a test!<\/p>\")"

these backslashes escape these quotes

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

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

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

See here for more information:

Custom Date and Time Format Strings

What is the difference between Scrum and Agile Development?

At an outset what I can say is - Agile is an evolutionary methodology from Unified Process which focuses on Iterative & Incremental Development (IID). IID emphasizes iterative development more on construction phases (actual coding) and incremental deliveries. It wouldn't emphasize more on Requirements Analysis (Inception) and Design (Elaboration) being handled in the iterations itself. So, Iteration here is not a "mini project by itself".

In Agile, we take this IDD a bit further, adding more realities like Team Collaboration, Evolutionary Requirements and Design etc. And SCRUM is the tool to enable it by considering the human factors and building around 'Wisdom of the Group' principle. So, Sprint here is a "mini project by itself" bettering a pure IID model.

So, iterations implemented in Agile way are, yes, theoretically Sprints (highlighting the size of the iterations being small and deliveries being quick). I don't really differentiate between Agile and SCRUM and I see that SCRUM is a natural way of putting the Agile principles into use.

TypeError: Router.use() requires middleware function but got a Object

check your routes.js file

example my routes.js

    const express = require('express')_x000D_
    const router = express.Router()_x000D_
    const usersController = require('../app/controllers/usersController')_x000D_
    const autheticateuser = require('../app/middlewares/authentication')_x000D_
    _x000D_'/users/login', autheticateuser, usersController.login)_x000D_'/users/register', autheticateuser, usersController.register)_x000D_

check end of routes.js

module.exports = router

if not there add and module.exports = router run again

If your Error is : "TypeError: or Route.get() requires middleware function but got a Object"

goto controller.js (i.e., usersController) and check all the function names you might misspelled , or you given in function routes file but missed in contollers

const User = require('../models/user')_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
module.exports.register = (req, res) => {_x000D_
    const data = req.body_x000D_
    const user = new User(data)_x000D_
        .then((user) => {_x000D_
        .catch((err) => {_x000D_

in routes.js i given two routes but in controllers i missed to define route for'/users/login')

this will make error **

"TypeError: requires middleware function but got a Object"


How to simplify a null-safe compareTo() implementation?

For the specific case where you know the data will not have nulls (always a good idea for strings) and the data is really large, you are still doing three comparisons before actually comparing the values, if you know for sure this is your case, you can optimize a tad bit. YMMV as readable code trumps minor optimization:

        if( != null && != null){
        // at least one is null
        return ( == ? 0 : ( != null ? 1 : -1);

HTTP status code for update and delete?

For a PUT request: HTTP 200 or HTTP 204 should imply "resource updated successfully".

For a DELETE request: HTTP 200 or HTTP 204 should imply "resource deleted successfully". HTTP 202 can also be returned which would imply that the instruction was accepted by the server and the "resource was marked for deletion".


If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.


A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

Source: HTTP/1.1 Method Definitions

HTTP 200 OK: Standard response for successful HTTP requests. The actual response will depend on the request method used.

HTTP 204 No Content: The server successfully processed the request, but is not returning any content

Source: List of HTTP status codes: 2xx Success

Mercurial undo last commit

Its workaround.

If you not push to server, you will clone into new folder else washout(delete all files) from your repository folder and clone new.

How to differ sessions in browser-tabs?

You have to realize that server-side sessions are an artificial add-on to HTTP. Since HTTP is stateless, the server needs to somehow recognize that a request belongs to a particular user it knows and has a session for. There are 2 ways to do this:

  • Cookies. The cleaner and more popular method, but it means that all browser tabs and windows by one user share the session - IMO this is in fact desirable, and I would be very annoyed at a site that made me login for each new tab, since I use tabs very intensively
  • URL rewriting. Any URL on the site has a session ID appended to it. This is more work (you have to do something everywhere you have a site-internal link), but makes it possible to have separate sessions in different tabs, though tabs opened through link will still share the session. It also means the user always has to log in when he comes to your site.

What are you trying to do anyway? Why would you want tabs to have separate sessions? Maybe there's a way to achieve your goal without using sessions at all?

Edit: For testing, other solutions can be found (such as running several browser instances on separate VMs). If one user needs to act in different roles at the same time, then the "role" concept should be handled in the app so that one login can have several roles. You'll have to decide whether this, using URL rewriting, or just living with the current situation is more acceptable, because it's simply not possible to handle browser tabs separately with cookie-based sessions.

How to get a subset of a javascript object's properties

  1. convert arguments to array

  2. use Array.forEach() to pick the property

    Object.prototype.pick = function(...args) {
       var obj = {};
       args.forEach(k => obj[k] = this[k])
       return obj
    var a = {0:"a",1:"b",2:"c"}
    var b = a.pick('1','2')  //output will be {1: "b", 2: "c"}

How do I query between two dates using MySQL?

Just Cast date_field as date

SELECT * FROM `objects` 
WHERE (cast(date_field as date) BETWEEN '2010-09-29' AND 
'2010-01-30' )

When restoring a backup, how do I disconnect all active connections?

This code worked for me, it kills all existing connections of a database. All you have to do is change the line Set @dbname = 'databaseName' so it has your database name.

Use Master

Declare @dbname sysname

Set @dbname = 'databaseName'

Declare @spid int
Select @spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(@dbname)
While @spid Is Not Null
        Execute ('Kill ' + @spid)
        Select @spid = min(spid) from master.dbo.sysprocesses
        where dbid = db_id(@dbname) and spid > @spid

after this I was able to restore it

How do you transfer or export SQL Server 2005 data to Excel

you can right click on a grid of results in SQL server, and choose save as CSV. you can then you can import this into Excel.

Excel gives you a import wizard, ensure you select comma delimited. it works fine for me when i needed to import 50k+ records into excel.

jQuery, get ID of each element in a class using .each?

patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){

Spaces in URLs?

A URL must not contain a literal space. It must either be encoded using the percent-encoding or a different encoding that uses URL-safe characters (like application/x-www-form-urlencoded that uses + instead of %20 for spaces).

But whether the statement is right or wrong depends on the interpretation: Syntactically, a URI must not contain a literal space and it must be encoded; semantically, a %20 is not a space (obviously) but it represents a space.

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

    background:url(./images/but.png) no-repeat;

.myButton:active  /* use Dot here */
    background:url(./images/but2.png) no-repeat;

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

I got the error as, "svn: Commit blocked by pre-commit hook (exit code 1) with output: Failed with exception: Lost connection to MySQL server at 'reading initial communication packet', system error: 104."

I tried 'svn commit' after 'svn cleanup'. And It works fine!.

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts, for the reasons explained in mark4o's answer.

Python: How exactly can you take a string, split it, reverse it and join it back together again?

You mean this?

from string import punctuation, digits

takeout = punctuation + digits

turnthis = "(fjskl) 234 = -345 089 abcdef"
turnthis = turnthis.translate(None, takeout)[::-1]
print turnthis

Windows Forms ProgressBar: Easiest way to start/stop marquee?

Use a progress bar with the style set to Marquee. This represents an indeterminate progress bar.

myProgressBar.Style = ProgressBarStyle.Marquee;

You can also use the MarqueeAnimationSpeed property to set how long it will take the little block of color to animate across your progress bar.

What is the JSF resource library for and how should it be used?

Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.

Real world examples

To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency or UIViewRoot#addComponentResource()) the following way:

<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />

It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.

Easier identifying

This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.

Also, when you're using a custom ResourceHandler, you can also apply more finer grained control over resources coming from a specific library when library is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler and GraphicResourceHandler; check the createResource() method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource or GraphicResource for the purpose.

Noted should be that RichFaces did it wrong. It didn't use any library at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.

Your own webapp

Your own webapp does not necessarily need a resource library. You'd best just omit it.

<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />

Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml template file:

<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />

And a /WEB-INF/templates/admin.xhtml template file:

<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />

For a real world example, check the OmniFaces showcase source code.

Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):

<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />

Library versioning

Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)* pattern to denote the resource library version.

 |-- resources
 |    `-- default
 |         `-- 1_0
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js

When using this markup:

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

This will generate the following HTML with the library version as v parameter:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_0" alt="" />

So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler will automatically serve the resource from the highest version number, according to numerical ordering rules.

So, when copying/renaming resources/default/1_0/* folder into resources/default/1_1/* like follows:

 |-- resources
 |    `-- default
 |         |-- 1_0
 |         |    :
 |         |
 |         `-- 1_1
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js

Then the last markup example would generate the following HTML:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_1" alt="" />

This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.

Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler. See also How to use JSF versioning for resources in jar.

See also:

Div side by side without float

The usual method when not using floats is to use display: inline-block:

.container div {
  display: inline-block;

Do note its limitations though: There is a additional space after the first bloc - this is because the two blocks are now essentially inline elements, like a and em, so whitespace between the two counts. This could break your layout and/or not look nice, and I'd prefer not to strip out all whitespaces between characters for the sake of this working.

Floats are also more flexible, in most cases.

TypeError: a bytes-like object is required, not 'str' in python and CSV

You are using Python 2 methodology instead of Python 3.





and you will get a file with the following output:

1,Andhra Pradesh,13,49378776
2,Arunachal Pradesh,16,1382611

In Python 3 csv takes the input in text mode, whereas in Python 2 it took it in binary mode.

Edited to Add

Here is the code I ran:

html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
table=soup.find('table', attrs={'class':'tableizer-table'})
for row in table.findAll('tr')[1:]:
    for cell in row.findAll('td'):
outfile = open('./immates.csv','w')
writer.writerow(['SNo', 'States', 'Dist', 'Population'])

Hide header in stack navigator React navigation

UPDATE as of version 5

As of version 5 it is the option headerShown in screenOptions

Example of usage:

    headerShown: false
  <Stack.Screen name="route-name" component={ScreenComponent} />

If you want only to hide the header on 1 screen you can do this by setting the screenOptions on the screen component see below for example:

<Stack.Screen options={{headerShown: false}} name="route-name" component={ScreenComponent} />

See also the blog about version 5

As of version 2.0.0-alpha.36 (2019-11-07),
there is a new navigationOption: headershown

      navigationOptions: {
        headerShown: false,

Old answer

I use this to hide the stack bar (notice this is the value of the second param):

    headerMode: 'none',
    navigationOptions: {
        headerVisible: false,

When you use the this method it will be hidden on all screens.

In your case it will look like this:

const MainNavigation = StackNavigator({
  otp: { screen: OTPlogin },
  otpverify: { screen: OTPverification },
  userVerified: {
    screen: TabNavigator({
    List: { screen: List },
    Settings: { screen: Settings }
  headerMode: 'none',
  navigationOptions: {
    headerVisible: false,

Bootstrap 3 Glyphicons CDN

An alternative would be to use Font-Awesome for icons:

Including Font-Awesome

Open Font-Awesome on CDNJS and copy the CSS url of the latest version:

<link rel="stylesheet" href="<url>">

Or in CSS

@import url("<url>");

For example (note, the version will change):

<link rel="stylesheet" href="">


<i class="fa fa-bed"></i>

It contains a lot of icons!

Maven dependency update on commandline

mvn -Dschemaname=public liquibase:update

How to set UICollectionViewCell Width and Height programmatically

Try below method

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: 100.0, height: 100.0)

The process cannot access the file because it is being used by another process (File is created but contains nothing)

File.AppendAllText does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText will fail, throwing the exception you see.

I suggest you used str.Write or str.WriteLine instead, as you already do elsewhere in your code.

Your file is created but contains nothing because the exception is thrown before str.Flush() and str.Close() are called.

How to replace DOM element in place using Javascript?

You can replace an HTML Element or Node using Node.replaceWith(newNode).

This example should keep all attributes and childs from origin node:

const links = document.querySelectorAll('a')

links.forEach(link => {
  const replacement = document.createElement('span')
  // copy attributes
  for (let i = 0; i < link.attributes.length; i++) {
     const attr = link.attributes[i]
     replacement.setAttribute(, attr.value)
  // copy content
  replacement.innerHTML = link.innerHTML
  // or you can use appendChild instead
  // link.childNodes.forEach(node => replacement.appendChild(node))


If you have these elements:

<a href="#link-1">Link 1</a>
<a href="#link-2">Link 2</a>
<a href="#link-3">Link 3</a>
<a href="#link-4">Link 4</a>

After running above codes, you will end up with these elements:

<span href="#link-1">Link 1</span>
<span href="#link-2">Link 2</span>
<span href="#link-3">Link 3</span>
<span href="#link-4">Link 4</span>

Two-dimensional array in Swift

Before using multidimensional arrays in Swift, consider their impact on performance. In my tests, the flattened array performed almost 2x better than the 2D version:

var table = [Int](repeating: 0, count: size * size)
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        let val = array[row] * array[column]
        // assign
        table[row * size + column] = val

Average execution time for filling up a 50x50 Array: 82.9ms


var table = [[Int]](repeating: [Int](repeating: 0, count: size), count: size)
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        // assign
        table[row][column] = val

Average execution time for filling up a 50x50 2D Array: 135ms

Both algorithms are O(n^2), so the difference in execution times is caused by the way we initialize the table.

Finally, the worst you can do is using append() to add new elements. That proved to be the slowest in my tests:

var table = [Int]()    
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {

Average execution time for filling up a 50x50 Array using append(): 2.59s


Avoid multidimensional arrays and use access by index if execution speed matters. 1D arrays are more performant, but your code might be a bit harder to understand.

You can run the performance tests yourself after downloading the demo project from my GitHub repo:

How can I schedule a daily backup with SQL Server Express?

Just use this script to dynamically backup all databases on the server. Then create batch file according to the article. It is usefull to create two batch files, one for full backup a and one for diff backup. Then Create two tasks in Task Scheduler, one for full and one for diff.

-- // Copyright © Microsoft Corporation.  All Rights Reserved.
-- // This code released under the terms of the
-- // Microsoft Public License (MS-PL,
USE [master] 
/****** Object:  StoredProcedure [dbo].[sp_BackupDatabases] ******/ 

-- ============================================= 
-- Author: Microsoft 
-- Create date: 2010-02-06
-- Description: Backup Databases for SQLExpress
-- Parameter1: databaseName 
-- Parameter2: backupType F=full, D=differential, L=log
-- Parameter3: backup file location
-- =============================================

CREATE PROCEDURE [dbo].[sp_BackupDatabases]  
            @databaseName sysname = null,
            @backupType CHAR(1),
            @backupLocation nvarchar(200) 


            DECLARE @DBs TABLE
                  ID int IDENTITY PRIMARY KEY,
                  DBNAME nvarchar(500)

             -- Pick out only databases which are online in case ALL databases are chosen to be backed up
             -- If specific database is chosen to be backed up only pick that out from @DBs
            INSERT INTO @DBs (DBNAME)
            SELECT Name FROM master.sys.databases
            where state=0
            AND name=@DatabaseName
            OR @DatabaseName IS NULL
            ORDER BY Name

            -- Filter out databases which do not need to backed up
            IF @backupType='F'
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
            ELSE IF @backupType='D'
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
            ELSE IF @backupType='L'
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')

            -- Declare variables
            DECLARE @BackupName varchar(100)
            DECLARE @BackupFile varchar(100)
            DECLARE @DBNAME varchar(300)
            DECLARE @sqlCommand NVARCHAR(1000) 
        DECLARE @dateTime NVARCHAR(20)
            DECLARE @Loop int                  

            -- Loop through the databases one by one
            SELECT @Loop = min(ID) FROM @DBs


-- Database Names have to be in [dbname] format since some have - or _ in their name
      SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'

-- Set the current date and time n yyyyhhmmss format
      SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' +  REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')  

-- Create backup filename in path\filename.extension format for full,diff and log backups
      IF @backupType = 'F'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
      ELSE IF @backupType = 'D'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
      ELSE IF @backupType = 'L'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'

-- Provide the backup a name for storing in the media
      IF @backupType = 'F'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
      IF @backupType = 'D'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime
      IF @backupType = 'L'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime

-- Generate the dynamic SQL command to be executed

       IF @backupType = 'F' 
               SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
       IF @backupType = 'D'
               SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'        
       IF @backupType = 'L' 
               SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'        

-- Execute the generated SQL command

-- Goto the next database
SELECT @Loop = min(ID) FROM @DBs where ID>@Loop


And batch file can look like this:

sqlcmd -S localhost\myDB -Q "EXEC sp_BackupDatabases @backupLocation='c:\Dropbox\backup\DB\', @backupType='F'"  >> c:\Dropbox\backup\DB\full.log 2>&1


sqlcmd -S localhost\myDB -Q "EXEC sp_BackupDatabases @backupLocation='c:\Dropbox\backup\DB\', @backupType='D'"  >> c:\Dropbox\backup\DB\diff.log 2>&1

The advantage of this method is that you don't need to change anything if you add new database or delete a database, you don't even need to list the databases in the script. Answer from JohnB is better/simpler for server with one database, this approach is more suitable for multi database servers.

Setting Java heap space under Maven 2 on Windows

The environment variable to set is MAVEN_OPTS, for example MAVEN_OPTS=-Xmx1024m. The maxmem configuration in the pom only applies when you set the compiler plugin to fork javac into a new JVM. Otherwise the plugin runs inside the same VM as Maven and thus within the memory passed on the command line via the MAVEN_OPTS.

To set MAVEN_OPTS under Windows 7:

  1. Right click on My Computer and select Properties (keyboard shortcut press Windows + Pause/Break)
  2. Click the Advanced System Settings link located in the left navigation of System Properties to display the Advanced System Properties
  3. Go to the Advanced tab and click the Environment Variables button located at the bottom of the Advanced System Properties configuration window
  4. Create a New user variable, set the Variable name to MAVEN_OPTS and set the Variable value to -Xmx1024m (or more)

Open a new command window and run mvn.

Delete all rows in an HTML table

the give below code works great. It removes all rows except header row. So this code really t

$("#Your_Table tr>td").remove();

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

Basically if you follow the issues in this link for 0.2 you'll likely get yourself fixed, I had the same problems with 0.2

Try catch statements in C

You use goto in C for similar error handling situations.
That is the closest equivalent of exceptions you can get in C.

Convert floating point number to a certain precision, and then copy to string

It's not print that does the formatting, It's a property of strings, so you can just use

newstring = "%.9f" % numvar

Can I pass an array as arguments to a method with variable arguments in Java?

It's ok to pass an array - in fact it amounts to the same thing

String.format("%s %s", "hello", "world!");

is the same as

String.format("%s %s", new Object[] { "hello", "world!"});

It's just syntactic sugar - the compiler converts the first one into the second, since the underlying method is expecting an array for the vararg parameter.


What's the difference between "Layers" and "Tiers"?

Layers are conceptual entities, and are used to separate the functionality of software system from a logical point of view; when you implement the system you organize these layers using different methods; in this condition we refer to them not as layers but as tiers.

Regex pattern inside SQL Replace function?

I think a simpler and faster approach is iterate by each character of the alphabet:

DECLARE @i int
SET @i = 0

WHILE(@i < 256)

    IF char(@i) NOT IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.')      

      UPDATE Table SET Column = replace(Column, char(@i), '')

    SET @i = @i + 1


Difference between Console.Read() and Console.ReadLine()?

Console.Read() reads a single key, where Console.Readline() waits for the Enter key.

Get week day name from a given month, day and year individually in SQL Server

I used

when (extract (weekday from DATE)=0) then 'Sunday'

and so on...

0 Sunday, 1 Monday...

How to test if a double is zero?

Numeric primitives in class scope are initialized to zero when not explicitly initialized.

Numeric primitives in local scope (variables in methods) must be explicitly initialized.

If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.

if(value != 0)
    //divide by value is safe when value is not exactly zero.

Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0.

public boolean isZero(double value, double threshold){
    return value >= -threshold && value <= threshold;

Is a URL allowed to contain a space?

Shorter answer: no, you must encode a space; it is correct to encode a space as +, but only in the query string; in the path you must use %20.

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx


  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName



You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

SVN remains in conflict?

One more solution below,

If the entire folder is removed and SVNis throwing the error "admin file .svn is missing", the following will be used to resolve the conflict to working state.

svn resolve --accept working "file / directory name "

Replace text inside td using jQuery having td containing other elements

Remove the textnode, and replace the <b> tag with whatever you need without ever touching the inputs :

$('#demoTable').find('tr > td').contents().filter(function() {
    return this.nodeType===3;
  .find('b').replaceWith($('<span />', {text: 'Hello Kitty'}));


Using an if statement to check if a div is empty

If you want a quick demo how you check for empty divs I'd suggest you to try this link:

Below you have some short examples:

Using CSS

If your div is empty without anything even no white-space, you can use CSS:

.someDiv:empty {
    display: none;

Unfortunately there is no CSS selector that selects the previous sibling element. There is only for the next sibling element: x ~ y

.someDiv:empty ~ .anotherDiv {
    display: none;

Using jQuery

Checking text length of element with text() function

if ( $('#leftmenu').text().length == 0 ) {
    // length of text is 0

Check if element has any children tags inside

if ( $('#leftmenu').children().length == 0 ) {
    // div has no other tags inside it

Check for empty elements if they have white-space

if ( $.trim( $('.someDiv').text() ).length == 0 ) {
    // white-space trimmed, div is empty

Node.js - get raw request body using Express

BE CAREFUL with those other answers as they will not play properly with bodyParser if you're looking to also support json, urlencoded, etc. To get it to work with bodyParser you should condition your handler to only register on the Content-Type header(s) you care about, just like bodyParser itself does.

To get the raw body content of a request with Content-Type: "text/plain" into req.rawBody you can do:

app.use(function(req, res, next) {
  var contentType = req.headers['content-type'] || ''
    , mime = contentType.split(';')[0];

  if (mime != 'text/plain') {
    return next();

  var data = '';
  req.on('data', function(chunk) {
    data += chunk;
  req.on('end', function() {
    req.rawBody = data;

How to save and extract session data in codeigniter

In codeigniter we are able to store session values in a database. In the config.php file make the sess_use_database variable true

$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';

and create a ci_session table in the database

    session_id varchar(40) DEFAULT '0' NOT NULL,
    ip_address varchar(45) DEFAULT '0' NOT NULL,
    user_agent varchar(120) NOT NULL,
    last_activity int(10) unsigned DEFAULT 0 NOT NULL,
    user_data text NOT NULL,
    PRIMARY KEY (session_id),
    KEY `last_activity_idx` (`last_activity`)

For more details and reference, click here

Can I use GDB to debug a running process?

Yes you can. Assume a process foo is running...

ps -elf | grep foo

look for the PID number

gdb -a {PID number}

"unexpected token import" in Nodejs5 and babel?

Current method is to use:

npm install --save-dev babel-cli babel-preset-env

And then in in .babelrc

    "presets": ["env"]

this install Babel support for latest version of js (es2015 and beyond) Check out babeljs

Do not forget to add babel-node to your scripts inside package.json use when running your js file as follows.

"scripts": {
   "test": "mocha",
    //Add this line to your scripts
   "populate": "node_modules/babel-cli/bin/babel-node.js" 

Now you can npm populate yourfile.js inside terminal.

If you are running windows and running error internal or external command not recognized, use node infront of the script as follow

node node_modules/babel-cli/bin/babel-node.js

Then npm run populate

missing private key in the distribution certificate on keychain

When I try to upload iOS build to test flight then error was appear.

"Missing privacy key".

enter image description here

Just 2 step for fix this error.

  1. Remove old certificate from
  2. Create new certificate from Xcode or

My problem has been solved (I am using Xcode 9.4.1).

Please check, Xcode created new certificate.

enter image description here

spring data jpa @query and pageable

With @Query , we can use pagination as well where you need to pass object of Pageable class at end of JPA method

For example:

Pageable pageableRequest = new PageRequest(page, size, Sort.Direction.DESC, rollNo);

Where, page = index of page (index start from zero)
size = No. of records
Sort.Direction = Sorting as per rollNo
rollNo = Field in User class

UserRepository repo
repo.findByFirstname("John", pageableRequest);

public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USER WHERE FIRSTNAME = :firstname)
  Page<User> findByLastname(@Param("firstname") String firstname, Pageable pageable);

How to extract the decision rules from scikit-learn decision-tree?

This builds on @paulkernfeld 's answer. If you have a dataframe X with your features and a target dataframe y with your resonses and you you want to get an idea which y value ended in which node (and also ant to plot it accordingly) you can do the following:

    def tree_to_code(tree, feature_names):
        from sklearn.tree import _tree
        codelines = []
        codelines.append('def get_cat(X_tmp):\n')
        codelines.append('   catout = []\n')
        codelines.append('   for codelines in range(0,X_tmp.shape[0]):\n')
        codelines.append('      Xin = X_tmp.iloc[codelines]\n')
        tree_ = tree.tree_
        feature_name = [
            feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
            for i in tree_.feature
        #print "def tree({}):".format(", ".join(feature_names))

        def recurse(node, depth):
            indent = "      " * depth
            if tree_.feature[node] != _tree.TREE_UNDEFINED:
                name = feature_name[node]
                threshold = tree_.threshold[node]
                codelines.append ('{}if Xin["{}"] <= {}:\n'.format(indent, name, threshold))
                recurse(tree_.children_left[node], depth + 1)
                codelines.append( '{}else:  # if Xin["{}"] > {}\n'.format(indent, name, threshold))
                recurse(tree_.children_right[node], depth + 1)
                codelines.append( '{}mycat = {}\n'.format(indent, node))

        recurse(0, 1)
        codelines.append('      catout.append(mycat)\n')
        codelines.append('   return pd.DataFrame(catout,index=X_tmp.index,columns=["category"])\n')
        codelines.append('node_ids = get_cat(X)\n')
        return codelines
    mycode = tree_to_code(clf,X.columns.values)

    # now execute the function and obtain the dataframe with all nodes
    node_ids = [int(x[0]) for x in node_ids.values]
    node_ids2 = pd.DataFrame(node_ids)

    print('make plot')
    import as cm
    colors = cm.rainbow(np.linspace(0, 1, 1+max( list(set(node_ids)))))
    #plt.figure(figsize=cm2inch(24, 21))
    for i in list(set(node_ids)):
        plt.plot(y[node_ids2.values==i],'o',color=colors[i], label=str(i))  
    mytitle = ['y colored by node']
    plt.title(mytitle ,fontsize=14)
    plt.xlabel('my xlabel')
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.00), shadow=True, ncol=9)

not the most elegant version but it does the job...

bootstrap datepicker setDate format dd/mm/yyyy

Changing to format: 'dd/mm/yyyy' didn't work for me, and changing that to dateFormat: 'dd/mm/yyyy' added year multiple times, The finest one for me was,

dateFormat: 'dd/mm/yy'

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

    function updateURL(url_params) {
        if (history.pushState) {
        var newurl = window.location.protocol + "//" + + window.location.pathname + '?' + url_params;

    function setActiveTab(tab) {
        $('.nav-tabs li').removeClass('active');
        $('.tab-content .tab-pane').removeClass('active');

        $('a[href="#tab-' + tab + '"]').closest('li').addClass('active');
        $('#tab-' + tab).addClass('active');

    // Set active tab
    $url_params = new URLSearchParams(;

    // Get active tab and remember it
        .on('click', function() {
        $href = $(this).attr('href')
        $active_tab = $href.replace('#tab-', '');

        $url_params.set('tab', $active_tab);

    if ($url_params.has('tab')) {
        $tab = $url_params.get('tab');
        $tab = '#tab-' + $tab;
        $myTab = JSON.stringify($tab);
        $thisTab = $('.nav-tabs a[href=' + $myTab  +']');
        $('.nav-tabs a[href=' + $myTab  +']').tab('show');

JQuery - how to select dropdown item based on value

You can use this jQuery code which I find it eaiser to use:

$('#your_id [value=3]').attr('selected', 'true');
<script src=""></script>_x000D_
<select id="your_id" name="name" class="form-control input-md">_x000D_
  <option value="1">Option #1</option>_x000D_
  <option value="2">Option #2</option>_x000D_
  <option value="3">Option #3</option>_x000D_
  <option value="4">Option #4</option>_x000D_
  <option value="5">Option #5</option>_x000D_
  <option value="6">Option #6</option>_x000D_
  <option value="7">Option #7</option>_x000D_

Remove all subviews?

In order to remove all subviews Syntax :

- (void)makeObjectsPerformSelector:(SEL)aSelector;

Usage :

[self.View.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

This method is present in NSArray.h file and uses NSArray(NSExtendedArray) interface

Can lambda functions be templated?

I've been playing with the latest clang version 5.0.1 compiling with the -std=c++17 flag and there is now some nice support for auto type parameters for lambdas:

#include <iostream>
#include <vector>
#include <stdexcept>

int main() {
    auto slice = [](auto input, int beg, int end) {
        using T = decltype(input);
        const auto size = input.size();
        if (beg > size || end > size || beg < 0 || end < 0) {
            throw std::out_of_range("beg/end must be between [0, input.size())");
        if (beg > end) {
            throw std::invalid_argument("beg must be less than end");
        return T(input.begin() + beg, input.begin() + end);
    auto v = std::vector<int> { 1,2,3,4,5 };
    for (auto e : slice(v, 1, 4)) {
        std::cout << e << " ";
    std::cout << std::endl;

What are these ^M's that keep showing up in my files in emacs?

If you don't have dos2unix utility installed on your system, you can create your own to get rid of Windows endline characters:

vi ~/dos2unix.bash:

with the following content

tr -d '\r' < $1 > repl.tmp
mv -f repl.tmp $1

In your ~/.bashrc, add the line:

alias 'dos2unix=~/dos2unix.bash'


dos2unix file_from_PC.txt

will remove ^M characters at lines ends in file_from_PC.txt. You can check if you have those or not by using cat:

cat -v file_from_PC.txt

Android, landscape only orientation?

One thing I've not found through the answers is that there are two possible landscape orientations, and I wanted to let both be available! So android:screenOrientation="landscape" will lock your app only to one of the 2 possibilities, but if you want your app to be limited to both landscape orientations (for them whom is not clear, having device on portrait, one is rotating left and the other one rotating right) this is what is needed:


CSV file written with Python has blank lines between each row

Use the method defined below to write data to the CSV file.

open('outputFile.csv', 'a',newline='')

Just add an additional newline='' parameter inside the open method :

def writePhoneSpecsToCSV():
    rowData=["field1", "field2"]
    with open('outputFile.csv', 'a',newline='') as csv_file:
        writer = csv.writer(csv_file)

This will write CSV rows without creating additional rows!

load jquery after the page is fully loaded

My guess is that you load jQuery in the <head> section of your page. While this is not harmful, it slows down page load. Try using this pattern to speed up initial loading time of the DOM-Tree:

<!doctype html>
    <meta charset="utf-8">

    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="">

    <!-- PAGE CONTENT -->

    <!-- JS -->
    <script type="text/javascript" src=""></script>
        $(function() {
            $('body').append('<p>I can happily use jQuery</p>');


Just add your scripts at the end of your <body>tag.

There are some scripts that need to be in the head due to practical reasons, the most prominent library being Modernizr

Regex expressions in Java, \\s vs. \\s+

The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times

Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}?   X, exactly n times
X{n,}?  X, at least n times
X{n,m}? X, at least n but not more than m times

Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+   X, exactly n times
X{n,}+  X, at least n times
X{n,m}+ X, at least n but not more than m times

Adding css class through aspx code behind

If you want to add attributes, including the class, you need to set runat="server" on the tag.

    <div id="classMe" runat="server"></div>

Then in the code-behind:

classMe.Attributes.Add("class", "some-class")

Using python PIL to turn a RGB image into a pure black and white image

Another option (which is useful e.g. for scientific purposes when you need to work with segmentation masks) is simply apply a threshold:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Binarize (make it black and white) an image with Python."""

from PIL import Image
from scipy.misc import imsave
import numpy

def binarize_image(img_path, target_path, threshold):
    """Binarize an image."""
    image_file =
    image = image_file.convert('L')  # convert image to monochrome
    image = numpy.array(image)
    image = binarize_array(image, threshold)
    imsave(target_path, image)

def binarize_array(numpy_array, threshold=200):
    """Binarize a numpy array."""
    for i in range(len(numpy_array)):
        for j in range(len(numpy_array[0])):
            if numpy_array[i][j] > threshold:
                numpy_array[i][j] = 255
                numpy_array[i][j] = 0
    return numpy_array

def get_parser():
    """Get parser object for script"""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    parser = ArgumentParser(description=__doc__,
    parser.add_argument("-i", "--input",
                        help="read this file",
    parser.add_argument("-o", "--output",
                        help="write binarized file hre",
                        help="Threshold when to show white")
    return parser

if __name__ == "__main__":
    args = get_parser().parse_args()
    binarize_image(args.input, args.output, args.threshold)

It looks like this for ./ -i convert_image.png -o result_bin.png --threshold 200:

enter image description here

How to get a index value from foreach loop in jstl

use varStatus to get the index c:forEach varStatus properties

<c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
    <li><a onclick="getCategoryIndex(${loop.index})" href="#">${categoryName}</a></li>

How do I access refs of a child component in the parent component

Using Ref forwarding you can pass the ref from parent to further down to a child.

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
  1. Create a React ref by calling React.createRef and assign it to a ref variable.
  2. Pass your ref down to by specifying it as a JSX attribute.
  3. React passes the ref to the (props, ref) => ... function inside forwardRef as a second argument.
  4. Forward this ref argument down to by specifying it as a JSX attribute.
  5. When the ref is attached, ref.current will point to the DOM node.

Note The second ref argument only exists when you define a component with React.forwardRef call. Regular functional or class components don’t receive the ref argument, and ref is not available in props either.

Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.

Reference: React Documentation.

How to reverse an animation on mouse out after hover

Using transform in combination with transition works flawlessly for me:

.ani-grow {
    -webkit-transition: all 0.5s ease; 
    -moz-transition: all 0.5s ease; 
    -o-transition: all 0.5s ease; 
    -ms-transition: all 0.5s ease; 
    transition: all 0.5s ease; 
.ani-grow:hover {
    transform: scale(1.01);

Print very long string completely in pandas dataframe

Another easier way to print the whole string is to call values on the dataframe.

df = pd.DataFrame({'one' : ['one', 'two', 
      'This is very long string very long string very long string veryvery long string']})


The Output will be

 ['This is very long string very long string very long string veryvery long string']]

Assign null to a SqlParameter

In my opinion the better way is to do this with the Parameters property of the SqlCommand class:

public static void AddCommandParameter(SqlCommand myCommand)
        (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex);

How to get a cookie from an AJAX response?

Similar to yebmouxing I could not the


method to work. It would only return null even if I had set HTTPOnly to false on my server.

I too wrote a simple js helper function to grab the cookies from the document. This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:

function getCookie(cookieName){
  var cookieArray = document.cookie.split(';');
  for(var i=0; i<cookieArray.length; i++){
    var cookie = cookieArray[i];
    while (cookie.charAt(0)==' '){
      cookie = cookie.substring(1);
    cookieHalves = cookie.split('=');
    if(cookieHalves[0]== cookieName){
      return cookieHalves[1];
  return "";

How to import popper.js?

You can download and import all of Bootstrap, and Popper, with a single command using Fetch Injection:

  '[email protected]/dist/js/bootstrap.min.js',
], fetchInject([
  '[email protected]/dist/js/tether.min.js'

Add CSS files if you need those too. Adjust versions and external sources to meet your needs and consider using sub-resource integrity checking if you're not hosting the files on your own domain or don't trust the source.

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

It may be worth mentioning that running tomcat as a non root user (which you should be doing) will prevent you from using a port below 1024 on *nix. If you want to use TC as a standalone server -- as its performance no longer requires it to be fronted by Apache or the like -- you'll want to bind to port 80 along with whatever IP address you're specifying.

You can do this by using IPTABLES to redirect port 80 to 8080.

Combine Regexp?

Combining the regex for the fourth option with any of the others doesn't work within one regex. 4 + 1 would mean either the string starts with @ or doesn't contain @ at all. You're going to need two separate comparisons to do that.

Is it safe to use Project Lombok?

My take on Lombok is that it merely provides shortcuts for writing bolilerplate Java code.
When it comes to using shortcuts for writing bolilerplate Java code, I would rely on such features provided by IDE -- like in Eclipse, we can go to menu Source > Generate Getters and Setters for generating getters and setters.
I would not rely on a library like Lombok for this:

  1. It pollutes your code with an indirection layer of alternative syntax (read @Getter, @Setter, etc. annotations). Rather than learning an alternative syntax for Java, I would switch to any other language that natively provides Lombok like syntax.
  2. Lombok requires the use of a Lombok supported IDE to work with your code. This dependency introduces a considerable risk for any non-trivial project. Does the open source Lombok project have enough resources to keep providing support for different versions of a wide range of Java IDE's available?
  3. Does the open source Lombok project have enough resources to keep providing support for newer versions of Java that will be coming in future?
  4. I also feel nervous that Lombok may introduce compatibility issues with widely used frameworks/libraries (like Spring, Hibernate, Jackson, JUnit, Mockito) that work with your byte code at runtime.

All in all I would not prefer to "spice up" my Java with Lombok.

Setting a property with an EventTrigger

As much as I love XAML, for this kinds of tasks I switch to code behind. Attached behaviors are a good pattern for this. Keep in mind, Expression Blend 3 provides a standard way to program and use behaviors. There are a few existing ones on the Expression Community Site.

How to add external library in IntelliJ IDEA?

Intellij IDEA 15: File->Project Structure...->Project Settings->Libraries

How to specify different Debug/Release output directories in QMake .pro file

For my Qt project, I use this scheme in *.pro file:

HEADERS += src/dialogs.h
SOURCES += src/main.cpp \

Release:DESTDIR = release
Release:OBJECTS_DIR = release/.obj
Release:MOC_DIR = release/.moc
Release:RCC_DIR = release/.rcc
Release:UI_DIR = release/.ui

Debug:DESTDIR = debug
Debug:OBJECTS_DIR = debug/.obj
Debug:MOC_DIR = debug/.moc
Debug:RCC_DIR = debug/.rcc
Debug:UI_DIR = debug/.ui

It`s simple, but nice! :)

Difference between app.use and app.get in express.js

In addition to the above explanations, what I experience:

app.use('/book', handler);  

will match all requests beginning with '/book' as URL. so it also matches '/book/1' or '/book/2'


matches only GET request with exact match. It will not handle URLs like '/book/1' or '/book/2'

So, if you want a global handler that handles all of your routes, then app.use('/') is the option. app.get('/') will handle only the root URL.