Programs & Examples On #Virtualhost

The term Virtual Host refers to the practice of running more than one web site (such as www.company1.com and www.company2.com) on a single machine. Virtual hosts can be "IP-based", meaning that you have a different IP address for every web site, or "name-based", meaning that you have multiple names running on each IP address. The fact that they are running on the same physical server is not apparent to the end user.

Apache default VirtualHost

I had the same issue. I could fix it by adding the following in httpd.conf itself before the IncludeOptional directives for virtual hosts. Now localhost and the IP 192.168.x.x both points to the default test page of Apache. All other virtual hosts are working as expected.

<VirtualHost *:80>
    DocumentRoot /var/www/html
</VirtualHost>

Reference: https://httpd.apache.org/docs/2.4/vhosts/name-based.html#defaultvhost

Apache error: _default_ virtualhost overlap on port 443

I ran into this problem because I had multiple wildcard entries for the same ports. You can easily check this by executing apache2ctl -S:

# apache2ctl -S
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 30000, the first has precedence
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 20001, the first has precedence
VirtualHost configuration:
11.22.33.44:80       is a NameVirtualHost
         default server xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
         port 80 namevhost xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
         [...]
11.22.33.44:443      is a NameVirtualHost
         default server yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
         port 443 namevhost yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
wildcard NameVirtualHosts and _default_ servers:
*:80                   hostname.com (/etc/apache2/sites-enabled/000-default:1)
*:20001                hostname.com (/etc/apache2/sites-enabled/000-default:33)
*:30000                hostname.com (/etc/apache2/sites-enabled/000-default:57)
_default_:443          hostname.com (/etc/apache2/sites-enabled/default-ssl:2)
*:20001                hostname.com (/etc/apache2/sites-enabled/default-ssl:163)
*:30000                hostname.com (/etc/apache2/sites-enabled/default-ssl:178)
Syntax OK

Notice how at the beginning of the output are a couple of warning lines. These will indicate which ports are creating the problems (however you probably already knew that).

Next, look at the end of the output and you can see exactly which files and lines the virtualhosts are defined that are creating the problem. In the above example, port 20001 is assigned both in /etc/apache2/sites-enabled/000-default on line 33 and /etc/apache2/sites-enabled/default-ssl on line 163. Likewise *:30000 is listed in 2 places. The solution (in my case) was simply to delete one of the entries.

Apache VirtualHost and localhost

Additional description for John Smith's answer from the official documentation. To understand why it is.

Main host goes away

If you are adding virtual hosts to an existing web server, you must also create a block for the existing host. The ServerName and DocumentRoot included in this virtual host should be the same as the global ServerName and DocumentRoot. List this virtual host first in the configuration file so that it will act as the default host.

For example, to work properly with XAMPP, to prevent VirtualHost overriding the main host, add the follow lines into file httpd-vhosts.conf:

# Main host
<VirtualHost *:80>
    ServerName localhost
    DocumentRoot "/xampp/htdocs"
</VirtualHost>

# Additional host
<VirtualHost *:80>
    # Over directives there
</VirtualHost>

nginx missing sites-available directory

Well, I think nginx by itself doesn't have that in its setup, because the Ubuntu-maintained package does it as a convention to imitate Debian's apache setup. You could create it yourself if you wanted to emulate the same setup.

Create /etc/nginx/sites-available and /etc/nginx/sites-enabled and then edit the http block inside /etc/nginx/nginx.conf and add this line

