Programs & Examples On #Apache

Use this tag (along with an appropriate programming-language tag) for programming questions relating to the Apache HTTP Server. Do not use this tag for questions about other Apache Foundation products. Note that server configuration questions are usually a better fit on https://serverfault.com

How to enable CORS in apache tomcat

Check this answer: Set CORS header in Tomcat

Note that you need Tomcat 7.0.41 or higher.

To know where the current instance of Tomcat is located try this:

System.out.println(System.getProperty("catalina.base"));

You'll see the path in the console view.

Then look for /conf/web.xml on that folder, open it and add the lines of the above link.

How do I allow HTTPS for Apache on localhost?

It's very simple,

just run the following commands

sudo a2enmod ssl

sudo service apache2 restart

sudo a2ensite default-ssl.conf

That's it, you are done.

If you want to force SSL (to use https always), edit the file:

sudo nano /etc/apache2/sites-available/000-default.conf

and add this one line

<VirtualHost *:80>
        . . .

        Redirect "/" "https://your_domain_or_IP/"

        . . .
</VirtualHost>

then restart again

sudo service apache2 restart

How can I disable mod_security in .htaccess file?

When the above solution doesn’t work try this:

<IfModule mod_security.c>
  SecRuleEngine Off
  SecFilterInheritance Off
  SecFilterEngine Off
  SecFilterScanPOST Off
  SecRuleRemoveById 300015 3000016 3000017
</IfModule>

Setting up a websocket on Apache?

I struggled to understand the proxy settings for websockets for https therefore let me put clarity here what i realized.

First you need to enable proxy and proxy_wstunnel apache modules and the apache configuration file will look like this.

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
      ServerName www.example.com
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/your_project_public_folder

      SSLEngine on
      SSLCertificateFile    /etc/ssl/certs/path_to_your_ssl_certificate
      SSLCertificateKeyFile /etc/ssl/private/path_to_your_ssl_key

      <Directory /var/www/your_project_public_folder>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted
              php_flag display_errors On
      </Directory>
      ProxyRequests Off 
      ProxyPass /wss/  ws://example.com:port_no

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
</IfModule>

in your frontend application use the url "wss://example.com/wss/" this is very important mostly if you are stuck with websockets you might be making mistake in the front end url. You probably putting url wrongly like below.

wss://example.com:8080/wss/ -> port no should not be mentioned
ws://example.com/wss/ -> url should start with wss only.
wss://example.com/wss -> url should end with / -> most important

also interesting part is the last /wss/ is same as proxypass value if you writing proxypass /ws/ then in the front end you should write /ws/ in the end of url.

How can I force users to access my page over HTTPS instead of HTTP?

Use $_SERVER['HTTPS'] to tell if it is SSL, and redirect to the right place if not.

And remember, the page that displays the form does not need to be fed via HTTPS, it's the post back URL that needs it most.

Edit: yes, as is pointed out below, it's best to have the entire process in HTTPS. It's much more reassuring - I was pointing out that the post is the most critical part. Also, you need to take care that any cookies are set to be secure, so they will only be sent via SSL. The mod_rewrite solution is also very nifty, I've used it to secure a lot of applications on my own website.

How do I configure Apache 2 to run Perl CGI scripts?

This post is intended to rescue the people who are suffering from *not being able to properly setup Apache2 for Perl on Ubuntu. (The system configurations specific to your Linux machine will be mentioned within square brackets, like [this]).

Possible outcome of an improperly setup Apache 2:

  1. Browser trying to download the .pl file instead of executing and giving out the result.
  2. Forbidden.
  3. Internal server error.

If one follows the steps described below with a reasonable intelligence, he/she can get through the errors mentioned above.