include /etc/nginx/sites-enabled/*;

Of course, all the files will be inside sites-available, and you'd create a symlink for them inside sites-enabled for those you want enabled.

Virtualhost For Wildcard Subdomain and Static Subdomain

This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.

<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com

SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"

VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"

DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

Thank you, that worked! But I replaced this

AllowOverride AuthConfig Indexes

with that

AllowOverride All

Otherwise, the .htaccess didn't work: I got problems with the RewriteEngine and the error message "RewriteEngine not allowed here".

Apache VirtualHost 403 Forbidden

It could be you haven't setup PHP~!

error_log per Virtual Host?

The default behaviour for error_log() is to output to the Apache error log. If this isn't happening check your php.ini settings for the error_log directive. Leave it unset to use the Apache log file for the current vhost.

How to debug an apache virtual host configuration?

I had a new VirtualHost configuration file that was not showing when using the apachectl -S command. After much head scratching I realised that my file did not have suffix ".conf". Once I renamed the file with that suffix my Vhost started showing and working!

how to create virtual host on XAMPP

I have added below configuration to the httpd.conf and restarted the lampp service and it started working. Thanks to all the above posts, which helped me to resolve issues one by one.

Listen 8080
<VirtualHost *:8080>
    ServerAdmin [email protected]
    DocumentRoot "/opt/lampp/docs/dummy-host2.example.com"
    ServerName localhost:8080
    ErrorLog "logs/dummy-host2.example.com-error_log"
    CustomLog "logs/dummy-host2.example.com-access_log" common
    <Directory "/opt/lampp/docs/dummy-host2.example.com">
        Require all granted 
    </Directory>
</VirtualHost>

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

You did not need

Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted

the only thing what you need is...

Require all granted

...inside the directory section.

See Apache 2.4 upgrading side:

http://httpd.apache.org/docs/2.4/upgrading.html

client denied by server configuration

The error "client denied by server configuration" generally means that somewhere in your configuration are Allow from and Deny from directives that are preventing access. Read the mod_authz_host documentation for more details.

You should be able to solve this in your VirtualHost by adding something like:

<Location />
  Allow from all
  Order Deny,Allow
</Location>

Or alternatively with a Directory directive:

<Directory "D:/Devel/matysart/matysart_dev1">
  Allow from all
  Order Deny,Allow
</Directory>

Some investigation of your Apache configuration files will probably turn up default restrictions on the default DocumentRoot.

Site does not exist error for a2ensite

You probably updated your Ubuntu installation and one of the updates included the upgrade of Apache to version 2.4.x

In Apache 2.4.x the vhost configuration files, located in the /etc/apache2/sites-available directory, must have the .conf extension.

Using terminal (mv command), rename all your existing configuration files and add the .conf extension to all of them.

mv /etc/apache2/sites-available/cmsplus.dev /etc/apache2/sites-available/cmsplus.dev.conf

If you get a "Permission denied" error, then add "sudo " in front of your terminal commands.

You do not need to make any other changes to the configuration files.

Enable the vhost(s):

a2ensite cmsplus.dev.conf

And then reload Apache:

service apache2 reload

Your sites should be up and running now.


UPDATE: As mentioned here, a Linux distribution that you installed changed the configuration to Include *.conf only. Therefore it has nothing to do with Apache 2.2 or 2.4

How to update a menu item shown in the ActionBar?

I have used this code:

public boolean onPrepareOptionsMenu (Menu menu) {       
    MenuInflater inflater = getMenuInflater();
    TextView title  = (TextView) findViewById(R.id.title);
    menu.getItem(0).setTitle(
        getString(R.string.payFor) + " " + title.getText().toString());
    menu.getItem(1).setTitle(getString(R.string.payFor) + "...");
    return true;        
}

And worked like a charm to me you can find OnPrepareOptionsMenu here

Removing duplicates from a String in Java

For the simplicity of the code- I have taken hardcore input, one can take input by using Scanner class also

    public class KillDuplicateCharInString {
    public static void main(String args[]) {
        String str= "aaaabccdde ";
        char arr[]= str.toCharArray();
        int n = arr.length;
        String finalStr="";
        for(int i=0;i<n;i++) {
            if(i==n-1){
                finalStr+=arr[i];
                break;
            }
            if(arr[i]==arr[i+1]) {
                continue;
            }
            else {
                finalStr+=arr[i];
            }
        }
        System.out.println(finalStr);



    }
}

Understanding the results of Execute Explain Plan in Oracle SQL Developer

In recent Oracle versions the COST represent the amount of time that the optimiser expects the query to take, expressed in units of the amount of time required for a single block read.

So if a single block read takes 2ms and the cost is expressed as "250", the query could be expected to take 500ms to complete.

The optimiser calculates the cost based on the estimated number of single block and multiblock reads, and the CPU consumption of the plan. the latter can be very useful in minimising the cost by performing certain operations before others to try and avoid high CPU cost operations.

This raises the question of how the optimiser knows how long operations take. recent Oracle versions allow the collections of "system statistics", which are definitely not to be confused with statistics on tables or indexes. The system statistics are measurements of the performance of the hardware, mostly importantly:

  1. How long a single block read takes
  2. How long a multiblock read takes
  3. How large a multiblock read is (often different to the maximum possible due to table extents being smaller than the maximum, and other reasons).
  4. CPU performance

These numbers can vary greatly according to the operating environment of the system, and different sets of statistics can be stored for "daytime OLTP" operations and "nighttime batch reporting" operations, and for "end of month reporting" if you wish.

Given these sets of statistics, a given query execution plan can be evaluated for cost in different operating environments, which might promote use of full table scans at some times or index scans at others.

The cost is not perfect, but the optimiser gets better at self-monitoring with every release, and can feedback the actual cost in comparison to the estimated cost in order to make better decisions for the future. this also makes it rather more difficult to predict.

Note that the cost is not necessarily wall clock time, as parallel query operations consume a total amount of time across multiple threads.

In older versions of Oracle the cost of CPU operations was ignored, and the relative costs of single and multiblock reads were effectively fixed according to init parameters.

How to select an element inside "this" in jQuery?

I use this to get the Parent, similarly for child

$( this ).children( 'li.target' ).css("border", "3px double red");

Good Luck

How to Git stash pop specific stash in 1.8.3?

git stash apply n

works as of git version 2.11

Original answer, possibly helping to debug issues with the older syntax involving shell escapes:

As pointed out previously, the curly braces may require escaping or quoting depending on your OS, shell, etc.

See "stash@{1} is ambiguous?" for some detailed hints of what may be going wrong, and how to work around it in various shells and platforms.

git stash list
git stash apply stash@{n}

git stash apply version

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

How to have image and text side by side

remove the margin for the h4 tag

h4 {
margin:0px;
}

Fiddle link

http://jsfiddle.net/Vinay199129/s3Qye/

Threading Example in Android

Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.

Android code - Main.java

package test12.tt;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView txt1 = (TextView) findViewById(R.id.sm);

        new Thread(new Runnable() { 
            public void run(){        
            txt1.setText("Thread!!");
            }
        }).start();

    }    
}

Android application xml - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView  
    android:id = "@+id/sm"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

</LinearLayout>

Using % for host when creating a MySQL user

Let's just test.

Connect as superuser, and then:

SHOW VARIABLES LIKE "%version%"; 
+-------------------------+------------------------------+ 
| Variable_name           | Value                        | 
+-------------------------+------------------------------+ 
| version                 | 10.0.23-MariaDB-0+deb8u1-log | 

and then

USE mysql;

Setup

Create a user foo with password bar for testing:

CREATE USER foo@'%' IDENTIFIED BY 'bar'; FLUSH PRIVILEGES;

Connect

To connect to the Unix Domain Socket (i.e. the I/O pipe that is named by the filesystem entry /var/run/mysqld/mysqld.sock or some such), run this on the command line (use the --protocol option to make doubly sure)

mysql -pbar -ufoo
mysql -pbar -ufoo --protocol=SOCKET

One expects that the above matches "user comes from localhost" but certainly not "user comes from 127.0.0.1".

To connect to the server from "127.0.0.1" instead, run this on the command line

mysql -pbar -ufoo --bind-address=127.0.0.1 --protocol=TCP

If you leave out --protocol=TCP, the mysql command will still try to use the Unix domain socket. You can also say:

mysql -pbar -ufoo --bind-address=127.0.0.1 --host=127.0.0.1

The two connection attempts in one line:

export MYSQL_PWD=bar; \
mysql -ufoo --protocol=SOCKET --execute="SELECT 1"; \
mysql -ufoo --bind-address=127.0.0.1 --host=127.0.0.1 --execute="SELECT 1"

(the password is set in the environment so that it is passed to the mysql process)

Verification In Case Of Doubt

To really check whether the connection goes via a TCP/IP socket or a Unix Domain socket

  1. get the PID of the mysql client process by examining the output of ps faux
  2. run lsof -n -p<yourpid>.

You will see something like:

mysql [PID] quux 3u IPv4 [code] 0t0 TCP 127.0.0.1:[port]->127.0.0.1:mysql (ESTABLISHED)

or

mysql [PID] quux 3u unix [code] 0t0 [code] socket

So:

Case 0: Host = '10.10.10.10' (null test)

update user set host='10.10.10.10' where user='foo'; flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Case 1: Host = '%'

update user set host='%' where user='foo'; flush privileges;
  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

Case 2: Host = 'localhost'

update user set host='localhost' where user='foo';flush privileges;

Behaviour varies and this apparently depends on skip-name-resolve. If set, causes lines with localhost to be ignored according to the log. The following can be seen in the error log: "'user' entry 'root@localhost' ignored in --skip-name-resolve mode.". This means no connecting through the Unix Domain Socket. But this is empirically not the case. localhost now means ONLY the Unix Domain Socket, and no longer matched 127.0.0.1.

skip-name-resolve is off:

  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

skip-name-resolve is on:

  • Connect using socket: OK
  • Connect from 127.0.0.1: FAILURE

Case 3: Host = '127.0.0.1'

update user set host='127.0.0.1' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: OK

Case 4: Host = ''

update user set host='' where user='foo';flush privileges;
  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

(According to MySQL 5.7: 6.2.4 Access Control, Stage 1: Connection Verification, The empty string '' also means “any host” but sorts after '%'. )

Case 5: Host = '192.168.0.1' (extra test)

('192.168.0.1' is one of my machine's IP addresses, change appropriately in your case)

update user set host='192.168.0.1' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

but

  • Connect using mysql -pbar -ufoo -h192.168.0.1: OK (!)

The latter because this is actually TCP connection coming from 192.168.0.1, as revealed by lsof:

TCP 192.168.0.1:37059->192.168.0.1:mysql (ESTABLISHED)

Edge Case A: Host = '0.0.0.0'

update user set host='0.0.0.0' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Edge Case B: Host = '255.255.255.255'

update user set host='255.255.255.255' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Edge Case C: Host = '127.0.0.2'

(127.0.0.2 is perfectly valid loopback address equivalent to 127.0.0.1 as defined in RFC6890)

update user set host='127.0.0.2' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Interestingly:

  • mysql -pbar -ufoo -h127.0.0.2 connects from 127.0.0.1 and is FAILURE
  • mysql -pbar -ufoo -h127.0.0.2 --bind-address=127.0.0.2 is OK

Cleanup

delete from user where user='foo';flush privileges;

Addendum

To see what is actually in the mysql.user table, which is one of the permission tables, use:

SELECT SUBSTR(password,1,6) as password, user, host,
Super_priv AS su,
Grant_priv as gr,
CONCAT(Select_priv, Lock_tables_priv) AS selock,
CONCAT(Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv) AS modif,
CONCAT(References_priv, Index_priv, Alter_priv) AS ria,
CONCAT(Create_tmp_table_priv, Create_view_priv, Show_view_priv) AS views,
CONCAT(Create_routine_priv, Alter_routine_priv, Execute_priv, Event_priv, Trigger_priv) AS funcs,
CONCAT(Repl_slave_priv, Repl_client_priv) AS replic,
CONCAT(Shutdown_priv, Process_priv, File_priv, Show_db_priv, Reload_priv, Create_user_priv) AS admin
FROM user ORDER BY user, host;

this gives:

+----------+----------+-----------+----+----+--------+-------+-----+-------+-------+--------+--------+
    | password | user     | host      | su | gr | selock | modif | ria | views | funcs | replic | admin  |
    +----------+----------+-----------+----+----+--------+-------+-----+-------+-------+--------+--------+
    | *E8D46   | foo      |           | N  | N  | NN     | NNNNN | NNN | NNN   | NNNNN | NN     | NNNNNN |

Similarly for table mysql.db:

SELECT host,db,user, 
       Grant_priv as gr,
       CONCAT(Select_priv, Lock_tables_priv) AS selock, 
       CONCAT(Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv) AS modif, 
       CONCAT(References_priv, Index_priv, Alter_priv) AS ria, 
       CONCAT(Create_tmp_table_priv, Create_view_priv, Show_view_priv) AS views, 
       CONCAT(Create_routine_priv, Alter_routine_priv, Execute_priv) AS funcs 
       FROM db ORDER BY user, db, host;

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

Entity Framework The underlying provider failed on Open

Always check for Inner Exception if any. In my case Inner Exception turned out to be really helpful in figuring out the issue.

My site was working fine in Dev Environment. But after i deployed to production, it started giving out this exception, but the Inner Exception was saying that Login failed for the particular user.
So i figured out it was something to do with the connection itself. Hence tried logging in using SSMS and even that failed.

Eventually figured out that exception showed up for the simple reason that the SQL server had only Windows Authentication enabled and SQL Authentication was failing which was what i was using for Authentication.

In short, changing Authentication to Mixed(SQL and Windows), fixed the issue for me. :)

How to get the list of all database users

EXEC sp_helpuser

or

SELECT * FROM sysusers

Both of these select all the users of the current database (not the server).

Running MSBuild fails to read SDKToolsPath

I agree with IanS's answer. No need to install new SDK. Just make sure the registry key values SDK35ToolsPath and SDK40ToolPath for MSBuild are pointing to correct registry key values.

In my case my project was targeted for .NET 3.5 and I had to set SDK35ToolsPath for key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0 to $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v6.0A\WinSDKNetFxTools@InstallationFolder). And everything worked.

How can one run multiple versions of PHP 5.x on a development LAMP server?

With CentOS, you can do it using a combination of fastcgi for one version of PHP, and php-fpm for the other, as described here:

https://web.archive.org/web/20130707085630/http://linuxplayer.org/2011/05/intall-multiple-version-of-php-on-one-server

Based on CentOS 5.6, for Apache only

1. Enable rpmforge and epel yum repository

wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
wget http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
sudo rpm -ivh rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
sudo rpm -ivh epel-release-5-4.noarch.rpm

2. Install php-5.1

CentOS/RHEL 5.x series have php-5.1 in box, simply install it with yum, eg:

sudo yum install php php-mysql php-mbstring php-mcrypt

3. Compile and install php 5.2 and 5.3 from source

For php 5.2 and 5.3, we can find many rpm packages on the Internet. However, they all conflict with the php which comes with CentOS, so, we’d better build and install them from soure, this is not difficult, the point is to install php at different location.

However, when install php as an apache module, we can only use one version of php at the same time. If we need to run different version of php on the same server, at the same time, for example, different virtual host may need different version of php. Fortunately, the cool FastCGI and PHP-FPM can help.

Build and install php-5.2 with fastcgi enabled

1) Install required dev packages

yum install gcc libxml2-devel bzip2-devel zlib-devel \
    curl-devel libmcrypt-devel libjpeg-devel \
    libpng-devel gd-devel mysql-devel

2) Compile and install

wget http://cn.php.net/get/php-5.2.17.tar.bz2/from/this/mirror
tar -xjf php-5.2.17.tar.bz2
cd php-5.2.17
./configure --prefix=/usr/local/php52 \
    --with-config-file-path=/etc/php52 \
    --with-config-file-scan-dir=/etc/php52/php.d \
    --with-libdir=lib64 \
    --with-mysql \
    --with-mysqli \
    --enable-fastcgi \
    --enable-force-cgi-redirect \
    --enable-mbstring \
    --disable-debug \
    --disable-rpath \
    --with-bz2 \
    --with-curl \
    --with-gettext \
    --with-iconv \
    --with-openssl \
    --with-gd \
    --with-mcrypt \
    --with-pcre-regex \
    --with-zlib
make -j4 > /dev/null
sudo make install
sudo mkdir /etc/php52
sudo cp php.ini-recommended /etc/php52/php.ini

3) create a fastcgi wrapper script

create file /usr/local/php52/bin/fcgiwrapper.sh

#!/bin/bash
PHP_FCGI_MAX_REQUESTS=10000
export PHP_FCGI_MAX_REQUESTS
exec /usr/local/php52/bin/php-cgi
chmod a+x /usr/local/php52/bin/fcgiwrapper.sh
Build and install php-5.3 with fpm enabled

wget http://cn.php.net/get/php-5.3.6.tar.bz2/from/this/mirror
tar -xjf php-5.3.6.tar.bz2 
cd php-5.3.6
./configure --prefix=/usr/local/php53 \
    --with-config-file-path=/etc/php53 \
    --with-config-file-scan-dir=/etc/php53/php.d \
    --enable-fpm \
    --with-fpm-user=apache \
    --with-fpm-group=apache \
    --with-libdir=lib64 \
    --with-mysql \
    --with-mysqli \
    --enable-mbstring \
    --disable-debug \
    --disable-rpath \
    --with-bz2 \
    --with-curl \
    --with-gettext \
    --with-iconv \
    --with-openssl \
    --with-gd \
    --with-mcrypt \
    --with-pcre-regex \
    --with-zlib 

make -j4 && sudo make install
sudo mkdir /etc/php53
sudo cp php.ini-production /etc/php53/php.ini

sed -i -e 's#php_fpm_CONF=\${prefix}/etc/php-fpm.conf#php_fpm_CONF=/etc/php53/php-fpm.conf#' \
    sapi/fpm/init.d.php-fpm
sudo cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
sudo chmod a+x /etc/init.d/php-fpm
sudo /sbin/chkconfig --add php-fpm
sudo /sbin/chkconfig php-fpm on

sudo cp sapi/fpm/php-fpm.conf /etc/php53/

Configue php-fpm

Edit /etc/php53/php-fpm.conf, change some settings. This step is mainly to uncomment some settings, you can adjust the value if you like.

pid = run/php-fpm.pid
listen = 127.0.0.1:9000
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20

Then, start fpm

sudo /etc/init.d/php-fpm start

Install and setup mod_fastcgi, mod_fcgid

sudo yum install libtool httpd-devel apr-devel
wget http://www.fastcgi.com/dist/mod_fastcgi-current.tar.gz
tar -xzf mod_fastcgi-current.tar.gz
cd mod_fastcgi-2.4.6
cp Makefile.AP2 Makefile
sudo make top_dir=/usr/lib64/httpd/ install
sudo sh -c "echo 'LoadModule fastcgi_module modules/mod_fastcgi.so' > /etc/httpd/conf.d/mod_fastcgi.conf"
yum install mod_fcgid

Setup and test virtual hosts

1) Add the following line to /etc/hosts

127.0.0.1 web1.example.com web2.example.com web3.example.com

2) Create web document root and drop an index.php under it to show phpinfo switch to user root, run

mkdir /var/www/fcgi-bin
for i in {1..3}; do
    web_root=/var/www/web$i
    mkdir $web_root
    echo "<?php phpinfo(); ?>" > $web_root/index.php
done

Note: The empty /var/www/fcgi-bin directory is required, DO NOT REMOVE IT LATER

3) Create Apache config file(append to httpd.conf)

NameVirtualHost *:80

# module settings
# mod_fcgid
<IfModule mod_fcgid.c>
        idletimeout 3600
        processlifetime 7200
        maxprocesscount 17
        maxrequestsperprocess 16
        ipcconnecttimeout 60 
        ipccommtimeout 90
</IfModule>
# mod_fastcgi with php-fpm
<IfModule mod_fastcgi.c>
        FastCgiExternalServer /var/www/fcgi-bin/php-fpm -host 127.0.0.1:9000
</IfModule>


# virtual hosts...

#################################################################
#1st virtual host, use mod_php, run php-5.1
#################################################################
<VirtualHost *:80>
        ServerName web1.example.com
        DocumentRoot "/var/www/web1"

        <ifmodule mod_php5.c>
                <FilesMatch \.php$>
                        AddHandler php5-script .php
                </FilesMatch>
        </IfModule>

        <Directory "/var/www/web1">
                DirectoryIndex index.php index.html index.htm
                Options -Indexes FollowSymLinks
                Order allow,deny
                Allow from all
        </Directory>

</VirtualHost>
#################################################################
#2nd virtual host, use mod_fcgid, run php-5.2
#################################################################
<VirtualHost *:80>
        ServerName web2.example.com
        DocumentRoot "/var/www/web2"

        <IfModule mod_fcgid.c>
                AddHandler fcgid-script .php
                FCGIWrapper /usr/local/php52/bin/fcgiwrapper.sh
        </IfModule>

        <Directory "/var/www/web2">
                DirectoryIndex index.php index.html index.htm
                Options -Indexes FollowSymLinks +ExecCGI
                Order allow,deny
                Allow from all
        </Directory>

</VirtualHost>
#################################################################
#3rd virtual host, use mod_fastcgi + php-fpm, run php-5.3
#################################################################
<VirtualHost *:80>
        ServerName web3.example.com
        DocumentRoot "/var/www/web3"


        <IfModule mod_fastcgi.c>
                ScriptAlias /fcgi-bin/ /var/www/fcgi-bin/
                AddHandler php5-fastcgi .php
                Action php5-fastcgi /fcgi-bin/php-fpm
        </IfModule>

        <Directory "/var/www/web3">
                DirectoryIndex index.php index.html index.htm
                Options -Indexes FollowSymLinks +ExecCGI
                Order allow,deny
                Allow from all
        </Directory>

</VirtualHost>

4) restart apache. visit the 3 sites respectly to view phpinfo and validate the result. ie:

http://web1.example.com
http://web2.example.com
http://web3.example.com

If all OK, you can use one of the 3 virtual host as template to create new virtual host, with the desired php version.

Referencing value in a closed Excel workbook using INDIRECT?

If you know the number of sheet you want to reference you can use below function to find out the name. Than you can use it in INDIRECT funcion.

Public Function GETSHEETNAME(address As String, Optional SheetNumber As Integer = 1) As String

    Set WS = GetObject(address).Worksheets
    GETSHEETNAME = WS(SheetNumber).Name

End Function

This solution doesn't require referenced workbook to be open - Excel gonna open it by itself (but it's gonna be hidden).

Zip folder in C#

There is a ZipPackage class in the System.IO.Packaging namespace which is built into .NET 3, 3.5, and 4.0.

http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx

Here is an example how to use it. http://www.codeproject.com/KB/files/ZipUnZipTool.aspx?display=Print

How to see my Eclipse version?

I believe you can find out Eclipse Platform version for every software product that is Eclipse-based.

  1. Open Installation Details:

    • Go to Help => About => Installation Details.
    • Or to Help => Install New Software... => click What is already installed? link.
  2. Choose Plug-ins tab => type org.eclipse.platform => check Version column.

  3. You can match version code and version name on https://wiki.eclipse.org/Older_Versions_Of_Eclipse

For example, check out GitEye (Git GUI client) GitEye Installation Details

Or checkout DBBeaver (DB manager):

enter image description here

How to close Browser Tab After Submitting a Form?

try onsubmit="submit(); window.close()"

Simpler way to create dictionary of separate variables?

Maybe I'm overthinking this but..

str_l = next((k for k,v in locals().items() if id(l) == id(v)))


>>> bar = True
>>> foo = False
>>> my_dict=dict(bar=bar, foo=foo)
>>> next((k for k,v in locals().items() if id(bar) == id(v)))
'bar'
>>> next((k for k,v in locals().items() if id(foo) == id(v)))
'foo'
>>> next((k for k,v in locals().items() if id(my_dict) == id(v)))
'my_dict'

How do I wrap text in a span?

You should use white-space with display table

Example:
    legend {
        display:table; /* Enable line-wrapping in IE8+ */
        white-space:normal; /* Enable line-wrapping in old versions of some other browsers */
    }

Jenkins could not run git

I got a very similar error when my Jenkins agent was running Java 11 instead of Java 8. It had nothing to do with configuring my git path! Downgrading the agent to Java 8 was the only solution I found.

Java - Create a new String instance with specified length and filled with specific character. Best solution?

public static String fillString(int count,char c) {
    StringBuilder sb = new StringBuilder( count );
    for( int i=0; i<count; i++ ) {
        sb.append( c ); 
    }
    return sb.toString();
}

What is wrong?

How to get the fragment instance from the FragmentActivity?

You can use use findFragmentById in FragmentManager.

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

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

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

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

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

In bootstrap how to add borders to rows without adding up?

Here is one solution:

div.row { 
  border: 1px solid;
  border-bottom: 0px;
}
.container div.row:last-child {
  border-bottom: 1px solid;
}

I'm not 100% its the most effiecent, but it works :D

http://jsfiddle.net/aaronmallen/7cb3Y/2/

Named placeholders in string formatting

My answer is to:

a) use StringBuilder when possible

b) keep (in any form: integer is the best, speciall char like dollar macro etc) position of "placeholder" and then use StringBuilder.insert() (few versions of arguments).

Using external libraries seems overkill and I belive degrade performance significant, when StringBuilder is converted to String internally.

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

What USB driver should we use for the Nexus 5?

I installed the LG United Mobile Driver, and I was finally able to get ADB to recognize my device.

Git: How to rebase to a specific commit?

A simpler solution is git rebase <SHA1 of B> topic. This works irrespective of where your HEAD is.

We can confirm this behaviour from git rebase doc

<upstream> Upstream branch to compare against. May be any valid commit, not just an existing branch name. Defaults to the configured upstream for the current branch.


You might be thinking what will happen if I mention SHA1 of topic too in the above command ?

git rebase <SHA1 of B> <SHA1 of topic>

This will also work but rebase then won't make Topic point to new branch so created and HEAD will be in detached state. So from here you have to manually delete old Topic and create a new branch reference on new branch created by rebase.

Find and replace string values in list

You can use, for example:

words = [word.replace('[br]','<br />') for word in words]

Render HTML to PDF in Django site

Try wkhtmltopdf with either one of the following wrappers

django-wkhtmltopdf or python-pdfkit

This worked great for me,supports javascript and css or anything for that matter which a webkit browser supports.

For more detailed tutorial please see this blog post

How to add a boolean datatype column to an existing table in sql?

In phpmyadmin, If you need to add a boolean datatype column to an existing table with default value true:

ALTER TABLE books
   isAvailable boolean default true;

How to build jars from IntelliJ properly?

Use Gradle to build your project, then the jar is within the build file. Here is a Stack Overflow link on how to build .jar files with Gradle.

Java project with Gradle and building jar file in Intellij IDEA - how to?

List comprehension vs. lambda + filter

Curiously on Python 3, I see filter performing faster than list comprehensions.

I always thought that the list comprehensions would be more performant. Something like: [name for name in brand_names_db if name is not None] The bytecode generated is a bit better.

>>> def f1(seq):
...     return list(filter(None, seq))
>>> def f2(seq):
...     return [i for i in seq if i is not None]
>>> disassemble(f1.__code__)
2         0 LOAD_GLOBAL              0 (list)
          2 LOAD_GLOBAL              1 (filter)
          4 LOAD_CONST               0 (None)
          6 LOAD_FAST                0 (seq)
          8 CALL_FUNCTION            2
         10 CALL_FUNCTION            1
         12 RETURN_VALUE
>>> disassemble(f2.__code__)
2           0 LOAD_CONST               1 (<code object <listcomp> at 0x10cfcaa50, file "<stdin>", line 2>)
          2 LOAD_CONST               2 ('f2.<locals>.<listcomp>')
          4 MAKE_FUNCTION            0
          6 LOAD_FAST                0 (seq)
          8 GET_ITER
         10 CALL_FUNCTION            1
         12 RETURN_VALUE

But they are actually slower:

   >>> timeit(stmt="f1(range(1000))", setup="from __main__ import f1,f2")
   21.177661532000116
   >>> timeit(stmt="f2(range(1000))", setup="from __main__ import f1,f2")
   42.233950221000214

How to round up value C# to the nearest integer?

It is also possible to round negative integers

// performing d = c * 3/4 where d can be pos or neg
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
// explanation:
// 1.) multiply:          c * a  
// 2.) if c is negative:  (c>0? subtract half of the dividend 
//                              (b>>1) is bit shift right = (b/2)
//     if c is positive:  else  add half of the dividend 
// 3.) do the division
// on a C51/52 (8bit embedded) or similar like ATmega the below code may execute in approx 12cpu cycles (not tested)

Extended from a tip somewhere else in here. Sorry, missed from where.

/* Example test: integer rounding example including negative*/
#include <stdio.h>
#include <string.h>

int main () {
   //rounding negative int
   // doing something like d = c * 3/4
   int a=3;
   int b=4;
   int c=-5;
   int d;
   int s=c;
   int e=c+10;


   for(int f=s; f<=e; f++) {
      printf("%d\t",f);

      double cd=f, ad=a, bd=b , dd;

      // d = c * 3/4  with double
      dd = cd * ad / bd;

      printf("%.2f\t",dd);
      printf("%.1f\t",dd);        
      printf("%.0f\t",dd);

      // try again with typecast have used that a lot in Borland C++ 35 years ago....... maybe evolution has overtaken it ;) ***
      // doing div before mul on purpose
      dd =(double)c * ((double)a / (double)b);
      printf("%.2f\t",dd);

      c=f;
      // d = c * 3/4  with integer rounding
      d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
      printf("%d\t",d);
      puts("");
  }
 return 0;
}

/* test output
in  2f     1f   0f cast int   
-5  -3.75   -3.8    -4  -3.75   -4  
-4  -3.00   -3.0    -3  -3.75   -3  
-3  -2.25   -2.2    -2  -3.00   -2  
-2  -1.50   -1.5    -2  -2.25   -2  
-1  -0.75   -0.8    -1  -1.50   -1  
 0   0.00    0.0     0  -0.75    0  
 1   0.75    0.8     1   0.00    1  
 2   1.50    1.5     2   0.75    2  
 3   2.25    2.2     2   1.50    2  
 4   3.00    3.0     3   2.25  3    
 5   3.75    3.8     4   3.00   

// by the way evolution: 
// Is there any decent small integer library out there for that by now?

Why AVD Manager options are not showing in Android Studio

Here is a screenshot of me fixing this. I've encountered it many times, and it's always due to this config-related jazz:

  1. Click Event Log (bottom right)
  2. Click Configure of the Android Framework detected notification
  3. Done

enter image description here

If you do this and your icon still isn't lit up, then you probably need to set up the emulator still. I would recommend investigating the SDK Manager if so.

How to deal with certificates using Selenium?

Delete all but the necessary certificate from your browser's certificate store and then configure the browser to automatically select the certificate when only one certificate is present.

Check if list<t> contains any of another list

Here is a sample to find if there are match elements in another list

List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};

if (nums1.Any(x => nums2.Any(y => y == x)))
{
    Console.WriteLine("There are equal elements");
}
else
{
    Console.WriteLine("No Match Found!");
}

Escaping single quotes in JavaScript string for JavaScript evaluation

var str ="fsdsd'4565sd"; str.replace(/'/g,"'")

This worked for me. Kindly try this

enter image description here

"Javac" doesn't work correctly on Windows 10

Add java path to environment variables and move it to the top of all the paths available there. It worked for me.

How to refer to Excel objects in Access VBA?

Inside a module

Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook

sub Initialize()
   set objExcelApp = new Excel.Application
end sub

sub ProcessDataWorkbook()
    dim ws as Worksheet
    set wb = objExcelApp.Workbooks.Open("path to my workbook")
    set ws = wb.Sheets(1)

    ws.Cells(1,1).Value = "Hello"
    ws.Cells(1,2).Value = "World"

    'Close the workbook
    wb.Close
    set wb = Nothing
end sub

sub Release()
   set objExcelApp = Nothing
end sub

Error sending json in POST to web API service

It require to include Content-Type:application/json in web api request header section when not mention any content then by default it is Content-Type:text/plain passes to request.

Best way to test api on postman tool.

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

How to check if PHP array is associative or sequential?

After some local benchmarking, debugging, compiler probing, profiling, and abusing 3v4l.org to benchmark across more versions (yes, I got a warning to stop) and comparing against every variation I could find...

I give you an organically derived best-average-worst-case scenario associative array test function that is at worst roughly as good as or better than all other average-case scenarios.

/**
 * Tests if an array is an associative array.
 *
 * @param array $array An array to test.
 * @return boolean True if the array is associative, otherwise false.
 */
function is_assoc(array &$arr) {
    // don't try to check non-arrays or empty arrays
    if (FALSE === is_array($arr) || 0 === ($l = count($arr))) {
        return false;
    }

    // shortcut by guessing at the beginning
    reset($arr);
    if (key($arr) !== 0) {
        return true;
    }

    // shortcut by guessing at the end
    end($arr);
    if (key($arr) !== $l-1) {
        return true;
    }

    // rely on php to optimize test by reference or fast compare
    return array_values($arr) !== $arr;
}

From https://3v4l.org/rkieX:

<?php

// array_values
function method_1(Array &$arr) {
    return $arr === array_values($arr);
}

// method_2 was DQ; did not actually work

// array_keys
function method_3(Array &$arr) {
    return array_keys($arr) === range(0, count($arr) - 1);
}

// foreach
function method_4(Array &$arr) {
    $idx = 0;
    foreach( $arr as $key => $val ){
        if( $key !== $idx )
            return FALSE;
        ++$idx;
    }
    return TRUE;
}

// guessing
function method_5(Array &$arr) {
    global $METHOD_5_KEY;
    $i = 0;
    $l = count($arr)-1;

    end($arr);
    if ( key($arr) !== $l )
        return FALSE;

    reset($arr);
    do {
        if ( $i !== key($arr) )
            return FALSE;
        ++$i;
        next($arr);
    } while ($i < $l);
    return TRUE;
}

// naieve
function method_6(Array &$arr) {
    $i = 0;
    $l = count($arr);
    do {
        if ( NULL === @$arr[$i] )
            return FALSE;
        ++$i;
    } while ($i < $l);
    return TRUE;
}

// deep reference reliance
function method_7(Array &$arr) {
    return array_keys(array_values($arr)) === array_keys($arr);
}


// organic (guessing + array_values)
function method_8(Array &$arr) {
    reset($arr);
    if ( key($arr) !== 0 )
        return FALSE;

    end($arr);
    if ( key($arr) !== count($arr)-1 )
        return FALSE;

    return array_values($arr) === $arr;
}

function benchmark(Array &$methods, Array &$target, $expected){    
    foreach($methods as $method){
        $start = microtime(true);
        for ($i = 0; $i < 2000; ++$i) {
            //$dummy = call_user_func($method, $target);
            if ( $method($target) !== $expected ) {
                echo "Method $method is disqualified for returning an incorrect result.\n";
                unset($methods[array_search($method,$methods,true)]);
                $i = 0;
                break;
            }
        }
        if ( $i != 0 ) {
            $end = microtime(true);
            echo "Time taken with $method = ".round(($end-$start)*1000.0,3)."ms\n";
        }
    }
}



$true_targets = [
    'Giant array' => range(0, 500),
    'Tiny array' => range(0, 20),
];


$g = range(0,10);
unset($g[0]);

$false_targets = [
    'Large array 1' => range(0, 100) + ['a'=>'a'] + range(101, 200),
    'Large array 2' => ['a'=>'a'] + range(0, 200),
    'Tiny array' => range(0, 10) + ['a'=>'a'] + range(11, 20),
    'Gotcha array' => $g,
];

$methods = [
    'method_1',
    'method_3',
    'method_4',
    'method_5',
    'method_6',
    'method_7',
    'method_8'
];


foreach($false_targets as $targetName => $target){
    echo "==== Benchmark using $targetName expecing FALSE ====\n";
    benchmark($methods, $target, false);
    echo "\n";
}
foreach($true_targets as $targetName => $target){
    echo "==== Benchmark using $targetName expecting TRUE ====\n";
    benchmark($methods, $target, true);
    echo "\n";
}

What is sr-only in Bootstrap 3?

Ensures that the object is displayed (or should be) only to readers and similar devices. It give more sense in context with other element with attribute aria-hidden="true".

<div class="alert alert-danger" role="alert">
  <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
  <span class="sr-only">Error:</span>
  Enter a valid email address
</div>

Glyphicon will be displayed on all other devices, word Error: on text readers.

Python convert tuple to string

Easiest way would be to use join like this:

>>> myTuple = ['h','e','l','l','o']
>>> ''.join(myTuple)
'hello'

This works because your delimiter is essentially nothing, not even a blank space: ''.

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

Let's say you have an array of data:

n = [1    2   3   4   6   12  18  51  69  81  ]

then you can 'foreach' it like this:

for i = n, i, end

This will echo every element in n (but replacing the i with more interesting stuff is also possible of course!)

Doctrine 2 ArrayCollection filter method

Your use case would be :

    $ArrayCollectionOfActiveUsers = $customer->users->filter(function($user) {
                        return $user->getActive() === TRUE;
                    });

if you add ->first() you'll get only the first entry returned, which is not what you want.

@ Sjwdavies You need to put () around the variable you pass to USE. You can also shorten as in_array return's a boolean already:

    $member->getComments()->filter( function($entry) use ($idsToFilter) {
        return in_array($entry->getId(), $idsToFilter);
    });

Find and replace with sed in directory and sub directories

grep -e apple your_site_root/**/*.* -s -l | xargs sed -i "" "s|apple|orage|"

Makefile, header dependencies

Martin's solution above works great, but does not handle .o files that reside in subdirectories. Godric points out that the -MT flag takes care of that problem, but it simultaneously prevents the .o file from being written correctly. The following will take care of both of those problems:

DEPS := $(OBJS:.o=.d)

-include $(DEPS)

%.o: %.c
    $(CC) $(CFLAGS) -MM -MT $@ -MF $(patsubst %.o,%.d,$@) $<
    $(CC) $(CFLAGS) -o $@ $<

Understanding .get() method in Python

To understand what is going on, let's take one letter(repeated more than once) in the sentence string and follow what happens when it goes through the loop.

Remember that we start off with an empty characters dictionary

characters = {}

I will pick the letter 'e'. Let's pass the character 'e' (found in the word The) for the first time through the loop. I will assume it's the first character to go through the loop and I'll substitute the variables with their values:

for 'e' in "The quick brown fox jumped over the lazy dog.":
    {}['e'] = {}.get('e', 0) + 1 

characters.get('e', 0) tells python to look for the key 'e' in the dictionary. If it's not found it returns 0. Since this is the first time 'e' is passed through the loop, the character 'e' is not found in the dictionary yet, so the get method returns 0. This 0 value is then added to the 1 (present in the characters[character] = characters.get(character,0) + 1 equation). After completion of the first loop using the 'e' character, we now have an entry in the dictionary like this: {'e': 1}

The dictionary is now:

characters = {'e': 1}

Now, let's pass the second 'e' (found in the word jumped) through the same loop. I'll assume it's the second character to go through the loop and I'll update the variables with their new values:

for 'e' in "The quick brown fox jumped over the lazy dog.":
    {'e': 1}['e'] = {'e': 1}.get('e', 0) + 1

Here the get method finds a key entry for 'e' and finds its value which is 1. We add this to the other 1 in characters.get(character, 0) + 1 and get 2 as result.

When we apply this in the characters[character] = characters.get(character, 0) + 1 equation:

characters['e'] = 2

It should be clear that the last equation assigns a new value 2 to the already present 'e' key. Therefore the dictionary is now:

characters = {'e': 2}

Java rounding up to an int using Math.ceil

There are two methods by which you can round up your double value.

  1. Math.ceil
  2. Math.floor

If you want your answer 4.90625 as 4 then you should use Math.floor and if you want your answer 4.90625 as 5 then you can use Math.ceil

You can refer following code for that.

public class TestClass {

    public static void main(String[] args) {
        int floorValue = (int) Math.floor((double)157 / 32);
        int ceilValue = (int) Math.ceil((double)157 / 32);
        System.out.println("Floor: "+floorValue);
        System.out.println("Ceil: "+ceilValue);

    }

}

Update multiple rows in same query using PostgreSQL

I don't think the accepted answer is entirely correct. It is order dependent. Here is an example that will not work correctly with an approach from the answer.

create table xxx (
    id varchar(64),
    is_enabled boolean
);

insert into xxx (id, is_enabled) values ('1',true);
insert into xxx (id, is_enabled) values ('2',true);
insert into xxx (id, is_enabled) values ('3',true);

UPDATE public.xxx AS pns
        SET is_enabled         = u.is_enabled
            FROM (
            VALUES
         (
            '3',
            false
         ,
            '1',
            true
         ,
            '2',
            false
         )
        ) AS u(id, is_enabled)
            WHERE u.id = pns.id;