Before starting the steps. Go to /etc/hosts file and add IP address / domain-name` for example:

127.0.0.1 www.BECK.com

Step 1: Install apache2 Step 2: Install mod_perl Step 3: Configure apache2

open sites-available/default and add the following,

<Files ~ "\.(pl|cgi)$">
    SetHandler perl-script
    PerlResponseHandler ModPerl::PerlRun
    Options +ExecCGI
    PerlSendHeader On
</Files>

<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>
<Directory [path-to-store-your-website-files-like-.html-(perl-scripts-should-be-stored-in-cgi-bin] >
####(The Perl/CGI scripts can be stored out of the cgi-bin directory, but that's a story for another day. Let's concentrate on washing out the issue at hand)
####
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ [path-where-you-want-your-.pl-and-.cgi-files]

<Directory [path-where-you-want-your-.pl-and-.cgi-files]>
    AllowOverride None
    Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
    AddHandler cgi-script .pl
    Order allow,deny
    allow from all
</Directory>
<Files ~ "\.(pl|cgi)$">
    SetHandler perl-script
    PerlResponseHandler ModPerl::PerlRun
    Options +ExecCGI
    PerlSendHeader On
</Files>

<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>
<Directory [path-to-store-your-website-files-like-.html-(perl-scripts-should-be-stored-in-cgi-bin] >
####(The Perl/CGI scripts can be stored out of the cgi-bin directory, but that's a story for another day. Let's concentrate on washing out the issue at hand)
####
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ [path-where-you-want-your-.pl-and-.cgi-files]

<Directory [path-where-you-want-your-.pl-and-.cgi-files]>
    AllowOverride None
    Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
    AddHandler cgi-script .pl
    Order allow,deny
    allow from all
</Directory>

Step 4:

Add the following lines to your /etc/apache2/apache2.conf file.

AddHandler cgi-script .cgi .pl
<Files ~ "\.pl$">
Options +ExecCGI
</Files>
<Files ~ "\.cgi$">
Options +ExecCGI
</Files>

<IfModule mod_perl.c>
<IfModule mod_alias.c>
Alias /perl/ /home/sly/host/perl/
</IfModule>
<Location /perl>
SetHandler perl-script
PerlHandler Apache::Registry
Options +ExecCGI
</Location>
</IfModule>

<Files ~ "\.pl$">
Options +ExecCGI
</Files>

Step 5:

Very important, or at least I guess so, only after doing this step, I got it to work.

AddHandler cgi-script .cgi .pl

<Files ~ "\.pl$">
Options +ExecCGI
</Files>
<Files ~ "\.cgi$">
Options +ExecCGI
</Files>

<IfModule mod_perl.c>
<IfModule mod_alias.c>
Alias /perl/ /home/sly/host/perl/
</IfModule>
<Location /perl>
SetHandler perl-script
PerlHandler Apache::Registry
Options +ExecCGI
</Location>
</IfModule>

<Files ~ "\.pl$">
Options +ExecCGI
</Files>

Step 6

Very important, or at least I guess so, only after doing this step, I got it to work.

Add the following to you /etc/apache2/sites-enabled/000-default file

<Files ~ "\.(pl|cgi)$">
SetHandler perl-script
PerlResponseHandler ModPerl::PerlRun
Options +ExecCGI
PerlSendHeader On
</Files>

Step 7:

Now add, your Perl script as test.pl in the place where you mentioned before in step 3 as [path-where-you-want-your-.pl-and-.cgi-files].

Give permissions to the .pl file using chmod and then, type the webaddress/cgi-bin/test.pl in the address bar of the browser, there you go, you got it.

(Now, many of the things would have been redundant in this post. Kindly ignore it.)

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

if you can get the proper response in your localhost and getting this error kind of error and if you are using nginx.

  1. Go to Server and open nginx.conf with :

    nano etc/nginx/nginx.conf

  2. Add following line in http block :

    proxy_buffering off;

  3. Save and exit the file

This solved my issue

Getting 404 Not Found error while trying to use ErrorDocument

When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,

 ErrorDocument 404 /yourfoldernames/errors/404.html

How do I disable directory browsing?

You can place an empty file called index.html into each directory that you don't want listed. This has several advantages:

  • It (usually) requires zero configuration on the server.
  • It will keep working, even if the server administrator decides to use "AllowOverride None" in the the server configuration. (If you use .htaccess files, this can lead to lots of "Error 500 - internal server error" messages for your users!).
  • It also allows you to move your files from one server to the next, again without having to mess with the apache configuration.

Theoretically, the autoindexing might be triggered by a different file (this is controlled by the DirectoryIndex option), but I have yet to encounter this in the real world.

XAMPP Apache Webserver localhost not working on MAC OS

I had to disable OSX's built-in Apache server (XAMPP support thread):

sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist

This allowed XAMPP to start on 80, while POW runs on 20559.

What had failed: I reconfigured /etc/apache2/httpd.conf to listen on an alternate port and rebooted OSX. No luck.

How to run php files on my computer

If you have apache running, put your file in server folder for html files and then call it from web-browser (Like http://localhost/myfile.php ).

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

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

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

how to configuring a xampp web server for different root directory

You can also put in a new virtual Host entry in the

c:\xampp\apache\conf\httpd-vhosts.conf

like:

<VirtualHost *:80>
  ServerAdmin [email protected]
  DocumentRoot "C:/xampp/htdocs/myproject/web"
  ServerName localhost
  ErrorLog "logs/dummy-host2.example.com-error.log"
  CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

With my centos 6.7 installation, not only did I have the problem starting httpd with root but also with xauth (getting /usr/bin/xauth: timeout in locking authority file /.Xauthority with underlying permission denied errors)

# setenforce 0

Fixed both issues.

Apache 13 permission denied in user's home directory

Have you changed the permissions on the individual files as well as just the directory?

chmod -R 777 /home/user/xxx

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

Executing a shell script from a PHP script

It's a simple problem. When you are running from terminal, you are running the php file from terminal as a privileged user. When you go to the php from your web browser, the php script is being run as the web server user which does not have permissions to execute files in your home directory. In Ubuntu, the www-data user is the apache web server user. If you're on ubuntu you would have to do the following: chown yourusername:www-data /home/testuser/testscript chmod g+x /home/testuser/testscript

what the above does is transfers user ownership of the file to you, and gives the webserver group ownership of it. the next command gives the group executable permission to the file. Now the next time you go ahead and do it from the browser, it should work.

How to check if memcache or memcached is installed for PHP?

I combined, minified and extended (some more checks) the answers from @Bijay Rungta and @J.C. Inacio

<?php
if(!extension_loaded('Memcache'))
{
    die("Memcache extension is not loaded");
}

if (!class_exists('Memcache')) 
{
    die('Memcache class not available');
}

$memcacheObj = new Memcache;
if(!$memcacheObj)
{
    die('Could not create memcache object');
}

if (!$memcacheObj->connect('localhost')) 
{
    die('Could not connect to memcache server');
}

// testdata to store in memcache
$testData = array(
    'the' => 'cake',
    'is' => 'a lie',
);

// set data (if not present)
$aData = $memcacheObj->get('data');
if (!$aData) 
{
    if(!$memcacheObj->set('data', $testData, 0, 300))
    {
        die('Memcache could not set the data');
    }
}

// try to fetch data
$aData = $memcacheObj->get('data');
if (!$aData) 
{
    die('Memcache is not responding with data');
}

if($aData !== $testData)
{
    die('Memcache is responding but with wrong data');
}

die('Memcache is working fine');

How to enable mod_rewrite for Apache 2.2

If non of the above works try editing /etc/apache2/sites-enabled/000-default

almost at the top you will find

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Change the AllowOverride None to AllowOverride All

this worked for me

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

No prompt use:

dir /x

Procure o nome reduzido do diretório na linha do "Program Files (x86)"

27/08/2018  15:07    <DIR>          PROGRA~2     Program Files (x86)

Coloque a seguinte configuração em php.ini para a opção:

extension_dir="C:\PROGRA~2\path\to\php\ext"

Acredito que isso resolverá seu problema.

Zorro

Switch php versions on commandline ubuntu 16.04

When installing laravel on Ubuntu 18.04, be default PHP 7.3.0RC3 install selected, but laravel and symfony will not install properly complaining about missin php-xml and php-zip, even though they are installed. You need to switch to php 7.1, using the instructions above or,

 sudo update-alternatives --set php /usr/bin/php7.1

now, running laravel new blog, will proceed correctly

ssl_error_rx_record_too_long and Apache SSL

I had a messed up virtual host config. Remember you need one virtual host without SSL for port 80, and another one with SSL for port 443. You cannot have both in one virtual host, as the webmin-generated config tried to do.

PHP not displaying errors even though display_errors = On

I had the same issue and finally solved it. My mistake was that I tried to change /etc/php5/cli/php.ini, but then I found another php.ini here: /etc/php5/apache2/php.ini, changed display_errors = On, restarted the web-server and it worked!

May be it would be helpful for someone absent-minded like me.

ab load testing

Load testing your API by using just ab is not enough. However, I think it's a great tool to give you a basic idea how your site is performant.

If you want to use the ab command in to test multiple API endpoints, with different data, all at the same time in background, you need to use "nohup" command. It runs any command even when you close the terminal.

I wrote a simple script that automates the whole process, feel free to use it: http://blog.ikvasnica.com/entry/load-test-multiple-api-endpoints-concurrently-use-this-simple-shell-script

.htaccess file to allow access to images folder to view pictures?

<Directory /uploads>
   Options +Indexes
</Directory>

Tips for debugging .htaccess rewrite rules

If you are working with url, You might want to check if you "Enable Mod Rewrite"

How to change XAMPP apache server port?

Have you tried to access your page by typing "http://localhost:8012" (after restarting the apache)?

XAMPP: Couldn't start Apache (Windows 10)

It looks like there are many options. The answer depends on your Windows installation. Here is my experience when having the same problem in a Windows 10 fresh install and fix the issue with the following step:

  1. Install Visual C++ Redistributable
  2. Open XAMPP and select configure in the Apache service
  3. Change the port 80 to 9000 or 81 or whatever you want in file httpd.conf on the line Listen 80
  4. Change the port on httpd-ssl.conf and change Listen 443 to Listen 441
  5. Restart XAMPP and start the Apache service. It works for me.

Note: I'm using XAMPP version 5.6.15 and XAMPP Control Panel version 3.2.2.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

In my case I got the error simply because I had changed the Listen 80 to listen 443 in the file

/etc/httpd/conf/httpd.conf 

Since I had installed mod_ssl using the yum commands

yum -y install mod_ssl  

there was a duplicate listen 443 directive in the file ssl.conf created during mod_ssl installation.

You can verify this if you have duplicate listen 80 or 443 by running the below command in linux centos (My linux)

grep  '443' /etc/httpd/conf.d/*

below is sample output

/etc/httpd/conf.d/ssl.conf:Listen 443 https
/etc/httpd/conf.d/ssl.conf:<VirtualHost _default_:443>
/etc/httpd/conf.d/ssl.conf:#ServerName www.example.com:443

Simply reverting the listen 443 in httd.conf to listen 80 fixed my issue.

How to enable local network users to access my WAMP sites?

if you use Windows and if you do all comments in above ,

You can check your network and sharing center.

Network and Sharing Center -> Advanced sharing settings ->Home or Work Profile Change

Thanks good work!

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

On linux, /etc/apache2/mods-enabled/php5.conf dans php5.load exists. If not, enables this modules (may require to sudo apt-get install libapache2-mod-php5).

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

make change in changes in /opt/lampp/phpmyadmin/config.inc.php    

<?php
    /* vim: set expandtab sw=4 ts=4 sts=4: */
    /**
     * phpMyAdmin sample configuration, you can use it as base for
     * manual configuration. For easier setup you can use setup/
     *
     * All directives are explained in documentation in the doc/ folder
     * or at <http://docs.phpmyadmin.net/>.
     *
     * @package PhpMyAdmin
     */

    /**
     * This is needed for cookie based authentication to encrypt password in
     * cookie
     */
    $cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */

    /**
     * Servers configuration
     */
    $i = 0;

    /**
     * First server
     */
    $i++;
    /* Authentication type */
    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    /* Server parameters */
    //$cfg['Servers'][$i]['host'] = 'localhost';
    //$cfg['Servers'][$i]['connect_type'] = 'tcp';
    $cfg['Servers'][$i]['compress'] = false;
    $cfg['Servers'][$i]['AllowNoPassword'] = true;

    /**
     * phpMyAdmin configuration storage settings.
     */

    /* User used to manipulate with storage */
    // $cfg['Servers'][$i]['controlhost'] = '';
    // $cfg['Servers'][$i]['controlport'] = '';



    $cfg['Servers'][1]['pmadb'] = 'phpmyadmin';
    $cfg['Servers'][1]['controluser'] = 'pma';
    $cfg['Servers'][1]['controlpass'] = '';

    $cfg['Servers'][1]['bookmarktable'] = 'pma_bookmark';
    $cfg['Servers'][1]['relation'] = 'pma_relation';
    $cfg['Servers'][1]['userconfig'] = 'pma_userconfig';
    $cfg['Servers'][1]['table_info'] = 'pma_table_info';
    $cfg['Servers'][1]['column_info'] = 'pma_column_info';
    $cfg['Servers'][1]['history'] = 'pma_history';
    $cfg['Servers'][1]['recent'] = 'pma_recent';
    $cfg['Servers'][1]['table_uiprefs'] = 'pma_table_uiprefs';
    $cfg['Servers'][1]['tracking'] = 'pma_tracking';
    $cfg['Servers'][1]['table_coords'] = 'pma_table_coords';
    $cfg['Servers'][1]['pdf_pages'] = 'pma_pdf_pages';
    $cfg['Servers'][1]['designer_coords'] = 'pma_designer_coords';



    // $cfg['Servers'][$i]['favorite'] = 'pma__favorite';
    // $cfg['Servers'][$i]['users'] = 'pma__users';
    // $cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
    // $cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
    // $cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
    // $cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
    // $cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
    // $cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
    /* Contrib / Swekey authentication */
    // $cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf';

    /**
     * End of servers configuration
     */

    /**
     * Directories for saving/loading files from server
     */
    $cfg['UploadDir'] = '';
    $cfg['SaveDir'] = '';

    /**
     * Whether to display icons or text or both icons and text in table row
     * action segment. Value can be either of 'icons', 'text' or 'both'.
     * default = 'both'
     */
    //$cfg['RowActionType'] = 'icons';

    /**
     * Defines whether a user should be displayed a "show all (records)"
     * button in browse mode or not.
     * default = false
     */
    //$cfg['ShowAll'] = true;

    /**
     * Number of rows displayed when browsing a result set. If the result
     * set contains more rows, "Previous" and "Next".
     * Possible values: 25, 50, 100, 250, 500
     * default = 25
     */
    //$cfg['MaxRows'] = 50;

    /**
     * Disallow editing of binary fields
     * valid values are:
     *   false    allow editing
     *   'blob'   allow editing except for BLOB fields
     *   'noblob' disallow editing except for BLOB fields
     *   'all'    disallow editing
     * default = 'blob'
     */
    //$cfg['ProtectBinary'] = false;

    /**
     * Default language to use, if not browser-defined or user-defined
     * (you find all languages in the locale folder)
     * uncomment the desired line:
     * default = 'en'
     */
    //$cfg['DefaultLang'] = 'en';
    //$cfg['DefaultLang'] = 'de';

    /**
     * How many columns should be used for table display of a database?
     * (a value larger than 1 results in some information being hidden)
     * default = 1
     */
    //$cfg['PropertiesNumColumns'] = 2;

    /**
     * Set to true if you want DB-based query history.If false, this utilizes
     * JS-routines to display query history (lost by window close)
     *
     * This requires configuration storage enabled, see above.
     * default = false
     */
    //$cfg['QueryHistoryDB'] = true;

    /**
     * When using DB-based query history, how many entries should be kept?
     * default = 25
     */
    //$cfg['QueryHistoryMax'] = 100;

    /**
     * Whether or not to query the user before sending the error report to
     * the phpMyAdmin team when a JavaScript error occurs
     *
     * Available options
     * ('ask' | 'always' | 'never')
     * default = 'ask'
     */
    //$cfg['SendErrorReports'] = 'always';

    /**
     * You can find more configuration options in the documentation
     * in the doc/ folder or at <http://docs.phpmyadmin.net/>.
     */

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

In my case, I stopped my docker hive container and run it again and finally, it worked. Hope it will be useful for someone.

Note: This might be caused because there might be an instance running in the background so stopping the container will stop all background instances.

how to make log4j to write to the console as well

Write the root logger as below for logging on both console and FILE

log4j.rootLogger=ERROR,console,FILE

And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).

How do I change the default index page in Apache?

You can also set DirectoryIndex in apache's httpd.conf file.

CentOS keeps this file in /etc/httpd/conf/httpd.conf Debian: /etc/apache2/apache2.conf

Open the file in your text editor and find the line starting with DirectoryIndex

To load landing.html as a default (but index.html if that's not found) change this line to read:

DirectoryIndex  landing.html index.html

Https to http redirect using htaccess

Attempt 2 was close to perfect. Just modify it slightly:

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

In case you need to run IIS on port 80/443 but on different IP address, you may use netsh http add iplisten xxx.xxx.xxx.xxx as described here: https://support.microsoft.com/en-us/help/954874/iis-binds-to-all-ip-addresses-on-a-server-when-you-install-iis-7-0-on

More details about netsh http add iplisten can be found here: https://msdn.microsoft.com/en-us/library/windows/desktop/cc307219.aspx

How can I convert a PFX certificate file for use with Apache on a linux server?

Took some tooling around but this is what I ended up with.

Generated and installed a certificate on IIS7. Exported as PFX from IIS

Convert to pkcs12

openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes

NOTE: While converting PFX to PEM format, openssl will put all the Certificates and Private Key into a single file. You will need to open the file in Text editor and copy each Certificate & Private key(including the BEGIN/END statements) to its own individual text file and save them as certificate.cer, CAcert.cer, privateKey.key respectively.

-----BEGIN PRIVATE KEY-----
Saved as certificate.key
-----END PRIVATE KEY-----

-----BEGIN CERTIFICATE-----
Saved as certificate.crt
-----END CERTIFICATE-----

Added to apache vhost w/ Webmin.

Lost httpd.conf file located apache

Get the path of running Apache

$ ps -ef | grep apache
apache   12846 14590  0 Oct20 ?        00:00:00 /usr/sbin/apache2

Append -V argument to the path

$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"

Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location

Apache server keeps crashing, "caught SIGTERM, shutting down"

Apache is not running

It could also be something as simple as Apache not being configured to start automatically on boot. Assuming you are on a Red Hat-like system such as CentOS or Fedora, the chkconfig –list command will show you which services are set to start for each runlevel. You should see a line like

    httpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off

If instead it says "off" all the way across, you can activate it with chkconfig httpd on. OR you can start apache manually from your panel.

laravel the requested url was not found on this server

In addition to all the answers if you still encounter some variation of the problem, edit the .env file and set APP_URL to your domain name as in:

 APP_URL=similar_to_my_avatar_link 

How to read Excel cell having Date with Apache POI?

For reading date cells this method has proven to be robust so far:

private LocalDate readCellAsDate(final Row row, final int pos) {
    if (pos == -1) {
        return null;
    }
    final Cell cell = row.getCell(pos - 1);
    if (cell != null) {
        cell.setCellType(CellType.NUMERIC);
    } else {
        return null;
    }
    if (DateUtil.isCellDateFormatted(cell)) {
        try {
            return cell.getDateCellValue().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        } catch (final NullPointerException e) {
            logger.error(e.getMessage());
            return null;
        }
    }
    return null;
}

Disable PHP in directory (including all sub-directories) with .htaccess

To disable all access to sub dirs (safest) use:

<Directory full-path-to/USERS>
     Order Deny,Allow
     Deny from All
 </Directory>

If you want to block only PHP files from being served directly, then do:

1 - Make sure you know what file extensions the server recognizes as PHP (and dont' allow people to override in htaccess). One of my servers is set to:

# Example of existing recognized extenstions:
AddType application/x-httpd-php .php .phtml .php3

2 - Based on the extensions add a Regular Expression to FilesMatch (or LocationMatch)

 <Directory full-path-to/USERS>
     <FilesMatch "(?i)\.(php|php3?|phtml)$">
            Order Deny,Allow
            Deny from All
    </FilesMatch>
 </Directory>

Or use Location to match php files (I prefer the above files approach)

<LocationMatch "/USERS/.*(?i)\.(php3?|phtml)$">
     Order Deny,Allow
     Deny from All
</LocationMatch>

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

I had same issue, was due to multiple copies of ssl.conf In /etc/httpd/conf.d - There should only be one.

enable cors in .htaccess

It's look like you are using an old version of slim(2.x). You can just add following lines to .htaccess and don't need to do anything in PHP scripts.

# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(domain_one\.com|domain_two\.net)$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers: Authorization

# Force to request 200 for options
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

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

For Apache 2.4.2: I was getting 403: Forbidden continuously when I was trying to access WAMP on my Windows 7 desktop from my iPhone on WiFi. On one blog, I found the solution - add Require all granted after Allow all in the <Directory> section. So this is how my <Directory> section looks like inside <VirtualHost>

<Directory "C:/wamp/www">
    Options Indexes FollowSymLinks MultiViews Includes ExecCGI
    AllowOverride All
    Order Allow,Deny
    Allow from all
    Require all granted
</Directory>

Apache: client denied by server configuration

Can you try changing "Allow from 127.0.0 192.168.1 ::1 localhost" to "Allow from all". If that fixes your problem, you need to be less restrict about where content can be requested from

Why are my PHP files showing as plain text?

You need to configure Apache (the webserver) to process PHP scripts as PHP. Check Apache's configuration. You need to load the module (the path may differ on your system):

LoadModule php5_module "c:/php/php5apache.dll"

And you also need to tell Apache what to process with PHP:

AddType application/x-httpd-php .php

See the documentation for more details.

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

Solved this by adding following

RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^ - [L]

Why use deflate instead of gzip for text files served by Apache?

There shouldn't be any difference in gzip & deflate for decompression. Gzip is just deflate with a few dozen byte header wrapped around it including a checksum. The checksum is the reason for the slower compression. However when you're precompressing zillions of files you want those checksums as a sanity check in your filesystem. In addition you can utilize commandline tools to get stats on the file. For our site we are precompressing a ton of static data (the entire open directory, 13,000 games, autocomplete for millions of keywords, etc.) and we are ranked 95% faster than all websites by Alexa. Faxo Search. However, we do utilize a home grown proprietary web server. Apache/mod_deflate just didn't cut it. When those files are compressed into the filesystem not only do you take a hit for your file with the minimum filesystem block size but all the unnecessary overhead in managing the file in the filesystem that the webserver could care less about. Your concerns should be total disk footprint and access/decompression time and secondarily speed in being able to get this data precompressed. The footprint is important because even though disk space is cheap you want as much as possible to fit in the cache.

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

I'd the same error even after recompiling the modules.

But I solved it you just have to specify the absolute path of your phpize.

Setting up SSL on a local xampp/apache server

I did all of the suggested stuff here and my code still did not work because I was using curl

If you are using curl in the php file, curl seems to reject all ssl traffic by default. A quick-fix that worked for me was to add:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

before calling:

 curl_exec():

in the php file.

I believe that this disables all verification of SSL certificates.

apache ProxyPass: how to preserve original IP address

The answer of JasonW is fine. But since apache httpd 2.4.6 there is a alternative: mod_remoteip

All what you must do is:

  1. May be you must install the mod_remoteip package
  2. Enable the module:

    LoadModule remoteip_module modules/mod_remoteip.so
    
  3. Add the following to your apache httpd config. Note that you must add this line not into the configuration of the proxy server. You must add this to the configuration of the proxy target httpd server (the server behind the proxy):

    RemoteIPHeader X-Forwarded-For
    

See at http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html for more informations and more options.

Internal Error 500 Apache, but nothing in the logs?

Please Note: The original poster was not specifically asking about PHP. All the php centric answers make large assumptions not relevant to the actual question.

The default error log as opposed to the scripts error logs usually has the (more) specific error. often it will be permissions denied or even an interpreter that can't be found.

This means the fault almost always lies with your script. e.g you uploaded a perl script but didnt give it execute permissions? or perhaps it was corrupted in a linux environment if you write the script in windows and then upload it to the server without the line endings being converted you will get this error.

in perl if you forget

print "content-type: text/html\r\n\r\n";

you will get this error

There are many reasons for it. so please first check your error log and then provide some more information.

The default error log is often in /var/log/httpd/error_log or /var/log/apache2/error.log.

The reason you look at the default error logs (as indicated above) is because errors don't always get posted into the custom error log as defined in the virtual host.

Assumes linux and not necessarily perl

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

It's permission problem. It is not "classic" read/write permissions of apache user, but selinux one.

Apache cannot write to files labeled as httpd_sys_content_t they can be only read by apache.

You have 2 possibilities:

  1. label svn repository files as httpd_sys_content_rw_t:

    chcon -R -t httpd_sys_content_rw_t /path/to/your/svn/repo
    
  2. set selinux boolean httpd_unified --> on

    setsebool -P httpd_unified=1
    

I prefer 2nd possibility. You can play also with other selinux booleans connected with httpd:

getsebool -a | grep httpd

apache mod_rewrite is not working or not enabled

On centOS7 I changed the file /etc/httpd/conf/httpd.conf

from AllowOverride None to AllowOverride All

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

i have found that similar issue on my system, and that was from skype installed before xampp installed. i got similar error. for fixing the error i followed these,

  1. logged out to skype for a while ,
  2. restarted apache from xampp control panel,
  3. checked on browser, whether it worked or not, by http://localhost/
  4. got it worked,
  5. signed in again to skype,
  6. all working great, as simple as that

i wasn't need nothing to install or uninstall, and this worked for me in less then 1 minute.

cheers

Is it possible to log all HTTP request headers with Apache?

In my case easiest way to get browser headers was to use php. It appends headers to file and prints them to test page.

<?php
$fp = fopen('m:/temp/requests.txt', 'a');
$time = $_SERVER['REQUEST_TIME'];
fwrite($fp, $time  "\n");
echo "$time.<br>";
foreach (getallheaders() as $name => $value) {
    $cur_hd = "$name: $value\n";
    fwrite($fp, $cur_hd);
    echo "$cur_hd.<br>";
}
fwrite($fp, "***\n");
fclose($fp);
?>

Forbidden: You don't have permission to access / on this server, WAMP Error

This could be one solution.

public class RegisterActivity extends AppCompatActivity {

    private static final String TAG = "RegisterActivity";
    private static final String URL_FOR_REGISTRATION = "http://192.168.10.4/android_login_example/register.php";
    ProgressDialog progressDialog;

    private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputAge;
    private Button btnSignUp;
    private Button btnLinkLogin;
    private RadioGroup genderRadioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        // Progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        signupInputName = (EditText) findViewById(R.id.signup_input_name);
        signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
        signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
        signupInputAge = (EditText) findViewById(R.id.signup_input_age);

        btnSignUp = (Button) findViewById(R.id.btn_signup);
        btnLinkLogin = (Button) findViewById(R.id.btn_link_login);

        genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitForm();
            }
        });
        btnLinkLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(i);
            }
        });
    }

    private void submitForm() {

        int selectedId = genderRadioGroup.getCheckedRadioButtonId();
        String gender;
        if(selectedId == R.id.female_radio_btn)
            gender = "Female";
        else
            gender = "Male";

        registerUser(signupInputName.getText().toString(),
                signupInputEmail.getText().toString(),
                signupInputPassword.getText().toString(),
                gender,
                signupInputAge.getText().toString());
    }

    private void registerUser(final String name,  final String email, final String password,
                              final String gender, final String dob) {
        // Tag used to cancel the request
        String cancel_req_tag = "register";

        progressDialog.setMessage("Adding you ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                URL_FOR_REGISTRATION, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    if (!error) {
                        String user = jObj.getJSONObject("user").getString("name");
                        Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();

                        // Launch login activity
                        Intent intent = new Intent(
                                RegisterActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {



                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);
                params.put("gender", gender);
                params.put("age", dob);
                return params;
            }
        };
        // Adding request to request queue
        AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
    }

    private void showDialog() {
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void hideDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }
    }

Project Links do not work on Wamp Server

Open index.php in www folder and set

$suppress_localhost = false;

This will prepend http://localhost/ to your project links

PHP code is not being executed, instead code shows on the page

I think the problem that it is showing code instead of the result is that it is not going to local host . recheck what address u r going in. are u going to a local file directory or to the local host.

from the screenshot u sent it is going to ur computer not to the localhost.

"file:/// " it should be "localhost/"

How to allow Cross domain request in apache2

First enable mod_headers on your server, then you can use header directive in both Apache conf and .htaccess.

  1. enable mod_headers
  • a2enmod headers
  1. configure header in .htaccess file
  • Header add Access-Control-Allow-Origin "*"
  • Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
  • Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Installing Apache Maven Plugin for Eclipse

I found Maven Integration for Eclipse here.

http://download.eclipse.org/technology/m2e/releases

After installing restart eclipse. Worked for me running Eclipse Juno.

Apache giving 403 forbidden errors

restorecon command works as below :

restorecon -v -R /var/www/html/

Apache VirtualHost and localhost

This is normal if you see it. Since it is the first virtual host entry, it will show local host.

Let’s say for example you didn't want that page to show. All you want to show is the "Apache, it works" page, so you would make a vhost entry before mysite.local as local host and point it to the "it works" page.

But this is normal. I had this problem before, so don't worry!

Installing mcrypt extension for PHP on OSX Mountain Lion

So after running brew install mcrypt php, I had to install php-mcrypt via pecl:

pecl install mcrypt-1.0.1

At the time of writing, mcrypt does not have a stable pecl release, 1.0.1 being the current release for php 7.2 and 7.3, and brew install php will install php 7.2.

X-Frame-Options on apache

This worked for me on all browsers:

  1. Created one page with all my javascript
  2. Created a 2nd page on the same server and embedded the first page using the object tag.
  3. On my third party site I used the Object tag to embed the 2nd page.
  4. Created a .htaccess file on the original server in the public_html folder and put Header unset X-Frame-Options in it.

How do you redirect HTTPS to HTTP?

As far as I'm aware of a simple meta refresh also works without causing errors:

<meta http-equiv="refresh" content="0;URL='http://www.yourdomain.com/path'">

How to force reloading php.ini file?

TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm service.

The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.

To restart the service:

Note: prepend sudo if not root

Using SysV Init scripts directly:

/etc/init.d/php-fpm restart        # typical
/etc/init.d/php5-fpm restart       # debian-style
/etc/init.d/php7.0-fpm restart     # debian-style PHP 7

Using service wrapper script

service php-fpm restart        # typical
service php5-fpm restart       # debian-style
service php7.0-fpm restart.    # debian-style PHP 7

Using Upstart (e.g. ubuntu):

restart php7.0-fpm         # typical (ubuntu is debian-based) PHP 7
restart php5-fpm           # typical (ubuntu is debian-based)
restart php-fpm            # uncommon

Using systemd (newer servers):

systemctl restart php-fpm.service        # typical
systemctl restart php5-fpm.service       # uncommon
systemctl restart php7.0-fpm.service     # uncommon PHP 7

Or whatever the equivalent is on your system.

The above commands taken directly from this server fault answer

How to increase apache timeout directive in .htaccess?

Just in case this helps anyone else:

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

htaccess <Directory> deny from all

You cannot use the Directory directive in .htaccess. However if you create a .htaccess file in the /system directory and place the following in it, you will get the same result

#place this in /system/.htaccess as you had before
deny from all

Tomcat in Intellij Idea Community Edition

Yes, its possible and its fairly easy.

  1. Near the run button, from the dropdown, choose "edit configurations..."
  2. On the left, click the plus, then maven and rename it "Tomcat" on the right side.
  3. for command line, enter "spring-boot:run"
  4. Under the runner tab, for 'VM Options', enter "-XX:MaxPermSize=256m -Xms128m -Xmx512m -Djava.awt.headless=true" NOTE: 'use project settings' should be unticked.
  5. For environment variables enter "env=dev"
  6. Finally, click Ok.

When you're ready to press run, if you go to "localhost:8080/< page_name > " you'll see your page.

My pom.xml file is the same as the Official spring tutorial Serving Web Content with Spring MVC

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

    <groupId>org.springframework</groupId>
    <artifactId>gs-serving-web-content</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

How to get back Lost phpMyAdmin Password, XAMPP

Reinstalling the software fixes the issue, just make sure not to delete the htdocs folder in the process.

How to deploy a React App on Apache web server

Before making the npm build,
1) Go to your React project root folder and open package.json.
2) Add "homepage" attribute to package.json

  • if you want to provide absolute path

    "homepage": "http://hostName.com/appLocation",
    "name": "react-app",
    "version": "1.1.0",
    
  • if you want to provide relative path

    "homepage": "./",
    "name": "react-app",
    

    Using relative path method may warn a syntax validation error in your IDE. But the build is made without any errors during compilation.

3) Save the package.json , and in terminal run npm run-script build
4) Copy the contents of build/ folder to your server directory.

PS: It is easy to use relative path method if you want to change the build file location in your server frequently.

Completely removing phpMyAdmin

I was having a similar problem. PHP was working on my sites configured by virtualmin but not for phpmyadmin. PHPMyAdmin would not execute and the file was being downloaded by the browser. Everything I was reading was saying that libapache2-mod-php5 was not installed but I knew it was... so the thing to do was to purge it and reinstall.

sudo apt-get purge libapache2-mod-php5

sudo apt-get install libapache2-mod-php5

sudo apt-get purge phpmyadmin

sudo apt-get install phpmyadmin

sudo /etc/init.d/apache2 restart

Apache and IIS side by side (both listening to port 80) on windows2003

Either two different IP addresses (like recommended) or one web server is reverse-proxying the other (which is listening on a port <>80).

For instance: Apache listens on port 80, IIS on port 8080. Every http request goes to Apache first (of course). You can then decide to forward every request to a particular (named virtual) domain or every request that contains a particular directory (e.g. http://www.example.com/winapp/) to the IIS.

Advantage of this concept is that you have only one server listening to the public instead of two, you are more flexible as with two distinct servers.

Drawbacks: some webapps are crappily designed and a real pain in the ass to integrate into a reverse-proxy infrastructure. A working IIS webapp is dependent on a working Apache, so we have some inter-dependencies.

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

  1. Navigate to your XAMPP directory, you will find a folder called apache, open it, then copy its path, my path is "D:\Hacking Tools 2\Programs\XAMPP V2\apache"
  2. Open up apache\conf\httpd.conf with any text editor
  3. Scroll down until line 30-40
  4. You will find a code like this: ServerRoot "xampp\apache"
  5. Now, change it to be the apache directory, as I said in Step #1, my path is "D:\Hacking Tools 2\Programs\XAMPP V2\apache", so, my code will be ServerRoot "D:\Hacking Tools 2\Programs\XAMPP V2\apache"
  6. It should look somehow like this: ServerRoot "D:\XAMPP\apache"
  7. Now go back to the XAMPP main directory and run xampp_start.exe

It worked for me, if it doesn't work for you, just comment with the error value after opening the xampp_start.exe

How to set up file permissions for Laravel?

First of your answer is.

sudo chmod -R 777/775 /path/project_folder

Now You need to understand permissions and options in ubuntu.

  • chmod - You can set permissions.
  • chown - You can set the ownership of files and directories.
  • 777 - read/write/execute.
  • 775 - read/execute.

Firefox "ssl_error_no_cypher_overlap" error

Under advanced settings of firefox you should be able to set the encryption. By default SSL3.0 and TLS1.0 should be checked, so if firefox is trying to create ssl 3.0 connectons try unchecking the ssl 3.0s setting.

if that doesn't work, try searching the about:config page for "ssl2" My Firefox has settings with ssl2 set to false by default...

The program can't start because MSVCR110.dll is missing from your computer

Weird, just had simmilar issue, went here http://www.microsoft.com/en-us/download/confirmation.aspx?id=30679 downloaded and installed vcredist_x86 (i'm using 32bit apache) and it works like a charm.

apache not accepting incoming connections from outside of localhost

If you are using RHEL/CentOS 7 (the OP was not, but I thought I'd share the solution for my case), then you will need to use firewalld instead of the iptables service mentioned in other answers.

firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload

And then check that it is running with:

firewall-cmd --permanent --zone=public --list-all

It should list 80/tcp under ports

How to debug an apache virtual host configuration?

Syntax check

To check configuration files for syntax errors:

# Red Hat-based (Fedora, CentOS) and OSX
httpd -t

# Debian-based (Ubuntu)
apache2ctl -t

# MacOS
apachectl -t

List virtual hosts

To list all virtual hosts, and their locations:

# Red Hat-based (Fedora, CentOS) and OSX
httpd -S

# Debian-based (Ubuntu)
apache2ctl -S

# MacOS
apachectl -S

Could not load the Tomcat server configuration

I know it's an old question and it has been solved already but for me the Tomcat conf/tomcat-users.xml file was created with a different encoding from the rest of the configuration files. The first line of that file looked like this:

<?xml version='1.0' encoding='cp65001'?>

All I had to do to solve the issue was change that line for:

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

And voila.

I have no idea what 'cp65001' means or why it was created like that.

Maybe this will help other users facing the same issue.

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

I am using xampp 1.7.3. Using inspiration from here: xampp 1.7.3 upgrade broken virtual hosts access forbidden

INSTEAD OF add <Directory> .. </Directory> in httpd-vhosts.conf, I add it in httpd.conf right after <Directory "D:/xampplite/cgi-bin"> .. </Directory>.

Here is what I add in httpd.conf:

<Directory "D:/CofeeShop">
    AllowOverride All
    Options  All
    Order allow,deny
    Allow from all
</Directory>

And here is what I add in httpd-vhosts.conf

<VirtualHost *:8001>
    ServerAdmin [email protected]
    DocumentRoot "D:/CofeeShop"
    ServerName localhost:8001
</VirtualHost>

I also add Listen 8001 in httpd.conf to complete my setting.

Hope it helps

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

And I simply got this error because I used a totally different DocumentRoot directory.

My main DocumentRoot was the default /var/www/html and on the VirtualHost I used /sites/example.com

I have created a link on /var/www/html/example.com (to /sites/example.com). DocumentRoot was set to /var/www/html/example.com

It worked like a charm.

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

I used

a2ensite default-ssl

and it worked like a charm.

If you want to force e.g. phpmyadmin to use SSL/https you will run into this problem if this link is missing.

WampServer orange icon

Before you can fix anything you need to know which service has not started, Apache or MySQL.

As the TEST PORT 80 utility is saying Apache is running its probably the MySQL service that has not started. Unless you have another Apache running!

So which service has not started???

If the wampmanager icon is not GREEN then one of the services ( Apache/MySQL ) has not started properly.

How to tell which service is not running if the wampmanager icon is orange.

Left click the wampmanager icon to reveal the menu-> Apache -> Service If the Start/Resume service menu is Green then Apache IS NOT running.

Left click the wampmanager icon to reveal the menu-> MySQL -> Service If the Start/Resume service menu is Green then MySQL IS NOT running.

If Apache is the service that is not running it is normally, but not always, because something else has captured port 80.

Now do, Left click the wampmanager icon to reveal the menu-> Apache -> Service -> Test port 80 This will launch a command window and display some information about what, if anything is using port 80.

Whatever it is should be re-configured to not use port 80 or uninstalled if you are not using it.

If port 80 is not the problem look for errors in the appropriate error log ( use the wamp manager menus to view the error logs )

If these do not exists or show no errors then also check the Windows Event Viewer Start -> Administrative Tools -> Event Viewer And look in the 'Windows Logs' -> Application' section accessed from the menu on the left of the dialog for error messages from Apache and or MySQL.

If its MYSQL that has not started.

Check the mysql error log by using the menus

wampmanager->MySQL->error log

Check the Windows Event log for messages from MYSQL

Check you dont have another MYSQL Server instance running.

How to Configure SKYPE so it does not require port 80 or 443

Run SKYPE then using the menus do this: Tools -> Options -> Advanced -> Connection Un-Check the checkbox next to 'Use port 80 and 443 as alternatives for incomming connections' Now restart SKYPE for these changes to take effect.

If you are running Windows 8 SKYPE comes as an app and this cannot ( as yet ) be configured in this way. However if you uninstall the SKYPE app and install SKYPE in the old way, you can reconfigure it, and it works just as well.

Running AMP (apache mysql php) on Android

Have you tried using Linux Installer to get a full Debian build on the phone? It's billed as being able to run a full LAMP environment in about 300M and has gotten some good reviews.

Permissions for /var/www/html

You just need 775 for /var/www/html as long as you are logging in as myuser. The 7 octal in the middle (which is for "group" acl) ensures that the group has permission to read/write/execute. As long as you belong to the group that owns the files, "myuser" should be able to write to them. You may need to give group permissions to all the files in the docuemnt root, though:

chmod -R g+w /var/www/html

How to use org.apache.commons package?

Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.

"[notice] child pid XXXX exit signal Segmentation fault (11)" in apache error.log

Attach gdb to one of the httpd child processes and reload or continue working and wait for a crash and then look at the backtrace. Do something like this:

$ ps -ef|grep httpd
0     681     1   0 10:38pm ??         0:00.45 /Applications/MAMP/Library/bin/httpd -k start
501   690   681   0 10:38pm ??         0:00.02 /Applications/MAMP/Library/bin/httpd -k start

...

Now attach gdb to one of the child processes, in this case PID 690 (columns are UID, PID, PPID, ...)

$ sudo gdb
(gdb) attach 690
Attaching to process 690.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ....................... done
0x9568ce29 in accept$NOCANCEL$UNIX2003 ()
(gdb) c
Continuing.

Wait for crash... then:

(gdb) backtrace

Or

(gdb) backtrace full

Should give you some clue what's going on. If you file a bug report you should include the backtrace.

If the crash is hard to reproduce it may be a good idea to configure Apache to only use one child processes for handling requests. The config is something like this:

StartServers 1
MinSpareServers 1
MaxSpareServers 1

Apache shutdown unexpectedly

On your XAMPP control panel, next to apache, select the "Config" option and select the first file (httpd.conf):

there, look for the "listen" line (you may use the find tool in the notepad) and there must be a line stating "Listen 80". Note: there are other lines with "listen" on them but they should be commented (start with a #), the one you need to change is the one saying exactly "listen 80". Now change it to "Listen 1337".

Start apache now.

If the error subsists, it's because there's another port that's already in use. So, select the config option again (next to apache in your xampp control panel) and select the second option this time (httpd-ssl.conf):

there, look for the line "Listen 443" and change it to "Listen 7331".

Start apache, it should be working now.

Tomcat is not running even though JAVA_HOME path is correct

Check the comparability, if you are using java 8 then use tomcat 9, if you are using java 7 then use tomcat 7. and also set the JAVA_HOME till C:\Program Files\Java\jdk1.8.0_101, not with bin.

XAMPP, Apache - Error: Apache shutdown unexpectedly

I received the same error above and what caused it for me was that in the file 'httpd-vhosts.conf' I put a comment inside the <Directory> tags like this...

<Directory "*PATH TO MY FOLDER*...">
        AllowOverride All
        Require all Granted    ## This directive could/should be set to denied.
</Directory>

Once I removed the comment, Apache started. I guess I should have put the comment on its own line. I just thought, like other web code, it could be there.

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

How can I install Apache Ant on Mac OS X?

To get Ant running on your Mac in 5 minutes, follow these steps.

Open up your terminal.

Perform these commands in order:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

brew install ant

If you don't have Java installed yet, you will get the following error: "Error: An unsatisfied requirement failed this build." Run this command next: brew cask install java to fix this.

The installation will resume.

Check your version of by running this command:

ant -version

And you're ready to go!

How do you run a command for each line of a file?

If you know you don't have any whitespace in the input:

xargs chmod 755 < file.txt

If there might be whitespace in the paths, and if you have GNU xargs:

tr '\n' '\0' < file.txt | xargs -0 chmod 755

How to parse JSON data with jQuery / JavaScript?

Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.

Then you could use the $.each() function to loop through the data:

$.ajax({ 
    type: 'GET', 
    url: 'http://example/functions.php', 
    data: { get_param: 'value' }, 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});

or use the $.getJSON method:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});

how to use json file in html code

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>

<script>

    $(function() {


   var people = [];

   $.getJSON('people.json', function(data) {
       $.each(data.person, function(i, f) {
          var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
           "<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
           $(tblRow).appendTo("#userdata tbody");
     });

   });

});
</script>
</head>

<body>

<div class="wrapper">
<div class="profile">
   <table id= "userdata" border="2">
  <thead>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email Address</th>
            <th>City</th>
        </thead>
      <tbody>

       </tbody>
   </table>

</div>
</div>

</body>
</html>

My JSON file:

{
   "person": [
       {
           "firstName": "Clark",
           "lastName": "Kent",
           "job": "Reporter",
           "roll": 20
       },
       {
           "firstName": "Bruce",
           "lastName": "Wayne",
           "job": "Playboy",
           "roll": 30
       },
       {
           "firstName": "Peter",
           "lastName": "Parker",
           "job": "Photographer",
           "roll": 40
       }
   ]
}

I succeeded in integrating a JSON file to HTML table after working a day on it!!!

Java maximum memory on Windows XP

I think it has more to do with how Windows is configured as hinted by this response: Java -Xmx Option

Some more testing: I was able to allocate 1300MB on an old Windows XP machine with only 768MB physical RAM (plus virtual memory). On my 2GB RAM machine I can only get 1220MB. On various other corporate machines (with older Windows XP) I was able to get 1400MB. The machine with a 1220MB limit is pretty new (just purchased from Dell), so maybe it has newer (and more bloated) Windows and DLLs (it's running Window XP Pro Version 2002 SP2).

array of string with unknown size

Is there a specific reason why you need to use an array? If you don't know the size before hand you might want to use List<String>

List<String> list = new List<String>();

list.Add("Hello");
list.Add("world");
list.Add("!");

Console.WriteLine(list[2]);

Will give you an output of

!

MSDN - List(T) for more information

Printing tuple with string formatting in Python

I think the best way to do this is:

t = (1,2,3)

print "This is a tuple: %s" % str(t)

If you're familiar with printf style formatting, then Python supports its own version. In Python, this is done using the "%" operator applied to strings (an overload of the modulo operator), which takes any string and applies printf-style formatting to it.

In our case, we are telling it to print "This is a tuple: ", and then adding a string "%s", and for the actual string, we're passing in a string representation of the tuple (by calling str(t)).

If you're not familiar with printf style formatting, I highly suggest learning, since it's very standard. Most languages support it in one way or another.

how to dynamically add options to an existing select in vanilla javascript

Try this;

   var data = "";
   data = "<option value = Some value> Some Option </option>";         
   options = [];
   options.push(data);
   select = document.getElementById("drop_down_id");
   select.innerHTML = optionsHTML.join('\n'); 

How to make JavaScript execute after page load?

Comparison

In below snippet I collect choosen methods and show their sequence. Remarks

  • the document.onload (X) is not supported by any modern browser (event is never fired)
  • if you use <body onload="bodyOnLoad()"> (F) and at the same time window.onload (E) then only first one will be executed (because it override second one)
  • event handler given in <body onload="..."> (F) is wrapped by additional onload function
  • document.onreadystatechange (D) not override document .addEventListener('readystatechange'...) (C) probably cecasue onXYZevent-like methods are independent than addEventListener queues (which allows add multiple listeners). Probably nothing happens between execution this two handlers.
  • all scripts write their timestamp in console - but scripts which also have access to div write their timestamps also in body (click "Full Page" link after script execution to see it).
  • solutions readystatechange (C,D) are executed multiple times by browser but for different document states:
    • loading - the document is loading (no fired in snippet)
    • interactive - the document is parsed, fired before DOMContentLoaded
    • complete - the document and resources are loaded, fired before body/window onload

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script>_x000D_
    // solution A_x000D_
    console.log(`[timestamp: ${Date.now()}] A: Head script`);_x000D_
    _x000D_
    // solution B_x000D_
    document.addEventListener("DOMContentLoaded", () => {_x000D_
      print(`[timestamp: ${Date.now()}] B: DOMContentLoaded`);_x000D_
    });_x000D_
_x000D_
    // solution C_x000D_
    document.addEventListener('readystatechange', () => {_x000D_
      print(`[timestamp: ${Date.now()}] C: ReadyState: ${document.readyState}`);_x000D_
    });_x000D_
   _x000D_
    // solution D_x000D_
    document.onreadystatechange = s=> {print(`[timestamp: ${Date.now()}] D: document.onreadystatechange ReadyState: ${document.readyState}`)};_x000D_
    _x000D_
    // solution E (never executed)_x000D_
    window.onload = () => {_x000D_
      print(`E: <body onload="..."> override this handler`);_x000D_
    };_x000D_
_x000D_
    // solution F_x000D_
    function bodyOnLoad() {_x000D_
      print(`[timestamp: ${Date.now()}] F: <body onload='...'>`);      _x000D_
      infoAboutOnLoad(); // additional info_x000D_
    }_x000D_
    _x000D_
    // solution X_x000D_
    document.onload = () => {print(`document.onload is never fired`)};_x000D_
_x000D_
_x000D_
_x000D_
    // HELPERS_x000D_
_x000D_
    function print(txt) { _x000D_
      console.log(txt);_x000D_
      if(mydiv) mydiv.innerHTML += txt.replace('<','&lt;').replace('>','&gt;') + '<br>';_x000D_
    }_x000D_
    _x000D_
    function infoAboutOnLoad() {_x000D_
      console.log("window.onload (after  override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
      console.log(`body.onload==window.onload --> ${document.body.onload==window.onload}`);_x000D_
    }_x000D_
            _x000D_
    console.log("window.onload (before override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body onload="bodyOnLoad()">_x000D_
  <div id="mydiv"></div>_x000D_
_x000D_
  <!-- this script must te at the bottom of <body> -->_x000D_
  <script>_x000D_
    // solution G_x000D_
    print(`[timestamp: ${Date.now()}] G: <body> bottom script`);_x000D_
  </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to navigate through textfields (Next / Done Buttons)

Hi to everyone please see this one

- (void)nextPrevious:(id)sender
{

  UIView *responder = [self.view findFirstResponder];   

  if (nil == responder || ![responder isKindOfClass:[GroupTextField class]]) {
    return;
  }

  switch([(UISegmentedControl *)sender selectedSegmentIndex]) {
    case 0:
      // previous
      if (nil != ((GroupTextField *)responder).previousControl) {
        [((GroupTextField *)responder).previousControl becomeFirstResponder];
        DebugLog(@"currentControl: %i previousControl: %i",((GroupTextField *)responder).tag,((GroupTextField *)responder).previousControl.tag);
      }
      break;
    case 1:
      // next
      if (nil != ((GroupTextField *)responder).nextControl) {
        [((GroupTextField *)responder).nextControl becomeFirstResponder];
        DebugLog(@"currentControl: %i nextControl: %i",((GroupTextField *)responder).tag,((GroupTextField *)responder).nextControl.tag);
      }     
      break;    
  }
}

How to set timer in android?

For those who can't rely on Chronometer, I made a utility class out of one of the suggestions:

public class TimerTextHelper implements Runnable {
   private final Handler handler = new Handler();
   private final TextView textView;
   private volatile long startTime;
   private volatile long elapsedTime;

   public TimerTextHelper(TextView textView) {
       this.textView = textView;
   }

   @Override
   public void run() {
       long millis = System.currentTimeMillis() - startTime;
       int seconds = (int) (millis / 1000);
       int minutes = seconds / 60;
       seconds = seconds % 60;

       textView.setText(String.format("%d:%02d", minutes, seconds));

       if (elapsedTime == -1) {
           handler.postDelayed(this, 500);
       }
   }

   public void start() {
       this.startTime = System.currentTimeMillis();
       this.elapsedTime = -1;
       handler.post(this);
   }

   public void stop() {
       this.elapsedTime = System.currentTimeMillis() - startTime;
       handler.removeCallbacks(this);
   }

   public long getElapsedTime() {
       return elapsedTime;
   }
 }

to use..just do:

 TimerTextHelper timerTextHelper = new TimerTextHelper(textView);
 timerTextHelper.start();

.....

 timerTextHelper.stop();
 long elapsedTime = timerTextHelper.getElapsedTime();

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

try using this one

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri https://apod.nasa.gov/apod/

What does print(... sep='', '\t' ) mean?

sep='' ignore whiteSpace. see the code to understand.Without sep=''

from itertools import permutations
s,k = input().split()
for i in list(permutations(sorted(s), int(k))):
    print(*i)

output:

HACK 2
A C
A H
A K
C A
C H
C K
H A
H C
H K
K A
K C
K H

using sep='' The code and output.

from itertools import permutations
s,k = input().split()
for i in list(permutations(sorted(s), int(k))):
    print(*i,sep='')

output:

HACK 2
AC
AH
AK
CA
CH
CK
HA
HC
HK
KA
KC
KH

Textarea Auto height

For those of us accomplishing this with Angular JS, I used a directive

HTML:

<textarea elastic ng-model="someProperty"></textarea>

JS:

.directive('elastic', [
    '$timeout',
    function($timeout) {
        return {
            restrict: 'A',
            link: function($scope, element) {
                $scope.initialHeight = $scope.initialHeight || element[0].style.height;
                var resize = function() {
                    element[0].style.height = $scope.initialHeight;
                    element[0].style.height = "" + element[0].scrollHeight + "px";
                };
                element.on("input change", resize);
                $timeout(resize, 0);
            }
        };
    }
]);

$timeout queues an event that will fire after the DOM loads, which is what's necessary to get the right scrollHeight (otherwise you'll get undefined)

What is the difference between char * const and const char *?

const always modifies the thing that comes before it (to the left of it), EXCEPT when it's the first thing in a type declaration, where it modifies the thing that comes after it (to the right of it).

So these two are the same:

int const *i1;
const int *i2;

they define pointers to a const int. You can change where i1 and i2 points, but you can't change the value they point at.

This:

int *const i3 = (int*) 0x12345678;

defines a const pointer to an integer and initializes it to point at memory location 12345678. You can change the int value at address 12345678, but you can't change the address that i3 points to.

Counting Chars in EditText Changed Listener

how about just getting the length of char in your EditText and display it?

something along the line of

tv.setText(s.length() + " / " + String.valueOf(charCounts));

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

CURRENT_DATE/CURDATE() not working as default DATE value

I came to this page with the same question in mind, but it worked for me!, Just thought to update here , may be helpful for someone later!!

MariaDB [niffdb]> desc invoice;
+---------+--------+------+-----+---------+----------------+
| Field   | Type   | Null | Key | Default | Extra          |
+---------+--------+------+-----+---------+----------------+
| inv_id  | int(4) | NO   | PRI | NULL    | auto_increment |
| cust_id | int(4) | NO   | MUL | NULL    |                |
| inv_dt  | date   | NO   |     | NULL    |                |
| smen_id | int(4) | NO   | MUL | NULL    |                |
+---------+--------+------+-----+---------+----------------+
4 rows in set (0.003 sec)

MariaDB [niffdb]> ALTER TABLE invoice MODIFY inv_dt DATE NOT NULL DEFAULT (CURRENT_DATE);
Query OK, 0 rows affected (0.003 sec)
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [niffdb]> desc invoice;
+---------+--------+------+-----+-----------+----------------+
| Field   | Type   | Null | Key | Default   | Extra          |
+---------+--------+------+-----+-----------+----------------+
| inv_id  | int(4) | NO   | PRI | NULL      | auto_increment |
| cust_id | int(4) | NO   | MUL | NULL      |                |
| inv_dt  | date   | NO   |     | curdate() |                |
| smen_id | int(4) | NO   | MUL | NULL      |                |
+---------+--------+------+-----+-----------+----------------+
4 rows in set (0.002 sec)

MariaDB [niffdb]> SELECT VERSION();
+---------------------------+
| VERSION()                 |
+---------------------------+
| 10.3.18-MariaDB-0+deb10u1 |
+---------------------------+
1 row in set (0.010 sec)

MariaDB [niffdb]>

Items in JSON object are out of order using "json.dumps"?

Both Python dict (before Python 3.7) and JSON object are unordered collections. You could pass sort_keys parameter, to sort the keys:

>>> import json
>>> json.dumps({'a': 1, 'b': 2})
'{"b": 2, "a": 1}'
>>> json.dumps({'a': 1, 'b': 2}, sort_keys=True)
'{"a": 1, "b": 2}'

If you need a particular order; you could use collections.OrderedDict:

>>> from collections import OrderedDict
>>> json.dumps(OrderedDict([("a", 1), ("b", 2)]))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict([("b", 2), ("a", 1)]))
'{"b": 2, "a": 1}'

Since Python 3.6, the keyword argument order is preserved and the above can be rewritten using a nicer syntax:

>>> json.dumps(OrderedDict(a=1, b=2))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict(b=2, a=1))
'{"b": 2, "a": 1}'

See PEP 468 – Preserving Keyword Argument Order.

If your input is given as JSON then to preserve the order (to get OrderedDict), you could pass object_pair_hook, as suggested by @Fred Yankowski:

>>> json.loads('{"a": 1, "b": 2}', object_pairs_hook=OrderedDict)
OrderedDict([('a', 1), ('b', 2)])
>>> json.loads('{"b": 2, "a": 1}', object_pairs_hook=OrderedDict)
OrderedDict([('b', 2), ('a', 1)])

Disable pasting text into HTML form

With Jquery you can do this with one simple codeline.

HTML:

<input id="email" name="email">

Code:

$(email).on('paste', false);

JSfiddle: https://jsfiddle.net/ZjR9P/2/

How to parse/read a YAML file into a Python object?

Here is one way to test which YAML implementation the user has selected on the virtualenv (or the system) and then define load_yaml_file appropriately:

load_yaml_file = None

if not load_yaml_file:
    try:
        import yaml
        load_yaml_file = lambda fn: yaml.load(open(fn))
    except:
        pass

if not load_yaml_file:
    import commands, json
    if commands.getstatusoutput('ruby --version')[0] == 0:
        def load_yaml_file(fn):
            ruby = "puts YAML.load_file('%s').to_json" % fn
            j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
            return json.loads(j[1])

if not load_yaml_file:
    import os, sys
    print """
ERROR: %s requires ruby or python-yaml  to be installed.

apt-get install ruby

  OR

apt-get install python-yaml

  OR

Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
   apt-get install epel-release
   apt-get install python-pip
   apt-get install libyaml-cpp-dev
   python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
  https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
  Pip might not play by all the rules.
  Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
  https://stackoverflow.com/questions/46326059/
  https://stackoverflow.com/questions/36410756/
  https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
  https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.

""" % sys.argv[0]
    os._exit(4)


# test
import sys
print load_yaml_file(sys.argv[1])

What are the options for storing hierarchical data in a relational database?

If your database supports arrays, you can also implement a lineage column or materialized path as an array of parent ids.

Specifically with Postgres you can then use the set operators to query the hierarchy, and get excellent performance with GIN indices. This makes finding parents, children, and depth pretty trivial in a single query. Updates are pretty manageable as well.

I have a full write up of using arrays for materialized paths if you're curious.

sql ORDER BY multiple values in specific order?

You can use a LEFT JOIN with a "VALUES ('f',1),('p',2),('a',3),('i',4)" and use the second column in your order-by expression. Postgres will use a Hash Join which will be much faster than a huge CASE if you have a lot of values. And it is easier to autogenerate.

If this ordering information is fixed, then it should have its own table.

How to install sklearn?

pip install numpy scipy scikit-learn

if you don't have pip, install it using

python get-pip.py

Download get-pip.py from the following link. or use curl to download it.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

phpMyAdmin + CentOS 6.0 - Forbidden

None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:

Edit file phpMyAdmin.conf

sudo nano /etc/httpd/conf.d/phpMyAdmin.conf

And replace this at the top:

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       #Require ip 127.0.0.1
       #Require ip ::1
       Require all granted
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

Size of character ('a') in C/C++

In C, the type of a character constant like 'a' is actually an int, with size of 4 (or some other implementation-dependent value). In C++, the type is char, with size of 1. This is one of many small differences between the two languages.

Javascript ajax call on page onload

This is really easy using a JavaScript library, e.g. using jQuery you could write:

$(document).ready(function(){
$.ajax({ url: "database/update.html",
        context: document.body,
        success: function(){
           alert("done");
        }});
});

Without jQuery, the simplest version might be as follows, but it does not account for browser differences or error handling:

<html>
  <body onload="updateDB();">
  </body>
  <script language="javascript">
    function updateDB() {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "database/update.html", true);
      xhr.send(null);
      /* ignore result */
    }
  </script>
</html>

See also:

Can anyone explain me StandardScaler?

StandardScaler performs the task of Standardization. Usually a dataset contains variables that are different in scale. For e.g. an Employee dataset will contain AGE column with values on scale 20-70 and SALARY column with values on scale 10000-80000.
As these two columns are different in scale, they are Standardized to have common scale while building machine learning model.

Change marker size in Google maps V3

This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.

The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);  

As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.

Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:

what happens when you leave anchor null on an enlarged shadow

The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null. In other words, leaving the anchor null ensures the tip points where it is supposed to point.

However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.

By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.

var pinShadow = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
    null,
    null,
    /* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
    new google.maps.Point(40, 110), 
    new google.maps.Size(120, 110)); 

to give this:

offset the enlarged shadow anchor explicitly

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

How to commit a change with both "message" and "description" from the command line?

In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.

git rebase -i origin/master

Then, your commits will appear:

pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments

Select the commit you want to reword and save.

pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments

Now, you have the opportunity to add header and body, where the first line will be the header.

Create perpetuum mobile

Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.

Error occurred during initialization of boot layer FindException: Module not found

The reason behind this is that meanwhile creating your own class, you had also accepted to create a default class as prescribed by your IDE and after writing your code in your own class, you are getting such an error. In order to eliminate this, go to the PROJECT folder ? src ? Default package. Keep only one class (in which you had written code) and delete others.

After that, run your program and it will definitely run without any error.

How to open port in Linux

The following configs works on Cent OS 6 or earlier

As stated above first have to disable selinux.

Step 1 nano /etc/sysconfig/selinux

Make sure the file has this configurations

SELINUX=disabled

SELINUXTYPE=targeted

Then restart the system

Step 2

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

Step 3

sudo service iptables save

For Cent OS 7

step 1

firewall-cmd --zone=public --permanent --add-port=8080/tcp

Step 2

firewall-cmd --reload

git add remote branch

I tested what @Samy Dindane suggested in the comment on the OP.

I believe it works, try

git fetch <remote_name> <remote_branch>:<local_branch>
git checkout <local_branch>

Here's an example for a fictitious remote repository named foo with a branch named bar where I create a local branch bar tracking the remote:

git fetch foo bar:bar
git checkout bar

SQL Views - no variables?

What I do is create a view that performs the same select as the table variable and link that view into the second view. So a view can select from another view. This achieves the same result

Change URL without refresh the page

Update

Based on Manipulating the browser history, passing the empty string as second parameter of pushState method (aka title) should be safe against future changes to the method, so it's better to use pushState like this:

history.pushState(null, '', '/en/step2');    

You can read more about that in mentioned article

Original Answer

Use history.pushState like this:

history.pushState(null, null, '/en/step2');

Update 2 to answer Idan Dagan's comment:

Why not using history.replaceState()?

From MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

That means if you use replaceState, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState doesn't add new entry to history) and it's not recommended and provide bad UX.

Update 3 to add window.onpopstate

So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState, you can detect the back/forward button navigation by using window.onpopstate like this:

window.onpopstate = function(e) {
    // ... 
};

As the first argument of pushState is an object, if you passed an object instead of null, you can access that object in onpopstate which is very handy, here is how:

window.onpopstate = function(e) {
    if(e.state) {
        console.log(e.state);
    }
};

Update 4 to add Reading the current state:

When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate event using the history.state property like this:

console.log(history.state);

Bonus: Use following to check history.pushState support:

if (history.pushState) {
  // \o/
}

Entity Framework - Generating Classes

EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull : http://www.devart.com/entitydeveloper/editions.html

invalid use of non-static data member

The nested class doesn't know about the outer class, and protected doesn't help. You'll have to pass some actual reference to objects of the nested class type. You could store a foo*, but perhaps a reference to the integer is enough:

class Outer
{
    int n;

public:
    class Inner
    {
        int & a;
    public:
        Inner(int & b) : a(b) { }
        int & get() { return a; }
    };

    // ...  for example:

    Inner inn;
    Outer() : inn(n) { }
};

Now you can instantiate inner classes like Inner i(n); and call i.get().

web.xml is missing and <failOnMissingWebXml> is set to true

I had the same problem, even though I had 'src/main/webapp/WEB-INF/' folder with correct web.xml.

The problem disappeared after I recreated (maven->eclipse) configuration with Maven build.. I executed mvn eclipse:clean eclipse:eclipse

And then I used Maven -> Update Project to add (eclipse->maven) plugin specific options.

What's the difference between a 302 and a 307 redirect?

307 came about because user agents adopted as a de facto behaviour to take POST requests that receive a 302 response and send a GET request to the Location response header.

That is the incorrect behaviour — only a 303 should cause a POST to turn into a GET. User agents should (but don't) stick with the POST method when requesting the new URL if the original POST request returned a 302.

307 was introduced to allow servers to make it clear to the user agent that a method change should not be made by the client when following the Location response header.

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

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

How to set min-height for bootstrap container

Two things are happening here.

  1. You are not using the container class properly.
  2. You are trying to override Bootstrap's CSS for the container class

Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.

What you want to do is the following:

<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
    <div class="row">
        <div class="col-md-4 myClassName">  <!-- myClassName is defined in my CSS as you defined your container -->
            <img src="#.jpg" height="200px" width="300px">
        </div>
    </div>
</div>

Here you can find more info on the Bootstrap grid system.

That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...

.container {
   padding-right: 15px;
   padding-left: 15px;
   margin-right: auto;
   margin-left: auto;
   max-width: 900px;
   overflow:hidden;
   min-height:0px !important;
}

But I have always found that the "!important" clause just makes for messy CSS.

What is the point of "final class" in Java?

Relevant reading: The Open-Closed Principle by Bob Martin.

Key quote:

Software Entities (Classes, Modules, Functions, etc.) should be open for Extension, but closed for Modification.

The final keyword is the means to enforce this in Java, whether it's used on methods or on classes.

How To Accept a File POST

I used Mike Wasson's answer before I updated all the NuGets in my webapi mvc4 project. Once I did, I had to re-write the file upload action:

    public Task<HttpResponseMessage> Upload(int id)
    {
        HttpRequestMessage request = this.Request;
        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
        }

        string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(o =>
            {
                FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);

                string guid = Guid.NewGuid().ToString();

                File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));

                return new HttpResponseMessage()
                {
                    Content = new StringContent("File uploaded.")
                };
            }
        );
        return task;
    }

Apparently BodyPartFileNames is no longer available within the MultipartFormDataStreamProvider.

Use CSS to make a span not clickable

CSS relates to visual styling and not behaviour, so the answer is no really.

You could however either use javascript to modify the behaviour or change the styling of the span in question so that it doesn't have the pointy finger, underline, etc. Styling it like that will still leave it clickable.

Even better, change your markup so that it reflects what you want it to do.

How to position background image in bottom right corner? (CSS)

This should do it:

<style>
body {
    background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>

http://www.w3schools.com/cssref/pr_background-position.asp

Excel: Searching for multiple terms in a cell

Another way

=IF(SUMPRODUCT(--(NOT(ISERR(SEARCH({"Gingrich","Obama","Romney"},C1)))))>0,"1","")

Also, if you keep a list of values in, say A1 to A3, then you can use

=IF(SUMPRODUCT(--(NOT(ISERR(SEARCH($A$1:$A$3,C1)))))>0,"1","")

The wildcards are not necessary at all in the Search() function, since Search() returns the position of the found string.

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

If you are running server already, don't forget to use http:// in the API call. This might cause a serious trouble.

JSON library for C#

The .net framework supports JSON through JavaScriptSerializer. Here is a good example to get you started.

using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace GoogleTranslator.GoogleJSON
{
    public class FooTest
    {
        public void Test()
        {
            const string json = @"{
              ""DisplayFieldName"" : ""ObjectName"", 
              ""FieldAliases"" : {
                ""ObjectName"" : ""ObjectName"", 
                ""ObjectType"" : ""ObjectType""
              }, 
              ""PositionType"" : ""Point"", 
              ""Reference"" : {
                ""Id"" : 1111
              }, 
              ""Objects"" : [
                {
                  ""Attributes"" : {
                    ""ObjectName"" : ""test name"", 
                    ""ObjectType"" : ""test type""
                  }, 
                  ""Position"" : 
                  {
                    ""X"" : 5, 
                    ""Y"" : 7
                  }
                }
              ]
            }";

            var ser = new JavaScriptSerializer();
            ser.Deserialize<Foo>(json);
        }
    }

    public class Foo
    {
        public Foo() { Objects = new List<SubObject>(); }
        public string DisplayFieldName { get; set; }
        public NameTypePair FieldAliases { get; set; }
        public PositionType PositionType { get; set; }
        public Ref Reference { get; set; }
        public List<SubObject> Objects { get; set; }
    }

    public class NameTypePair
    {
        public string ObjectName { get; set; }
        public string ObjectType { get; set; }
    }

    public enum PositionType { None, Point }
    public class Ref
    {
        public int Id { get; set; }
    }

    public class SubObject
    {
        public NameTypePair Attributes { get; set; }
        public Position Position { get; set; }
    }

    public class Position
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
}

Is it possible to pull just one file in Git?

git checkout master -- myplugin.js

master = branch name

myplugin.js = file name

Launch an app on OS X with command line

In OS X 10.6, the open command was enhanced to allow passing of arguments to the application:

open ./AppName.app --args -AppCommandLineArg

But for older versions of Mac OS X, and because app bundles aren't designed to be passed command line arguments, the conventional mechanism is to use Apple Events for files like here for Cocoa apps or here for Carbon apps. You could also probably do something kludgey by passing parameters in using environment variables.

Timing a command's execution in PowerShell

Here's a function I wrote which works similarly to the Unix time command:

function time {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$command,
        [switch]$quiet = $false
    )
    $start = Get-Date
    try {
        if ( -not $quiet ) {
            iex $command | Write-Host
        } else {
            iex $command > $null
        }
    } finally {
        $(Get-Date) - $start
    }
}

Source: https://gist.github.com/bender-the-greatest/741f696d965ed9728dc6287bdd336874

check if file exists in php

Based on your comment to Haim, is this a file on your own server? If so, you need to use the file system path, not url (e.g. file_exists( '/path/to/images/thumbnail.jpg' )).

How do I set up access control in SVN?

@Stephen Bailey

To complete your answer, you can also delegate the user rights to the project manager, through a plain text file in your repository.

To do that, you set up your SVN database with a default authz file containing the following:

###########################################################################
# The content of this file always precedes the content of the
# $REPOS/admin/acl_descriptions.txt file.
# It describes the immutable permissions on main folders.
###########################################################################
[groups]
svnadmins = xxx,yyy,....

[/]
@svnadmins = rw
* = r
[/admin]
@svnadmins = rw
@projadmins = r
* =

[/admin/acl_descriptions.txt]
@projadmins = rw

This default authz file authorizes the SVN administrators to modify a visible plain text file within your SVN repository, called '/admin/acl_descriptions.txt', in which the SVN administrators or project managers will modify and register the users.

Then you set up a pre-commit hook which will detect if the revision is composed of that file (and only that file).

If it is, this hook's script will validate the content of your plain text file and check if each line is compliant with the SVN syntax.

Then a post-commit hook will update the \conf\authz file with the concatenation of:

  • the TEMPLATE authz file presented above
  • the plain text file /admin/acl_descriptions.txt

The first iteration is done by the SVN administrator, who adds:

[groups]
projadmins = zzzz

He commits his modification, and that updates the authz file.

Then the project manager 'zzzz' can add, remove or declare any group of users and any users he wants. He commits the file and the authz file is updated.

That way, the SVN administrator does not have to individually manage any and all users for all SVN repositories.

JQuery wait for page to finish loading before starting the slideshow?

You probably already know about $(document).ready(...). What you need is a preloading mechanism; something that fetches data (text or images or whatever) before showing it off. This can make a site feel much more professional.

Take a look at jQuery.Preload (there are others). jQuery.Preload has several ways of triggering preloading, and also provides callback functionality (when the image is preloaded, then show it). I have used it heavily, and it works great.

Here's how easy it is to get started with jQuery.Preload:

$(function() {
  // First get the preload fetches under way
  $.preload(["images/button-background.png", "images/button-highlight.png"]);
  // Then do anything else that you would normally do here
  doSomeStuff();
});

Get User's Current Location / Coordinates

import Foundation
import CoreLocation

enum Result<T> {
  case success(T)
  case failure(Error)
}

final class LocationService: NSObject {
    private let manager: CLLocationManager

    init(manager: CLLocationManager = .init()) {
        self.manager = manager
        super.init()
        manager.delegate = self
    }

    var newLocation: ((Result<CLLocation>) -> Void)?
    var didChangeStatus: ((Bool) -> Void)?

    var status: CLAuthorizationStatus {
        return CLLocationManager.authorizationStatus()
    }

    func requestLocationAuthorization() {
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            manager.startUpdatingLocation()
            //locationManager.startUpdatingHeading()
        }
    }

    func getLocation() {
        manager.requestLocation()
    }

    deinit {
        manager.stopUpdatingLocation()
    }

}

 extension LocationService: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        newLocation?(.failure(error))
        manager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.sorted(by: {$0.timestamp > $1.timestamp}).first {
            newLocation?(.success(location))
        }
        manager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined, .restricted, .denied:
            didChangeStatus?(false)
        default:
            didChangeStatus?(true)
        }
    }
}

Needs to write this code in required ViewController.

 //NOTE:: Add permission in info.plist::: NSLocationWhenInUseUsageDescription


let locationService = LocationService()

 @IBAction func action_AllowButtonTapped(_ sender: Any) {
     didTapAllow()
 }

 func didTapAllow() {
     locationService.requestLocationAuthorization()
 }

 func getCurrentLocationCoordinates(){
   locationService.newLocation = {result in
     switch result {
      case .success(let location):
      print(location.coordinate.latitude, location.coordinate.longitude)
      case .failure(let error):
      assertionFailure("Error getting the users location \(error)")
   }
  }
}

func getCurrentLocationCoordinates() {
    locationService.newLocation = { result in
        switch result {
        case .success(let location):
            print(location.coordinate.latitude, location.coordinate.longitude)
            CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
                if error != nil {
                    print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
                    return
                }
                if (placemarks?.count)! > 0 {
                    print("placemarks", placemarks!)
                    let pmark = placemarks?[0]
                    self.displayLocationInfo(pmark)
                } else {
                    print("Problem with the data received from geocoder")
                }
            })
        case .failure(let error):
            assertionFailure("Error getting the users location \(error)")
        }
    }
}

Update statement with inner join on Oracle

Using description instead of desc for table2,

update
  table1
set
  value = (select code from table2 where description = table1.value)
where
  exists (select 1 from table2 where description = table1.value)
  and
  table1.updatetype = 'blah'
;

Display Back Arrow on Toolbar

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setNavigationIcon(R.drawable.back_arrow); // your drawable
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed(); // Implemented by activity
        }
    });

And for API 21+ android:navigationIcon

<android.support.v7.widget.Toolbar
    android:navigationIcon="@drawable/back_arrow"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"/>

What is the difference between ports 465 and 587?

I don't want to name names, but someone appears to be completely wrong. The referenced standards body stated the following: submissions 465 tcp Message Submission over TLS protocol [IESG] [IETF_Chair] 2017-12-12 [RFC8314]

If you are so inclined, you may wish to read the referenced RFC.

This seems to clearly imply that port 465 is the best way to force encrypted communication and be sure that it is in place. Port 587 offers no such guarantee.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

Do below steps :

  1. Check the version of chrome browser.

  2. download chromedriver of same version from https://sites.google.com/a/chromium.org/chromedriver/

  3. Give correct path in the pycharm and run the code.

Replace console output in Python

Added a little bit more functionality to the example of Aravind Voggu:

def progressBar(name, value, endvalue, bar_length = 50, width = 20):
        percent = float(value) / endvalue
        arrow = '-' * int(round(percent*bar_length) - 1) + '>'
        spaces = ' ' * (bar_length - len(arrow))
        sys.stdout.write("\r{0: <{1}} : [{2}]{3}%".format(\
                         name, width, arrow + spaces, int(round(percent*100))))
        sys.stdout.flush()
        if value == endvalue:     
             sys.stdout.write('\n\n')

Now you are able to generate multiple progressbars without replacing the previous one.

I've also added name as a value with a fixed width.

For two loops and two times the use of progressBar() the result will look like:

progress bar animation

Delete last char of string

string strgroupids = string.Empty;

groupIds.ForEach(g =>
{
    strgroupids = strgroupids + g.ToString() + ",";
});

strgroupids = strgroupids.Substring(0, strgroupids.Length - 1);

Note that the use of ForEach here is normally considered "wrong" (read for example http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx)

Using some LINQ:

string strgroupids = groupIds.Aggregate(string.Empty, (p, q) => p + q + ',');
strgroupids = strgroupids.Substring(0, str1.Length - 1);

Without end-substringing:

string strgroupids = groupIds.Aggregate(string.Empty, (p, q) => (p != string.Empty ? p + "," + q : q.ToString()));

How to convert a string or integer to binary in Ruby?

In ruby Integer class, to_s is defined to receive non required argument radix called base, pass 2 if you want to receive binary representation of a string.

Here is a link for an official documentation of String#to_s

  1.upto(10).each { |n|  puts n.to_s(2) }

Twitter API - Display all tweets with a certain hashtag?

UPDATE for v1.1:

Rather than giving q="search_string" give it q="hashtag" in URL encoded form to return results with HASHTAG ONLY. So your query would become:

    GET https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames

%23 is URL encoded form of #. Try the link out in your browser and it should work.

You can optimize the query by adding since_id and max_id parameters detailed here. Hope this helps !

Note: Search API is now a OAUTH authenticated call, so please include your access_tokens to the above call

Updated

Twitter Search doc link: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html

Convert a tensor to numpy array in Tensorflow?

If you see there is a method _numpy(), e.g for an EagerTensor simply call the above method and you will get an ndarray.

How to install MySQLdb package? (ImportError: No module named setuptools)

@main:

$ su
$ yum install MySQL-python

and it will be installed (MySQLdb).

How do I add indices to MySQL tables?

You say you have an index, the explain says otherwise. However, if you really do, this is how to continue:

If you have an index on the column, and MySQL decides not to use it, it may by because:

  1. There's another index in the query MySQL deems more appropriate to use, and it can use only one. The solution is usually an index spanning multiple columns if their normal method of retrieval is by value of more then one column.
  2. MySQL decides there are to many matching rows, and thinks a tablescan is probably faster. If that isn't the case, sometimes an ANALYZE TABLE helps.
  3. In more complex queries, it decides not to use it based on extremely intelligent thought-out voodoo in the query-plan that for some reason just not fits your current requirements.

In the case of (2) or (3), you could coax MySQL into using the index by index hint sytax, but if you do, be sure run some tests to determine whether it actually improves performance to use the index as you hint it.

Generate a dummy-variable

Hi i wrote this general function to generate a dummy variable which essentially replicates the replace function in Stata.

If x is the data frame is x and i want a dummy variable called a which will take value 1 when x$b takes value c

introducedummy<-function(x,a,b,c){
   g<-c(a,b,c)
  n<-nrow(x)
  newcol<-g[1]
  p<-colnames(x)
  p2<-c(p,newcol)
  new1<-numeric(n)
  state<-x[,g[2]]
  interest<-g[3]
  for(i in 1:n){
    if(state[i]==interest){
      new1[i]=1
    }
    else{
      new1[i]=0
    }
  }
    x$added<-new1
    colnames(x)<-p2
    x
  }

Find all elements with a certain attribute value in jquery

$('div[imageId="imageN"]').each(function() {
    // `this` is the div
});

To check for the sole existence of the attribute, no matter which value, you could use ths selector instead: $('div[imageId]')

Hibernate-sequence doesn't exist

This might be caused by HHH-10876 which got fixed so make sure you update to:

  • Hibernate ORM 5.2.1,
  • Hibernate ORM 5.1.1,
  • Hibernate ORM 5.0.11

difference between System.out.println() and System.err.println()

Those commands use different output streams. By default both messages will be printed on console but it's possible for example to redirect one or both of these to a file.

java MyApp 2>errors.txt

This will redirect System.err to errors.txt file.

Hiding the scroll bar on an HTML page

My answer will scroll even when overflow:hidden;, using jQuery:

For example, scroll horizontally with the mouse wheel:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type='text/javascript' src='/js/jquery.mousewheel.min.js'></script>
<script type="text/javascript">
    $(function() {

       $("YourSelector").mousewheel(function(event, delta) {

          this.scrollLeft -= (delta * 30);
          event.preventDefault();
       });
    });
</script>

What is an MvcHtmlString and when should I use it?

This is a late answer but if anyone reading this question is using razor, what you should remember is that razor encodes everything by default, but by using MvcHtmlString in your html helpers you can tell razor that it doesn't need to encode it.

If you want razor to not encode a string use

@Html.Raw("<span>hi</span>")

Decompiling Raw(), shows us that it's wrapping the string in a HtmlString

public IHtmlString Raw(string value) {
    return new HtmlString(value); 
}

"HtmlString only exists in ASP.NET 4.

MvcHtmlString was a compatibility shim added to MVC 2 to support both .NET 3.5 and .NET 4. Now that MVC 3 is .NET 4 only, it's a fairly trivial subclass of HtmlString presumably for MVC 2->3 for source compatibility." source

How to set proxy for wget?

After trying many tutorials to configure my Ubuntu 16.04 LTS behind a authenticated proxy, it worked with these steps:

Edit /etc/wgetrc:

$ sudo nano /etc/wgetrc

Uncomment these lines:

#https_proxy = http://proxy.yoyodyne.com:18023/
#http_proxy = http://proxy.yoyodyne.com:18023/
#ftp_proxy = http://proxy.yoyodyne.com:18023/
#use_proxy = on

Change http://proxy.yoyodyne.com:18023/ to http://username:password@domain:port/

IMPORTANT: If it still doesn't work, check if your password has special characters, such as #, @, ... If this is the case, escape them (for example, replace passw@rd with passw%40rd).

How to install trusted CA certificate on Android device?

Prior to Android KitKat you have to root your device to install new certificates.

From Android KitKat (4.0) up to Nougat (7.0) it's possible and easy. I was able to install the Charles Web Debbuging Proxy cert on my un-rooted device and successfully sniff SSL traffic.

Extract from http://wiki.cacert.org/FAQ/ImportRootCert

Before Android version 4.0, with Android version Gingerbread & Froyo, there was a single read-only file ( /system/etc/security/cacerts.bks ) containing the trust store with all the CA ('system') certificates trusted by default on Android. Both system apps and all applications developed with the Android SDK use this. Use these instructions on installing CAcert certificates on Android Gingerbread, Froyo, ...

Starting from Android 4.0 (Android ICS/'Ice Cream Sandwich', Android 4.3 'Jelly Bean' & Android 4.4 'KitKat'), system trusted certificates are on the (read-only) system partition in the folder '/system/etc/security/' as individual files. However, users can now easily add their own 'user' certificates which will be stored in '/data/misc/keychain/certs-added'.

System-installed certificates can be managed on the Android device in the Settings -> Security -> Certificates -> 'System'-section, whereas the user trusted certificates are manged in the 'User'-section there. When using user trusted certificates, Android will force the user of the Android device to implement additional safety measures: the use of a PIN-code, a pattern-lock or a password to unlock the device are mandatory when user-supplied certificates are used.

Installing CAcert certificates as 'user trusted'-certificates is very easy. Installing new certificates as 'system trusted'-certificates requires more work (and requires root access), but it has the advantage of avoiding the Android lockscreen requirement.

From Android N onwards it gets a littler harder, see this extract from the Charles proxy website:

As of Android N, you need to add configuration to your app in order to have it trust the SSL certificates generated by Charles SSL Proxying. This means that you can only use SSL Proxying with apps that you control.

In order to configure your app to trust Charles, you need to add a Network Security Configuration File to your app. This file can override the system default, enabling your app to trust user installed CA certificates (e.g. the Charles Root Certificate). You can specify that this only applies in debug builds of your application, so that production builds use the default trust profile.

Add a file res/xml/network_security_config.xml to your app:

<network-security-config>    
    <debug-overrides> 
        <trust-anchors> 
            <!-- Trust user added CAs while debuggable only -->
            <certificates src="user" /> 
        </trust-anchors>    
    </debug-overrides>  
</network-security-config>

Then add a reference to this file in your app's manifest, as follows:

<?xml version="1.0" encoding="utf-8"?> 
<manifest>
    <application android:networkSecurityConfig="@xml/network_security_config">
    </application> 
</manifest>

Override devise registrations controller

In your form are you passing in any other attributes, via mass assignment that don't belong to your user model, or any of the nested models?

If so, I believe the ActiveRecord::UnknownAttributeError is triggered in this instance.

Otherwise, I think you can just create your own controller, by generating something like this:

# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end

  def create
    # add custom create logic here
  end

  def update
    super
  end
end 

And then tell devise to use that controller instead of the default with:

# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}

How to Clear Console in Java?

Use the following code:


System.out.println("\f");

'\f' is an escape sequence which represents FormFeed. This is what I have used in my projects to clear the console. This is simpler than the other codes, I guess.

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

For PHP, put this line of code before you start printing your XML:

while(ob_get_level()) ob_end_clean();

Simple C example of doing an HTTP POST and consuming the response

Handle added.
Added Host header.
Added linux / windows support, tested (XP,WIN7).
WARNING: ERROR : "segmentation fault" if no host,path or port as argument.

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#ifdef __linux__ 
    #include <sys/socket.h> /* socket, connect */
    #include <netdb.h> /* struct hostent, gethostbyname */
    #include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#elif _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <windows.h>
    #pragma comment(lib,"ws2_32.lib") //Winsock Library

#else

#endif

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{

    int i;
    struct hostent *server;
    struct sockaddr_in serv_addr;
    int bytes, sent, received, total, message_size;
    char *message, response[4096];
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";
    char *path = strlen(argv[4])>0?argv[4]:"/";
    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
                printf("Process 1\n");
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(path);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
                printf("Process 2\n");
        message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(path);                            /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }
            printf("Allocating...\n");
    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,                                          /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"",host);            /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,host);                                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            path,host);                                        /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }
    printf("Processed\n");
    /* What are we going to send? */
    printf("Request:\n%s\n",message);
        /* lookup the ip address */

    total = strlen(message);
    /* create the socket */
    #ifdef _WIN32
WSADATA wsa;
SOCKET s;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");

server = gethostbyname(host);
serv_addr.sin_addr.s_addr = inet_addr(server->h_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
//Connect to remote server
if (connect(s , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
{
    printf("connect failed with error code : %d" , WSAGetLastError());
    return 1;
}

puts("Connected");
if( send(s , message , strlen(message) , 0) < 0)
{
    printf("Send failed with error code : %d" , WSAGetLastError());
    return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if((received = recv(s , response , 2000 , 0)) == SOCKET_ERROR)
{
    printf("recv failed with error code : %d" , WSAGetLastError());
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
response[received] = '\0';
puts(response);

closesocket(s);
WSACleanup();
    #endif
    #ifdef __linux__ 
    int sockfd;
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) error("ERROR opening socket");
        /* fill in the structure */
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(portno);
        memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
                /* connect the socket */
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
            error("ERROR connecting");
                /* send the request */

    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);
    /* receive the response */
    memset(response, 0, sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    printf("Response: \n");
    do {
       printf("%s", response);
       memset(response, 0, sizeof(response));
       bytes = recv(sockfd, response, 1024, 0);
        if (bytes < 0)
           printf("ERROR reading response from socket");
       if (bytes == 0)
           break;
       received+=bytes;
    } while (1);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);
    #endif


    free(message);

    return 0;
}

Oracle SQL - DATE greater than statement

You need to convert the string to date using the to_date() function

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');

This will work only if OrderDate is stored in Date format. If it is Varchar you should apply to_date() func on that column also like

 SELECT * FROM OrderArchive
    WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.

You can check this by running in Windows PowerShell:

> Get-Service ssh-agent

And then check the output of status is not running.

Status   Name               DisplayName
------   ----               -----------
Stopped  ssh-agent          OpenSSH Authentication Agent

Then check that the service has been disabled by running

> Get-Service ssh-agent | Select StartType

StartType
---------
Disabled

I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:

 > Get-Service -Name ssh-agent | Set-Service -StartupType Manual

Alternatively, you can set it through the GUI if you prefer.

services.msc showing the properties of the OpenSSH Agent

How to automatically generate a stacktrace when my program crashes

I found that @tgamblin solution is not complete. It cannot handle with stackoverflow. I think because by default signal handler is called with the same stack and SIGSEGV is thrown twice. To protect you need register an independent stack for the signal handler.

You can check this with code below. By default the handler fails. With defined macro STACK_OVERFLOW it's all right.

#include <iostream>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <cassert>

using namespace std;

//#define STACK_OVERFLOW

#ifdef STACK_OVERFLOW
static char stack_body[64*1024];
static stack_t sigseg_stack;
#endif

static struct sigaction sigseg_handler;

void handler(int sig) {
  cerr << "sig seg fault handler" << endl;
  const int asize = 10;
  void *array[asize];
  size_t size;

  // get void*'s for all entries on the stack
  size = backtrace(array, asize);

  // print out all the frames to stderr
  cerr << "stack trace: " << endl;
  backtrace_symbols_fd(array, size, STDERR_FILENO);
  cerr << "resend SIGSEGV to get core dump" << endl;
  signal(sig, SIG_DFL);
  kill(getpid(), sig);
}

void foo() {
  foo();
}

int main(int argc, char **argv) {
#ifdef STACK_OVERFLOW
  sigseg_stack.ss_sp = stack_body;
  sigseg_stack.ss_flags = SS_ONSTACK;
  sigseg_stack.ss_size = sizeof(stack_body);
  assert(!sigaltstack(&sigseg_stack, nullptr));
  sigseg_handler.sa_flags = SA_ONSTACK;
#else
  sigseg_handler.sa_flags = SA_RESTART;  
#endif
  sigseg_handler.sa_handler = &handler;
  assert(!sigaction(SIGSEGV, &sigseg_handler, nullptr));
  cout << "sig action set" << endl;
  foo();
  return 0;
} 

Django: multiple models in one template using forms

"I want to hide some of the fields and do some complex validation."

I start with the built-in admin interface.

  1. Build the ModelForm to show the desired fields.

  2. Extend the Form with the validation rules within the form. Usually this is a clean method.

    Be sure this part works reasonably well.

Once this is done, you can move away from the built-in admin interface.

Then you can fool around with multiple, partially related forms on a single web page. This is a bunch of template stuff to present all the forms on a single page.

Then you have to write the view function to read and validated the various form things and do the various object saves().

"Is it a design issue if I break down and hand-code everything?" No, it's just a lot of time for not much benefit.

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

Is there a <meta> tag to turn off caching in all browsers?

This is a link to a great Case Study on the industry wide misunderstanding of controlling caches.

http://securityevaluators.com/knowledge/case_studies/caching/

In summary, according to this article, only Cache-Control: no-store is recognized by Chrome, Firefox, and IE. IE recognizes other controls, but Chrome and Firefox do not.

Get variable from PHP to JavaScript

You can print the PHP variable into your javascript while your page is created.

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>

Of course this is for simple variables and not objects.

Manually put files to Android emulator SD card

Use the adb tool that comes with the SDK.

adb push myDirectory /sdcard/targetDir

If you only specify /sdcard/ (with the trailing slash) as destination, then the CONTENTS of myDirectory will end up in the root of /sdcard.

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

getElementById in React

You may have to perform a diff and put document.getElementById('name') code inside a condition, in case your component is something like this:

// using the new hooks API
function Comp(props) {
  const { isLoading, data } = props;
  useEffect(() => {
    if (data) {
      var name = document.getElementById('name').value;
    }
  }, [data]) // this diff is necessary

  if (isLoading) return <div>isLoading</div>
  return (
    <div id='name'>Comp</div>
  );
}

If diff is not performed then, you will get null.

Get an image extension from an uploaded file in Laravel

return $picName = time().'.'.$request->file->extension();

The time() function will make the image unique then the .$request->file->extension() gets the image extension for you.

You can use this it works well with Laravel 6 and above.

How to print instances of a class using print()?

Just to add my two cents to @dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:

"[...] to return a string that would yield an object with the same value when passed to eval(), [...]"

Given this class definition:

class Test(object):
    def __init__(self, a, b):
        self._a = a
        self._b = b

    def __str__(self):
        return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)

    def __repr__(self):
        return 'Test("%s","%s")' % (self._a, self._b)

Now, is easy to serialize instance of Test class:

x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print

y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print

So, running last piece of code, we'll get:

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

But, as I said in my last comment: more info is just here!

Regex for numbers only

I think that this one is the simplest one and it accepts European and USA way of writing numbers e.g. USA 10,555.12 European 10.555,12 Also this one does not allow several commas or dots one after each other e.g. 10..22 or 10,.22 In addition to this numbers like .55 or ,55 would pass. This may be handy.

^([,|.]?[0-9])+$

Array to Collection: Optimized code

Arrays.asList(array)

Arrays uses new ArrayList(array). But this is not the java.util.ArrayList. It's very similar though. Note that this constructor takes the array and places it as the backing array of the list. So it is O(1).

In case you already have the list created, Collections.addAll(list, array), but that's less efficient.

Update: Thus your Collections.addAll(list, array) becomes a good option. A wrapper of it is guava's Lists.newArrayList(array).

See :hover state in Chrome Developer Tools

I wanted to see the hover state on my Bootstrap tooltips. Forcing the the :hover state in Chrome dev Tools did not create the required output, yet triggering the mouseenter event via console did the trick in Chrome. If jQuery exists on the page you can run:

$('.YOUR-TOOL-TIP-CLASS').trigger('mouseenter');

Forcing hover or mouseenter for Bootstrap Tooltips

System.Net.Http: missing from namespace? (using .net 4.5)

HttpClient lives in the System.Net.Http namespace.

You'll need to add:

using System.Net.Http;

And make sure you are referencing System.Net.Http.dll in .NET 4.5.


The code posted doesn't appear to do anything with webClient. Is there something wrong with the code that is actually compiling using HttpWebRequest?


Update

To open the Add Reference dialog right-click on your project in Solution Explorer and select Add Reference.... It should look something like:

enter image description here

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT * FROM 
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser

Uncaught Typeerror: cannot read property 'innerHTML' of null

Looks like the script executes before the DOM loads. Try loading the script asynchronously.

 <script src="yourcode.js" async></script>

Stored procedure with default parameters

I wrote with parameters that are predefined

They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:

Alter Procedure [Test]
    @StartDate AS varchar(6) = NULL, 
    @EndDate AS varchar(6) = NULL
AS
...

NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.

Now you can call it without passing any arguments e.g. exec dbo.TEST

[Vue warn]: Cannot find element

I think the problem is your script is executed before the target dom element is loaded in the dom... one reason could be that you have placed your script in the head of the page or in a script tag that is placed before the div element #main. So when the script is executed it won't be able to find the target element thus the error.

One solution is to place your script in the load event handler like

window.onload = function () {
    var main = new Vue({
        el: '#main',
        data: {
            currentActivity: 'home'
        }
    });
}

Another syntax

window.addEventListener('load', function () {
    //your script
})

mysql after insert trigger which updates another table's column

Try this:

DELIMITER $$
CREATE TRIGGER occupy_trig
AFTER INSERT ON `OccupiedRoom` FOR EACH ROW
begin
       DECLARE id_exists Boolean;
       -- Check BookingRequest table
       SELECT 1
       INTO @id_exists
       FROM BookingRequest
       WHERE BookingRequest.idRequest= NEW.idRequest;

       IF @id_exists = 1
       THEN
           UPDATE BookingRequest
           SET status = '1'
           WHERE idRequest = NEW.idRequest;
        END IF;
END;
$$
DELIMITER ;

jquery variable syntax

$self has little to do with $, which is an alias for jQuery in this case. Some people prefer to put a dollar sign together with the variable to make a distinction between regular vars and jQuery objects.

example:

var self = 'some string';
var $self = 'another string';

These are declared as two different variables. It's like putting underscore before private variables.

A somewhat popular pattern is:

var foo = 'some string';
var $foo = $('.foo');

That way, you know $foo is a cached jQuery object later on in the code.

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

I found a simple explanation.

Short Answer:

dependencies "...are those that your project really needs to be able to work in production."

devDependencies "...are those that you need during development."

peerDependencies "if you want to create and publish your own library so that it can be used as a dependency"

More details in this post: https://code-trotter.com/web/dependencies-vs-devdependencies-vs-peerdependencies

complex if statement in python

if
  ...
  # several checks
  ...
elif not (1024<=var<=65535 or var == 80 or var == 443)
  # fail
else
  ...

Converting to upper and lower case in Java

String a = "ABCD"

using this

a.toLowerCase();

all letters will convert to simple, "abcd"
using this

a.toUpperCase()

all letters will convert to Capital, "ABCD"

this conver first letter to capital:

a.substring(0,1).toUpperCase()

this conver other letter Simple

a.substring(1).toLowerCase();

we can get sum of these two

a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();

result = "Abcd"

Removing Spaces from a String in C?

Here is the simplest thing i could think of. Note that this program uses second command line argument (argv[1]) as a line to delete whitespaces from.

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

/*The function itself with debug printing to help you trace through it.*/

char* trim(const char* str)
{
    char* res = malloc(sizeof(str) + 1);
    char* copy = malloc(sizeof(str) + 1);
    copy = strncpy(copy, str, strlen(str) + 1);
    int index = 0;

    for (int i = 0; i < strlen(copy) + 1; i++) {
        if (copy[i] != ' ')
        {
            res[index] = copy[i];
            index++;
        }
        printf("End of iteration %d\n", i);
        printf("Here is the initial line: %s\n", copy);
        printf("Here is the resulting line: %s\n", res);
        printf("\n");
    }
    return res;
}

int main(int argc, char* argv[])
{
    //trim function test

    const char* line = argv[1];
    printf("Here is the line: %s\n", line);

    char* res = malloc(sizeof(line) + 1);
    res = trim(line);

    printf("\nAnd here is the formatted line: %s\n", res);

    return 0;
}

How to concat string + i?

You can concatenate strings using strcat. If you plan on concatenating numbers as strings, you must first use num2str to convert the numbers to strings.

Also, strings can't be stored in a vector or matrix, so f must be defined as a cell array, and must be indexed using { and } (instead of normal round brackets).

f = cell(N, 1);
for i=1:N
   f{i} = strcat('f', num2str(i));
end

Right pad a string with variable number of spaces

Whammo blammo (for leading spaces):

SELECT 
    RIGHT(space(60) + cust_name, 60),
    RIGHT(space(60) + cust_address, 60)

OR (for trailing spaces)

SELECT
    LEFT(cust_name + space(60), 60),
    LEFT(cust_address + space(60), 60),

Import CSV into SQL Server (including automatic table creation)

SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.

You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...

From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.

If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

Command line to remove an environment variable from the OS level configuration

setx FOOBAR ""

just causes the value of FOOBAR to be a null string. (Although, it shows with the set command with the "" so maybe double-quotes is the string.)

I used:

set FOOBAR=

and then FOOBAR was no longer listed in the set command. (Log-off was not required.)

Windows 7 32 bit, using the command prompt, non-administrator is what I used. (Not cmd or Windows + R, which might be different.)

BTW, I did not see the variable I created anywhere in the registry after I created it. I'm using RegEdit not as administrator.

Given an array of numbers, return array of products of all other numbers (no division)

One more solution, Using division. with twice traversal. Multiply all the elements and then start dividing it by each element.

How do you share constants in NodeJS modules?

In my opinion, utilizing Object.freeze allows for a DRYer and more declarative style. My preferred pattern is:

./lib/constants.js

module.exports = Object.freeze({
    MY_CONSTANT: 'some value',
    ANOTHER_CONSTANT: 'another value'
});

./lib/some-module.js

var constants = require('./constants');

console.log(constants.MY_CONSTANT); // 'some value'

constants.MY_CONSTANT = 'some other value';

console.log(constants.MY_CONSTANT); // 'some value'

Outdated Performance Warning

The following issue was fixed in v8 in Jan 2014 and is no longer relevant to most developers:

Be aware that both setting writable to false and using Object.freeze have a massive performance penalty in v8 - https://bugs.chromium.org/p/v8/issues/detail?id=1858 and http://jsperf.com/performance-frozen-object

Are there any naming convention guidelines for REST APIs?

I would say that it's preferable to use as few special characters as possible in REST URLs. One of the benefits of REST is that it makes the "interface" for a service easy to read. Camel case or Pascal case is probably good for the resource names (Users or users). I don't think there are really any hard standards around REST.

Also, I think Gandalf is right, it's usually cleaner in REST to not use query string parameters, but instead create paths that define which resources you want to deal with.

http://api.example.com/HelloWorld/Users/12345/Order/3/etc

How to check whether a string contains a substring in JavaScript?

Another alternative is KMP (Knuth–Morris–Pratt).

The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.

Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:

// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.

_x000D_
_x000D_
function kmpSearch(pattern, text) {_x000D_
  if (pattern.length == 0)_x000D_
    return 0; // Immediate match_x000D_
_x000D_
  // Compute longest suffix-prefix table_x000D_
  var lsp = [0]; // Base case_x000D_
  for (var i = 1; i < pattern.length; i++) {_x000D_
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
    while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1];_x000D_
    if (pattern.charAt(i) == pattern.charAt(j))_x000D_
      j++;_x000D_
    lsp.push(j);_x000D_
  }_x000D_
_x000D_
  // Walk through text string_x000D_
  var j = 0; // Number of chars matched in pattern_x000D_
  for (var i = 0; i < text.length; i++) {_x000D_
    while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1]; // Fall back in the pattern_x000D_
    if (text.charAt(i) == pattern.charAt(j)) {_x000D_
      j++; // Next char matched, increment position_x000D_
      if (j == pattern.length)_x000D_
        return i - (j - 1);_x000D_
    }_x000D_
  }_x000D_
  return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
_x000D_
_x000D_

It is more efficient to use if-return-return or if-else-return?

From Chromium's style guide:

Don't use else after return:

# Bad
if (foo)
  return 1
else
  return 2

# Good
if (foo)
  return 1
return 2

return 1 if foo else 2

Python 2: AttributeError: 'list' object has no attribute 'strip'

strip() is a method for strings, you are calling it on a list, hence the error.

>>> 'strip' in dir(str)
True
>>> 'strip' in dir(list)
False

To do what you want, just do

>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]

Since, you want the elements to be in a single list (and not a list of lists), you have two options.

  1. Create an empty list and append elements to it.
  2. Flatten the list.

To do the first, follow the code:

>>> l1 = []
>>> for elem in l:
        l1.extend(elem.strip().split(';'))  
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

To do the second, use itertools.chain

>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
>>> from itertools import chain
>>> list(chain(*l1))
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

How to run a program automatically as admin on Windows 7 at startup?

You can do this by installing the task while running as administrator via the TaskSchedler library. I'm making the assumption here that .NET/C# is a suitable platform/language given your related questions.

This library gives you granular access to the Task Scheduler API, so you can adjust settings that you cannot otherwise set via the command line by calling schtasks, such as the priority of the startup. Being a parental control application, you'll want it to have a startup priority of 0 (maximum), which schtasks will create by default a priority of 7.

Below is a code example of installing a properly configured startup task to run the desired application as administrator indefinitely at logon. This code will install a task for the very process that it's running from.

/*
Copyright © 2017 Jesse Nicholson  
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/// <summary>
/// Used for synchronization when creating run at startup task.
/// </summary>
private ReaderWriterLockSlim m_runAtStartupLock = new ReaderWriterLockSlim();

public void EnsureStarupTaskExists()
{
    try
    {
        m_runAtStartupLock.EnterWriteLock();


        using(var ts = new Microsoft.Win32.TaskScheduler.TaskService())
        {
            // Start off by deleting existing tasks always. Ensure we have a clean/current install of the task.
            ts.RootFolder.DeleteTask(Process.GetCurrentProcess().ProcessName, false);

            // Create a new task definition and assign properties
            using(var td = ts.NewTask())
            {
                td.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
                // This is not normally necessary. RealTime is the highest priority that
                // there is.
                td.Settings.Priority = ProcessPriorityClass.RealTime;
                td.Settings.DisallowStartIfOnBatteries = false;
                td.Settings.StopIfGoingOnBatteries = false;
                td.Settings.WakeToRun = false;
                td.Settings.AllowDemandStart = false;
                td.Settings.IdleSettings.RestartOnIdle = false;                    
                td.Settings.IdleSettings.StopOnIdleEnd = false;
                td.Settings.RestartCount = 0;                    
                td.Settings.AllowHardTerminate = false;
                td.Settings.Hidden = true;
                td.Settings.Volatile = false;
                td.Settings.Enabled = true;
                td.Settings.Compatibility = Microsoft.Win32.TaskScheduler.TaskCompatibility.V2;
                td.Settings.ExecutionTimeLimit = TimeSpan.Zero;

                td.RegistrationInfo.Description = "Runs the content filter at startup.";

                // Create a trigger that will fire the task at this time every other day
                var logonTrigger = new Microsoft.Win32.TaskScheduler.LogonTrigger();
                logonTrigger.Enabled = true;                    
                logonTrigger.Repetition.StopAtDurationEnd = false;
                logonTrigger.ExecutionTimeLimit = TimeSpan.Zero;
                td.Triggers.Add(logonTrigger);

                // Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/StartMinimized", null));

                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(Process.GetCurrentProcess().ProcessName, td);
            }
        }                
    }
    finally
    {
        m_runAtStartupLock.ExitWriteLock();
    }
}

Insert variable into Header Location PHP

<?php
$variable1 = "foo";
$variable2 = "bar";


header('Location: http://linkhere.com?fieldname1=$variable1&fieldname2=$variable2&fieldname3=$variable3);

?>

This works without any quotations.

how to make a jquery "$.post" request synchronous

jQuery < 1.8

May I suggest that you use $.ajax() instead of $.post() as it's much more customizable.

If you are calling $.post(), e.g., like this:

$.post( url, data, success, dataType );

You could turn it into its $.ajax() equivalent:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType,
  async:false
});

Please note the async:false at the end of the $.ajax() parameter object.

Here you have a full detail of the $.ajax() parameters: jQuery.ajax() – jQuery API Documentation.


jQuery >=1.8 "async:false" deprecation notice

jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:

  • use a plugin e.g. BlockUI;
  • manually add an overlay before calling $.ajax(), and then remove it when the AJAX .done() callback is called.

Please have a look at this answer for an example.

How to make a div with a circular shape?

Use a border-radius property of 50%.

So for example:

.example-div {

    border-radius: 50%

}

I ran into a merge conflict. How can I abort the merge?

If you end up with merge conflict and doesn't have anything to commit, but still a merge error is being displayed. After applying all the below mentioned commands,

git reset --hard HEAD
git pull --strategy=theirs remote_branch
git fetch origin
git reset --hard origin

Please remove

.git\index.lock

File [cut paste to some other location in case of recovery] and then enter any of below command depending on which version you want.

git reset --hard HEAD
git reset --hard origin

Hope that helps!!!

Show Youtube video source into HTML5 video tag?

The easiest answer is given by W3schools. https://www.w3schools.com/html/html_youtube.asp

  1. Upload your video to Youtube
  2. Note the Video ID
  3. Now write this code in your HTML5.
<iframe width="640" height="520"
src="https://www.youtube.com/embed/<VideoID>">
</iframe>

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

jQuery - simple input validation - "empty" and "not empty"

JQuery's :empty selector selects all elements on the page that are empty in the sense that they have no child elements, including text nodes, not all inputs that have no text in them.

Jquery: How to check if an input element has not been filled in.

Here's the code stolen from the above thread:

$('#apply-form input').blur(function()          //whenever you click off an input element
{                   
    if( !$(this).val() ) {                      //if it is blank. 
         alert('empty');    
    }
});

This works because an empty string in JavaScript is a 'falsy value', which basically means if you try to use it as a boolean value it will always evaluate to false. If you want, you can change the conditional to $(this).val() === '' for added clarity. :D

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

A simple work around(it worked for me) is use the IP address instead of localhost. This should be fine for your development tasks.

Android: Remove all the previous activities from the back stack

You can try finishAffinity(), it closes all current activities and works on and above Android 4.1

Getting Raw XML From SOAPMessage in Java

It is pretty old thread but recently i had a similar issue. I was calling a downstream soap service, from a rest service, and I needed to return the xml response coming from the downstream server as is.

So, i ended up adding a SoapMessageContext handler to get the XML response. Then i injected the response xml into servlet context as an attribute.

public boolean handleMessage(SOAPMessageContext context) {

            // Get xml response
            try {

                ServletContext servletContext =
                        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext();

                SOAPMessage msg = context.getMessage();

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                msg.writeTo(out);
                String strMsg = new String(out.toByteArray());

                servletContext.setAttribute("responseXml", strMsg);

                return true;
            } catch (Exception e) {
                return false;
            }
        }

Then I have retrieved the xml response string in the service layer.

ServletContext servletContext =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext();

        String msg = (String) servletContext.getAttribute("responseXml");

Didn't have chance to test it yet but this approach must be thread safe since it is using the servlet context.

HTML Canvas Full Screen

Well, I was looking to make my canvas fullscreen too, This is how i did it. I'll post the entire index.html since I am not a CSS expert yet : (basically just using position:fixed and width and height as 100% and top and left as 0% and i nested this CSS code for every tag. I also have min-height and min-width as 100%. When I tried it with a 1px border the border size was changing as I zoomed in and out but the canvas remained fullscreen.)

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
<head>_x000D_
<title>MOUSEOVER</title>_x000D_
<script "text/javascript" src="main.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body id="BODY_CONTAINER" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
_x000D_
_x000D_
<div id="DIV_GUI_CONTAINER" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
<canvas id="myCanvas"  style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
</canvas>_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

EDIT: add this to the canvas element:

_x000D_
_x000D_
<canvas id="myCanvas" width="" height="" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
</canvas>
_x000D_
_x000D_
_x000D_

add this to the javascript

canvas.width = window.screen.width;

canvas.height = window.screen.height;

I found this made the drawing a lot smoother than my original comment.

Thanks.

Load and execution sequence of a web page?

According to your sample,

<html>
 <head>
  <script src="jquery.js" type="text/javascript"></script>
  <script src="abc.js" type="text/javascript">
  </script>
  <link rel="stylesheets" type="text/css" href="abc.css"></link>
  <style>h2{font-wight:bold;}</style>
  <script>
  $(document).ready(function(){
     $("#img").attr("src", "kkk.png");
  });
 </script>
 </head>
 <body>
    <img id="img" src="abc.jpg" style="width:400px;height:300px;"/>
    <script src="kkk.js" type="text/javascript"></script>
 </body>
</html>

roughly the execution flow is about as follows:

  1. The HTML document gets downloaded
  2. The parsing of the HTML document starts
  3. HTML Parsing reaches <script src="jquery.js" ...
  4. jquery.js is downloaded and parsed
  5. HTML parsing reaches <script src="abc.js" ...
  6. abc.js is downloaded, parsed and run
  7. HTML parsing reaches <link href="abc.css" ...
  8. abc.css is downloaded and parsed
  9. HTML parsing reaches <style>...</style>
  10. Internal CSS rules are parsed and defined
  11. HTML parsing reaches <script>...</script>
  12. Internal Javascript is parsed and run
  13. HTML Parsing reaches <img src="abc.jpg" ...
  14. abc.jpg is downloaded and displayed
  15. HTML Parsing reaches <script src="kkk.js" ...
  16. kkk.js is downloaded, parsed and run
  17. Parsing of HTML document ends

Note that the download may be asynchronous and non-blocking due to behaviours of the browser. For example, in Firefox there is this setting which limits the number of simultaneous requests per domain.

Also depending on whether the component has already been cached or not, the component may not be requested again in a near-future request. If the component has been cached, the component will be loaded from the cache instead of the actual URL.

When the parsing is ended and document is ready and loaded, the events onload is fired. Thus when onload is fired, the $("#img").attr("src","kkk.png"); is run. So:

  1. Document is ready, onload is fired.
  2. Javascript execution hits $("#img").attr("src", "kkk.png");
  3. kkk.png is downloaded and loads into #img

The $(document).ready() event is actually the event fired when all page components are loaded and ready. Read more about it: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

Edit - This portion elaborates more on the parallel or not part:

By default, and from my current understanding, browser usually runs each page on 3 ways: HTML parser, Javascript/DOM, and CSS.

The HTML parser is responsible for parsing and interpreting the markup language and thus must be able to make calls to the other 2 components.

For example when the parser comes across this line:

<a href="#" onclick="alert('test');return false;" style="font-weight:bold">a hypertext link</a>

The parser will make 3 calls, two to Javascript and one to CSS. Firstly, the parser will create this element and register it in the DOM namespace, together with all the attributes related to this element. Secondly, the parser will call to bind the onclick event to this particular element. Lastly, it will make another call to the CSS thread to apply the CSS style to this particular element.

The execution is top down and single threaded. Javascript may look multi-threaded, but the fact is that Javascript is single threaded. This is why when loading external javascript file, the parsing of the main HTML page is suspended.

However, the CSS files can be download simultaneously because CSS rules are always being applied - meaning to say elements are always repainted with the freshest CSS rules defined - thus making it unblocking.

An element will only be available in the DOM after it has been parsed. Thus when working with a specific element, the script is always placed after, or within the window onload event.

Script like this will cause error (on jQuery):

<script type="text/javascript">/* <![CDATA[ */
  alert($("#mydiv").html());
/* ]]> */</script>
<div id="mydiv">Hello World</div>

Because when the script is parsed, #mydiv element is still not defined. Instead this would work:

<div id="mydiv">Hello World</div>
<script type="text/javascript">/* <![CDATA[ */
  alert($("#mydiv").html());
/* ]]> */</script>

OR

<script type="text/javascript">/* <![CDATA[ */
  $(window).ready(function(){
                    alert($("#mydiv").html());
                  });
/* ]]> */</script>
<div id="mydiv">Hello World</div>

Regex Email validation

Email validation using regex

    string pattern = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z";

    //check first string
   if (Regex.IsMatch(EmailId1 , pattern))
   {    
       //if email is valid
        Console.WriteLine(EmailId1+ " is a valid Email address ");
   }

Source: email validation c#

Validation Without Regex using MailAddress.MailAddress(String) class constructor

public bool IsEmailValid(string emailaddress)
{
 try
 {
    MailAddress m = new MailAddress(emailaddress);
    return true;
 }
 catch (FormatException)
 {
    return false;
 }
}

Why there is no ConcurrentHashSet against ConcurrentHashMap

Why not use: CopyOnWriteArraySet from java.util.concurrent?

What is the difference between declarative and imperative paradigm in programming?

In computer science, declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.

From http://en.wikipedia.org/wiki/Declarative_programming

in a nutshell the declarative language is simpler because it lacks the complexity of control flow ( loops, if statements, etc. )

A good comparison is the ASP.Net 'code-behind' model. You have declarative '.ASPX' files and then the imperative 'ASPX.CS' code files. I often find that if I can do all I need in the declarative half of the script a lot more people can follow what's being done.

How to debug in Django, the good way?

The easiest way to debug python - especially for programmers that are used to Visual Studio - is using PTVS (Python Tools for Visual Studio). The steps are simple:

  1. Download and install it from http://pytools.codeplex.com/
  2. Set breakpoints and press F5.
  3. Your breakpoint is hit, you can view/change the variables as easy as debugging C#/C++ programs.
  4. That's all :)

If you want to debug Django using PTVS, you need to do the following:

  1. In Project settings - General tab, set "Startup File" to "manage.py", the entry point of the Django program.
  2. In Project settings - Debug tab, set "Script Arguments" to "runserver --noreload". The key point is the "--noreload" here. If you don't set it, your breakpoints won't be hit.
  3. Enjoy it.

How to pass parameters or arguments into a gradle task

I think you probably want to view the minification of each set of css as a separate task

task minifyBrandACss(type: com.eriwen.gradle.css.tasks.MinifyCssTask) {
     source = "src/main/webapp/css/brandA/styles.css"
     dest = "${buildDir}/brandA/styles.css"
}

etc etc

BTW executing your minify tasks in an action of the war task seems odd to me - wouldn't it make more sense to make them a dependency of the war task?

Refreshing data in RecyclerView and keeping its scroll position

If you have one or more EditTexts inside of a recyclerview items, disable the autofocus of these, putting this configuration in the parent view of recyclerview:

android:focusable="true"
android:focusableInTouchMode="true"

I had this issue when I started another activity launched from a recyclerview item, when I came back and set an update of one field in one item with notifyItemChanged(position) the scroll of RV moves, and my conclusion was that, the autofocus of EditText Items, the code above solved my issue.

best.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

You may try to put the right database name in connection url in the configuration file. As I had the same error while run the POJO class file and it has been solved by this.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!

I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:

  1. The image aspect ratio is preserved
  2. The image's original size is maintained (that is, it can never shrink only grow)

The markup relies on a wrapper element:

<div id="wrap"><img src="test.png" /></div>

Given the above markup you then use these rules:

#wrap {
  height: 100px;
  width: 100px;
}
#wrap img {
  min-height: 100%;
  min-width: 100%;
}

If you then control the size of wrapper you get the interesting scale effects that I list above.

To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.

  1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100.
  2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200.

So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.

This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

There are multiple ways how to present a timespan in the database.

time

This datatype is supported since SQL Server 2008 and is the prefered way to store a TimeSpan. There is no mapping needed. It also works well with SQL code.

public TimeSpan ValidityPeriod { get; set; }

However, as stated in the original question, this datatype is limited to 24 hours.

datetimeoffset

The datetimeoffset datatype maps directly to System.DateTimeOffset. It's used to express the offset between a datetime/datetime2 to UTC, but you can also use it for TimeSpan.

However, since the datatype suggests a very specific semantic, so you should also consider other options.

datetime / datetime2

One approach might be to use the datetime or datetime2 types. This is best in scenarios where you need to process the values in the database directly, ie. for views, stored procedures, or reports. The drawback is that you need to substract the value DateTime(1900,01,01,00,00,00) from the date to get back the timespan in your business logic.

public DateTime ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return ValidityPeriod - DateTime(1900,01,01,00,00,00); }
    set { ValidityPeriod = DateTime(1900,01,01,00,00,00) + value; }
}

bigint

Another approach might be to convert the TimeSpan into ticks and use the bigint datatype. However, this approach has the drawback that it's cumbersome to use in SQL queries.

public long ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return TimeSpan.FromTicks(ValidityPeriod); }
    set { ValidityPeriod = value.Ticks; }
}

varchar(N)

This is best for cases where the value should be readable by humans. You might also use this format in SQL queries by utilizing the CONVERT(datetime, ValidityPeriod) function. Dependent on the required precision, you will need between 8 and 25 characters.

public string ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return TimeSpan.Parse(ValidityPeriod); }
    set { ValidityPeriod = value.ToString("HH:mm:ss"); }
}

Bonus: Period and Duration

Using a string, you can also store NodaTime datatypes, especially Duration and Period. The first is basically the same as a TimeSpan, while the later respects that some days and months are longer or shorter than others (ie. January has 31 days and February has 28 or 29; some days are longer or shorter because of daylight saving time). In such cases, using a TimeSpan is the wrong choice.

You can use this code to convert Periods:

using NodaTime;
using NodaTime.Serialization.JsonNet;

internal static class PeriodExtensions
{
    public static Period ToPeriod(this string input)
    {
        var js = JsonSerializer.Create(new JsonSerializerSettings());
        js.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
        var quoted = string.Concat(@"""", input, @"""");
        return js.Deserialize<Period>(new JsonTextReader(new StringReader(quoted)));
    }
}

And then use it like

public string ValidityPeriod { get; set; }

[NotMapped]
public Period ValidityPeriodPeriod
{
    get => ValidityPeriod.ToPeriod();
    set => ValidityPeriod = value.ToString();
}

I really like NodaTime and it often saves me from tricky bugs and lots of headache. The drawback here is that you really can't use it in SQL queries and need to do calculations in-memory.

CLR User-Defined Type

You also have the option to use a custom datatype and support a custom TimeSpan class directly. See CLR User-Defined Types for details.

The drawback here is that the datatype might not behave well with SQL Reports. Also, some versions of SQL Server (Azure, Linux, Data Warehouse) are not supported.

Value Conversions

Starting with EntityFramework Core 2.1, you have the option to use Value Conversions.

However, when using this, EF will not be able to convert many queries into SQL, causing queries to run in-memory; potentially transfering lots and lots of data to your application.

So at least for now, it might be better not to use it, and just map the query result with Automapper.

pandas dataframe convert column type to string or categorical

Prior answers focused on nominal data (e.g. unordered). If there is a reason to impose order for an ordinal variable, then one would use:

# Transform to category
df['zipcode_category'] = df['zipcode_category'].astype('category')

# Add ordered category
df['zipcode_ordered'] = df['zipcode_category']

# Setup the ordering
df.zipcode_ordered.cat.set_categories(
    new_categories = [90211, 90210], ordered = True, inplace = True
)

# Output IDs
df['zipcode_ordered_id'] = df.zipcode_ordered.cat.codes
print(df)
#  zipcode_category zipcode_ordered  zipcode_ordered_id
#            90210           90210                   1
#            90211           90211                   0

More details on setting ordered categories can be found at the pandas website:

https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#sorting-and-order

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Add repository annotation before your DAO Implementation Class. example:

@Repository
public class EmpDAOImpl extends BaseNamedParameterJdbcDaoSupportUAM 
implements EmpDAO{ 
}

How can a file be copied?

You can use one of the copy functions from the shutil package:

??????????????????????????????????????????????????????????????????????????????
Function              preserves     supports          accepts     copies other
                      permissions   directory dest.   file obj    metadata  
------------------------------------------------------------------------------
shutil.copy              ?             ?                 ?           ?
shutil.copy2             ?             ?                 ?           ?
shutil.copyfile          ?             ?                 ?           ?
shutil.copyfileobj       ?             ?                 ?           ?
??????????????????????????????????????????????????????????????????????????????

Example:

import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')

What's your most controversial programming opinion?

If I were being controversial, I'd have to suggest that Jon Skeet isn't omnipotent..

Drawing a simple line graph in Java

Hovercraft Full Of Eels' answer is very good, but i had to change it a bit in order to get it working on my program:

int y1 = (int) ((this.height - 2 * BORDER_GAP) - (values.get(i) * yScale - BORDER_GAP));

instead of

int y1 = (int) (scores.get(i) * yScale + BORDER_GAP);

because if i used his way the graphic would be upside down

(you'd see it if you used hardcoded values (e.g 1,3,5,7,9) instead of random values)

OnChange event using React JS for drop down

Thank you Felix Kling, but his answer need a little change:

var MySelect = React.createClass({
 getInitialState: function() {
     return {
         value: 'select'
     }
 },
 change: function(event){
     this.setState({value: event.target.value});
 },
 render: function(){
    return(
       <div>
           <select id="lang" onChange={this.change.bind(this)} value={this.state.value}>
              <option value="select">Select</option>
              <option value="Java">Java</option>
              <option value="C++">C++</option>
           </select>
           <p></p>
           <p>{this.state.value}</p>
       </div>
    );
 }
});
React.render(<MySelect />, document.body); 

How do I move to end of line in Vim?

Possibly unrelated, but if you want to start a new line after the current line, you can use o anywhere in the line.

Abstract Class vs Interface in C++

An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).

How to decrypt Hash Password in Laravel

Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).

The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.

Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).

For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.

Changing navigation title programmatically

Normally, the best-practice is to set the title on the UIViewController. By doing this, the UINavigationItem is also set. Generally, this is better than programmatically allocating and initializing a UINavigationBar that's not linked to anything.

You miss out on some of the benefits and functionality that the UINavigationBar was designed for. Here is a link to the documentation that may help you. It discusses the different properties you can set on the actual bar and on a UINavigationItem.

Just keep in mind:

  1. You lose back button functionality (unless you wire it yourself)
  2. The built-in "drag from the left-hand side to swipe back" gesture is forfeited

UINavigationController's are your friends.

Handling onchange event in HTML.DropDownList Razor MVC

Description

You can use another overload of the DropDownList method. Pick the one you need and pass in a object with your html attributes.

Sample

@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })

More Information

How to get a value from the last inserted row?

for example:

 Connection conn = null;
            PreparedStatement sth = null;
            ResultSet rs =null;
            try {
                conn = delegate.getConnection();
                sth = conn.prepareStatement(INSERT_SQL);
                sth.setString(1, pais.getNombre());
                sth.executeUpdate();
                rs=sth.getGeneratedKeys();
                if(rs.next()){
                    Integer id = (Integer) rs.getInt(1);
                    pais.setId(id);
                }
            } 

with ,Statement.RETURN_GENERATED_KEYS);" no found.

'Incomplete final line' warning when trying to read a .csv file into R

I realized that several answers have been provided but no real fix yet.

The reason, as mentioned above, is a "End of line" missing at the end of the CSV file.

While the real Fix should come from Microsoft, the walk around is to open the CSV file with a Text-editor and add a line at the end of the file (aka press return key). I use ATOM software as a text/code editor but virtually all basic text editor would do.

In the meanwhile, please report the bug to Microsoft.

Question: It seems to me that it is a office 2016 problem. Does anyone have the issue on a PC?

Calculating difference between two timestamps in Oracle in milliseconds

Here's a stored proc to do it:

CREATE OR REPLACE function timestamp_diff(a timestamp, b timestamp) return number is 
begin
  return extract (day    from (a-b))*24*60*60 +
         extract (hour   from (a-b))*60*60+
         extract (minute from (a-b))*60+
         extract (second from (a-b));
end;
/

Up Vote if you also wanted to beat the crap out of the Oracle developer who negated to his job!

BECAUSE comparing timestamps for the first time should take everyone an hour or so...

Order by multiple columns with Doctrine

In Doctrine 2.x you can't pass multiple order by using doctrine 'orderBy' or 'addOrderBy' as above examples. Because, it automatically adds the 'ASC' at the end of the last column name when you left the second parameter blank, such as in the 'orderBy' function.

For an example ->orderBy('a.fist_name ASC, a.last_name ASC') will output SQL something like this 'ORDER BY first_name ASC, last_name ASC ASC'. So this is SQL syntax error. Simply because default of the orderBy or addOrderBy is 'ASC'.

To add multiple order by's you need to use 'add' function. And it will be like this.

->add('orderBy','first_name ASC, last_name ASC'). This will give you the correctly formatted SQL.

More info on add() function. https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html#low-level-api

Hope this helps. Cheers!

Function to clear the console in R and RStudio

shell("cls") if on Windows,

shell("clear") if on Linux or Mac.

(shell() passes a command (or any string) to the host terminal.)

Android Gradle Apache HttpClient does not exist?

This is what I did, and it works for me.

step 1: add this in the build.grade(module: app)

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

step 2: sync the project and done.

Best way to get user GPS location in background in Android

Download the source code from here (Get Current Location Using Background Service)

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="servicetutorial.service">

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".GoogleService"></service>
    </application>

</manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ffffff"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#3F51B5"
        android:text="Location using service"
        android:textColor="#ffffff"
        android:textSize="20dp"
        android:gravity="center"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"

        android:orientation="vertical">



    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="50dp">

        <TextView
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="Latitude"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp"
            android:textColor="#000000"
            android:textSize="20dp"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/tv_latitude"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp"
            android:textColor="#000000"
            android:textSize="20dp"/>


    </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="horizontal"
            android:layout_height="50dp">

            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="Longitude"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:textColor="#000000"
                android:textSize="20dp"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:id="@+id/tv_longitude"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:textColor="#000000"
                android:textSize="20dp"/>


        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="horizontal"
            android:layout_height="50dp">

            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="Address"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:textColor="#000000"
                android:textSize="20dp"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:id="@+id/tv_address"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:textColor="#000000"
                android:textSize="20dp"/>


        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="horizontal"
            android:layout_height="50dp">

            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="Area"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:textColor="#000000"
                android:textSize="20dp"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:id="@+id/tv_area"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:textColor="#000000"
                android:textSize="20dp"/>


        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="horizontal"
            android:layout_height="50dp">

            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="Locality"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:textColor="#000000"
                android:textSize="20dp"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:id="@+id/tv_locality"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:textColor="#000000"
                android:textSize="20dp"/>


        </LinearLayout>

    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_start"
        android:text="Get Location"
        android:layout_alignParentBottom="true"/>



</RelativeLayout>

MainActivity.java

package servicetutorial.service;

import android.*;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.preference.PreferenceManager;
import android.renderscript.Double2;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends Activity {
    Button btn_start;
    private static final int REQUEST_PERMISSIONS = 100;
    boolean boolean_permission;
    TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality;
    SharedPreferences mPref;
    SharedPreferences.Editor medit;
    Double latitude,longitude;
    Geocoder geocoder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_start = (Button) findViewById(R.id.btn_start);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_latitude = (TextView) findViewById(R.id.tv_latitude);
        tv_longitude = (TextView) findViewById(R.id.tv_longitude);
        tv_area = (TextView)findViewById(R.id.tv_area);
        tv_locality = (TextView)findViewById(R.id.tv_locality);
        geocoder = new Geocoder(this, Locale.getDefault());
        mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        medit = mPref.edit();


        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (boolean_permission) {

                    if (mPref.getString("service", "").matches("")) {
                        medit.putString("service", "service").commit();

                        Intent intent = new Intent(getApplicationContext(), GoogleService.class);
                        startService(intent);

                    } else {
                        Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
                }

            }
        });

        fn_permission();
    }

    private void fn_permission() {
        if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {

            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {


            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION

                        },
                        REQUEST_PERMISSIONS);

            }
        } else {
            boolean_permission = true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case REQUEST_PERMISSIONS: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    boolean_permission = true;

                } else {
                    Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();

                }
            }
        }
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            latitude = Double.valueOf(intent.getStringExtra("latutide"));
            longitude = Double.valueOf(intent.getStringExtra("longitude"));

            List<Address> addresses = null;

            try {
                addresses = geocoder.getFromLocation(latitude, longitude, 1);
                String cityName = addresses.get(0).getAddressLine(0);
                String stateName = addresses.get(0).getAddressLine(1);
                String countryName = addresses.get(0).getAddressLine(2);

                tv_area.setText(addresses.get(0).getAdminArea());
                tv_locality.setText(stateName);
                tv_address.setText(countryName);



            } catch (IOException e1) {
                e1.printStackTrace();
            }


            tv_latitude.setText(latitude+"");
            tv_longitude.setText(longitude+"");
            tv_address.getText();


        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));

    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
    }


}

GoogleService.java

package servicetutorial.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by deepshikha on 24/11/16.
 */

public class GoogleService extends Service implements LocationListener{

    boolean isGPSEnable = false;
    boolean isNetworkEnable = false;
    double latitude,longitude;
    LocationManager locationManager;
    Location location;
    private Handler mHandler = new Handler();
    private Timer mTimer = null;
    long notify_interval = 1000;
    public static String str_receiver = "servicetutorial.service.receiver";
    Intent intent;




    public GoogleService() {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mTimer = new Timer();
        mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
        intent = new Intent(str_receiver);
//        fn_getlocation();
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    private void fn_getlocation(){
        locationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
        isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnable && !isNetworkEnable){

        }else {

            if (isNetworkEnable){
                location = null;
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,0,this);
                if (locationManager!=null){
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location!=null){

                        Log.e("latitude",location.getLatitude()+"");
                        Log.e("longitude",location.getLongitude()+"");

                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        fn_update(location);
                    }
                }

            }


            if (isGPSEnable){
                location = null;
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
                if (locationManager!=null){
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location!=null){
                        Log.e("latitude",location.getLatitude()+"");
                        Log.e("longitude",location.getLongitude()+"");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        fn_update(location);
                    }
                }
            }


        }

    }

    private class TimerTaskToGetLocation extends TimerTask{
        @Override
        public void run() {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    fn_getlocation();
                }
            });

        }
    }

    private void fn_update(Location location){

        intent.putExtra("latutide",location.getLatitude()+"");
        intent.putExtra("longitude",location.getLongitude()+"");
        sendBroadcast(intent);
    }


}

Add this dependency

compile 'com.google.android.gms:play-services:9.4.0'

Can I add extension methods to an existing static class?

The following was rejected as an edit to tvanfosson's answer. I was asked to contribute it as my own answer. I used his suggestion and finished the implementation of a ConfigurationManager wrapper. In principle I simply filled out the ... in tvanfosson's answer.

No. Extension methods require an instance of an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.

public static class ConfigurationManagerWrapper
{
    public static NameValueCollection AppSettings
    {
        get { return ConfigurationManager.AppSettings; }
    }

    public static ConnectionStringSettingsCollection ConnectionStrings
    {
        get { return ConfigurationManager.ConnectionStrings; }
    }

    public static object GetSection(string sectionName)
    {
        return ConfigurationManager.GetSection(sectionName);
    }

    public static Configuration OpenExeConfiguration(string exePath)
    {
        return ConfigurationManager.OpenExeConfiguration(exePath);
    }

    public static Configuration OpenMachineConfiguration()
    {
        return ConfigurationManager.OpenMachineConfiguration();
    }

    public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel)
    {
        return ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel);
    }

    public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)
    {
        return ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
    }

    public static void RefreshSection(string sectionName)
    {
        ConfigurationManager.RefreshSection(sectionName);
    }
}

How to load property file from classpath?

If you use the static method and load the properties file from the classpath folder so you can use the below code :

//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));

Uncaught TypeError: undefined is not a function on loading jquery-min.js

In case there are any morons out there like me, I had this frustrating problem because I forgot a simple

new

keyword before instantiating a new object.

How can I remove all my changes in my SVN working directory?

You can use the following command to revert all local changes:

svn st -q | awk '{print $2;}' | xargs svn revert

Compile to a stand-alone executable (.exe) in Visual Studio

I don't think it is possible to do what the questioner asks which is to avoid dll hell by merging all the project files into one .exe.

The framework issue is a red herring. The problem that occurs is that when you have multiple projects depending on one library it is a PITA to keep the libraries in sync. Each time the library changes, all the .exes that depend on it and are not updated will die horribly.

Telling people to learn C as one response did is arrogant and ignorant.

Adding ASP.NET MVC5 Identity Authentication to an existing project

This is what I did to integrate Identity with an existing database.

  1. Create a sample MVC project with MVC template. This has all the code needed for Identity implementation - Startup.Auth.cs, IdentityConfig.cs, Account Controller code, Manage Controller, Models and related views.

  2. Install the necessary nuget packages for Identity and OWIN. You will get an idea by seeing the references in the sample Project and the answer by @Sam

  3. Copy all these code to your existing project. Please note don't forget to add the "DefaultConnection" connection string for Identity to map to your database. Please check the ApplicationDBContext class in IdentityModel.cs where you will find the reference to "DefaultConnection" connection string.

  4. This is the SQL script I ran on my existing database to create necessary tables:

    USE ["YourDatabse"]
    GO
    /****** Object:  Table [dbo].[AspNetRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetRoles](
    [Id] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED 
    (
      [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserClaims]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserClaims](
       [Id] [int] IDENTITY(1,1) NOT NULL,
       [UserId] [nvarchar](128) NOT NULL,
       [ClaimType] [nvarchar](max) NULL,
       [ClaimValue] [nvarchar](max) NULL,
    CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED 
    (
       [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserLogins]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserLogins](
        [LoginProvider] [nvarchar](128) NOT NULL,
        [ProviderKey] [nvarchar](128) NOT NULL,
        [UserId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED 
    (
        [LoginProvider] ASC,
        [ProviderKey] ASC,
        [UserId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserRoles](
       [UserId] [nvarchar](128) NOT NULL,
       [RoleId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED 
    (
        [UserId] ASC,
        [RoleId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUsers]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUsers](
        [Id] [nvarchar](128) NOT NULL,
        [Email] [nvarchar](256) NULL,
        [EmailConfirmed] [bit] NOT NULL,
        [PasswordHash] [nvarchar](max) NULL,
        [SecurityStamp] [nvarchar](max) NULL,
        [PhoneNumber] [nvarchar](max) NULL,
        [PhoneNumberConfirmed] [bit] NOT NULL,
        [TwoFactorEnabled] [bit] NOT NULL,
        [LockoutEndDateUtc] [datetime] NULL,
        [LockoutEnabled] [bit] NOT NULL,
        [AccessFailedCount] [int] NOT NULL,
        [UserName] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED 
    (
        [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
     GO
     ALTER TABLE [dbo].[AspNetUserClaims]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserLogins]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY([RoleId])
     REFERENCES [dbo].[AspNetRoles] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId]
     GO
    
  5. Check and solve any remaining errors and you are done. Identity will handle the rest :)

SQL Server Creating a temp table for this query

If you want to create a temp table after check exist table.You can use the following code

DROP TABLE IF EXISTS tempdb.dbo.#temptable
CREATE TABLE #temptable
  (
   SiteName             NVARCHAR(50),
   BillingMonth         varchar(10),
   Consumption          INT,
  )

After creating the temporary table, you can insert data into this table as a regular table:

INSERT INTO #temptable
SELECT COLUMN1,...
FROM
(...)

or

INSERT INTO #temptable
VALUES (value1, value2, value3, ...);

The SELECT statement is used to select data from a temp table.

SELECT * FROM #temptable

you can manually remove the temporary table by using the DROP TABLE statement:

DROP TABLE #temptable;

Adobe Reader Command Line Reference

I found this:

http://www.robvanderwoude.com/commandlineswitches.php#Acrobat

Open a PDF file with navigation pane active, zoom out to 50%, and search for and highlight the word "batch":

AcroRd32.exe /A "zoom=50&navpanes=1=OpenActions&search=batch" PdfFile

React-Router open Link in new tab

Starting with react_router 1.0, the props will be passed onto the anchor tag. You can directly use target="_blank". Discussed here: https://github.com/ReactTraining/react-router/issues/2188

How to replace plain URLs with links?

If you need to show shorter link (only domain), but with same long URL, you can try my modification of Sam Hasler's code version posted above

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/([-A-Z0-9+&@#%?=~_|!:,.;]*)([-A-Z0-9+&@#%?\/=~_|!:,.;]*)[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, "<a href='$1' target='_blank'>$3</a>");
}

HashMap with multiple values under the same key

I am so used to just doing this with a Data Dictionary in Objective C. It was harder to get a similar result in Java for Android. I ended up creating a custom class, and then just doing a hashmap of my custom class.

public class Test1 {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addview);

//create the datastring
    HashMap<Integer, myClass> hm = new HashMap<Integer, myClass>();
    hm.put(1, new myClass("Car", "Small", 3000));
    hm.put(2, new myClass("Truck", "Large", 4000));
    hm.put(3, new myClass("Motorcycle", "Small", 1000));

//pull the datastring back for a specific item.
//also can edit the data using the set methods.  this just shows getting it for display.
    myClass test1 = hm.get(1);
    String testitem = test1.getItem();
    int testprice = test1.getPrice();
    Log.i("Class Info Example",testitem+Integer.toString(testprice));
}
}

//custom class.  You could make it public to use on several activities, or just include in the activity if using only here
class myClass{
    private String item;
    private String type;
    private int price;

    public myClass(String itm, String ty, int pr){
        this.item = itm;
        this.price = pr;
        this.type = ty;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public String getType() {
        return item;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

}

DataGridView checkbox column - value and functionality

If you have a gridview containing more than one checkbox .... you should try this ....

Object[] o=new Object[6];

for (int i = 0; i < dgverlist.RowCount; i++)
{
    for (int j = 2; j < dgverlist.ColumnCount; j++)
    {
        DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
        ch1 = (DataGridViewCheckBoxCell)dgverlist.Rows[i].Cells[j];

        if (ch1.Value != null)
        {
           o[i] = ch1.OwningColumn.HeaderText.ToString();

            MessageBox.Show(o[i].ToString());
        }
    }
}

Regex to match string containing two names in any order

You can make use of regex's quantifier feature since lookaround may not be supported all the time.

(\bjames\b){1,}.*(\bjack\b){1,}|(\bjack\b){1,}.*(\bjames\b){1,}

jQuery: Get height of hidden element in jQuery

Following Nick Craver's solution, setting the element's visibility allows it to get accurate dimensions. I've used this solution very very often. However, having to reset the styles manually, I've come to find this cumbersome, given that modifying the element's initial positioning/display in my css through development, I often forget to update the related javascript code. The following code doesn't reset the styles per say, but removes the inline styles added by javascript:

$("#myDiv")
.css({
    position:   'absolute',
    visibility: 'hidden',
    display:    'block'
});

optionHeight = $("#myDiv").height();
optionWidth = $("#myDiv").width();

$("#myDiv").attr('style', '');

The only assumption here is that there can't be other inline styles or else they will be removed aswell. The benefit here, however, is that the element's styles are returned to what they were in the css stylesheet. As a consequence, you can write this up as a function where an element is passed through, and a height or width is returned.

Another issue I've found of setting the styles inline via js is that when dealing with transitions through css3, you become forced to adapt your style rules' weights to be stronger than an inline style, which can be frustrating sometimes.

React Native fetch() Network Request Failed

I got the same issue on Android 9 because of the "http" and issue resolved by just adding android:usesCleartextTraffic="true" in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
  android:usesCleartextTraffic="true"
 .......>
 .......
</application>

Change mysql user password using command line

In windows 10, just exit out of current login and run this on command line

--> mysqladmin -u root password “newpassword”

where instead of root could be any user.

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

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

Scale iFrame css width 100% like an image

Big difference between an image and an iframe is the fact that an image keeps its aspect-ratio. You could combine an image and an iframe with will result in a responsive iframe. Hope this answerers your question.

Check this link for example : http://jsfiddle.net/Masau/7WRHM/

HTML:

<div class="wrapper">
    <div class="h_iframe">
        <!-- a transparent image is preferable -->
        <img class="ratio" src="http://placehold.it/16x9"/>
        <iframe src="http://www.youtube.com/embed/WsFWhL4Y84Y" frameborder="0" allowfullscreen></iframe>
    </div>
    <p>Please scale the "result" window to notice the effect.</p>
</div>

CSS:

html,body        {height:100%;}
.wrapper         {width:80%;height:100%;margin:0 auto;background:#CCC}
.h_iframe        {position:relative;}
.h_iframe .ratio {display:block;width:100%;height:auto;}
.h_iframe iframe {position:absolute;top:0;left:0;width:100%; height:100%;}

note: This only works with a fixed aspect-ratio.

Using Gulp to Concatenate and Uglify files

My gulp file produces a final compiled-bundle-min.js, hope this helps someone.

enter image description here

//Gulpfile.js

var gulp = require("gulp");
var watch = require("gulp-watch");

var concat = require("gulp-concat");
var rename = require("gulp-rename");
var uglify = require("gulp-uglify");
var del = require("del");
var minifyCSS = require("gulp-minify-css");
var copy = require("gulp-copy");
var bower = require("gulp-bower");
var sourcemaps = require("gulp-sourcemaps");

var path = {
    src: "bower_components/",
    lib: "lib/"
}

var config = {
    jquerysrc: [
        path.src + "jquery/dist/jquery.js",
        path.src + "jquery-validation/dist/jquery.validate.js",
        path.src + "jquery-validation/dist/jquery.validate.unobtrusive.js"
    ],
    jquerybundle: path.lib + "jquery-bundle.js",
    ngsrc: [
        path.src + "angular/angular.js",
         path.src + "angular-route/angular-route.js",
         path.src + "angular-resource/angular-resource.js"
    ],
    ngbundle: path.lib + "ng-bundle.js",

    //JavaScript files that will be combined into a Bootstrap bundle
    bootstrapsrc: [
        path.src + "bootstrap/dist/js/bootstrap.js"
    ],
    bootstrapbundle: path.lib + "bootstrap-bundle.js"
}

// Synchronously delete the output script file(s)
gulp.task("clean-scripts", function (cb) {
    del(["lib","dist"], cb);
});

//Create a jquery bundled file
gulp.task("jquery-bundle", ["clean-scripts", "bower-restore"], function () {
    return gulp.src(config.jquerysrc)
     .pipe(concat("jquery-bundle.js"))
     .pipe(gulp.dest("lib"));
});

//Create a angular bundled file
gulp.task("ng-bundle", ["clean-scripts", "bower-restore"], function () {
    return gulp.src(config.ngsrc)
     .pipe(concat("ng-bundle.js"))
     .pipe(gulp.dest("lib"));
});

//Create a bootstrap bundled file
gulp.task("bootstrap-bundle", ["clean-scripts", "bower-restore"], function     () {
    return gulp.src(config.bootstrapsrc)
     .pipe(concat("bootstrap-bundle.js"))
     .pipe(gulp.dest("lib"));
});


// Combine and the vendor files from bower into bundles (output to the Scripts folder)
gulp.task("bundle-scripts", ["jquery-bundle", "ng-bundle", "bootstrap-bundle"], function () {

});

//Restore all bower packages
gulp.task("bower-restore", function () {
    return bower();
});

//build lib scripts
gulp.task("compile-lib", ["bundle-scripts"], function () {
    return gulp.src("lib/*.js")
        .pipe(sourcemaps.init())
        .pipe(concat("compiled-bundle.js"))
        .pipe(gulp.dest("dist"))
        .pipe(rename("compiled-bundle.min.js"))
        .pipe(uglify())
        .pipe(sourcemaps.write("./"))
        .pipe(gulp.dest("dist"));
});

Sending emails in Node.js?

Nodemailer Module is the simplest way to send emails in node.js.

Try this sample example form: http://www.tutorialindustry.com/nodejs-mail-tutorial-using-nodemailer-module

Additional Info: http://www.nodemailer.com/

What type of hash does WordPress use?

The best way to do this is using WordPress class to authenticate users. Here is my solutions:

1. Include following WordPress PHP file:

include_once(dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . "wp-includes" . DIRECTORY_SEPARATOR . "class-phpass.php");

2. Create an object of PasswordHash class:

$wp_hasher = new PasswordHash(8, true);

3. call CheckPassword function to authenticate user:

$check = $wp_hasher->CheckPassword($password, $row['user_pass']);

4. check $check variable:

if($check) {
   echo "password is correct";
} else {
   echo "password is incorrect";
}

Please Note that: $password is the un-hashed password in clear text whereas $row['user_pass'] is the hashed password that you need to fetch from the database.

Calculate a MD5 hash from a string

I suppose it is better to use UTF-8 encoding in the string MD5.

public static string MD5(this string s)
{
    using (var provider = System.Security.Cryptography.MD5.Create())
    {
        StringBuilder builder = new StringBuilder();                           

        foreach (byte b in provider.ComputeHash(Encoding.UTF8.GetBytes(s)))
            builder.Append(b.ToString("x2").ToLower());

        return builder.ToString();
    }
}

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

It is today possible to configure Safari to access local files.

  • By default Safari doesn't allow access to local files.
  • To enable this option: First you need to enable the develop menu.
  • Click on the Develop menu Select Disable Local File Restrictions.

Source: http://ccm.net/faq/36342-safari-how-to-enable-local-file-access

TypeError: 'list' object cannot be interpreted as an integer

For me i was getting this error because i needed to put the arrays in paratheses. The error is a bit tricky in this case...

ie. concatenate((a, b)) is right

not concatenate(a, b)

hope that helps.

Difference between parameter and argument

Argument is often used in the sense of actual argument vs. formal parameter.

The formal parameter is what is given in the function declaration/definition/prototype, while the actual argument is what is passed when calling the function — an instance of a formal parameter, if you will.

That being said, they are often used interchangeably, their exact use depending on different programming languages and their communities. For example, I have also heard actual parameter etc.

So here, x and y would be formal parameters:

int foo(int x, int y) {
    ...
}

Whereas here, in the function call, 5 and z are the actual arguments:

foo(5, z);

How to turn a string formula into a "real" formula

Say, let we have column E filled by formulas that returns string, like:

= " = " & D7

where D7 cell consist more complicated formula, that composes final desired result, say:

= 3.02 * 1024 * 1024 * 1024

And so in all huge qty of rows that are.

When rows are a little - it just enough to copy desired cells as values (by RMB)
to nearest column, say G, and press F2 with following Enter in each of rows.
However, in case of huge qty of rows it's impossible ...

So, No VBA. No extra formulas. No F&R

No mistakes, no typo, but stupid mechanical actions instead only,

Like on a Ford conveyor. And in just a few seconds only:

  1. [Assume, all of involved columns are in "General" format.]
  2. Open Notepad++
  3. Select entire column D
  4. Ctrl+C
  5. Ctrl+V in NPP
  6. Ctrl+A in NPP
  7. Select cell in the first row of desired column G1
  8. Ctrl+V
  9. Enjoy :) .

How can a query multiply 2 cell for each row MySQL?

You can do it with:

UPDATE mytable SET Total = Pieces * Price;

Inserting an item in a Tuple

You can cast it to a list, insert the item, then cast it back to a tuple.

a = ('Product', '500.00', '1200.00')
a = list(a)
a.insert(3, 'foobar')
a = tuple(a)
print a

>> ('Product', '500.00', '1200.00', 'foobar')

How can I convert a string to upper- or lower-case with XSLT?

upper-case(string) and lower-case(string)

How to select the row with the maximum value in each group

Another data.table solution:

library(data.table)
setDT(group)[, head(.SD[order(-pt)], 1), by = .(Subject)]

How do I create a new user in a SQL Azure database?

Edit - Contained User (v12 and later)

As of Sql Azure 12, databases will be created as Contained Databases which will allow users to be created directly in your database, without the need for a server login via master.

CREATE USER [MyUser] WITH PASSWORD = 'Secret';
ALTER ROLE [db_datareader] ADD MEMBER [MyUser];

Note when connecting to the database when using a contained user that you must always specify the database in the connection string.

Connecting via a contained User

Traditional Server Login - Database User (Pre v 12)

Just to add to @Igorek's answer, you can do the following in Sql Server Management Studio:

Create the new Login on the server
In master (via the Available databases drop down in SSMS - this is because USE master doesn't work in Azure):

enter image description here

create the login:

CREATE LOGIN username WITH password='password';

Create the new User in the database
Switch to the actual database (again via the available databases drop down, or a new connection)

CREATE USER username FROM LOGIN username;

(I've assumed that you want the user and logins to tie up as username, but change if this isn't the case.)

Now add the user to the relevant security roles

EXEC sp_addrolemember N'db_owner', N'username'
GO

(Obviously an app user should have less privileges than dbo.)

Returning JSON object as response in Spring Boot

If you need to return a JSON object using a String, then the following should work:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
...

@RestController
@RequestMapping("/student")
public class StudentController {

    @GetMapping
    @RequestMapping("/")
    public ResponseEntity<JsonNode> get() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode json = mapper.readTree("{\"id\": \"132\", \"name\": \"Alice\"}");
        return ResponseEntity.ok(json);
    }
    ...
}

Remove all whitespaces from NSString

That is for removing any space that is when you getting text from any text field but if you want to remove space between string you can use

xyz =[xyz.text stringByReplacingOccurrencesOfString:@" " withString:@""];

It will replace empty space with no space and empty field is taken care of by below method:

searchbar.text=[searchbar.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

Return multiple values to a method caller

you can try this "KeyValuePair"

private KeyValuePair<int, int> GetNumbers()
{
  return new KeyValuePair<int, int>(1, 2);
}


var numbers = GetNumbers();

Console.WriteLine("Output : {0}, {1}",numbers.Key, numbers.Value);

Output :

Output : 1, 2

Random integer in VB.NET

Dim rnd As Random = New Random
rnd.Next(n)

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateful server keeps state between connections. A stateless server does not.

So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.

When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.

HTTP and NFS are stateless protocols. Each request stands on its own.

Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.

SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.

Is there a Sleep/Pause/Wait function in JavaScript?

You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout to kick off a function after a delay:

setTimeout(function(){alert("hi")}, 1000);

Depending on your needs, setInterval might be useful, too.

How to execute an SSIS package from .NET?

You can use this Function if you have some variable in the SSIS.

    Package pkg;

    Microsoft.SqlServer.Dts.Runtime.Application app;
    DTSExecResult pkgResults;
    Variables vars;

    app = new Microsoft.SqlServer.Dts.Runtime.Application();
    pkg = app.LoadPackage(" Location of your SSIS package", null);

    vars = pkg.Variables;

    // your variables
    vars["somevariable1"].Value = "yourvariable1";
    vars["somevariable2"].Value = "yourvariable2";

    pkgResults = pkg.Execute(null, vars, null, null, null);

    if (pkgResults == DTSExecResult.Success)
    {
        Console.WriteLine("Package ran successfully");
    }
    else
    {

        Console.WriteLine("Package failed");
    }

How to hide reference counts in VS2013?

Another option is to use mouse, right click on "x reference". Context menu "CodeLens Options" will appear, saving all the navigation headache.

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

Import SQL dump into PostgreSQL database

Works pretty well, in command line, all arguments are required, -W is for password

psql -h localhost -U user -W -d database_name -f path/to/file.sql