select * from xxx;

So the question still stands, is there a way to do it in an order independent way?

---- after trying a few things this seems to be order independent

UPDATE public.xxx AS pns
        SET is_enabled         = u.is_enabled
            FROM (
            SELECT '3' as id, false as is_enabled UNION
            SELECT '1' as id, true as is_enabled UNION
            SELECT '2' as id, false as is_enabled
         ) as u
            WHERE u.id = pns.id;

How to terminate script execution when debugging in Google Chrome?

If you are encountering this while using the debugger statement,

debugger;

... then I think the page will continue running forever until the js runtime yields, or the next break. Assuming you're in break-on-error mode (the pause-icon toggle), you can ensure a break happens by instead doing something like:

debugger;throw 1;

or maybe call a non-existent function:

debugger;z();

(Of course this doesn't help if you are trying to step through functions, though perhaps you could dynamically add in a throw 1 or z() or somesuch in the Sources panel, ctrl-S to save, and then ctrl-R to refresh... this may however skip one breakpoint, but may work if you're in a loop.)

If you are doing a loop and expect to trigger the debugger statement again, you could just type throw 1 instead.

throw 1;

Then when you hit ctrl-R, the next throw will be hit, and the page will refresh.

(tested with Chrome v38, circa Apr 2017)

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

I was facing same problem when I installed JRE by Oracle and solved this problem after my research.

I moved the environment path C:\Program Files (x86)\Common Files\Oracle\Java\javapath below H:\Program Files\Java\jdk-13.0.1\bin

Like this:

Path

H:\Program Files\Java\jdk-13.0.1\bin
C:\Program Files (x86)\Common Files\Oracle\Java\javapath

OR

Path

%JAVA_HOME%
%JRE_HOME%

How can I programmatically generate keypress events in C#?

I've not used it, but SendKeys may do what you want.

Use SendKeys to send keystrokes and keystroke combinations to the active application. This class cannot be instantiated. To send a keystroke to a class and immediately continue with the flow of your program, use Send. To wait for any processes started by the keystroke, use SendWait.

System.Windows.Forms.SendKeys.Send("A");
System.Windows.Forms.SendKeys.Send("{ENTER}");

Microsoft has some more usage examples here.

Giving a border to an HTML table row, <tr>

_x000D_
_x000D_
<table cellpadding="0" cellspacing="0" width="100%" style="border: 1px;" rules="none">_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <th style="width: 96px;">Column 1</th>_x000D_
            <th style="width: 96px;">Column 2</th>_x000D_
            <th style="width: 96px;">Column 3</th>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
            <td style="border-left: thin solid; border-top: thin solid; border-bottom: thin solid;">&nbsp;</td>_x000D_
            <td style="border-top: thin solid; border-bottom: thin solid;">&nbsp;</td>_x000D_
            <td style="border-top: thin solid; border-bottom: thin solid; border-right: thin solid;">&nbsp;</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Bootstrap 3.0 Popovers and tooltips

You have a syntax error in your script and, as noted by xXPhenom22Xx, you must instantiate the tooltip.

<script type="text/javascript">

    $(document).ready(function() {

        $('.btn-danger').tooltip();

    }); //END $(document).ready()

</script>

Note that I used your class "btn-danger". You can create a different class, or use an id="someidthatimakeup".

How to stop a setTimeout loop?

setTimeout returns a timer handle, which you can use to stop the timeout with clearTimeout.

So for instance:

function setBgPosition() {
    var c = 0,
        timer = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c >= numbers.length) {
            c = 0;
        }
        timer = setTimeout(run, 200);
    }
    timer = setTimeout(run, 200);

    return stop;

    function stop() {
        if (timer) {
            clearTimeout(timer);
            timer = 0;
        }
}

So you'd use that as:

var stop = setBgPosition();
// ...later, when you're ready to stop...
stop();

Note that rather than having setBgPosition call itself again, I've just had it set c back to 0. Otherwise, this wouldn't work. Also note that I've used 0 as a handle value for when the timeout isn't pending; 0 isn't a valid return value from setTimeout so it makes a handy flag.

This is also one of the (few) places I think you'd be better off with setInterval rather than setTimeout. setInterval repeats. So:

function setBgPosition() {
    var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c >= numbers.length) {
            c = 0;
        }
    }
    return setInterval(run, 200);
}

Used like this:

var timer = setBgPosition();
// ...later, when you're ready to stop...
clearInterval(timer);

All of the above notwithstanding, I'd want to find a way to make setBgPosition stop things itself, by detecting that some completion condition has been satisfied.

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

My approach was:

openssl version
OpenSSL 1.0.1e 11 Feb 2013

wget https://www.openssl.org/source/openssl-1.0.2a.tar.gz
wget http://www.linuxfromscratch.org/patches/blfs/svn/openssl-1.0.2a-fix_parallel_build-1.patch
tar xzf openssl-1.0.2a.tar.gz
cd openssl-1.0.2a
patch -Np1 -i ../openssl-1.0.2a-fix_parallel_build-1.patch
./config --prefix=/usr --openssldir=/etc/ssl --libdir=lib shared zlib-dynamic
make
make install

openssl version
OpenSSL 1.0.2a 19 Mar 2015 

How to check if string contains Latin characters only?

No jQuery Needed

if (str.match(/[a-z]/i)) {
    // alphabet letters found
}

What are bitwise shift (bit-shift) operators and how do they work?

Note that in the Java implementation, the number of bits to shift is mod'd by the size of the source.

For example:

(long) 4 >> 65

equals 2. You might expect shifting the bits to the right 65 times would zero everything out, but it's actually the equivalent of:

(long) 4 >> (65 % 64)

This is true for <<, >>, and >>>. I have not tried it out in other languages.

Node.js get file extension

Update

Since the original answer, extname() has been added to the path module, see Snowfish answer

Original answer:

I'm using this function to get a file extension, because I didn't find a way to do it in an easier way (but I think there is) :

function getExtension(filename) {
    var ext = path.extname(filename||'').split('.');
    return ext[ext.length - 1];
}

you must require 'path' to use it.

another method which does not use the path module :

function getExtension(filename) {
    var i = filename.lastIndexOf('.');
    return (i < 0) ? '' : filename.substr(i);
}

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

matplotlib error - no module named tkinter

Almost all answers I searched for this issue say that Python on Windows comes with tkinter and tcl already installed, and I had no luck trying to download or install them using pip, or actviestate.com site. I eventually found that when I was installing python using the binary installer, I had unchecked the module related to TCL and tkinter. So, I ran the binary installer again and chose to modify my python version by this time selecting this option. No need to do anything manually then. If you go to your python terminal, then the following commands should show you version of tkinter installed with your Python:

import tkinter
import _tkinter
tkinter._test()

Fling gesture detection on grid layout

There's some proposition over the web (and this page) to use ViewConfiguration.getScaledTouchSlop() to have a device-scaled value for SWIPE_MIN_DISTANCE.

getScaledTouchSlop() is intended for the "scrolling threshold" distance, not swipe. The scrolling threshold distance has to be smaller than a "swing between page" threshold distance. For example, this function returns 12 pixels on my Samsung GS2, and the examples quoted in this page are around 100 pixels.

With API Level 8 (Android 2.2, Froyo), you've got getScaledPagingTouchSlop(), intended for page swipe. On my device, it returns 24 (pixels). So if you're on API Level < 8, I think "2 * getScaledTouchSlop()" should be the "standard" swipe threshold. But users of my application with small screens told me that it was too few... As on my application, you can scroll vertically, and change page horizontally. With the proposed value, they sometimes change page instead of scrolling.

Using the rJava package on Win7 64 bit with R

Sorry for necro. I have too run into the same issue and found out that rJava expects JAVA_HOME to point to JRE. If you have JDK installed, most probably your JAVA_HOME points to JDK. My quick solution:

Sys.setenv(JAVA_HOME=paste(Sys.getenv("JAVA_HOME"), "jre", sep="\\"))

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

You should add reference to "Microsoft.AspNet.WebApi.Client" package (read this article for samples).

Without any additional extension, you may use standard PostAsync method:

client.PostAsync(uri, new StringContent(jsonInString, Encoding.UTF8, "application/json"));

where jsonInString value you can get by calling JsonConvert.SerializeObject(<your object>);

File URL "Not allowed to load local resource" in the Internet Browser

You just need to replace all image network paths to byte strings in HTML string. For this first you required HtmlAgilityPack to convert Html string to Html document. https://www.nuget.org/packages/HtmlAgilityPack

Find Below code to convert each image src network path(or local path) to byte sting. It will definitely display all images with network path(or local path) in IE,chrome and firefox.

string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString();

        // Decode the encoded string.
        StringWriter myWriter = new StringWriter();
        HttpUtility.HtmlDecode(encodedHtmlString, myWriter);
        string DecodedHtmlString = myWriter.ToString();

        //find and replace each img src with byte string
         HtmlDocument document = new HtmlDocument();
         document.LoadHtml(DecodedHtmlString);
         document.DocumentNode.Descendants("img")
          .Where(e =>
        {
            string src = e.GetAttributeValue("src", null) ?? "";
            return !string.IsNullOrEmpty(src);//&& src.StartsWith("data:image");
        })
        .ToList()
                    .ForEach(x =>
                    {
                        string currentSrcValue = x.GetAttributeValue("src", null);                                
                        string filePath = Path.GetDirectoryName(currentSrcValue) + "\\";
                        string filename = Path.GetFileName(currentSrcValue);
                        string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
                        FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
                        BinaryReader br = new BinaryReader(fs);
                        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                        br.Close();
                        fs.Close();
                        x.SetAttributeValue("src", "data:" + contenttype + ";base64," + Convert.ToBase64String(bytes));                                
                    });

        string result = document.DocumentNode.OuterHtml;
        //Encode HTML string
        string myEncodedString = HttpUtility.HtmlEncode(result);

        Emailmodel.DtEmailFields.Rows[0]["Body"] = myEncodedString;

Mysql command not found in OS X 10.7

Maybe I'll help someone else. None of the above answers worked for Catalina. Finally, this solved the problem

echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> /Users/$(whoami)/.bash_profile

Of course, you have to change for the version of mysql you have installed

Set background color in PHP?

CSS supports text input for colors (i.e. "black" = #000000 "white" = #ffffff) So I think the helpful solution we are looking for here is how can one have PHP take the output from an HTML form text input box and have it tell CSS to use this line of text for background color.

So that when a a user types "blue" into the text field titled "what is your favorite color", they are returned a page with a blue background, or whatever color they happen to type in so long as it is recognized by CSS.

I believe Dan is on the right track, but may need to elaborate for use PHP newbies, when I try this I am returned a green screen no matter what is typed in (I even set this up as an elseif to display a white background if no data is entered in the text field, still green?

Is there a GUI design app for the Tkinter / grid geometry?

The best tool for doing layouts using grid, IMHO, is graph paper and a pencil. I know you're asking for some type of program, but it really does work. I've been doing Tk programming for a couple of decades so layout comes quite easily for me, yet I still break out graph paper when I have a complex GUI.

Another thing to think about is this: The real power of Tkinter geometry managers comes from using them together*. If you set out to use only grid, or only pack, you're doing it wrong. Instead, design your GUI on paper first, then look for patterns that are best solved by one or the other. Pack is the right choice for certain types of layouts, and grid is the right choice for others. For a very small set of problems, place is the right choice. Don't limit your thinking to using only one of the geometry managers.

* The only caveat to using both geometry managers is that you should only use one per container (a container can be any widget, but typically it will be a frame).

Vim 80 column layout concerns

Simon Howard's answer is great. But /\%81v.\+/ fails to highlight tabs that exceed column 81 . So I did a little tweak, based on the stuff I found on VIM wiki and HS's choice of colors above:

highlight OverLength ctermbg=darkred ctermfg=white guibg=#FFD9D9
match OverLength /\%>80v.\+/

And now VIM will highlight anything that exceeds column 80.

Node.js global variables

The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.

Use a JavaScript file and then use module exports.

Example:

File globals.js

var Globals = {
    'domain':'www.MrGlobal.com';
}

module.exports = Globals;

Then if you want to use these, use require.

var globals = require('globals'); // << globals.js path
globals.domain // << Domain.

How to check size of a file using Bash?

Based on gniourf_gniourf’s answer,

find "file.txt" -size -90k

will write file.txt to stdout if and only if the size of file.txt is less than 90K, and

find "file.txt" -size -90k -exec command \;

will execute the command command if file.txt has a size less than 90K.  I have tested this on Linux.  From find(1),

…  Command-line arguments following (the -H, -L and -P options) are taken to be names of files or directories to be examined, up to the first argument that begins with ‘-’, …

(emphasis added).

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

As pointed out, Do not use Windows Authentication, Use SQL Server Authentication

Also if you created connection using "Server Connection" dialog, make sure to check the connections in web.config. It is likely that you created/modified connection and it was stored as trusted connection in web.config. Simply use this authentication

<add name="MyDBConnectionString" connectionString="Data Source=localhost;Initial Catalog=Finantial;User ID=xxx;Password=xxx" providerName="System.Data.SqlClient"/>

which should fix the error.

How to correctly use the ASP.NET FileUpload control

My solution in code behind was:

System.Web.UI.WebControls.FileUpload fileUpload;

I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

What worked for me tho is this library https://pypi.org/project/silence-tensorflow/

Install this library and do as instructed on the page, it works like a charm!

Getting a directory name from a filename

Using Boost.Filesystem:

boost::filesystem::path p("C:\\folder\\foo.txt");
boost::filesystem::path dir = p.parent_path();

How to commit changes to a new branch

If you haven't committed changes

If your changes are compatible with the other branch

This is the case from the question because the OP wants to commit to a new branch and also applies if your changes are compatible with the target branch without triggering an overwrite.

As in the accepted answer by John Brodie, you can simply checkout the new branch and commit the work:

git checkout -b branch_name
git add <files>
git commit -m "message"

If your changes are incompatible with the other branch

If you get the error:

error: Your local changes to the following files would be overwritten by checkout:
...
Please commit your changes or stash them before you switch branches

Then you can stash your work, create a new branch, then pop your stash changes, and resolve the conflicts:

git stash
git checkout -b branch_name
git stash pop

It will be as if you had made those changes after creating the new branch. Then you can commit as usual:

git add <files>
git commit -m "message"

If you have committed changes

If you want to keep the commits in the original branch

See the answer by Carl Norum with cherry-picking, which is the right tool in this case:

git checkout <target name>
git cherry-pick <original branch>

If you don't want to keep the commits in the original branch

See the answer by joeytwiddle on this potential duplicate. Follow any of the above steps as appropriate, then roll back the original branch:

git branch -f <original branch> <earlier commit id>

If you have pushed your changes to a shared remote like GitHub, you should not attempt this roll-back unless you know what you are doing.

How to get the top position of an element?

If you want the position relative to the document then:

$("#myTable").offset().top;

but often you will want the position relative to the closest positioned parent:

$("#myTable").position().top;

How to calculate percentage with a SQL statement

In any sql server version you could use a variable for the total of all grades like this:

declare @countOfAll decimal(18, 4)
select @countOfAll = COUNT(*) from Grades

select
Grade,  COUNT(*) / @countOfAll * 100
from Grades
group by Grade

Best practices for styling HTML emails

Campaign Monitor have an excellent support matrix detailing what's supported and what isn't among various mail clients.

You can use a service like Litmus to view how an email appears across several clients and whether they get caught by filters, etc.

no module named zlib

I had a lot of problems making a virtual environment (venv) as described in the tensorflow installation guide.

Most of the commands listed in this post didn't help me either so, if this is also your case this is what I did:

  1. pip3 install --user pipenv
  2. pip install virtualenv

Installs the dependencies to create a virtual environment

  1. mkdir myenv

Makes a new directory called myenv but you can call it whatever you want e.g. mynewenv

  1. cd myenv

Or whatever you call your directory so: cd [your_directory_name]

  1. virtualenv -p /usr/bin/python3 venv

Creates a virtual environment called venv in the folder myenv. You can call your virtual env whatever you like e.g. vitualenv [v_env_name]

  1. source ./venv/bin/activate

Activates the virtual environment. Note that if you choose a different v. env. name your commands should be written as such source ./[v_env_name]/bin/activate

  1. deactivate

Deactivates the virtual environment.

Note: I am using Python 3.6.6 & Ubuntu 18.04

source for the commands

AttributeError: 'tuple' object has no attribute

I am working in python flask: I had the same problem... There was a "," after I declared my my form variables; I am working with wtforms. That is what caused all the confusion

Getting the index of a particular item in array

     int i=  Array.IndexOf(temp1,  temp1.Where(x=>x.Contains("abc")).FirstOrDefault());

What is ViewModel in MVC?

ViewModel is workaround that patches the conceptual clumsiness of the MVC framework. It represents the 4th layer in the 3-layer Model-View-Controller architecture. when Model (domain model) is not appropriate, too big (bigger than 2-3 fields) for the View, we create smaller ViewModel to pass it to the View.

How to remove all files from directory without removing directory in Node.js

Yes, there is a module fs-extra. There is a method .emptyDir() inside this module which does the job. Here is an example:

const fsExtra = require('fs-extra')

fsExtra.emptyDirSync(fileDir)

There is also an asynchronous version of this module too. Anyone can check out the link.

iOS: set font size of UILabel Programmatically

In Swift 3.0, you could use this code below:

let textLabel = UILabel(frame: CGRect(x:containerView.frame.width/2 - 35, y: 
    containerView.frame.height/2 + 10, width: 70, height: 20))
    textLabel.text = "Add Text"
    textLabel.font = UIFont(name: "Helvetica", size: 15.0) // set fontName and Size
    textLabel.textAlignment = .center
    containerView.addSubview(textLabel) // containerView is a UIView

error MSB6006: "cmd.exe" exited with code 1

Navigate from Error List Tab to the Visual Studios Output folder by one of the following:

  • Select tab Output in standard VS view at the bottom
  • Click in Menubar View > Output or Ctrl+Alt+O

where Show output from <build> should be selected.

You can find out more by analyzing the output logs.


In my case it was an error in the Cmake step, see below. It could be in any build step, as described in the other answers.

> -- Build Type is debug 
> CMake Error in CMakeLists.txt:
>     A logical block opening on the line
>     <path_to_file:line_number>    
>     is not closed.

Unable to set variables in bash script

here's your amended script

#!/bin/bash    
folder="ABC" #no spaces between assignment    
useracct='test'    
day=$(date "+%d") # use $() to assign return value of date command to variable    
month=$(date "+%B")     
year=$(date "+%Y")    
folderToBeMoved="/users/$useracct/Documents/Archive/Primetime.eyetv"    
newfoldername="/Volumes/Media/Network/$folder/$month$day$year"    
ECHO "Network is $network" $network    
ECHO "day is $day"    
ECHO "Month is $month"    
ECHO "YEAR is $year"    
ECHO "source is $folderToBeMoved"    
ECHO "dest is $newfoldername"    

mkdir "$newfoldername"    
cp -R "$folderToBeMoved" "$newfoldername"
if [ -f "$newfoldername/Primetime.eyetv" ]; then # <-- put a space at square brackets and quote your variables.
 rm "$folderToBeMoved";
fi

Get second child using jQuery

How's this:

$(t).first().next()

MAJOR UPDATE:

Apart from how beautiful the answer looks, you must also give a thought to the performance of the code. Therefore, it is also relavant to know what exactly is in the $(t) variable. Is it an array of <TD> or is it a <TR> node with several <TD>s inside it? To further illustrate the point, see the jsPerf scores on a <ul> list with 50 <li> children:

http://jsperf.com/second-child-selector

The $(t).first().next() method is the fastest here, by far.

But, on the other hand, if you take the <tr> node and find the <td> children and and run the same test, the results won't be the same.

Hope it helps. :)

Why does sed not replace all occurrences?

You have to put a g at the end, it stands for "global":

echo dog dog dos | sed -r 's:dog:log:g'
                                     ^

How to delete a cookie using jQuery?

You can try this:

$.removeCookie('the_cookie', { path: '/' });

source: https://github.com/carhartl/jquery-cookie#readme

Kill python interpeter in linux from the terminal

pgrep -f youAppFile.py | xargs kill -9

pgrep returns the PID of the specific file will only kill the specific application.

Programmatically getting the MAC of an Android device

Its Working with Marshmallow

package com.keshav.fetchmacaddress;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.e("keshav","getMacAddr -> " +getMacAddr());
    }

    public static String getMacAddr() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(Integer.toHexString(b & 0xFF) + ":");
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            //handle exception
        }
        return "";
    }
}

What is the purpose of backbone.js?

JQuery and Mootools are just a toolbox with lot of tools of your project. Backbone acts like an architecture or a backbone for your project on which you can build an application using JQuery or Mootools.

How do I format a date in VBA with an abbreviated month?

I'm using

Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"

to format a column

So I guess

Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"

would do the trick for you.

More: NumberFormat function.

SQL alias for SELECT statement

Yes, but you can select only one column in your subselect

SELECT (SELECT id FROM bla) AS my_select FROM bla2

How can I install Python's pip3 on my Mac?

Similar to Oksana but add python3

$ brew rm python 
$ brew rm python3 
$ rm -rf /usr/local/opt/python
$ rm -rf /usr/local/opt/python3
$ brew prune 
$ brew install python3
$ brew postinstall python3

Seem now work for pip3 under mac os x 10.13.3 Xcode 9.2

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Handy for linux virtual machines; Use 75% of your total system memory for Tomcat. Yay AWK.

Put at start of "{tomcat}/bin/startup.sh"

export CATALINA_OPTS="-Xmx`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`k"

Creating a LinkedList class from scratch

How about a fully functional implementation of a non-recursive Linked List?

I created this for my Algorithms I class as a stepping stone to gain a better understanding before moving onto writing a doubly-linked queue class for an assignment.

Here's the code:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedList<T> implements Iterable<T> {
    private Node first;
    private Node last;
    private int N;

    public LinkedList() {
        first = null;
        last = null;
        N = 0;
    }

    public void add(T item) {
        if (item == null) { throw new NullPointerException("The first argument for addLast() is null."); }
        if (!isEmpty()) {
            Node prev = last;
            last = new Node(item, null);
            prev.next = last;
        }
        else {
            last = new Node(item, null);
            first = last;
        }
        N++;
    }

    public boolean remove(T item) {
        if (isEmpty()) { throw new IllegalStateException("Cannot remove() from and empty list."); }
        boolean result = false;
        Node prev = first;
        Node curr = first;
        while (curr.next != null || curr == last) {
            if (curr.data.equals(item)) {
                // remove the last remaining element
                if (N == 1) { first = null; last = null; }
                // remove first element
                else if (curr.equals(first)) { first = first.next; }
                // remove last element
                else if (curr.equals(last)) { last = prev; last.next = null; }
                // remove element
                else { prev.next = curr.next; }
                N--;
                result = true;
                break;
            }
            prev = curr;
            curr = prev.next;
        }
        return result;
    }

    public int size() {
        return N;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    private class Node {
        private T data;
        private Node next;

        public Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }
    }

    public Iterator<T> iterator() { return new LinkedListIterator(); }

    private class LinkedListIterator implements Iterator<T> {
        private Node current = first;

        public T next() {
            if (!hasNext()) { throw new NoSuchElementException(); }
            T item = current.data;
            current = current.next;
            return item;
        }

        public boolean hasNext() { return current != null; }

        public void remove() { throw new UnsupportedOperationException(); }
    }

    @Override public String toString() {
        StringBuilder s = new StringBuilder();
        for (T item : this)
            s.append(item + " ");
        return s.toString();
    }

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        while(!StdIn.isEmpty()) {
            String input = StdIn.readString();
            if (input.equals("print")) { StdOut.println(list.toString()); continue; }
            if (input.charAt(0) == ('+')) { list.add(input.substring(1)); continue; }
            if (input.charAt(0) == ('-')) { list.remove(input.substring(1)); continue; }
            break;
        }
    }
}

Note: It's a pretty basic implementation of a singly-linked-list. The 'T' type is a generic type placeholder. Basically, this linked list should work with any type that inherits from Object. If you use it for primitive types be sure to use the nullable class equivalents (ex 'Integer' for the 'int' type). The 'last' variable isn't really necessary except that it shortens insertions to O(1) time. Removals are slow since they run in O(N) time but it allows you to remove the first occurrence of a value in the list.

If you want you could also look into implementing:

  • addFirst() - add a new item to the beginning of the LinkedList
  • removeFirst() - remove the first item from the LinkedList
  • removeLast() - remove the last item from the LinkedList
  • addAll() - add a list/array of items to the LinkedList
  • removeAll() - remove a list/array of items from the LinkedList
  • contains() - check to see if the LinkedList contains an item
  • contains() - clear all items in the LinkedList

Honestly, it only takes a few lines of code to make this a doubly-linked list. The main difference between this and a doubly-linked-list is that the Node instances of a doubly-linked list require an additional reference that points to the previous element in the list.

The benefit of this over a recursive implementation is that it's faster and you don't have to worry about flooding the stack when you traverse large lists.

There are 3 commands to test this in the debugger/console:

  • Prefixing a value by a '+' will add it to the list.
  • Prefixing with a '-' will remove the first occurrence from the list.
  • Typing 'print' will print out the list with the values separated by spaces.

If you have never seen the internals of how one of these works I suggest you step through the following in the debugger:

  • add() - tacks a new node onto the end or initializes the first/last values if the list is empty
  • remove() - walks the list from the start-to-end. If it finds a match it removes that item and connects the broken links between the previous and next links in the chain. Special exceptions are added when there is no previous or next link.
  • toString() - uses the foreach iterator to simply walk the list chain from beginning-to-end.

While there are better and more efficient approaches for lists like array-lists, understanding how the application traverses via references/pointers is integral to understanding how many higher-level data structures work.

Singleton design pattern vs Singleton beans in Spring container

Singleton scope in spring means single instance in a Spring context ..
Spring container merely returns the same instance again and again for subsequent calls to get the bean.


And spring doesn't bother if the class of the bean is coded as singleton or not , in fact if the class is coded as singleton whose constructor as private, Spring use BeanUtils.instantiateClass (javadoc here) to set the constructor to accessible and invoke it.

Alternatively, we can use a factory-method attribute in bean definition like this

    <bean id="exampleBean" class="example.Singleton"  factory-method="getInstance"/>

Android Camera Preview Stretched

@Hesam 's answer is correct, CameraPreview will work in all portrait devices, but if the device is in landscape mode or in multi-window mode, this code is working perfect, just replace onMeasure()

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
    setMeasuredDimension(width, height);

    int rotation = ((Activity) mContext).getWindowManager().getDefaultDisplay().getRotation();
    if ((Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {//portrait
        mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, height, width);
    } else
        mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);//landscape

    if (mPreviewSize == null) return;
    float ratio;
    if (mPreviewSize.height >= mPreviewSize.width) {
        ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
    } else ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && ((Activity) mContext).isInMultiWindowMode()) {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ||
                !(Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {
            setMeasuredDimension(width, (int) (width / ratio));
        } else {
            setMeasuredDimension((int) (height / ratio), height);
        }
    } else {
        if ((Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {
            Log.e("---", "onMeasure: " + height + " - " + width * ratio);
            //2264 - 2400.0 pix c -- yes
            //2240 - 2560.0 samsung -- yes
            //1582 - 1440.0 pix 2 -- no
            //1864 - 2048.0 sam tab -- yes
            //848 - 789.4737 iball -- no
            //1640 - 1600.0 nexus 7 -- no
            //1093 - 1066.6667 lenovo -- no
            //if width * ratio is > height, need to minus toolbar height
           if ((width * ratio) < height)
                setMeasuredDimension(width, (int) (width * ratio));
            else
                setMeasuredDimension(width, (int) (width * ratio) - toolbarHeight);
        } else {
            setMeasuredDimension((int) (height * ratio), height);
        }
    }
    requestLayout();
}

Should functions return null or an empty object?

I prefer null, since it's compatible with the null-coalescing operator (??).

How to execute powershell commands from a batch file?

This is what the code would look like in a batch file(tested, works):

powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"

Based on the information from:

http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/

Proper usage of Optional.ifPresent()

Why write complicated code when you could make it simple?

Indeed, if you are absolutely going to use the Optional class, the most simple code is what you have already written ...

if (user.isPresent())
{
    doSomethingWithUser(user.get());
}

This code has the advantages of being

  1. readable
  2. easy to debug (breakpoint)
  3. not tricky

Just because Oracle has added the Optional class in Java 8 doesn't mean that this class must be used in all situation.

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

Spring cron expression for every after 30 minutes

Graphically, the cron syntax for Quarz is (source):

+-------------------- second (0 - 59)
|  +----------------- minute (0 - 59)
|  |  +-------------- hour (0 - 23)
|  |  |  +----------- day of month (1 - 31)
|  |  |  |  +-------- month (1 - 12)
|  |  |  |  |  +----- day of week (0 - 6) (Sunday=0 or 7)
|  |  |  |  |  |  +-- year [optional]
|  |  |  |  |  |  |
*  *  *  *  *  *  * command to be executed 

So if you want to run a command every 30 minutes you can say either of these:

0 0/30 * * * * ?
0 0,30 * * * * ?

You can check crontab expressions using either of these:

  • crontab.guru — (disclaimer: I am not related to that page at all, only that I find it very useful). This page uses UNIX style of cron that does not have seconds in it, while Spring does as the first field.
  • Cron Expression Generator & Explainer - Quartz — cron formatter, allowing seconds also.

Add/remove class with jquery based on vertical scroll?

For Android mobile $(window).scroll(function() and $(document).scroll(function() may or may not work. So instead use the following.

jQuery(document.body).scroll(function() {
        var scroll = jQuery(document.body).scrollTop();

        if (scroll >= 300) {
            //alert();
            header.addClass("sticky");
        } else {
            header.removeClass('sticky');
        }
    });

This code worked for me. Hope it will help you.

java.io.IOException: Server returned HTTP response code: 500

The problem must be with the parameters you are passing(You must be passing blank parameters). For example : http://www.myurl.com?id=5&name= Check if you are handling this at the server you are calling.

Converting char[] to byte[]

private static byte[] charArrayToByteArray(char[] c_array) {
        byte[] b_array = new byte[c_array.length];
        for(int i= 0; i < c_array.length; i++) {
            b_array[i] = (byte)(0xFF & (int)c_array[i]);
        }
        return b_array;
}

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.

bower proxy configuration

Are you using Windows? Just set the environment variable http_proxy...

set http_proxy=http://your-proxy-address.com:port

... and bower will pick this up. Rather than dealing with a unique config file in your project folder - right? (side-note: when-the-F! will windows allow us to create a .file using explorer? c'mon windows!)

What is the difference between association, aggregation and composition?

As others said, an association is a relationship between objects, aggregation and composition are types of association.

From an implementation point of view, an aggregation is obtained by having a class member by reference. For example, if class A aggregates an object of class B, you'll have something like this (in C++):

class A {
    B & element;
  // or B * element;
};

The semantics of aggregation is that when an object A is destroyed, the B object it is storing will still exists. When using composition, you have a stronger relationship, usually by storing the member by value:

class A {
    B element;
};

Here, when an A object is destroyed, the B object it contains will be destroyed too. The easiest way to achieve this is by storing the member by value, but you could also use some smart pointer, or delete the member in the destructor:

class A {
    std::auto_ptr<B> element;
};

class A {
    B * element;

    ~A() {
        delete B;
    }
};

The important point is that in a composition, the container object owns the contained one, whereas in aggregation, it references it.

Set timeout for ajax (jQuery)

You could use the timeout setting in the ajax options like this:

$.ajax({
    url: "test.html",
    timeout: 3000,
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/

Remember that when a timeout occurs, the error handler is triggered and not the success handler :)

Issue with background color in JavaFX 8

panel.setStyle("-fx-background-color: #FFFFFF;");

docker: "build" requires 1 argument. See 'docker build --help'

In case anyone is running into this problem when trying to tag -t the image and also build it from a file that is NOT named Dockerfile (i.e. not using simply the . path), you can do it like this:

docker build -t my_image -f my_dockerfile .

Notice that docker expects a directory as the parameter and the filename as an option.

Format Date output in JSF

Use <f:convertDateTime>. You can nest this in any input and output component. Pattern rules are same as java.text.SimpleDateFormat.

<h:outputText value="#{someBean.dateField}" >
    <f:convertDateTime pattern="dd.MM.yyyy HH:mm" />
</h:outputText>

How do I use reflection to invoke a private method?

And if you really want to get yourself in trouble, make it easier to execute by writing an extension method:

static class AccessExtensions
{
    public static object call(this object o, string methodName, params object[] args)
    {
        var mi = o.GetType ().GetMethod (methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
        if (mi != null) {
            return mi.Invoke (o, args);
        }
        return null;
    }
}

And usage:

    class Counter
    {
        public int count { get; private set; }
        void incr(int value) { count += value; }
    }

    [Test]
    public void making_questionable_life_choices()
    {
        Counter c = new Counter ();
        c.call ("incr", 2);             // "incr" is private !
        c.call ("incr", 3);
        Assert.AreEqual (5, c.count);
    }

Template not provided using create-react-app

Using the command npm uninstall -g create-react-app didn't work for me.

But this worked:

yarn global remove create-react-app

and then:

npx create-react-app my-app

MySQL "between" clause not inclusive?

select * from person where DATE(dob) between '2011-01-01' and '2011-01-31'

Surprisingly such conversions are solutions to many problems in MySQL.

How to save LogCat contents to file?

To save the Log cat content to the file, you need to redirect to the android sdk's platform tools folder and hit the below command

adb logcat > logcat.txt

In Android Studio, version 3.6RC1, file will be created of the name "logcat.txt" in respective project folder. you can change the name according to your interest. enjoy

jquery remove "selected" attribute of option?

Well, I spent a lot of time on this issue. To get an answer working with Chrome AND IE, I had to change my approach. The idea is to avoid removing the selected option (because cannot remove it properly with IE). => this implies to select option not by adding or setting the selected attribute on the option, but to choose an option at the "select" level using the selectedIndex prop.

Before :

$('#myselect option:contains("value")').attr('selected','selected');
$('#myselect option:contains("value")').removeAttr('selected'); => KO with IE

After :

$('#myselect').prop('selectedIndex', $('#myselect option:contains("value")').index());
$('#myselect').prop('selectedIndex','-1'); => OK with all browsers

Hope it will help

What does body-parser do with express?

Yes we can work without body-parser. When you don't use that you get the raw request, and your body and headers are not in the root object of request parameter . You will have to individually manipulate all the fields.

Or you can use body-parser, as the express team is maintaining it .

What body-parser can do for you: It simplifies the request.
How to use it: Here is example:

Install npm install body-parser --save

This how to use body-parser in express:

const express = require('express'),
      app = express(),
      bodyParser = require('body-parser');

// support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

Link.

https://github.com/expressjs/body-parser.

And then you can get body and headers in root request object . Example

app.post("/posturl",function(req,res,next){
    console.log(req.body);
    res.send("response");
})

SQL conditional SELECT

You want the CASE statement:

SELECT
  CASE 
    WHEN @SelectField1 = 1 THEN Field1
    WHEN @SelectField2 = 1 THEN Field2
    ELSE NULL
  END AS NewField
FROM Table

EDIT: My example is for combining the two fields into one field, depending on the parameters supplied. It is a one-or-neither solution (not both). If you want the possibility of having both fields in the output, use Quassnoi's solution.

Multi-gradient shapes

You can layer gradient shapes in the xml using a layer-list. Imagine a button with the default state as below, where the second item is semi-transparent. It adds a sort of vignetting. (Please excuse the custom-defined colours.)

<!-- Normal state. -->
<item>
    <layer-list>
        <item>  
            <shape>
                <gradient 
                    android:startColor="@color/grey_light"
                    android:endColor="@color/grey_dark"
                    android:type="linear"
                    android:angle="270"
                    android:centerColor="@color/grey_mediumtodark" />
                <stroke
                    android:width="1dp"
                    android:color="@color/grey_dark" />
                <corners
                    android:radius="5dp" />
            </shape>
        </item>
        <item>  
            <shape>
                <gradient 
                    android:startColor="#00666666"
                    android:endColor="#77666666"
                    android:type="radial"
                    android:gradientRadius="200"
                    android:centerColor="#00666666"
                    android:centerX="0.5"
                    android:centerY="0" />
                <stroke
                    android:width="1dp"
                    android:color="@color/grey_dark" />
                <corners
                    android:radius="5dp" />
            </shape>
        </item>
    </layer-list>
</item>

SQL Server command line backup statement

Here's an example you can run as a batch script (copy-paste into a .bat file), using the SQLCMD utility in Sql Server client tools:

BACKUP:

echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:

:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%DATE:~-4%.%DATE:~7,2%.%DATE:~4,2%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=your server name here
echo.

sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause

RESTORE:

echo off
cls
echo -- RESTORE DATABASE --
set /p BACKUPFILENAME=Enter backup file name:%CD%\
set /p DATABASENAME=Enter database name:
set SERVERNAME=your server name here
sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"

:: WARNING - delete the database, suits me
:: sqlcmd -E -S %SERVERNAME% -d master -Q "IF EXISTS (SELECT * FROM sysdatabases WHERE name=N'%DATABASENAME%' ) DROP DATABASE [%DATABASENAME%]"
:: sqlcmd -E -S %SERVERNAME% -d master -Q "CREATE DATABASE [%DATABASENAME%]"

:: restore
sqlcmd -E -S %SERVERNAME% -d master -Q "RESTORE DATABASE [%DATABASENAME%] FROM DISK = N'%CD%\%BACKUPFILENAME%' WITH REPLACE"

:: remap user/login (http://msdn.microsoft.com/en-us/library/ms174378.aspx)
sqlcmd -E -S %SERVERNAME% -d %DATABASENAME% -Q "sp_change_users_login 'Update_One', 'login-name', 'user-name'"
sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET MULTI_USER"
echo.
pause

Are dictionaries ordered in Python 3.6+?

To fully answer this question in 2020, let me quote several statements from official Python docs:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.

Changed in version 3.8: Dictionaries are now reversible.

Dictionaries and dictionary views are reversible.

A statement regarding OrderedDict vs Dict:

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).

CardView Corner Radius

If you're setting the card background programmatically, make use you use cardView.setCardBackgroundColor() and not cardView.setBackgroundColor() and make sure use using app:cardPreventCornerOverlap="true" on the cardView.xml. That fixed it for me.

Btw, the above code (in quotations) is in Kotlin and not Java. Use the java equivalent if you're using Java.

How to sort an ArrayList in Java

Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);

Is there a REAL performance difference between INT and VARCHAR primary keys?

Depends on the length.. If the varchar will be 20 characters, and the int is 4, then if you use an int, your index will have FIVE times as many nodes per page of index space on disk... That means that traversing the index will require one fifth as many physical and/or logical reads..

So, if performance is an issue, given the opportunity, always use an integral non-meaningful key (called a surrogate) for your tables, and for Foreign Keys that reference the rows in these tables...

At the same time, to guarantee data consistency, every table where it matters should also have a meaningful non-numeric alternate key, (or unique Index) to ensure that duplicate rows cannot be inserted (duplicate based on meaningful table attributes) .

For the specific use you are talking about (like state lookups ) it really doesn't matter because the size of the table is so small.. In general there is no impact on performance from indices on tables with less than a few thousand rows...

How to link to apps on the app store

At least iOS 9 and above

  • Open directly in the App Store

An app

itms-apps://itunes.apple.com/app/[appName]/[appID]

List of developer's apps

itms-apps://itunes.apple.com/developer/[developerName]/[developerID]

Gridview row editing - dynamic binding to a DropDownList

The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.

I used it to change the value of two label controls - lblEditModifiedBy and lblEditModifiedOn - when I was editing a row, so that the correct ModifiedBy and ModifiedOn would be saved to the db on 'Update'.

When I clicked the 'Update' button, in the RowUpdating event it showed the new values I entered in the OldValues list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource attached to the GridView.)

The fix to this is using balexandre's code, but in a modified form in the gv_DataBound event:

protected void gv_DataBound(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in gv.Rows)
    {
        if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            // Here you will get the Control you need like:
            ((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
            ((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
        }
    }
}

C# int to enum conversion

Casting should be enough. If you're using C# 3.0 you can make a handy extension method to parse enum values:

public static TEnum ToEnum<TInput, TEnum>(this TInput value)
{
    Type type = typeof(TEnum);

    if (value == default(TInput))
    {
        throw new ArgumentException("Value is null or empty.", "value");
    }

    if (!type.IsEnum)
    {
        throw new ArgumentException("Enum expected.", "TEnum");
    }

    return (TEnum)Enum.Parse(type, value.ToString(), true);
}

Password encryption at client side

There are MD5 libraries available for javascript. Keep in mind that this solution will not work if you need to support users who do not have javascript available.

The more common solution is to use HTTPS. With HTTPS, SSL encryption is negotiated between your web server and the client, transparently encrypting all traffic.

Parse string to date with moment.js

moment was perfect for what I needed. NOTE it ignores the hours and minutes and just does it's thing if you let it. This was perfect for me as my API call brings back the date and time but I only care about the date.

function momentTest() {

  var varDate = "2018-01-19 18:05:01.423";
  var myDate =  moment(varDate,"YYYY-MM-DD").format("DD-MM-YYYY");
  var todayDate = moment().format("DD-MM-YYYY");  
  var yesterdayDate = moment().subtract(1, 'days').format("DD-MM-YYYY");   
  var tomorrowDate = moment().add(1, 'days').format("DD-MM-YYYY");

  alert(todayDate);

  if (myDate == todayDate) {
    alert("date is today");
  } else if (myDate == yesterdayDate) {
    alert("date is yesterday");
  } else if (myDate == tomorrowDate) {
    alert("date is tomorrow");
  } else {
    alert("It's not today, tomorrow or yesterday!");
  }
}

Getting Unexpected Token Export

I fixed this by making an entry point file like.

// index.js
require = require('esm')(module)
module.exports = require('./app.js')

and any file I imported inside app.js and beyond worked with imports/exports now you just run it like node index.js

Note: if app.js uses export default, this becomes require('./app.js').default when using the entry point file.

Eliminate space before \begin{itemize}

The cleanest way for you to accomplish this is to use the enumitem package (https://ctan.org/pkg/enumitem). For example,

enter image description here

\documentclass{article}
\usepackage{enumitem}% http://ctan.org/pkg/enumitem
\begin{document}
\noindent Here is some text and I want to make sure
there is no spacing the different items. 
\begin{itemize}[noitemsep]
  \item Item 1
  \item Item 2
  \item Item 3
\end{itemize}
\noindent Here is some text and I want to make sure
there is no spacing between this line and the item
list below it.
\begin{itemize}[noitemsep,topsep=0pt]
  \item Item 1
  \item Item 2
  \item Item 3
\end{itemize}
\end{document}

Furthermore, if you want to use this setting globally across lists, you can use

\usepackage{enumitem}% http://ctan.org/pkg/enumitem
\setlist[itemize]{noitemsep, topsep=0pt}

However, note that this package does not work well with the beamer package which is used to make presentations in Latex.

Java Interfaces/Implementation naming convention

The standard C# convention, which works well enough in Java too, is to prefix all interfaces with an I - so your file handler interface will be IFileHandler and your truck interface will be ITruck. It's consistent, and makes it easy to tell interfaces from classes.

pandas DataFrame: replace nan values with average of columns

Try:

sub2['income'].fillna((sub2['income'].mean()), inplace=True)

Genymotion error at start 'Unable to load virtualbox'

Don't ask what this has to do with that , but by right clicking the genymotion application file and changing to compatibility to Vista solved the problem!

Iterating through list of list in Python

x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
output = []

def lister(l):
    for item in l:
        if type(item) in [list, tuple, set]:
            lister(item)
        else:
            output.append(item)

lister(x)

Setting values of input fields with Angular 6

As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

Template

<form [formGroup]="mainForm" ng-submit="submitForm()">
  Global Price: <input type="number" formControlName="globalPrice">
  <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
  <table border formArrayName="orderLines">
  <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
    <tr>
       <td>{{orderLine.time | date}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input formControlName="price" type="number"></td>
    </tr>
</ng-container>
  </table>
</form>

Component

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  mainForm: FormGroup;
  orderLines = [
    {price: 10, time: new Date(), quantity: 2},
    {price: 20, time: new Date(), quantity: 3},
    {price: 30, time: new Date(), quantity: 3},
    {price: 40, time: new Date(), quantity: 5}
    ]
  constructor() {
    this.mainForm = this.getForm();
  }

  getForm(): FormGroup {
    return new FormGroup({
      globalPrice: new FormControl(),
      orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
    })
  }

  getFormGroupForLine(orderLine: any): FormGroup {
    return new FormGroup({
      price: new FormControl(orderLine.price)
    })
  }

  applyPriceToAll() {
    const formLines = this.mainForm.get('orderLines') as FormArray;
    const globalPrice = this.mainForm.get('globalPrice').value;
    formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
    // optionally recheck value and validity without emit event.
  }

  submitForm() {

  }
}

Junit test case for database insert method with DAO and web service

This is one sample dao test using junit in spring project.

import java.util.List;

import junit.framework.Assert;

import org.jboss.tools.example.springmvc.domain.Member;
import org.jboss.tools.example.springmvc.repo.MemberDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml",
"classpath:/META-INF/spring/applicationContext.xml"})
@Transactional
@TransactionConfiguration(defaultRollback=true)
public class MemberDaoTest
{
    @Autowired
    private MemberDao memberDao;

    @Test
    public void testFindById()
    {
        Member member = memberDao.findById(0l);

        Assert.assertEquals("John Smith", member.getName());
        Assert.assertEquals("[email protected]", member.getEmail());
        Assert.assertEquals("2125551212", member.getPhoneNumber());
        return;
    }

    @Test
    public void testFindByEmail()
    {
        Member member = memberDao.findByEmail("[email protected]");

        Assert.assertEquals("John Smith", member.getName());
        Assert.assertEquals("[email protected]", member.getEmail());
        Assert.assertEquals("2125551212", member.getPhoneNumber());
        return;
    }

    @Test
    public void testRegister()
    {
        Member member = new Member();
        member.setEmail("[email protected]");
        member.setName("Jane Doe");
        member.setPhoneNumber("2125552121");

        memberDao.register(member);
        Long id = member.getId();
        Assert.assertNotNull(id);

        Assert.assertEquals(2, memberDao.findAllOrderedByName().size());
        Member newMember = memberDao.findById(id);

        Assert.assertEquals("Jane Doe", newMember.getName());
        Assert.assertEquals("[email protected]", newMember.getEmail());
        Assert.assertEquals("2125552121", newMember.getPhoneNumber());
        return;
    }

    @Test
    public void testFindAllOrderedByName()
    {
        Member member = new Member();
        member.setEmail("[email protected]");
        member.setName("Jane Doe");
        member.setPhoneNumber("2125552121");
        memberDao.register(member);

        List<Member> members = memberDao.findAllOrderedByName();
        Assert.assertEquals(2, members.size());
        Member newMember = members.get(0);

        Assert.assertEquals("Jane Doe", newMember.getName());
        Assert.assertEquals("[email protected]", newMember.getEmail());
        Assert.assertEquals("2125552121", newMember.getPhoneNumber());
        return;
    }
}

How to get the latest tag name in current branch in Git?

"Most recent" could have two meanings in terms of git.

You could mean, "which tag has the creation date latest in time", and most of the answers here are for that question. In terms of your question, you would want to return tag c.

Or you could mean "which tag is the closest in development history to some named branch", usually the branch you are on, HEAD. In your question, this would return tag a.

These might be different of course:

A->B->C->D->E->F (HEAD)
       \     \
        \     X->Y->Z (v0.2)
         P->Q (v0.1)

Imagine the developer tag'ed Z as v0.2 on Monday, and then tag'ed Q as v0.1 on Tuesday. v0.1 is the more recent, but v0.2 is closer in development history to HEAD, in the sense that the path it is on starts at a point closer to HEAD.

I think you usually want this second answer, closer in development history. You can find that out by using git log v0.2..HEAD etc for each tag. This gives you the number of commits on HEAD since the path ending at v0.2 diverged from the path followed by HEAD.

Here's a Python script that does that by iterating through all the tags running this check, and then printing out the tag with fewest commits on HEAD since the tag path diverged:

https://github.com/MacPython/terryfy/blob/master/git-closest-tag

git describe does something slightly different, in that it tracks back from (e.g.) HEAD to find the first tag that is on a path back in the history from HEAD. In git terms, git describe looks for tags that are "reachable" from HEAD. It will therefore not find tags like v0.2 that are not on the path back from HEAD, but a path that diverged from there.

Only numbers. Input number in React

I tried to mimic your code and noticed that there's an issue on React with <input type='number' />. For workaround, check this example and try it yourself: https://codepen.io/zvona/pen/WjpKJX?editors=0010

You need to define it as normal input (type='text') with pattern for numbers only:

    <input type="text" pattern="[0-9]*"
     onInput={this.handleChange.bind(this)} value={this.state.financialGoal} />

And then to compare the validity of input:

const financialGoal = (evt.target.validity.valid) ? 
  evt.target.value : this.state.financialGoal;

The biggest caveat on this approach is when it comes to mobile --> where keyboard isn't in numeric but in normal alphabetic format.

Install python 2.6 in CentOS

Late to the party, but the OP should have gone with Buildout or Virtualenv, and sidestepped the problem completely.

I am currently working on a Centos server, well, toiling away would be the proper term and I can assure everyone that the only way I am able to blink back the tears whilst using the software equivalents of fire hardened spears, is buildout.

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Example

  [class*='section-']:not(.section-name) {
    @include opacity(0.6);
    // Write your css code here
  }

// Opacity 0.6 all "section-" but not "section-name"

Sorting string array in C#

This code snippet is working properly enter image description here

How do I check that a Java String is not all whitespaces?

If you are using Java 11, the new isBlank string method will come in handy:

!s.isBlank();

If you are using Java 8, 9 or 10, you could build a simple stream to check that a string is not whitespace only:

!s.chars().allMatch(Character::isWhitespace));

In addition to not requiring any third-party libraries such as Apache Commons Lang, these solutions have the advantage of handling any white space character, and not just plain ' ' spaces as would a trim-based solution suggested in many other answers. You can refer to the Javadocs for an exhaustive list of all supported white space types. Note that empty strings are also covered in both cases.

TypeError: 'int' object is not subscriptable

Just to be clear, all the answers so far are correct, but the reasoning behind them is not explained very well.

The sumall variable is not yet a string. Parentheticals will not convert to a string (e.g. summ = (int(birthday[0])+int(birthday[1])) still returns an integer. It looks like you most likely intended to type str((int(sumall[0])+int(sumall[1]))), but forgot to. The reason the str() function fixes everything is because it converts anything in it compatible to a string.

Using @property versus getters and setters

I think both have their place. One issue with using @property is that it is hard to extend the behaviour of getters or setters in subclasses using standard class mechanisms. The problem is that the actual getter/setter functions are hidden in the property.

You can actually get hold of the functions, e.g. with

class C(object):
    _p = 1
    @property
    def p(self):
        return self._p
    @p.setter
    def p(self, val):
        self._p = val

you can access the getter and setter functions as C.p.fget and C.p.fset, but you can't easily use the normal method inheritance (e.g. super) facilities to extend them. After some digging into the intricacies of super, you can indeed use super in this way:

# Using super():
class D(C):
    # Cannot use super(D,D) here to define the property
    # since D is not yet defined in this scope.
    @property
    def p(self):
        return super(D,D).p.fget(self)

    @p.setter
    def p(self, val):
        print 'Implement extra functionality here for D'
        super(D,D).p.fset(self, val)

# Using a direct reference to C
class E(C):
    p = C.p

    @p.setter
    def p(self, val):
        print 'Implement extra functionality here for E'
        C.p.fset(self, val)

Using super() is, however, quite clunky, since the property has to be redefined, and you have to use the slightly counter-intuitive super(cls,cls) mechanism to get an unbound copy of p.

Scroll / Jump to id without jQuery

Oxi's answer is just wrong.¹

What you want is:

var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;

Working example:

(function (){
  var i = 20, l = 20, html = '';
  while (i--){
    html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
    html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
    html += '[ Scroll to #DIV' +i+ ' ]</a>';
    html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
  }
  document.write( html );
})();

¹ I haven't got enough reputation to comment on his answer

How to load a resource from WEB-INF directory of a web archive

Here is how it works for me with no Servlet use.

Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml

  1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )

  2. Now let's use class loader:

    InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
    

Embed Google Map code in HTML with marker

I would suggest this way, one line iframe. no javascript needed at all. In query ?q=,

_x000D_
_x000D_
<iframe src="http://maps.google.com/maps?q=12.927923,77.627108&z=15&output=embed"></iframe>
_x000D_
_x000D_
_x000D_

#if DEBUG vs. Conditional("DEBUG")

Usually you would need it in Program.cs where you want to decide to run either Debug on Non-Debug code and that too mostly in Windows Services. So I created a readonly field IsDebugMode and set its value in static constructor as shown below.

static class Program
{

    #region Private variable
    static readonly bool IsDebugMode = false;
    #endregion Private variable

    #region Constrcutors
    static Program()
    {
 #if DEBUG
        IsDebugMode = true;
 #endif
    }
    #endregion

    #region Main

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main(string[] args)
    {

        if (IsDebugMode)
        {
            MyService myService = new MyService(args);
            myService.OnDebug();             
        }
        else
        {
            ServiceBase[] services = new ServiceBase[] { new MyService (args) };
            services.Run(args);
        }
    }

    #endregion Main        
}

Check if a value is within a range of numbers

If you're already using lodash, you could use the inRange() function: https://lodash.com/docs/4.17.15#inRange

_.inRange(3, 2, 4);
// => true

_.inRange(4, 8);
// => true

_.inRange(4, 2);
// => false

_.inRange(2, 2);
// => false

_.inRange(1.2, 2);
// => true

_.inRange(5.2, 4);
// => false

_.inRange(-3, -2, -6);
// => true

React prevent event bubbling in nested components on click

React uses event delegation with a single event listener on document for events that bubble, like 'click' in this example, which means stopping propagation is not possible; the real event has already propagated by the time you interact with it in React. stopPropagation on React's synthetic event is possible because React handles propagation of synthetic events internally.

stopPropagation: function(e){
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
}

Is <img> element block level or inline level?

<img> is a replaced element; it has a display value of inline by default, but its default dimensions are defined by the embedded image's intrinsic values, like it were inline-block. You can set properties like border/border-radius, padding/margin, width, height, etc. on an image.

Replaced elements : They're elements whose contents are not affected by the current document's styles. The position of the replaced element can be affected using CSS, but not the contents of the replaced element itself.

Referenece : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

Make cross-domain ajax JSONP request with jQuery

Try

alert(xml.Data[0].City)

Case sensitivly!

How to count total lines changed by a specific author in a Git repository?

For windows users you can use following batch script that counts added/removed lines for specified author

@echo off

set added=0
set removed=0

for /f "tokens=1-3 delims= " %%A in ('git log --pretty^=tformat: --numstat --author^=%1') do call :Count %%A %%B %%C

@echo added=%added%
@echo removed=%removed%
goto :eof

:Count
  if NOT "%1" == "-" set /a added=%added% + %1
  if NOT "%2" == "-" set /a removed=%removed% + %2
goto :eof

https://gist.github.com/zVolodymyr/62e78a744d99d414d56646a5e8a1ff4f

how to add button click event in android studio

Different ways to handle button event

Button btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {            
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(context, "Button 1", 
     Toast.LENGTH_LONG).show();
        }
    });

[Check this article for more details about button event handlers]

Replacing column values in a pandas DataFrame

This is very compact:

w['female'][w['female'] == 'female']=1
w['female'][w['female'] == 'male']=0

Another good one:

w['female'] = w['female'].replace(regex='female', value=1)
w['female'] = w['female'].replace(regex='male', value=0)

Is it possible to refresh a single UITableViewCell in a UITableView?

If you are using custom TableViewCells, the generic

[self.tableView reloadData];    

does not effectively answer this question unless you leave the current view and come back. Neither does the first answer.

To successfully reload your first table view cell without switching views, use the following code:

//For iOS 5 and later
- (void)reloadTopCell {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}

Insert the following refresh method which calls to the above method so you can custom reload only the top cell (or the entire table view if you wish):

- (void)refresh:(UIRefreshControl *)refreshControl {
    //call to the method which will perform the function
    [self reloadTopCell];

    //finish refreshing 
    [refreshControl endRefreshing];
}

Now that you have that sorted, inside of your viewDidLoad add the following:

//refresh table view
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];

[refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];

[self.tableView addSubview:refreshControl];

You now have a custom refresh table feature that will reload the top cell. To reload the entire table, add the

[self.tableView reloadData]; to your new refresh method.

If you wish to reload the data every time you switch views, implement the method:

//ensure that it reloads the table view data when switching to this view
- (void) viewWillAppear:(BOOL)animated {
    [self.tableView reloadData];
}

How can I find out what version of git I'm running?

Or even just

git version

Results in something like

git version 1.8.3.msysgit.0

Is there a Google Chrome-only CSS hack?

I have found this works ONLY in Chrome (where it's red) and not Safari and all other browsers (where it's green)...

.style {
color: green;
(-bracket-:hack;
    color: red;
);
}

From http://mynthon.net/howto/webdev/css-hacks-for-google-chrome.htm

Make Div overlay ENTIRE page (not just viewport)?

I looked at Nate Barr's answer above, which you seemed to like. It doesn't seem very different from the simpler

html {background-color: grey}

How to implement the Android ActionBar back button?

Make sure your the ActionBar Home Button is enabled in the Activity:

Android, API 5+:

@Override
public void onBackPressed() {
     ...
     super.onBackPressed();
}

ActionBarSherlock and App-Compat, API 7+:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

Android, API 11+:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

Example MainActivity that extends ActionBarActivity:

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Back button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home: 
            // API 5+ solution
            onBackPressed();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

This way all the activities you want can have the backpress.

Android, API 16+:

http://developer.android.com/training/implementing-navigation/ancestral.html

AndroidManifest.xml:

<application ... >
    ...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- The meta-data element is needed for versions lower than 4.1 -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

Example MainActivity that extends ActionBarActivity:

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Back button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

java.util.NoSuchElementException: No line found

Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.

For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.

Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called

      "java.util.NoSuchElementException: No line found".

If you have to call "sc.nextLine()" n times, then you have to have at least n lines.

Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.

standard size for html newsletter template

Bdizzle,

I would recommend that you read this link

You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.

Be happy, Julian

How to get .app file of a xcode application

I know as for Appium Mobile Automation you need .app file to run ios app on Simulator.So as like me many of you face this problem. So I explain how to create that .app file and where it is located.

1.Open Xcode.

2.Click on your sample project.(If you don't have then click on create new xcode project)

3.In left panel inside screen you will see products folder then click and expand that, you will see the list.

  1. Then right click on .app file and click on Show in Finder and thats your .app file. Now you can copy or use that path in capabilities for appium desktop or in framework.

Check the attached screenshot for detail

MySQL SELECT query string matching

Incorrect:

SELECT * FROM customers WHERE name LIKE '%Bob Smith%';

Instead:

select count(*)
from rearp.customers c
where c.name  LIKE '%Bob smith.8%';

select count will just query (totals)

C will link the db.table to the names row you need this to index

LIKE should be obvs

8 will call all references in DB 8 or less (not really needed but i like neatness)

Logging in Scala

This is how I got Scala Logging working for me:

Put this in your build.sbt:

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.7.2",
libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.3"

Then, after doing an sbt update, this prints out a friendly log message:

import com.typesafe.scalalogging._
object MyApp extends App with LazyLogging {
  logger.info("Hello there")
}

If you are using Play, you can of course simply import play.api.Logger for writing log messages: Logger.debug("Hi").

See the docs for more info.

Check if any ancestor has a class using jQuery

There are many ways to filter for element ancestors.

if ($elem.closest('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents().hasClass('parentClass')) {/*...*/}
if ($('.parentClass').has($elem).length /* > 0*/) {/*...*/}
if ($elem.is('.parentClass *')) {/*...*/} 

Beware, closest() method includes element itself while checking for selector.

Alternatively, if you have a unique selector matching the $elem, e.g #myElem, you can use:

if ($('.parentClass:has(#myElem)').length /* > 0*/) {/*...*/}
if(document.querySelector('.parentClass #myElem')) {/*...*/}

If you want to match an element depending any of its ancestor class for styling purpose only, just use a CSS rule:

.parentClass #myElem { /* CSS property set */ }

how to call url of any other website in php

use curl php library: http://php.net/manual/en/book.curl.php

direct example: CURL_EXEC:

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Using an IF Statement in a MySQL SELECT query

try this code worked for me

SELECT user_display_image AS user_image,
       user_display_name AS user_name,
       invitee_phone,
       (CASE WHEN invitee_status = 1 THEN "attending"
             WHEN invitee_status = 2 THEN "unsure"
             WHEN invitee_status = 3 THEN "declined"
             WHEN invitee_status = 0 THEN "notreviwed"
       END) AS invitee_status
  FROM your_table

Can you animate a height change on a UITableViewCell when selected?

Add a property to keep track of the selected cell

@property (nonatomic) int currentSelection;

Set it to a sentinel value in (for example) viewDidLoad, to make sure that the UITableView starts in the 'normal' position

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //sentinel
    self.currentSelection = -1;
}

In heightForRowAtIndexPath you can set the height you want for the selected cell

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    int rowHeight;
    if ([indexPath row] == self.currentSelection) {
        rowHeight = self.newCellHeight;
    } else rowHeight = 57.0f;
    return rowHeight;
}

In didSelectRowAtIndexPath you save the current selection and save a dynamic height, if required

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        // do things with your cell here

        // set selection
        self.currentSelection = indexPath.row;
        // save height for full text label
        self.newCellHeight = cell.titleLbl.frame.size.height + cell.descriptionLbl.frame.size.height + 10;

        // animate
        [tableView beginUpdates];
        [tableView endUpdates];
    }
}

In didDeselectRowAtIndexPath set the selection index back to the sentinel value and animate the cell back to normal form

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {       
        // do things with your cell here

        // sentinel
        self.currentSelection = -1;

        // animate
        [tableView beginUpdates];
        [tableView endUpdates];
    }
}

Height of status bar in Android

If you know exactly the size VS height

like

for example in a device with 320 X 480 screen size the status bar height is 25px, for a device with 480 x 800 the status bar height must be 38px

then you can just get the width of your view / the screen size you can just use an if else statement to get the height of status bar

int value under 10 convert to string two digit number

This blog post is a great little cheat-sheet to keep handy when trying to format strings to a variety of formats.

link to trojan removed

Edit

The link was removed because Google temporarily warned that the site (or related site) may have been spreading malicious software. It is now off the list an no longer reported as problematic. Google "SteveX String Formatting" you'll find the search result and you can visit it at your discretion.

Pro JavaScript programmer interview questions (with answers)

intermediate programmers should have technical mastery of their tools.

if he's passed the technical phone screen-esque questions above, make him sketch out something stupid on the spot, like an ajax url shortner. then grill him on his portfolio. no amazing portfolio = intermediate developer in this domain and not the guy you want in charge of your shiny new project.

How can I add an element after another element?

Solved jQuery: Add element after another element

<script>
$( "p" ).append( "<strong>Hello</strong>" );
</script>

OR

<script type="text/javascript"> 
jQuery(document).ready(function(){
jQuery ( ".sidebar_cart" ) .append( "<a href='http://#'>Continue Shopping</a>" );
});
</script>

Check if argparse optional argument is set or not

Here is my solution to see if I am using an argparse variable

import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-1", "--first", required=True)
ap.add_argument("-2", "--second", required=True)
ap.add_argument("-3", "--third", required=False) 
# Combine all arguments into a list called args
args = vars(ap.parse_args())
if args["third"] is not None:
# do something

This might give more insight to the above answer which I used and adapted to work for my program.

Bootstrap 3 breakpoints and media queries

for bootstrap 3 I have the following code in my navbar component

/**
 * Navbar styling.
 */
@mobile:          ~"screen and (max-width: @{screen-xs-max})";
@tablet:          ~"screen and (min-width: @{screen-sm-min})";
@normal:          ~"screen and (min-width: @{screen-md-min})";
@wide:            ~"screen and (min-width: @{screen-lg-min})";
@grid-breakpoint: ~"screen and (min-width: @{grid-float-breakpoint})";

then you can use something like

@media wide { selector: style }

This uses whatever value you have the variables set to.

Escaping allows you to use any arbitrary string as property or variable value. Anything inside ~"anything" or ~'anything' is used as is with no changes except interpolation.

http://lesscss.org

Ignore outliers in ggplot2 boxplot

I had the same problem and precomputed the values for Q1, Q2, median, ymin, ymax using boxplot.stats:

# Load package and generate data
library(ggplot2)
data <- rnorm(100)

# Compute boxplot statistics
stats <- boxplot.stats(data)$stats
df <- data.frame(x="label1", ymin=stats[1], lower=stats[2], middle=stats[3], 
                 upper=stats[4], ymax=stats[5])

# Create plot
p <- ggplot(df, aes(x=x, lower=lower, upper=upper, middle=middle, ymin=ymin, 
                    ymax=ymax)) + 
    geom_boxplot(stat="identity")
p

The result is a boxplot without outliers. enter image description here

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

For data with sparse matches, using string.search is the fastest across browsers. It re-slices a string each iteration to :

function lastIndexOfSearch(string, regex, index) {
  if(index === 0 || index)
     string = string.slice(0, Math.max(0,index));
  var idx;
  var offset = -1;
  while ((idx = string.search(regex)) !== -1) {
    offset += idx + 1;
    string = string.slice(idx + 1);
  }
  return offset;
}

For dense data I made this. It's complex compared to the execute method, but for dense data, it's 2-10x faster than every other method I tried, and about 100x faster than the accepted solution. The main points are:

  1. It calls exec on the regex passed in once to verify there is a match or quit early. I do this using (?= in a similar method, but on IE checking with exec is dramatically faster.
  2. It constructs and caches a modified regex in the format '(r).(?!.?r)'
  3. The new regex is executed and the results from either that exec, or the first exec, are returned;

    function lastIndexOfGroupSimple(string, regex, index) {
        if (index === 0 || index) string = string.slice(0, Math.max(0, index + 1));
        regex.lastIndex = 0;
        var lastRegex, index
        flags = 'g' + (regex.multiline ? 'm' : '') + (regex.ignoreCase ? 'i' : ''),
        key = regex.source + '$' + flags,
        match = regex.exec(string);
        if (!match) return -1;
        if (lastIndexOfGroupSimple.cache === undefined) lastIndexOfGroupSimple.cache = {};
        lastRegex = lastIndexOfGroupSimple.cache[key];
        if (!lastRegex)
            lastIndexOfGroupSimple.cache[key] = lastRegex = new RegExp('.*(' + regex.source + ')(?!.*?' + regex.source + ')', flags);
        index = match.index;
        lastRegex.lastIndex = match.index;
        return (match = lastRegex.exec(string)) ? lastRegex.lastIndex - match[1].length : index;
    };
    

jsPerf of methods

I don't understand the purpose of the tests up top. Situations that require a regex are impossible to compare against a call to indexOf, which I think is the point of making the method in the first place. To get the test to pass, it makes more sense to use 'xxx+(?!x)', than adjust the way the regex iterates.

Limit file format when using <input type="file">?

Use input tag with accept attribute

<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" />

Click here for the latest browser compatibility table

Live demo here

To select only image files, you can use this accept="image/*"

<input type="file" name="my-image" id="image" accept="image/*" />

Live demo here

Only gif, jpg and png will be shown, screen grab from Chrome version 44 Only gif, jpg and png will be shown, screen grab from Chrome version 44

How to right align widget in horizontal linear layout Android?

Try to add empty View inside horizontal LinearLayout before element that you want to see right, e.g.:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />                

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Real mouse position in canvas

The Simple 1:1 Scenario

For situations where the canvas element is 1:1 compared to the bitmap size, you can get the mouse positions by using this snippet:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
}

Just call it from your event with the event and canvas as arguments. It returns an object with x and y for the mouse positions.

As the mouse position you are getting is relative to the client window you'll have to subtract the position of the canvas element to convert it relative to the element itself.

Example of integration in your code:

//put this outside the event loop..
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");

function draw(evt) {
    var pos = getMousePos(canvas, evt);

    context.fillStyle = "#000000";
    context.fillRect (pos.x, pos.y, 4, 4);
}

Note: borders and padding will affect position if applied directly to the canvas element so these needs to be considered via getComputedStyle() - or apply those styles to a parent div instead.

When Element and Bitmap are of different sizes

When there is the situation of having the element at a different size than the bitmap itself, for example, the element is scaled using CSS or there is pixel-aspect ratio etc. you will have to address this.

Example:

function  getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect(), // abs. size of element
      scaleX = canvas.width / rect.width,    // relationship bitmap vs. element for X
      scaleY = canvas.height / rect.height;  // relationship bitmap vs. element for Y

  return {
    x: (evt.clientX - rect.left) * scaleX,   // scale mouse coordinates after they have
    y: (evt.clientY - rect.top) * scaleY     // been adjusted to be relative to element
  }
}

With transformations applied to context (scale, rotation etc.)

Then there is the more complicated case where you have applied transformation to the context such as rotation, skew/shear, scale, translate etc. To deal with this you can calculate the inverse matrix of the current matrix.

Newer browsers let you read the current matrix via the currentTransform property and Firefox (current alpha) even provide a inverted matrix through the mozCurrentTransformInverted. Firefox however, via mozCurrentTransform, will return an Array and not DOMMatrix as it should. Neither Chrome, when enabled via experimental flags, will return a DOMMatrix but a SVGMatrix.

In most cases however you will have to implement a custom matrix solution of your own (such as my own solution here - free/MIT project) until this get full support.

When you eventually have obtained the matrix regardless of path you take to obtain one, you'll need to invert it and apply it to your mouse coordinates. The coordinates are then passed to the canvas which will use its matrix to convert it to back wherever it is at the moment.

This way the point will be in the correct position relative to the mouse. Also here you need to adjust the coordinates (before applying the inverse matrix to them) to be relative to the element.

An example just showing the matrix steps

function draw(evt) {
    var pos = getMousePos(canvas, evt);        // get adjusted coordinates as above
    var imatrix = matrix.inverse();            // get inverted matrix somehow
    pos = imatrix.applyToPoint(pos.x, pos.y);  // apply to adjusted coordinate

    context.fillStyle = "#000000";
    context.fillRect(pos.x-1, pos.y-1, 2, 2);
}

An example of using currentTransform when implemented would be:

    var pos = getMousePos(canvas, e);          // get adjusted coordinates as above
    var matrix = ctx.currentTransform;         // W3C (future)
    var imatrix = matrix.invertSelf();         // invert

    // apply to point:
    var x = pos.x * imatrix.a + pos.y * imatrix.c + imatrix.e;
    var y = pos.x * imatrix.b + pos.y * imatrix.d + imatrix.f;

Update I made a free solution (MIT) to embed all these steps into a single easy-to-use object that can be found here and also takes care of a few other nitty-gritty things most ignore.

Why doesn't java.io.File have a close method?

java.io.File doesn't represent an open file, it represents a path in the filesystem. Therefore having close method on it doesn't make sense.

Actually, this class was misnamed by the library authors, it should be called something like Path.

Neither BindingResult nor plain target object for bean name available as request attribute

I had a similar problem in IntelliJ IDEA. My code was 100% correct, but after starting the Tomcat, you receive an exception. java.lang.IllegalStateException: Neither BindingResult

I just removed and added again Tomcat configuration. And it worked for me.

A picture Tomcat configuration

enter image description here

TextFX menu is missing in Notepad++

It should usually work using the method Dave described in his answer. (I can confirm seeing "TextFX Characters" in the Available tab in Plugin Manager.)

If it does not, you can try downloading the zip file from here and put its contents (it's one file called NppTextFX.dll) inside the plugins folder where Notepad++ is installed. I suggest doing this while Notepad++ itself is not running.

Extracting substrings in Go

Go strings are not null terminated, and to remove the last char of a string you can simply do:

s = s[:len(s)-1]

CSS: background image on background color

body 
{
background-image:url('image/img2.jpg');
margin: 0px;
 padding: 0px;
}

fatal error: Python.h: No such file or directory

If you are using tox to run tests on multiple versions of Python, you may need to install the Python dev libraries for each version of Python you are testing on.

sudo apt-get install python2.6-dev 
sudo apt-get install python2.7-dev 
etc.

Clear dropdown using jQuery Select2

This works for me:

 $remote.select2('data', {id: null, text: null})

It also works with jQuery validate when you clear it that way.

-- edit 2013-04-09

At the time of writing this response, it was the only way. With recent patches, a proper and better way is now available.

$remote.select2('data', null)

How to get primary key column in Oracle?

Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;

(This will list the primary key and then)

Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’; 

(This will give you the column, here PK_XYZ is the primay key name)

How do I close an Android alertdialog

AlertDialog.Builder ad = new AlertDialog.Builder(this);  
ad.setTitle("Unanswered Questions");  
ad.setMessage("You have not answered all the questions.");   
ad.setPositiveButton("OK", new DialogInterface.OnClickListener() {  
   public void onClick(DialogInterface dialog, int id) {  
     dialog.dismiss(); 
}  
});  
ad.show();