Programs & Examples On #Xampp

XAMPP is a cross-platform Apache distribution bundled with MySQL, PHP and Perl.

make script execution to unlimited

Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:

C:\path\to\script> php script.php

Or, if you're using the PHP CGI, I think it's:

C:\path\to\script> php-cgi script.php

Plus, you would also set ini_set('max_execution_time', 0); in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.

PHP: maximum execution time when importing .SQL data file

You're trying to import a huge dataset via a web interface.

By default PHP scripts run in the context of a web server have a maximum execution time limit because you don't want a single errant PHP script tying up the entire server and causing a denial of service.

For that reason your import is failing. PHPMyAdmin is a web application and is hitting the limit imposed by PHP.

You could try raising the limit but that limit exists for a good reason so that's not advisable. Running a script that is going to take a very long time to execute in a web server is a very bad idea.

PHPMyAdmin isn't really intended for heavy duty jobs like this, it's meant for day to day housekeeping tasks and troubleshooting.

Your best option is to use the proper tools for the job, such as the mysql commandline tools. Assuming your file is an SQL dump then you can try running the following from the commandline:

mysql -u(your user name here) -p(your password here) -h(your sql server name here) (db name here) < /path/to/your/sql/dump.sql

Or if you aren't comfortable with commandline tools then something like SQLYog (for Windows), Sequel Pro (for Mac), etc may be more suitable for running an import job

phpmyadmin "no data received to import" error, how to fix?

if none of the above solutions worked for you.

in my case phpmyadmin was using a deferent configuration file(php.ini). to know what config file used by phpmyadmin :

go /usr/share/phpmyadmin then edit index.php file and make it start with this

<?php
phpinfo();
die();
// ...

now when you visit localhost/phpmyadmin you can search for php.ini.

you can tell where the config file is , in my case it was /etc/php/7.3/apache2/php.ini

now you need to update upload_max_filesize and post_max_size and you may need to change upload_tmp_dir

save your changes and then run sudo service apache2 restart

now everything should be OK

mysql said: Cannot connect: invalid settings. xampp

if you are using google chrome you can fix the problem via , trying any one of the steps mentioned on this page but you need to clear your whole browsing history .... clear all the data that chrome saved onto your computer by pressing ctrl+h and the clearing all the browsing data select all the fields now restart php my admin and all will work

how to access the command line for xampp on windows

Like all other had said above, you need to add path. But not sure for what reason if I add C:\xampp\php in path of System Variable won't work but if I add it in path of User Variable work fine.

Although I had added and using other command line tools by adding in system variables work fine

So just in case if someone had same problem as me. Windows 10

enter image description here

XAMPP - Apache could not start - Attempting to start Apache service

IF PORT 80 IS NOT THE ISSUE!

Check to see if the port 80 is in use first as this can be an issue. You can do this by typing "netstat -an" into cmd. The look for 0.0.0.0:80 under Local Address, if you find this is in use then follow the solution from @Karthik. However, I had a similar issue but my port 80 was not in use. My XAMPP had wrong paths locations, steps to fix this:

1.Find out the Apache version you are using, you can find this by looking in Services (Control panel, Admin Tools, Services) and finding Apache in my case it was listed as Apache2.4

2.Close XAMPP.

3.Run cmd as admin.

4.execute 'sc delete "Apache2.4"' (put your version in place of mine and without the surrounding ' ', but with the " " around Apache).

5.execute 'sc delete "mySQL"', again remove the '' when you type it.

6.reopen XAMPP and try starting Apache

If you are having trouble with FileZill, Mercury, or Tomcat you could try it here too, but I have not tested that myself.

Hope this helps!

XAMPP - MySQL shutdown unexpectedly

Guys just make sure you dont have MySql Server installed. Because I have MySql server pre-installed and when I start mysql from xampp control panel some port conflicts are happening and its not working.. SO before starting the mysql from xampp control panel make sure mysql server is not installed. I use .net so I have installed mysql server in the Past. Uninstalling it solved my Problem....

MySQL Database won't start in XAMPP Manager-osx

On Mac, I checked the mysql error log file at:

/Applications/XAMPP/xamppfiles/var/mysql/MyPCName.local.err

There I found

InnoDB: Error: could not open single-table tablespace file ./some_db_name/some_table_name.ibd

After I deleted that .ibd file and then started MySql, it started.

How to enable cURL in PHP / XAMPP

Actually I did it by uncommenting extension=php_curl.dll in the xampp\apache\bin\php.ini file.

how to get login option for phpmyadmin in xampp

Can you set the password to the phpmyadmin here

http://localhost/security/index.php

How do I test a website using XAMPP?

The webpages on an online server reside in a location which looks somewhat like this: http://www.somerandomsite.com/index.php

Since xampp is Offline, it sets up a local server whose address is like this http://localhost/

Basically, xampp sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\ folder.

The browser locates the server in localhost and will search through the above folder for any resources available in there.

So create any number of folders inside the "xampp\htdocs\" each folder thus forming a website (as you build it).

Sometimes apache won't even start. This is due to the clashing of ports with some applications. Some of them I commonly encounter is Skype. See to that it is killed completely and restart apache

error running apache after xampp install

I got the same error when xampp was installed on windows 10.

www.example.com:443:0 server certificate does NOT include an ID which matches the server name

So I opened httpd-ssl.conf file in xampp folder and changed the following line

ServerName www.example.com:443

To

ServerName localhost

And the problem was fixed.

Xampp Access Forbidden php

The way I resolved this was setup error logs correctly, first

<VirtualHost *:80>
    DocumentRoot "D:/websites/test/"
    ServerName test.dev
    ErrorLog "D:/websites/test/logs/error.log"
    CustomLog "D:/websites/test/logs/access.log" common
    <Directory D:/websites/test/>  
        AllowOverride none
        Require all granted  
    </Directory>
</VirtualHost>

After this error are being logged into "D:/websites/test/logs/" make sure to create logs folder yourself. The exact error that was recorded in error log was

AH01630: client denied by server configuration:

Which pointed me to correct solution using this link which said for the above error

Require all granted 

is required. My sample sample code above fixes the problem by the way.

Where to change the value of lower_case_table_names=2 on windows xampp

I have same problem while importing database from linux to Windows. It lowercases Database name aswell as Tables' name. Use following steps for same problem:

  1. Open c:\xampp\mysql\bin\my.ini in editor.
  2. look for

# The MySQL server

[mysqld]

3 . Find

lower_case_table_names

and change value to 2


if not avail copy this at the end of this [mysqld] portion.

lower_case_table_names = 2

This will surely work.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

  1. Open Task Manager (Ctrl+Alt+Delete).
  2. Go to "Details" tab.
  3. Sort by PID number.
  4. End process that is using PID number indicated in error.
  5. Restart XAMPP.

XAMPP, Apache - Error: Apache shutdown unexpectedly

I tried to execute httpd.exe in cmd and got error that there's syntax error in httpd-vhosts.conf. I checked file and found what's wrong and it's working fine now.

So, if you are facing this error then it may be because of httpd-vhosts or any other file.

Try to execute the program via cmd and you will get the error details and the line where is syntax error.

Best of luck

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

UTF-8 encoded html pages show ? (questions marks) instead of characters

When [dropping] the encoding settings mentioned above all characters [are rendered] correctly but the encoding that is detected shows either windows-1252 or ISO-8859-1 depending on the browser.

Then that's what you're really sending. None of the encoding settings in your bullet list will actually modify your output in any way; all they do is tell the browser what encoding to assume when interpreting what you send. That's why you're getting those ?s - you're telling the browser that what you're sending is UTF-8, but it's really ISO-8859-1.

How can I access the MySQL command line with XAMPP for Windows?

For windows

cd\xampp\mysql\bin
mysql -u root -p

Just a simple commands for linux to open mysql :

sudo /opt/lampp/bin/mysql

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

Try resetting your password since it seems it has changed you can reset your password by going to

C:\xampp\mysql

and clicking on the resetroot.bat file

Then change in the php config file the password back to blank and you should have access again

Accessing localhost (xampp) from another computer over LAN network - how to?

Thanks for a detailed explanation.

Just to Elaborate, in Windows, Go to Control Panel -> Firewall, in exceptions "add http and port 80". Then in Services check mark "http (web server port 80)" and "https (web server port 443)" ONLY if you need https to work also. Ok, OK, Close

Then go to any computer on network and type http://computer-name (where you change the firewall and has the xampp running on it) in your web browser and happy days :)

How do I run a file on localhost?

Looking at your other question I assume you are trying to run a php or asp file or something on your webserver and this is your first attempt in webdesign.

Once you have installed php correctly (which you probably did when you got XAMPP) just place whatever file you want under your localhost (/www/var/html perhaps?) and it should run. You can check this of course at localhost/file.php in your browser.

httpd-xampp.conf: How to allow access to an external IP besides localhost?

In windows all you have to do is to go to windows search Allow an app through Windows Firewall.click on Allow another app select Apache and mark public and private both . Open cmd by pressing windows button+r write cmd than in cmd write ipconfig find out your ip . than open up your browser write down your ip http://172.16..x and you will be on the xampp startup page.if you want to access your local site simply put / infront of your ip e.g http://192.168.1.x/yousite. Now you are able to access your website in private network computers .

i hope this will resolve your problem

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

I tried everything but nothing worked. So I just used : chmod -R 777 to htdocs. At least it's only in my local.

XAMPP Apache won't start

Open services.msc directly from command prompt and disabled SQL Server reporting services

& SQL Server analysis services.

Maximum execution time in phpMyadmin

Go to xampp/php/php.ini

Find this line:

max_execution_time=30

And change its value to any number you want. Restart Apache.

Xampp MySQL not starting - "Attempting to start MySQL service..."

If you have other testing applications like SQL web batch etc, uninstall them because they are running in port 3306.

Upgrading PHP in XAMPP for Windows?

You can go through the following link as it helped me, should work for you as well. http://hype-free.blogspot.com/2007/07/updating-php-in-xampp-for-windows.html

Realizing that my answer helped couple of users, here is the edit from original link:

Edit:

First of all Always backup your data.

  1. Download the latest binary version of PHP (make sure to get the .zip package not the installer)
  2. De-archive it to a directory
  3. Overwrite the contents of directory in the php subfolder of your XAMPP installation directory.
  4. Overwrite the contents of the directory apache\bin with the newer versions.
  5. Now the trick: take the files which have a '_2' in their names (for example php5apache2_2.dll or php5apache2_2_filter.dll), copy them in the apache\bin subdirectory and remove the '_2' part, overwriting the existing files. This is necessary because by XAMPP uses Apache version 2.2 and the files with the 2 prefix are built for Apache 2.0, so you must take the files build for the newer version (which has a different plugin interface) and rename them in the filenames XAMPP expects.

NOTE: there are two directories to be updated with new version of files, namely php sub-directory and apache/bin sub-directory, inside XAMPP installation.

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

On newer versions of PHP on Windows, the majority of answers here won't work, since the corresponding configuration lines have changed.

For PHP 7.x, you need to uncomment (remove the ; at the beginning of the line) the following lines:

extension_dir = "ext"
extension=openssl

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

  1. Find php.ini [\xampp\php]
  2. Just set these in php.ini:
upload_max_filesize = 1000M;
post_max_size = 1000M;
  1. Rebot server
    • Stop Apache and MySQL
    • Start again Apache and MySQL

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

if you before use localhost and root your file be cached

remove /bootstap/cache/config.php

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

How to fix warning from date() in PHP"

error_reporting(E_ALL ^ E_WARNING);

:)

You should change subject to "How to fix warning from date() in PHP"...

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

mysql_ functions have been removed from PHP 7. You can now use MySQLi or PDO.

MySQLi example:

mysqli_connect($mysql_hostname, $mysql_username, $mysql_password, $mysql_dbname);

mysqli_connect reference link

How do I use MySQL through XAMPP?

Changing XAMPP Default Port: If you want to get XAMPP up and running, you should consider changing the port from the default 80 to say 7777.

  • In the XAMPP Control Panel, click on the Apache – Config button which is located next to the ‘Logs’ button.

  • Select ‘Apache (httpd.conf)’ from the drop down. (Notepad should open)

  • Do Ctrl+F to find ’80’ and change line Listen 80 to Listen 7777

  • Find again and change line ServerName localhost:80 to ServerName localhost:7777

  • Save and re-start Apache. It should be running by now.

The only demerit to this technique is, you have to explicitly include the port number in the localhost url. Rather than http://localhost it becomes http://localhost:7777.

WAMP/XAMPP is responding very slow over localhost

After try each instuction on this post, for me works when i add in:

Avira >>
Real-Time Protection >>
Configuration >>
Exception >>

Add Proccess:

  1. xampp\apache\bin\httpd.exe
  2. xampp\mysql\bin\mysqld.exe
  3. xampp\xampp-control.exe

enter image description here

how to create virtual host on XAMPP

Apache Virtual Host documentation Setting up a virtual host (vhost) provides several benefits:

  • Virtual Hosts make URLs cleaner – localhost/mysite vs mysite.local.
  • Virtual Hosts make permissions easier – restrict access for a single vhost on a local network vs permitting access to all sites on your local network.
  • Some applications require a “.” in the URL (ahem Magento). While you can setup localhost.com/mysite by editing the Windows hosts file, creating a vhost is a better solution.

VirtualHost Directive Contains directives that apply only to a specific hostname or IP address

Location Directive Applies the enclosed directives only to matching URLs

Example changes over configuration file - D:\xampp\apache\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin localhost
    DocumentRoot "D:/xampp/htdocs"
    ServerName localhost
</VirtualHost>

<VirtualHost localhost:80>
  ServerAdmin [email protected]
  DocumentRoot "/www/docs/host.example.com"
  #DocumentRoot "D:\xampp\htdocs\phpPages"
  ServerName host.example.com
  ErrorLog "logs/host.example.com-error_log"
  TransferLog "logs/host.example.com-access_log"
</VirtualHost>

# To get view of PHP application in the Browser.
<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "D:\xampp\htdocs\app1"
    ServerName app1.yash.com
    ServerAlias app1.yash.com
    ErrorLog "logs/app1.yash.com-error.log"
    CustomLog "logs/app1.yash.com-access.log" combined
    
    # App1 communication proxy call to Java War applications from XAMP
    <Location /ServletApp1>
            ProxyPass  http://app1.yashJava.com:8080/ServletApp1
            ProxyPassReverse  http://app1.yashJava.com:8080/ServletApp1
            Order Allow,Deny
            Allow from all
    </Location>
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "D:\xampp\htdocs\app2"
    ServerName app2.yash.com
    ErrorLog "logs/app2.yash.com-error.log"
    CustomLog "logs/app2.yash.com-access.log" combined
    
    # App1 communication proxy call to Java War applications from XAMP
    <Location /ServletApp2>
            ProxyPass  http://app1.yashJava.com:8080/ServletApp2
            ProxyPassReverse  http://app1.yashJava.com:8080/ServletApp2
            Order Allow,Deny
            Allow from all
    </Location>
</VirtualHost>

Update Your Windows Hosts File « Open your Windows hosts file located in C:\Windows\System32\drivers\etc\hosts.

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost

127.0.0.1       test.com
127.0.0.1       example.com
127.0.0.1       myssl.yash.com

D:\xampp\apache\conf\httpd.conf, [httpd-ssl.conf](http://httpd.apache.org/docs/2.2/mod/mod_ssl.html)

# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost> directive.
# Listen 0.0.0.0:80 | [::]:80
Listen 80

LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule speling_module modules/mod_speling.so

# ServerAdmin: Your address, where problems with the server should be e-mailed.
# This address appears on some server-generated pages, such as error documents.
#  e.g. [email protected]
ServerAdmin postmaster@localhost
ServerName localhost:80
DocumentRoot "D:/xampp/htdocs"

<Directory "D:/xampp/htdocs">
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Require all granted
</Directory>

# Virtual hosts
Include "conf/extra/httpd-vhosts.conf"

# ===== httpd-ssl.conf - SSL Virtual Host Context =====
# Note: Configurations that use IPv6 but not IPv4-mapped addresses need two
#       Listen directives: "Listen [::]:443" and "Listen 0.0.0.0:443"
Listen 443
## SSL Virtual Host Context
<VirtualHost _default_:443>
    DocumentRoot "D:\xampp\htdocs\projectFolderSSL"
    ServerName myssl.yash.com:443
    ServerAlias myssl.yash.com:443
        
    ServerAdmin webmaster@localhost
    ErrorLog "logs/error.log"
    <IfModule log_config_module>
        CustomLog "logs/access.log" combined
    </IfModule>
    
    ## Redirecting URL from Web server to Application server over different machine.
    # myssl.yash.com:443/ServletWebApp
    <Location /path>
        ProxyPass  http://java.yash2.com:8444/ServletWebApp
        ProxyPassReverse  http://java.yash2.com:8444/ServletWebApp
        Order Allow,Deny
        Allow from all
    </Location>
    
    #SSLCertificateFile "conf/ssl.crt/server.crt"
    SSLCertificateFile "D:\SSL_Vendor\yash.crt"
    
    #SSLCertificateKeyFile "conf/ssl.key/server.key"
    SSLCertificateKeyFile "D:\SSL_Vendor\private-key.key"
    
    #SSLCertificateChainFile "conf/ssl.crt/server-ca.crt"
    SSLCertificateChainFile "D:\SSL_Vendor\intermediate.crt"
</VirtualHost>
# ===== httpd-ssl.conf - SSL Virtual Host Context =====

@see

Error when trying to access XAMPP from a network

This answer is for XAMPP on Ubuntu.

The manual for installation and download is on (site official)

http://www.apachefriends.org/it/xampp-linux.html

After to start XAMPP simply call this command:

sudo /opt/lampp/lampp start

You should now see something like this on your screen:

Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.

If you have this

Starting XAMPP for Linux 1.8.1...                                                             
XAMPP: Another web server daemon is already running.                                          
XAMPP: Another MySQL daemon is already running.                                               
XAMPP: Starting ProFTPD...                                                                    
XAMPP for Linux started

. The solution is

sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop

And the restast with sudo //opt/lampp/lampp restart

You to fix most of the security weaknesses simply call the following command:

/opt/lampp/lampp security

After the change this file

sudo kate //opt/lampp/etc/extra/httpd-xampp.conf

Find and replace on

    #
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    Allow from all
    #\
    #   fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
    #   fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Xampp localhost/dashboard

Wanna a list of folder in xampp?

Just delete or change the file index.php to index.txt. And you will get the list just typing url: localhost.

Browser screenshot

Apache shutdown unexpectedly

I shut down the computer and restarted after installing the software and that fixed my problem.

Enabling SSL with XAMPP

In case you are on Mac OS (catalina or mojave) and wants to enable HTTPS/SSL on XAMPP for Mac, you need to enable the virtual host and use the default certificates included in XAMPP. On your httpd-vhosts.conf file add a new vhost:

<VirtualHost *:443>
    ServerAdmin [email protected]
    DocumentRoot "/Users/your-user/your-site"
    ServerName your-site.local
    SSLEngine on
    SSLCertificateFile "etc/ssl.crt/server.crt" 
    SSLCertificateKeyFile "etc/ssl.key/server.key"
    <Directory "/Users/your-user/your-site">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Apache - MySQL Service detected with wrong path. / Ports already in use

Set XAMPP controlpanel to run under Administrator priviledges.

In Win 7 1. First make sure XAMPP control panel is not running 2. SHIFT+right click on XAMPP Control Panel 3. Click on properties 4. In properties select tab 'Compatibility' 5. On bottom of the tab under 'Privilege level' check the box "Run this program as an administrator" 6. Click OK

this worked for me

Apache won't run in xampp

In my case, it was something else. One day earlier I tried to install Magento using bitnami of xampp. And I deleted That Module

I opened the httpd.conf and found this line:

Include "C:/xampp/apps/magento/conf/httpd-prefix.conf"

I just commented it with #,

Now it's running fine. :)

Is there way to use two PHP versions in XAMPP?

I know this is the old post but I want to share there is library for still running mysql_connect() in PHP 7. It works by overriding the real function (mysql_connect() is overridden by mysqli_connect() which work on this library).

I found from this video https://www.youtube.com/watch?v=Eqd-jJu4sQ4

hopefully it helps

XAMPP Start automatically on Windows 7 startup

Go to the Config button (up right) and select the Autostart for Apache.enter image description here

XAMPP Apache Webserver localhost not working on MAC OS

This solution worked perfectly fine for me..

1) close XAMPP control

2) Open Activity Monitor(Launchpad->Other->Activity Monitor)

3) select filter for All processes (default is My processes)

4) in fulltext search type: httpd

5) kill all httpd items

6) relaunch XAMPP control and launch apache again

Hurray :)

How to turn on/off MySQL strict mode in localhost (xampp)?

In my case, I need to add:

sql_mode="STRICT_TRANS_TABLES"

under [mysqld] in the file my.ini located in C:\xampp\mysql\bin.

Access denied for root user in MySQL command-line

I had the same issue, and it turned out to be that MariaDB was set to allow only root to log in locally via the unix_socket plug-in, so clearing that setting allowed successfully logging in with the user specified on the command line, provided a correct password is entered, of course. See this answer on Ask Ubuntu

Make XAMPP / Apache serve file outside of htdocs folder

Solution to allow Apache 2 to host websites outside of htdocs:

Underneath the "DocumentRoot" directive in httpd.conf, you should see a directory block. Replace this directory block with:

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Allow from all
</Directory> 

REMEMBER NOT TO USE THIS CONFIGURATION IN A REAL ENVIRONMENT

PHP - SSL certificate error: unable to get local issuer certificate

elaborating on the above answers for server deployment.

$hostname = gethostname();
if($hostname=="mydevpc")
{
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}

should do the trick for development environment without compromising the server when deployed.

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

You do not have to install another version of Xampp. I've managed to use PHP 5.6 on my Xampp PHP 7 version. Here is what you need to do to make it works:

  1. Raname (backup) <XAMPP_DIR>\php to <XAMPP_DIR>\php~7
  2. Copy (backup) <XAMPP_DIR>\apache\conf\extra\httpd-xampp.conf to <XAMPP_DIR>\apache\conf\extra\httpd-xampp~7.conf
  3. Download PHP5 and unpack it to <XAMPP_DIR>\php
  4. Edit <XAMPP_DIR>\apache\conf\extra\httpd-xampp.conf and change all php5 occurrences to php7. You need to change php7apache2_4.dll to php5apache2_4.dll, php7ts.dll to php5ts.dll and php7_module to php5_module
  5. Ensure all your paths are correct like extension_dir in php.ini.

Restart Apache and voila.

What is the difference between XAMPP or WAMP Server & IIS?

In addition to the above, WAMP supports 64 bit PHP on Windows systems while XAMPP only offers 32 bit versions. This actually made me switch to WAMP on my Windows machine since you need 64 bit PHP 7 to get bigint numbers correctly from MySQL

how can I enable PHP Extension intl?

If the below line is not available or commented in C:\xampp\php\php.ini, then add it or uncomment and restart the apache server then it works.

extension=php_intl.dll

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

I am using UniServer Zero XIV 13.x.x UniController XIV V2.3.1:

enter image description here

From the command line I did this:

mysql> CREATE USER 'pmauser'@'%' IDENTIFIED BY 'MyPasswordHere!';
Query OK, 0 rows affected (0.07 sec)

mysql> GRANT ALL PRIVILEGES ON *.* TO 'pmauser'@'%' WITH GRANT OPTION;
Query OK, 0 rows affected (0.02 sec)

Then I went to C:\...\wamp\ZeroXIV_unicontroller_2_3_1\UniServerZ\home\us_opt1\config.inc.php and modified the file to have this:

/* PMA User advanced features */
//////////$cfg['Servers'][$i]['controluser']    = 'pma';
//////////$cfg['Servers'][$i]['controlpass']    = $password;
$cfg['Servers'][$i]['controluser']    = 'pmauser';
$cfg['Servers'][$i]['controlpass']    = 'MyPasswordHere!';

I restarted Apache and MySQL. The error is gone!

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

user: root

password: [blank]

XAMPP v3.2.2

XAMPP permissions on Mac OS X?

Tried the above but the option to amend the permission was not available for the htdocs folder,

My solution was:

  1. Open applications folder
  2. Locate XAMPP folder
  3. Right click, get info (as described above)
  4. In pop-up window locate the 'sharing & permission' section
  5. Click the 'locked' padlock symbol
  6. Enter admin password
  7. Change 'Everyone' permissions to read & write
  8. In the get info window still, select the 'cog' icon' drop down option at the very bottom and select 'Apply to enclosed items' this will adjust the permission across all sub-folders as well.
  9. Re-lock the padlock symbol
  10. Close the 'Get Info' window.

Task complete, this will now allow you to populate sub-folders within the htdocs folder as needed to populate your website(s).

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

(MAC) check the /Applications/XAMPP/etc/httpd.conf file there is a section that by default is commented out. Search for "Virtual hosts". If you delete the # in the next line, like in the picture, you should just need to restart apache and then you're good to go. uncomment to allow virtual hosts

XAMPP - Error: MySQL shutdown unexpectedly

the true way is RECONFIGURE your app.with setup of MYSQL .you can open your setup again and change port from 3306 to 3307.

enter image description here

Access XAMPP Localhost from Internet

First, you need to configure your computer to get a static IP from your router. Instructions for how to do this can be found: here

For example, let's say you picked the IP address 192.168.1.102. After the above step is completed, you should be able to get to the website on your local machine by going to both http://localhost and http://192.168.1.102, since your computer will now always have that IP address on your network.

If you look up your IP address (such as http://www.ip-adress.com/), the IP you see is actually the IP of your router. When your friend accesses your website, you'll give him this IP. However, you need to tell your router that when it gets a request for a webpage, forward that request to your server. This is done through port forwarding.

Two examples of how to do this can be found here and here, although the exact screens you see will vary depending on the manufacturer of your router (Google for exact instructions, if needed).

For the Linksys router I have, I enter http://192.168.1.1/, enter my username/password, Applications & Gaming tab > Port Range Forward. Enter the application name (whatever you want to call it), start port (80), end port (80), protocol (TCP), ip address (using the above example, you would enter 192.168.1.102, which is the static IP you assigned your server), and be sure to check to enable the forwarding. Restart your router and the changes should take effect.

Having done all that, your friend should now be able to access your webpage by going to his web browser on his machine and entering http://IP.address.of.your.computer (the same one you see when you go here ).

As mentioned earlier, the IP address assigned to you by your ISP will eventually change whether you sign offline or not. I strongly recommend using DynDns, which is absolutely free. You can choose a hostname at their domain (such as cuga.kicks-ass.net) and your friend can then always access your website by simply going to http://cuga.kicks-ass.net in his browser. Here is their site again: DynDns

I hope this helps.

How to configure XAMPP to send mail from localhost?

You can test send mail in Your PC without Internet

you should use Papercut this simple application to test send mail. and you don't need to configure anything.

Just run it and try test send mail:

test_sendmail.php

<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";

mail($to,$subject,$txt,$headers);
?>

and you will see this:

enter image description here

I hope you will have a good day. you can find me on Youtube for more tutorial Piseth Sok

Cheer!

How do I free my port 80 on localhost Windows?

I was trying to install nginx from here - http://nginx.org/en/docs/windows.html

Going to http://localhost/ will show something, at least a proper "not found" message
This is because 80 is the default port, and it was taken by other processes.

Now run below command:

net stop http

    // Above command stopped below services  
    // - SSDP Discovery  
    // - Print Spooler  
    // - BranchCache  
    // - Function Discovery Resource Publication  
    // - Function Discovery Provider Host  

Now, going to http://localhost/ will fail with a broken link page message.

Main process was BranchCache
This process, after stopped, will restart in a few seconds.
So we need to run other commands we need soon, an example below:

// this will stop
net stop http

// immeidately run other command you want to
start nginx

Now, going to http://localhost/ gave me:

Welcome to nginx!

Hope that helps.

How to downgrade php from 5.5 to 5.3

It is possible! Yes

In many cases, you might want to use XAMPP with a different PHP version than the one that comes preinstalled. You might do this to get the benefits of a newer version of PHP, or to reproduce bugs using an earlier version of PHP.

To use a different version of PHP with XAMPP, follow these steps:

  1. Download a binary build of the PHP version that you wish to use from the PHP website, and extract the contents of the compressed archive file to your XAMPP installation directory (usually, C:\xampp). Ensure that you give it a different directory name to avoid overwriting the existing PHP version. For example, in this tutorial, we’ll call the new directory C:\xampp\php5-6-0. NOTE : Ensure that the PHP build you download matches the Apache build (VC9 or VC11) in your XAMPP platform.

  2. Within the new directory, rename the php.ini-development file to php.ini. If you prefer to use production settings, you could instead rename the php.ini-production file to php.ini.

  3. Edit the httpd-xampp.conf file in the apache\conf\extra\ subdirectory of your XAMPP installation directory. Within this file, search for all instances of the old PHP directory path and replace them with the path to the new PHP directory created in Step 1. In particular, be sure to change the lines

    LoadFile "/xampp/php/php5ts.dll"
    LoadFile "/xampp/php/libpq.dll"
    LoadModule php5_module "/xampp/php/php5apache2_4.dll"

to

    LoadFile "/xampp/php5-6-0/php5ts.dll"
    LoadFile "/xampp/php5-6-0/libpq.dll"
    LoadModule php5_module "/xampp/php5-6-0/php5apache2_4.dll"

NOTE : Remember to adjust the file and directory paths above to reflect valid paths on your system.

  1. Restart your Apache server through the XAMPP control panel for your changes to take effect. The new version of PHP should now be active. To verify this, browse to the URL http://localhost/xampp/phpinfo.php, which displays the output of the phpinfo() command, and check the version number at the top of the page.

How to get back Lost phpMyAdmin Password, XAMPP

The only solution worked for me:

(source: https://stackoverflow.com/a/22784404/2377343 )

You need to stop Mysql and change user password using Commands.

Where to find htdocs in XAMPP Mac

Go to Volumes Tab and click Mount

enter image description here

You can find it under Locations in the Sidebar. Click on it.

enter image description here

Open this folder: Lamp

enter image description here

You can find the htdocs folder inside Lamp, just like the below screenshot:

enter image description here

Note: I am using macOS Catalina.

XAMPP: Couldn't start Apache (Windows 10)

After playing around, really all you have to do is change two lines in the httpd.conf file:

Change "Listen 80" to "Listen 122" (or anything else you want)

and

"ServerName Localhost:80" to "Localhost:122" (or the port you changed above)

Then it all should fire right up :P

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

I had the same error and it occured when changing the mysql/data folder to another folder.
I just copied all folders inside mysql/data folder to a new location except for two files. Those are ib_logfile0 and ib_logfile1; those are automatically created when starting the MySQL server. That worked for me.

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

Start your XAMPP server by using:

  • {XAMPP}\xampp-control.exe
  • {XAMPP}\apache_start.bat

Then you have to use the URI http://localhost/index.html because htdocs is the document root of the Apache server.

If you're getting redirected to http://localhost/xampp/*, then index.php located in the htdocs folder is the problem because index.php files have a higher priority than index.html files. You could temporarily rename index.php.

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

There are many possible answers for this problem. The most common and most likely is that you're running another program which is blocking port 80 or 443. If you've installed Skype, then you've found your problem! Change apache's port settings to 81 and apache will work. There's a good tutorial on that To check this you can open up your command line by clicking the start menu, and typing 'cmd', and enter the command

    netstat -nab

this wil return a list of programs that will vaguely resemble this pattern

    [someprogram.exe]
    UDP     [fe80::numbers:numbers:numbers:numbers%numbers]:portnumber

You need to find a line (or lines) ending in :80 and terminate them in order to start apache. If there is no line ending in :80, there are more things you can do.

First, navigate to xampp's directory (default is c:\xampp) and double click apache_start.bat. This will open up a comand line and return more detailed errors about why apache can't run. Mostly, be looking for syntax errors that you could've created by editing your httpd.conf, or httpd-ssl.conf files. This is very easy to do if you've edited it and are a new user.

If still this fails, your last hope is to check the apache error log by clicking on the logs tab in apache's row in the xampp control panel and clicking error log.

If none of this works, don't give up! You got this!

Edit: If you change the port of apache, you will also have to go into httpd.conf (located in xampp/apache/conf) and near line 184, replace

ServerName localhost:80

with

ServerName localhost:81

It is also possible to specify port 81 in the url of your localhost, i.e.

localhost:81/my_project.php

Where does PHP's error log reside in XAMPP?

\xampp\php\logs did not exist at all for me - for whatever reason.

I simply had to create a folder in \xampp\php\ called logs and then the php_error_log file was created and written to.

How to set xampp open localhost:8080 instead of just localhost

Steps using XAMPP GUI:

Step-1: Click on Config button

enter image description here

Step-2: Click on Service and Port Settings button

enter image description here

Final step: Change your port and Save

enter image description here

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

This is the Different Solution, Check if your Services are running correctly, if WAMP icon showing orange color, and 2 out of 3 services are running it's showing, then this solution will work . Root cause:

If in your system mysql was there, later you installed WAMP then again one MYSQL will install as WAMP package, default port for MYSQL is 3306 , So in both mysql the port will be 3306, which is a port conflict, So just change the port it will work fine. Steps to change the Port.

  1. Right click the WAMP icon.
  2. Chose Tool
  3. Change the port in Port used by MySql Section

Access to the requested object is only available from the local network phpmyadmin

On Xampp 5.6.3 Windows Path C:\xampp\apache\conf\extra\httpd-xampp.conf comment in this: #Require local

New XAMPP security concept ... #Require local ...

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

How to change XAMPP apache server port?

The best solution is to reconfigure the XAMPP Apache server to listen and use different port numbers. Here is how you do it:

1) First, you need to open the Apache “httpd.conf” file and configure it to use/listen on a new port no. To open httpd.conf file, click the “Config” button next to Apache “Start” and “Admin” buttons. In the popup menu that opens, click and open httpd.conf

2) Within the httpd.conf file search for “listen”. You’ll find two rows with something like:

#Listen 12.34.56.78:80
Listen 80

Change the port no to a port no. of your choice (e.g. port 1234) like below

#Listen 12.34.56.78:1234
Listen 1234

3) Next, in the same httpd.conf file look for “ServerName localhost:” Set it to the new port no.

ServerName localhost:1234

4) Save and close the httpd.conf file.

5) Now click the Apache config button again and open the “httpd-ssl.conf” file.

6) In the httpd-ssl.conf file, look for “Listen” again. You may find:

Listen 443

Change it to listen on a new port no of your choice. Say like:

Listen 1443

7) In the same httpd-ssl.conf file find another line that says <VirtualHost _default_:443>. Change this to your new port no. (like 1443)

8) Also in the same httpd-ssl.conf you can find another line defining the port no. For that look for “ServerName”. you might find something like:

ServerName www.example.com:443 or  ServerName localhost:433

Change this ServerName to your new port no.

8) Save and close the httpd-ssl.conf file.

9) Finally, there’s just one more place you should change the port no. For that, click and open the “Config” button of your XAMPP Control Panel. Then click the, “Service and Port Settings” button. Within it, click the “Apache” tab and enter and save the new port nos in the “main port” and “SSL port” boxes. Click save and close the config boxes.

That should do the trick. Now “Start” Apache and if everything goes well, your Apache server should start up.

You will also see the Apache Port/s no in the XAMPP control panel has change to the new port IDs you set.

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

For me (also XAMPP on Windows 7), this is what worked:

<Directory "C:\projects\myfolder\htdocs">`
   AllowOverride All
   Require all granted
   Options Indexes FollowSymLinks
</Directory>` 

It is this line that would cause the 403:

Order allow,deny

XAMPP on Windows - Apache not starting

For me, the problem was I had two installations of Apache Tomcat

The following steps solved my problem:

  1. Open up services.msc in command prompt
  2. Select the Apache Tomcat service, right click and select properties
  3. Check the path to the executable of the service
  4. Follow the instructions in https://stackoverflow.com/questions/7190480/modifying-the-path-to-executable-of-a-windows-service to change the path to "\tomcat\bin\tomcat7.exe" //RS//Tomcat7
  5. Restart XAMPP Control Panel

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

I stopped MySQL sudo service mysql stop and then started xammp sudo /opt/lampp/lampp start and it worked!

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Say you let vmware use port 443, and use another ssl port in XAMPP Apache (httpd-ssl.conf) :

The red error will keep popping in XAMPP Control Panel. You also need to change the port in the XAMPP Control Panel configuration :

In XAMPP Control Panel, click the "Config" button (top-left). Then click "Service and Port Settings". There you can set the ports to match the ports used by Apache.

display data from SQL database into php/ html table

You say you have a database on PhpMyAdmin, so you are using MySQL. PHP provides functions for connecting to a MySQL database.

$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');

$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);

echo "<table>"; // start a table tag in the HTML

while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";  //$row['index'] the index here is a field name
}

echo "</table>"; //Close the table in HTML

mysql_close(); //Make sure to close out the database connection

In the while loop (which runs every time we encounter a result row), we echo which creates a new table row. I also add a to contain the fields.

This is a very basic template. You see the other answers using mysqli_connect instead of mysql_connect. mysqli stands for mysql improved. It offers a better range of features. You notice it is also a little bit more complex. It depends on what you need.

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

I couldn't get this working. Started with PHP 5.3, then tried to switch to PHP 5.28 from xampp-win32-1.7.0.zip. Couldn't get it to work. Then, I got smart and figured out i was working with XAMPP and you can install it wherever you want, so I did a fresh install from scratch with xampp-win32-1.7.0.zip. The whole point of working with XAMPP is so you don't have to fuss with the sysadmin stuff. Using it in that context got me up and running in no time.

Localhost : 404 not found

If your server is still listening on port 80, check the permission on the DocumentRoot folder and if DirectoryIndex file existed.

PhpMyAdmin not working on localhost

Same Object Not Found problem here - both in Xampp as well as in Wamp. It turns out the root name of "phpmyadmin" was "PhpMyAdmin". I got rid of all the capitals, renaming the folder to "phpmyadmin", and after a couple of reloads phpmyadmin was working.

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.

Where do I put my php files to have Xampp parse them?

Look into the httpd.conf and/or httpd-vhosts.conf files and search for the DocumentRoot entry. If you configure multiple virtual hosts, there may be more than one of those, separated in <VirtualHost> tags.

How to setup FTP on xampp

XAMPP for linux and mac comes with ProFTPD. Make sure to start the service from XAMPP control panel -> manage servers.

Further complete instructions can be found at localhost XAMPP dashboard -> How-to guides -> Configure FTP Access. I have pasted them below :

  1. Open a new Linux terminal and ensure you are logged in as root.

  2. Create a new group named ftp. This group will contain those user accounts allowed to upload files via FTP.

groupadd ftp

  1. Add your account (in this example, susan) to the new group. Add other users if needed.

usermod -a -G ftp susan

  1. Change the ownership and permissions of the htdocs/ subdirectory of the XAMPP installation directory (typically, /opt/lampp) so that it is writable by the the new ftp group.

cd /opt/lampp chown root.ftp htdocs chmod 775 htdocs

  1. Ensure that proFTPD is running in the XAMPP control panel.

You can now transfer files to the XAMPP server using the steps below:

  1. Start an FTP client like winSCP or FileZilla and enter connection details as below.

If you’re connecting to the server from the same system, use "127.0.0.1" as the host address. If you’re connecting from a different system, use the network hostname or IP address of the XAMPP server.

Use "21" as the port.

Enter your Linux username and password as your FTP credentials.

Your FTP client should now connect to the server and enter the /opt/lampp/htdocs/ directory, which is the default Web server document root.

  1. Transfer the file from your home directory to the server using normal FTP transfer conventions. If you’re using a graphical FTP client, you can usually drag and drop the file from one directory to the other. If you’re using a command-line FTP client, you can use the FTP PUT command.

Once the file is successfully transferred, you should be able to see it in action.

How to enable curl in xampp?

It should be available in php.ini file. You need to un-comment the line for curl extension:

  ;extension=php_curl.dll
  ^----- remove semi-colon

What is the location of mysql client ".my.cnf" in XAMPP for Windows?

Go to control panel ? services, look for MySQL and right click choose properties. If there, in “path to EXE file”, there is a parameter like

--defaults-file="X:\path\to\my.ini"

this is the file the server actually uses (independent of what mysql --help prints).

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

Only one process can use port 80 at a time. Port 80 is the default port for web servers, so when you navigate to websites over HTTP, you are actually navigating to that server's port 80 by default (when you use HTTPS, the port is 443).

You can try to hunt down all the programs that are running on port 80, but there's an easier way that will work for development. When running XAMPP, click "Config" under "Apache". Replace Listen 80 with Listen 8080 and ServerName localhost:80 to ServerName localhost:8080.

Then, when you want to look at your masterpiece, navigate to http://localhost:8080 in your browser.

How to locate the php.ini file (xampp)

Am running LAMP on Debian and mine is in:

/etc/php/7.0/apache2/php.ini

Port 443 in use by "Unable to open process" with PID 4

I had a similar issue where port 443 was blocked by PID 4. After breaking my head for several hours I found the command netsh show urlacl which gave me an idea of the system process blocking the port.

To run command run cmd or windows shell in administrator mode.

netsh

http

show urlacl

I got response a which showed 443 was blocked by NT Service SSTPSvc Reserved URL

Response

https://+:443/sra_{BA195980-CD49-458b-9E23-C84EE0ADCD75}/ User: NT SERVICE\SstpSvc Listen: Yes Delegate: Yes User: BUILTIN\Administrators Listen: No Delegate: No User: NT AUTHORITY\SYSTEM Listen: Yes Delegate: Yes

With this information I followed the microsoft link to change the listening port for SSTP based vpn. https://support.microsoft.com/en-in/kb/947032

This resolved my port issue.

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

An error in your httpd.conf or other Apache config files will cause this. Revert httpd.conf et al to the pristine, installer versions and see if Apache runs again.

(I tried Skype and other suggestions here, no luck, but logs [XAMPP > Apache > Logs button] showed that it ran once when first installed. That was the giveaway.)

Likely errors:

  • Did you edit with a Windows text editor that changes line endings to non-Unix? (Solution here.)
  • Missing or invalid DSO files (.so)

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

It is just a matter of changing the port user by mysql:3308 to 3306

Just right click on wamp-> select tools

under Port Used By mysql:3308 clcik on "use a port other than 3308

In the text port text box appear : type 3306 and save. Wait until the wampserver restarts and get green.

Now run your PHP code, It will work. That's it - Good Luck

XAMPP Port 80 in use by "Unable to open process" with PID 4

I had the following error message Port 80 in use by "Unable to open process" with PID 4! Apache WILL NOT start without the configured ports free! You need to uninstall/disable/reconfigure the blocking application or reconfigure Apache and the Control Panel to listen on a different port Starting Check-Timer Control Panel Ready

opened the httpd.conf and changed the listen port from 80 to 1234 in both places

Listen 12.34.56.78:1234

Listen 1234

Then go to Config for the xampp control panel and go to service and port setting and changed the port from 80 to 1234

That worked.

XAMPP Object not found error

Agree @Drixson Oseña: You should not write localhost/xampp/...., else write for e.g: localhost/mw-config/index.php

Import mysql DB with XAMPP in command LINE

Copy Database Dump File at (Windows PC) D:\xampp\mysql\bin

mysql -h localhost -u root Databasename <@data11.sql

Force browser to refresh css, javascript, etc

Make sure this isn't happening from your DNS. For example Cloudflare has it where you can turn on development mode where it forces a purge on your stylesheets and images as Cloudflare offers accelerated cache. This will disable it and force it to update everytime someone visits your site.

xampp MySQL does not start

I found out that re-installing Xampp as an administrator and running it as an Administrator worked.

XAMPP installation on Win 8.1 with UAC Warning

There are two things you need to check:

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC (User Account Control) as it restricts certain administrative function needed to run a web server.

To ensure that your user account has administrator privilege, run lusrmgr.msc from the Windows Start > Run menu to bring up the Local Users and Groups Windows. Double-click on your user account that appears under Users, and verifies that it is a member of Administrators.

To disable UAC (as an administrator), from Control Panel:

  1. Type UAC in the search field in the upper right corner.
  2. Click Change User Account Control settings in the search results.
  3. Drag the slider down to Never notifyand click OK.

open up the User Accounts window from Control Panel. Click on the Turn User Account Control on or off option, and un-check the checkbox.

Alternately, if you don't want to disable UAC, you will have to install XAMPP in a different folder, outside of C:\Program Files (x86), such as C:\xampp.

Hope this helps.

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

Difference between request.getSession() and request.getSession(true)

request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).

Which HTTP methods match up to which CRUD methods?

It depends on the concrete situation.. but in general:

PUT = update or change a concrete resource with a concrete URI of the resource.

POST = create a new resource under the source of the given URI.

I.e.

Edit a blog post:

PUT: /blog/entry/1

Create a new one:

POST: /blog/entry

PUT may create a new resource in some circumstances where the URI of the new ressource is clear before the request. POST can be used to implement several other use cases, too, which are not covered by the others (GET, PUT, DELETE, HEAD, OPTIONS)

The general understanding for CRUD systems is GET = request, POST = create, Put = update, DELETE = delete

Python: How to keep repeating a program until a specific input is obtained?

This is a small program that will keep asking an input until required input is given.

we should keep the required number as a string, otherwise it may not work. input is taken as string by default

required_number = '18'

while True:
    number = input("Enter the number\n")
    if number == required_number:
        print ("GOT IT")
        break
    else:
        print ("Wrong number try again")

or you can use eval(input()) method

required_number = 18

while True:
    number = eval(input("Enter the number\n"))
    if number == required_number:
        print ("GOT IT")
        break
    else:
        print ("Wrong number try again")

How to compare numbers in bash?

In bash, you should do your check in arithmetic context:

if (( a > b )); then
    ...
fi

For POSIX shells that don't support (()), you can use -lt and -gt.

if [ "$a" -gt "$b" ]; then
    ...
fi

You can get a full list of comparison operators with help test or man test.

How to set up datasource with Spring for HikariCP?

you need to write this structure on your bean configuration (this is your datasource):

<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
    <property name="poolName" value="springHikariCP" />
    <property name="connectionTestQuery" value="SELECT 1" />
    <property name="dataSourceClassName" value="${hibernate.dataSourceClassName}" />
    <property name="maximumPoolSize" value="${hibernate.hikari.maximumPoolSize}" />
    <property name="idleTimeout" value="${hibernate.hikari.idleTimeout}" />

    <property name="dataSourceProperties">
        <props>
            <prop key="url">${dataSource.url}</prop>
            <prop key="user">${dataSource.username}</prop>
            <prop key="password">${dataSource.password}</prop>
        </props>
    </property>
</bean>

<!-- HikariCP configuration -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <constructor-arg ref="hikariConfig" />
</bean>

This is my example and it is working. You just need to put your properties on hibernate.properties and set it before:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:hibernate.properties</value>
        </list>
    </property>
</bean>

Obs.: the versions are
log4j: 1.2.16
springframework: 3.1.4.RELEASE
HikariCP: 1.4.0

Properties file (hibernate.properties):

hibernate.dataSourceClassName=oracle.jdbc.pool.OracleDataSource
hibernate.hikari.maximumPoolSize=10
hibernate.hikari.idleTimeout=30000
dataSource.url=jdbc:oracle:thin:@localhost:1521:xe
dataSource.username=admin
dataSource.password=

MySQL ORDER BY rand(), name ASC

Beware of ORDER BY RAND() because of performance and results. Check this article out: http://jan.kneschke.de/projects/mysql/order-by-rand/

Python Set Comprehension

You can generate pairs like this:

{(x, x + 2) for x in r if x + 2 in r}

Then all that is left to do is to get a condition to make them prime, which you have already done in the first example.

A different way of doing it: (Although slower for large sets of primes)

{(x, y) for x in r for y in r if x + 2 == y}

How to close a GUI when I push a JButton?

You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.

The System.exit(0) will terminates the currently running Java Virtual Machine.

Encoding conversion in java

I would just like to add that if the String is originally encoded using the wrong encoding it might be impossible to change it to another encoding without errors. The question does not state that the conversion here is made from wrong encoding to correct encoding but I personally stumbled to this question just because of this situation so just a heads up for others as well.

This answer in other question gives an explanation why the conversion does not always yield correct results https://stackoverflow.com/a/2623793/4702806

Adding Buttons To Google Sheets and Set value to Cells on clicking

You can insert an image that looks like a button. Then attach a script to the image.

  • INSERT menu
  • Image

Insert Image

You can insert any image. The image can be edited in the spreadsheet

Edit Image

Image of a Button

Image of Button

Assign a function name to an image:

Assign Function

How to view query error in PDO PHP

/* Provoke an error -- the BONES table does not exist */

$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);

output

Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)

How to check if cursor exists (open status)

You can use the CURSOR_STATUS function to determine its state.

IF CURSOR_STATUS('global','myCursor')>=-1
BEGIN
 DEALLOCATE myCursor
END

String concatenation with Groovy

def my_string = "some string"
println "here: " + my_string 

Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

How to launch PowerShell (not a script) from the command line

If you go to C:\Windows\system32\Windowspowershell\v1.0 (and C:\Windows\syswow64\Windowspowershell\v1.0 on x64 machines) in Windows Explorer and double-click powershell.exe you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe can be set independently from the default properties.

To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.

Running start powershell from cmd.exe should start a new console with your default settings.

EOL conversion in notepad ++

In Notepad++, use replace all with regular expression. This has advantage over conversion command in menu that you can operate on entire folder w/o having to open each file or drag n drop (on several hundred files it will noticeably become slower) plus you can also set filename wildcard filter.

(\r?\n)|(\r\n?)

to

\n

This will match every possible line ending pattern (single \r, \n or \r\n) back to \n. (Or \r\n if you are converting to windows-style)

To operate on multiple files, either:

  • Use "Replace All in all opened document" in "Replace" tab. You will have to drag and drop all files into Notepad++ first. It's good that you will have control over which file to operate on but can be slow if there several hundreds or thousands files.
  • "Replace in files" in "Find in files" tab, by file filter of you choice, e.g., *.cpp *.cs under one specified directory.

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

To address the question more generally...

Keep in mind that using synchronized on methods is really just shorthand (assume class is SomeClass):

synchronized static void foo() {
    ...
}

is the same as

static void foo() {
    synchronized(SomeClass.class) {
        ...
    }
}

and

synchronized void foo() {
    ...
}

is the same as

void foo() {
    synchronized(this) {
        ...
    }
}

You can use any object as the lock. If you want to lock subsets of static methods, you can

class SomeClass {
    private static final Object LOCK_1 = new Object() {};
    private static final Object LOCK_2 = new Object() {};
    static void foo() {
        synchronized(LOCK_1) {...}
    }
    static void fee() {
        synchronized(LOCK_1) {...}
    }
    static void fie() {
        synchronized(LOCK_2) {...}
    }
    static void fo() {
        synchronized(LOCK_2) {...}
    }
}

(for non-static methods, you would want to make the locks be non-static fields)

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()]

C/C++ switch case with string

Just use a if() { } else if () { } chain. Using a hash value is going to be a maintenance nightmare. switch is intended to be a low-level statement which would not be appropriate for string comparisons.

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

Save and load MemoryStream to/from a file

For anyone looking for the short versions:

var memoryStream = new MemoryStream(File.ReadAllBytes("1.dat"));

File.WriteAllBytes("1.dat", memoryStream.ToArray()); 

How to select data where a field has a min value in MySQL?

this will give you result that has the minimum price on all records.

SELECT *
FROM pieces
WHERE price =  ( SELECT MIN(price) FROM pieces )

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

In my case I did a wrong modification in the image.

I was able to find the problem checking the image shape.

print img.shape

Validating an XML against referenced XSD in C#

A simpler way, if you are using .NET 3.5, is to use XDocument and XmlSchemaSet validation.

XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);

XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
    msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);

See the MSDN documentation for more assistance.

Regex doesn't work in String.matches()

Used

String[] words = {"{apf","hum_","dkoe","12f"};
    for(String s:words)
    {
        if(s.matches("[a-z]+"))
        {
            System.out.println(s);
        }
    }

JAVA_HOME and PATH are set but java -version still shows the old one

When it searches for java it looks from left to right in path entries which are separated by : so you need to add the path of latest jdk/bin directory before /usr/bin, so when it searches it'll find the latest one and stop searching further.

i.e. PATH=/usr/java/jdk_1.8/bin:/usr/bin:..... and so on.

then initialize user profile using command: source ~/.bash_profile

and check with: [which java]

you'll get the right one.

Cannot create SSPI context

Perhaps you have used Integrated Security = SSPI in connection string. SSPI is used for Trusted connections using Windows Authentication.hence, to work properly in windows authentication, either your system and database server should be in same domain and using same DNS server address, or should be in trusted domain.

if your system and database server is in same domain, Check DNS server address of IPV4 properties in your system's network connection and provide same DNS server being used by database server.

rsync error: failed to set times on "/foo/bar": Operation not permitted

This happened to me on a partition of type xfs (rw,relatime,seclabel,attr2,inode64,noquota), where the directories where owned by another user in a group we were both members of. The group membership was already established before login, and the whole directory structure was group-writeable. I had manually run sudo chown -R otheruser.group directory and sudo chmod -R g+rw directory to confirm this.

I still have no idea why it didn't work originally, but taking ownership with sudo chown -R myuser.group directory fixed it. Perhaps SELinux-related?

Right click to select a row in a Datagridview and show a menu to delete it

It is work for me without any errors:

this.dataGridView2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown); 
this.dataGridView2.Click += new System.EventHandler(this.DeleteRow_Click);

And this

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        var hti = dataGridView2.HitTest(e.X, e.Y);
        dataGridView2.ClearSelection();
        dataGridView2.Rows[hti.RowIndex].Selected = true;
    }

}


private void DeleteRow_Click(object sender, EventArgs e)
{
    Int32 rowToDelete = dataGridView2.Rows.GetFirstRow(DataGridViewElementStates.Selected);
    if (rowToDelete == -1) { }
    else 
    {
        dataGridView2.Rows.RemoveAt(rowToDelete);
        dataGridView2.ClearSelection();
    }
}

Is it possible to opt-out of dark mode on iOS 13?

If you will add UIUserInterfaceStyle key to the plist file, possibly Apple will reject release build as mentioned here: https://stackoverflow.com/a/56546554/7524146 Anyway it's annoying to explicitly tell each ViewController self.overrideUserInterfaceStyle = .light. But you can use this peace of code once for your root window object:

if #available(iOS 13.0, *) {
    if window.responds(to: Selector(("overrideUserInterfaceStyle"))) {
        window.setValue(UIUserInterfaceStyle.light.rawValue, forKey: "overrideUserInterfaceStyle")
    }
}

Just notice you can't do this inside application(application: didFinishLaunchingWithOptions:) because for this selector will not respond true at that early stage. But you can do it later on. It's super easy if you are using custom AppPresenter or AppRouter class in your app instead of starting UI in the AppDelegate automatically.

Anaconda / Python: Change Anaconda Prompt User Path

In Windows, if you have the shortcut in your taskbar, right-click the "Anaconda Prompt" icon, you'll see:

  • Anaconda Prompt
  • Unpin from taskbar (if pinned)
  • Close window

Right-click on "Anaconda Prompt" again.

Click "Properties"

Add the path you want your anaconda prompt to open up into in the "Start In:" section.

Note - you can also do this by searching for "Anaconda Prompt" in the Start Menu. The directions above are specifically for the shortcut.

How can I convert an Integer to localized month name in Java?

There is an issue when you use DateFormatSymbols class for its getMonthName method to get Month by Name it show Month by Number in some Android devices. I have resolved this issue by doing this way:

In String_array.xml

<string-array name="year_month_name">
    <item>January</item>
    <item>February</item>
    <item>March</item>
    <item>April</item>
    <item>May</item>
    <item>June</item>
    <item>July</item>
    <item>August</item>
    <item>September</item>
    <item>October</item>
    <item>November</item>
    <item>December</item>
    </string-array>

In Java class just call this array like this way:

public String[] getYearMonthName() {
        return getResources().getStringArray(R.array.year_month_names);
        //or like 
       //return cntx.getResources().getStringArray(R.array.month_names);
    } 

      String[] months = getYearMonthName(); 
           if (i < months.length) {
            monthShow.setMonthName(months[i] + " " + year);

            }

Happy Coding :)

.mp4 file not playing in chrome

This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video  controls >
 <source src="sample.mp4" type="video/mp4">
 <track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>

the video and subtitle files are stored in the same folder as default.htm

I have the very latest version of Chrome (just updated this morning)

When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!

(note that if I input localhost.. to IE11 the video plays!!!!

In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.

This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4

How to get the current location in Google Maps Android API v2?

It will give the current location.

mMap.setMyLocationEnabled(true);
Location userLocation = mMap.getMyLocation();
        LatLng myLocation = null;
        if (userLocation != null) {
            myLocation = new LatLng(userLocation.getLatitude(),
                    userLocation.getLongitude());
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
                    mMap.getMaxZoomLevel()-5));

What is a lambda expression in C++11?

Answers

Q: What is a lambda expression in C++11?

A: Under the hood, it is the object of an autogenerated class with overloading operator() const. Such object is called closure and created by compiler. This 'closure' concept is near with the bind concept from C++11. But lambdas typically generate better code. And calls through closures allow full inlining.

Q: When would I use one?

A: To define "simple and small logic" and ask compiler perform generation from previous question. You give a compiler some expressions which you want to be inside operator(). All other stuff compiler will generate to you.

Q: What class of problem do they solve that wasn't possible prior to their introduction?

A: It is some kind of syntax sugar like operators overloading instead of functions for custom add, subrtact operations...But it save more lines of unneeded code to wrap 1-3 lines of real logic to some classes, and etc.! Some engineers think that if the number of lines is smaller then there is a less chance to make errors in it (I'm also think so)

Example of usage

auto x = [=](int arg1){printf("%i", arg1); };
void(*f)(int) = x;
f(1);
x(1);

Extras about lambdas, not covered by question. Ignore this section if you're not interest

1. Captured values. What you can to capture

1.1. You can reference to a variable with static storage duration in lambdas. They all are captured.

1.2. You can use lambda for capture values "by value". In such case captured vars will be copied to the function object (closure).

[captureVar1,captureVar2](int arg1){}

1.3. You can capture be reference. & -- in this context mean reference, not pointers.

   [&captureVar1,&captureVar2](int arg1){}

1.4. It exists notation to capture all non-static vars by value, or by reference

  [=](int arg1){} // capture all not-static vars by value

  [&](int arg1){} // capture all not-static vars by reference

1.5. It exists notation to capture all non-static vars by value, or by reference and specify smth. more. Examples: Capture all not-static vars by value, but by reference capture Param2

[=,&Param2](int arg1){} 

Capture all not-static vars by reference, but by value capture Param2

[&,Param2](int arg1){} 

2. Return type deduction

2.1. Lambda return type can be deduced if lambda is one expression. Or you can explicitly specify it.

[=](int arg1)->trailing_return_type{return trailing_return_type();}

If lambda has more then one expression, then return type must be specified via trailing return type. Also, similar syntax can be applied to auto functions and member-functions

3. Captured values. What you can not capture

3.1. You can capture only local vars, not member variable of the object.

4. ?onversions

4.1 !! Lambda is not a function pointer and it is not an anonymous function, but capture-less lambdas can be implicitly converted to a function pointer.

p.s.

  1. More about lambda grammar information can be found in Working draft for Programming Language C++ #337, 2012-01-16, 5.1.2. Lambda Expressions, p.88

  2. In C++14 the extra feature which has named as "init capture" have been added. It allow to perform arbitarily declaration of closure data members:

    auto toFloat = [](int value) { return float(value);};
    auto interpolate = [min = toFloat(0), max = toFloat(255)](int value)->float { return (value - min) / (max - min);};
    

Get current folder path

This block of code makes a path of your app directory in string type

string path="";
path=System.AppContext.BaseDirectory;

good luck

How does database indexing work?

Why is it needed?

When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously.

Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires N/2 block accesses (on average), where N is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at N block accesses.

Whereas with a sorted field, a Binary Search may be used, which has log2 N block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial.

What is indexing?

Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.

The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed.

How does it work?

Firstly, let’s outline a sample database table schema;

Field name       Data type      Size on disk
id (Primary key) Unsigned INT   4 bytes
firstName        Char(50)       50 bytes
lastName         Char(50)       50 bytes
emailAddress     Char(100)      100 bytes

Note: char was used in place of varchar to allow for an accurate size on disk value. This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the id (a sorted key field) and one using the firstName (a non-key unsorted field).

Example 1 - sorted vs unsorted fields

Given our sample database of r = 5,000,000 records of a fixed size giving a record length of R = 204 bytes and they are stored in a table using the MyISAM engine which is using the default block size B = 1,024 bytes. The blocking factor of the table would be bfr = (B/R) = 1024/204 = 5 records per disk block. The total number of blocks required to hold the table is N = (r/bfr) = 5000000/5 = 1,000,000 blocks.

A linear search on the id field would require an average of N/2 = 500,000 block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of log2 1000000 = 19.93 = 20 block accesses. Instantly we can see this is a drastic improvement.

Now the firstName field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact N = 1,000,000 block accesses. It is this situation that indexing aims to correct.

Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the firstName field is outlined below;

Field name       Data type      Size on disk
firstName        Char(50)       50 bytes
(record pointer) Special        4 bytes

Note: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table.

Example 2 - indexing

Given our sample database of r = 5,000,000 records with an index record length of R = 54 bytes and using the default block size B = 1,024 bytes. The blocking factor of the index would be bfr = (B/R) = 1024/54 = 18 records per disk block. The total number of blocks required to hold the index is N = (r/bfr) = 5000000/18 = 277,778 blocks.

Now a search using the firstName field can utilize the index to increase performance. This allows for a binary search of the index with an average of log2 277778 = 18.08 = 19 block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to 19 + 1 = 20 block accesses, a far cry from the 1,000,000 block accesses required to find a firstName match in the non-indexed table.

When should it be used?

Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index.

Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space.

How to use a parameter in ExecStart command line?

Although systemd indeed does not provide way to pass command-line arguments for unit files, there are possibilities to write instances: http://0pointer.de/blog/projects/instances.html

For example: /lib/systemd/system/[email protected] looks something like this:

[Unit]
Description=Serial Getty on %I
BindTo=dev-%i.device
After=dev-%i.device systemd-user-sessions.service

[Service]
ExecStart=-/sbin/agetty -s %I 115200,38400,9600
Restart=always
RestartSec=0

So, you may start it like:

$ systemctl start [email protected]
$ systemctl start [email protected]

For systemd it will different instances:

$ systemctl status [email protected]
[email protected] - Getty on ttyUSB0
      Loaded: loaded (/lib/systemd/system/[email protected]; static)
      Active: active (running) since Mon, 26 Sep 2011 04:20:44 +0200; 2s ago
    Main PID: 5443 (agetty)
      CGroup: name=systemd:/system/[email protected]/ttyUSB0
          + 5443 /sbin/agetty -s ttyUSB0 115200,38400,9600

It also mean great possibility enable and disable it separately.

Off course it lack much power of command line parsing, but in common way it is used as some sort of config files selection. For example you may look at Fedora [email protected]: http://pkgs.fedoraproject.org/cgit/openvpn.git/tree/[email protected]

What is the difference between Google App Engine and Google Compute Engine?

Google Compute Engine (GCE)

Virtual Machines (VMs) hosted in the cloud. Before the cloud, these were often called Virtual Private Servers (VPS). You'd use these the same way you'd use a physical server, where you install and configure the operating system, install your application, install the database, keep the OS up-to-date, etc. This is known as Infrastructure-as-a-Service (IaaS).

VMs are most useful when you have an existing application running on a VM or server in your datacenter, and want to easily migrate it to GCP.

Google App Engine

App Engine hosts and runs your code, without requiring you to deal with the operating system, networking, and many of the other things you'd have to manage with a physical server or VM. Think of it as a runtime, which can automatically deploy, version, and scale your application. This is called Platform-as-a-Service (PaaS).

App Engine is most useful when you want automated deployment and automated scaling of your application. Unless your application requires custom OS configuration, App Engine is often advantageous over configuring and managing VMs by hand.

List files in local git repo?

This command:

git ls-tree --full-tree -r --name-only HEAD

lists all of the already committed files being tracked by your git repo.

How to change the background-color of jumbrotron?

Just remove class full from <html> and add it to <body> tag. Then set style background-color:transparent !important; for the Jumbotron div (as Amit Joki said in his answer).

Convert a string into an int

Yet another way: if you are working with a C string, e.g. const char *, C native atoi() is more convenient.

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I was readying this solutions and this example may help.

My database have two tables (email and credit_card) with primary keys for their IDs. Another table (client) refers to this tables IDs as foreign keys. I have a reason to have the email apart from the client data.

First I insert the row data for the referenced tables (email, credit_card) then you get the ID for each, those IDs are needed in the third table (client).

If you don't insert first the rows in the referenced tables, MySQL wont be able to make the correspondences when you insert a new row in the third table that reference the foreign keys.

If you first insert the referenced rows for the referenced tables, then the row that refers to foreign keys, no error occurs.

Hope this helps.

What is the opposite of :hover (on mouse leave)?

Put your duration time in the non-hover selection:

li a {
  background-color: #111;
  transition:1s;
}

li a:hover {
  padding:19px;
}

Freeing up a TCP/IP port?

sudo killall -9 "process name"

How do I convert a string to a double in Python?

The decimal operator might be more in line with what you are looking for:

>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434

Creating temporary files in bash

You might want to look at mktemp

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of 'Xs' appended to it, for example /tmp/tfile.XXXXXXXXXX. The trailing 'Xs' are replaced with a combination of the current process number and random letters.

For more details: man mktemp

Matching an empty input box using CSS

If supporting legacy browsers is not needed, you could use a combination of required, valid, and invalid.

The good thing about using this is the valid and invalid pseudo-elements work well with the type attributes of input fields. For example:

_x000D_
_x000D_
input:invalid, textarea:invalid { _x000D_
    box-shadow: 0 0 5px #d45252;_x000D_
    border-color: #b03535_x000D_
}_x000D_
_x000D_
input:valid, textarea:valid {_x000D_
    box-shadow: 0 0 5px #5cd053;_x000D_
    border-color: #28921f;_x000D_
}
_x000D_
<input type="email" name="email" placeholder="[email protected]" required />_x000D_
<input type="url" name="website" placeholder="http://johndoe.com"/>_x000D_
<input type="text" name="name" placeholder="John Doe" required/>
_x000D_
_x000D_
_x000D_

For reference, JSFiddle here: http://jsfiddle.net/0sf6m46j/

Return None if Dictionary key is not available

Use dict.get

Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Relative div height

add this to you CSS:

html, body
{
    height: 100%;
}

working Fiddle

when you say to wrap to be 100%, 100% of what? of its parent (body), so his parent has to have some height.

and the same goes for body, his parent his html. html parent his the viewport.. so, by setting them both to 100%, wrap can also have a percentage height.

also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use

*
{
    padding: 0;
    margin: 0;
}

to disable that.

Look at That Fiddle

Where to find the win32api module for Python?

There is a a new option as well: get it via pip! There is a package pypiwin32 with wheels available, so you can just install with: pip install pypiwin32!

Edit: Per comment from @movermeyer, the main project now publishes wheels at pywin32, and so can be installed with pip install pywin32

Calling JMX MBean method from a shell script

Potentially its easiest to write this in Java

import javax.management.*;
import javax.management.remote.*;

public class JmxInvoke {

    public static void main(String... args) throws Exception {
        JMXConnectorFactory.connect(new JMXServiceURL(args[0]))
            .getMBeanServerConnection().invoke(new ObjectName(args[1]), args[2], new Object[]{}, new String[]{});    
    }

}

This would compile to a single .class and needs no dependencies in server or any complicated maven packaging.

call it with

javac JmxInvoke.java
java -cp . JmxInvoke [url] [beanName] [method]

Select SQL results grouped by weeks

the provided solutions seem a little complex? this might help:

https://msdn.microsoft.com/en-us/library/ms174420.aspx

select
   mystuff,
   DATEPART ( year, MyDateColumn ) as yearnr,
   DATEPART ( week, MyDateColumn ) as weeknr
from mytable
group by ...etc

JSON serialization/deserialization in ASP.Net Core

.net core

using System.Text.Json;

To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft side

Assert that a WebElement is not present using Selenium WebDriver with java

For appium 1.6.0 and above

    WebElement button = (new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//XCUIElementTypeButton[@name='your button']"))));
    button.click();

    Assert.assertTrue(!button.isDisplayed());

Environment variables for java installation

  1. Download the JDK
  2. Install it
  3. Then Setup environment variables like this :
  4. Click on EDIT

enter image description here

  1. Then click PATH, Click Add , Then Add it like this: enter image description here

String in function parameter

char *arr; above statement implies that arr is a character pointer and it can point to either one character or strings of character

& char arr[]; above statement implies that arr is strings of character and can store as many characters as possible or even one but will always count on '\0' character hence making it a string ( e.g. char arr[]= "a" is similar to char arr[]={'a','\0'} )

But when used as parameters in called function, the string passed is stored character by character in formal arguments making no difference.

Java: How To Call Non Static Method From Main Method?

Since you want to call a non-static method from main, you just need to create an object of that class consisting non-static method and then you will be able to call the method using objectname.methodname(); But if you write the method as static then you won't need to create object and you will be able to call the method using methodname(); from main. And this will be more efficient as it will take less memory than the object created without static method.

Efficiently getting all divisors of a given number

Factors are paired. 1 and 24, 2 and 12, 3 and 8, 4 and 6.

An improvement of your algorithm could be to iterate to the square root of num instead of all the way to num, and then calculate the paired factors using num / i.

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');

Subtracting two lists in Python

Here's a relatively long but efficient and readable solution. It's O(n).

def list_diff(list1, list2):
    counts = {}
    for x in list1:
        try:
            counts[x] += 1
        except:
            counts[x] = 1
    for x in list2:
        try:
            counts[x] -= 1
            if counts[x] < 0:
                raise ValueError('All elements of list2 not in list2')
        except:
            raise ValueError('All elements of list2 not in list1') 
    result = []
    for k, v in counts.iteritems():
        result += v*[k] 
    return result

a = [0, 1, 1, 2, 0]
b = [0, 1, 1]
%timeit list_diff(a, b)
%timeit list_diff(1000*a, 1000*b)
%timeit list_diff(1000000*a, 1000000*b)
100000 loops, best of 3: 4.8 µs per loop
1000 loops, best of 3: 1.18 ms per loop
1 loops, best of 3: 1.21 s per loop

ExecutorService, how to wait for all tasks to finish

I will just wait for the executor to terminate with a specified timeout that you think it is suitable for the tasks to complete.

 try {  
         //do stuff here 
         exe.execute(thread);
    } finally {
        exe.shutdown();
    }
    boolean result = exe.awaitTermination(4, TimeUnit.HOURS);
    if (!result)

    {
        LOGGER.error("It took more than 4 hour for the executor to stop, this shouldn't be the normal behaviour.");
    }

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

C++ multiline string literal

Just to elucidate a bit on @emsr's comment in @unwind's answer, if one is not fortunate enough to have a C++11 compiler (say GCC 4.2.1), and one wants to embed the newlines in the string (either char * or class string), one can write something like this:

const char *text =
  "This text is pretty long, but will be\n"
  "concatenated into just a single string.\n"
  "The disadvantage is that you have to quote\n"
  "each part, and newlines must be literal as\n"
  "usual.";

Very obvious, true, but @emsr's short comment didn't jump out at me when I read this the first time, so I had to discover this for myself. Hopefully, I've saved someone else a few minutes.

Start and stop a timer PHP

For your purpose, this simple class should be all you need:

class Timer {
    private $time = null;
    public function __construct() {
        $this->time = time();
        echo 'Working - please wait..<br/>';
    }

    public function __destruct() {
        echo '<br/>Job finished in '.(time()-$this->time).' seconds.';
    }
}


$t = new Timer(); // echoes "Working, please wait.."

[some operations]

unset($t);  // echoes "Job finished in n seconds." n = seconds elapsed

Set focus on textbox in WPF

try FocusManager.SetFocusedElement

FocusManager.SetFocusedElement(parentElement, txtCompanyID)

Rotating and spacing axis labels in ggplot2

To make the text on the tick labels fully visible and read in the same direction as the y-axis label, change the last line to

q + theme(axis.text.x=element_text(angle=90, hjust=1))

Getting the last revision number in SVN?

If you want to analyse a local working copy, the best tool is svnversion, which comes with Subversion and produces output like 968:1000M. The documentation says:

The version number will be a single number if the working copy is single revision, unmodified, not switched and with an URL that matches the TRAIL_URL argument. If the working copy is unusual the version number will be more complex:

4123:4168     mixed revision working copy
4168M         modified working copy
4123S         switched working copy
4123:4168MS   mixed revision, modified, switched working copy

How to read XML using XPath in Java

Here is an example of processing xpath with vtd-xml... for heavy duty XML processing it is second to none. here is the a recent paper on this subject Processing XML with Java – A Performance Benchmark

import com.ximpleware.*;

public class changeAttrVal {
    public  static  void main(String s[]) throws VTDException,java.io.UnsupportedEncodingException,java.io.IOException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        XMLModifier xm = new XMLModifier(vn);
        ap.selectXPath("/*/place[@id=\"p14\" and   @initialMarking=\"2\"]/@initialMarking");
        int i=0;
        while((i=ap.evalXPath())!=-1){
            xm.updateToken(i+1, "499");// change initial marking from 2 to 499
        }
        xm.output("new.xml");
    }

}

File path issues in R using Windows ("Hex digits in character string" error)

A simple way is to use python. in python terminal type

r"C:\Users\surfcat\Desktop\2006_dissimilarity.csv" and you'll get back 'C:\Users\surfcat\Desktop\2006_dissimilarity.csv'

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.

How to map calculated properties with JPA and Hibernate

Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.

Here is an example mapping

@EntityView(Order.class)
interface OrderSummary {
  Integer getId();
  @Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
  BigDecimal getOrderAmount();
  @Mapping("COUNT(orderPositions)")
  Long getItemCount();
}

Fetching this will generate a JPQL/HQL query similar to this

SELECT
  o.id,
  SUM(p.price * p.amount * p.tax),
  COUNT(p.id)
FROM
  Order o
LEFT JOIN
  o.orderPositions p
GROUP BY
  o.id

Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html

What does the @ symbol before a variable name mean in C#?

It allows you to use a C# keyword as a variable. For example:

class MyClass
{
   public string name { get; set; }
   public string @class { get; set; }
}

Get day of week in SQL Server 2005/2008

You can use DATEPART(dw, GETDATE()) but be aware that the result will rely on SQL server setting @@DATEFIRST value which is the first day of week setting (In Europe default value 7 which is Sunday).

If you want to change the first day of week to another value, you could use SET DATEFIRST but this may affect everywhere in your query session which you do not want.

Alternative way is to explicitly specify the first day of week value as parameter and avoid depending on @@DATEFIRST setting. You can use the following formula to achieve that when need it:

(DATEPART(dw, GETDATE()) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1

where @WeekStartDay is the first day of the week you want for your system (from 1 to 7 which means from Monday to Sunday).

I have wrapped it into below function so we can reuse it easily:

CREATE FUNCTION [dbo].[GetDayInWeek](@InputDateTime DATETIME, @WeekStartDay INT)
RETURNS INT
AS
BEGIN
    --Note: @WeekStartDay is number from [1 - 7] which is from Monday to Sunday
    RETURN (DATEPART(dw, @InputDateTime) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1 
END

Example usage: GetDayInWeek('2019-02-04 00:00:00', 1)

It is equivalent to following (but independent to SQL server DATEFIRST setting):

SET DATEFIRST 1
DATEPART(dw, '2019-02-04 00:00:00')

How to Write text file Java

It's not creating a file because you never actually created the file. You made an object for it. Creating an instance doesn't create the file.

File newFile = new File("directory", "fileName.txt");

You can do this to make a file:

newFile.createNewFile();

You can do this to make a folder:

newFile.mkdir();

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

The error message means that any method that calls showfile() must either declare that it, in turn, throws IOException, or the call must be inside a try block that catches IOException. When you call showfile(), you do neither of these; for example, your filecontent constructor neither declares IOException nor contains a try block.

The intent is that some method, somewhere, should contain a try block, and catch and handle this exception. The compiler is trying to force you to handle the exception somewhere.

By the way, this code is (sorry to be so blunt) horrible. You don't close any of the files you open, the BufferedReader always points to the first file, even though you seem to be trying to make it point to another, the loops contain off-by-one errors that will cause various exceptions, etc. When you do get this to compile, it will not work as you expect. I think you need to slow down a little.

'Class' does not contain a definition for 'Method'

I had the same problem. I changed the Version of Assembly in AssemblyInfo.cs in the Properties Folder. But, I don't have any idea why this problem happened. Maybe the compiler doesn't understand that this dll is newer, just changing the version of Assembly.

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

Best way to convert list to comma separated string in java

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here

CAST DECIMAL to INT

You could try the FLOOR function like this:

SELECT FLOOR(columnName), moreColumns, etc 
FROM myTable 
WHERE ... 

You could also try the FORMAT function, provided you know the decimal places can be omitted:

SELECT FORMAT(columnName,0), moreColumns, etc 
FROM myTable 
WHERE ... 

You could combine the two functions

SELECT FORMAT(FLOOR(columnName),0), moreColumns, etc 
FROM myTable 
WHERE ... 

Store mysql query output into a shell variable

A more direct way would be:

myvar=$(mysql mydatabase -u $user -p$password -se "SELECT a, b, c FROM table_a")

Changing MongoDB data store directory

Create a file called mongod.cfg in MongoDB folder if you dont have it. In my case: C:\Users\ivanbtrujillo\MongoDB

Then, edit mongod.cfg with notepad and add a line with the following (our custom dbpath):

dbpath=C:\Users\ivanbtrujillo\MongoDB\data\db

In this file you should especify the logpath too. My mongod.cfg file is:

logpath=C:\Users\ivanbtrujillo\MongoDB\log\mongo.log
dbpath=C:\Users\ivanbtrujillo\MongoDB\data\db

If you uses mongoDB as a windows service, you have to change this key and especify the mongod.cfg file.

To install mongodb as a windows service run this command:

**"C:\Users\ivanbtrujillo\MongoDB\bin\mongod.exe" --config "C:\Users\ivanbtrujillo\MongoDB\mongod.cfg" –install**

Open regedit.exe and go to the following route:

HKEYLOCALMACHINE\SYSTEM\CurrentControlSet\services\MongoDB

MongoDB service does not work, we have to edit the ImagePath key, delete its content and put the following:

**"C:\Users\ivanbtrujillo\MongoDB\bin\mongod.exe" --config "C:\Users\ivanbtrujillo\MongoDB\mongod.cfg" 
--logpath="C:\Users\ivanbtrujillo\MongoDB\log\mongo.log" –service**

We indicates to mongo it's config file and its logpath.

Then when you init the mongodb service, it works.

Here is a full tutorial to install mongoDB in windows: http://ivanbtrujillo.herokuapp.com/2014/07/24/installing-mongodb-as-a-service-windows/

Hope it helps,

Install a Python package into a different directory using pip?

Newer versions of pip (8 or later) can directly use the --prefix option:

pip install --prefix=$PREFIX_PATH package_name

where $PREFIX_PATH is the installation prefix where lib, bin and other top-level folders are placed.

Backbone.js fetch with parameters

changing:

collection.fetch({ data: { page: 1} });

to:

collection.fetch({ data: $.param({ page: 1}) });

So with out over doing it, this is called with your {data: {page:1}} object as options

Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default JSON-request options.
    var params = _.extend({
      type:         type,
      dataType:     'json',
      processData:  false
    }, options);

    // Ensure that we have a URL.
    if (!params.url) {
      params.url = getUrl(model) || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (!params.data && model && (method == 'create' || method == 'update')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(model.toJSON());
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (Backbone.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.processData = true;
      params.data        = params.data ? {model : params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (Backbone.emulateHTTP) {
      if (type === 'PUT' || type === 'DELETE') {
        if (Backbone.emulateJSON) params.data._method = type;
        params.type = 'POST';
        params.beforeSend = function(xhr) {
          xhr.setRequestHeader('X-HTTP-Method-Override', type);
        };
      }
    }

    // Make the request.
    return $.ajax(params);
};

So it sends the 'data' to jQuery.ajax which will do its best to append whatever params.data is to the URL.

C# "No suitable method found to override." -- but there is one

You're not inheriting from your base class:

public class Ext : Base {
    // constructor

    public override void Draw()
    {
    }
}

Are there dictionaries in php?

http://php.net/manual/en/language.types.array.php

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

Standard arrays can be used that way.

XAMPP - Error: MySQL shutdown unexpectedly

If your skype is open, Quit skype and try,

or

Go to your xampp/wamp installed, search for httpd.conf. Open that file using textpad/notepad, search for Listen or 80 , update listen port to 8081 and save the file. Restart xampp/wamp, start the servers.


or
follow below steps in skype enter image description here

Swap x and y axis without manually swapping values

  1. Click somewhere on the chart to select it.

  2. You should now see 3 new tabs appear at the top of the screen called "Design", "Layout" and "Format".

  3. Click on the "Design" tab.

  4. There will be a button called "Switch Row/Column" within the "data" group, click it.

How can I delete all Git branches which have been merged?

Based on some of these answers I made my own Bash script to do it too!

It uses git branch --merged and git branch -d to delete the branches that have been merged and prompts you for each of the branches before deleting.

merged_branches(){
  local current_branch=$(git rev-parse --abbrev-ref HEAD)
  for branch in $(git branch --merged | cut -c3-)
    do
      echo "Branch $branch is already merged into $current_branch."
      echo "Would you like to delete it? [Y]es/[N]o "
      read REPLY
      if [[ $REPLY =~ ^[Yy] ]]; then
        git branch -d $branch
      fi
  done
}

Calculate mean and standard deviation from a vector of samples in C++ using Boost

It seems the following elegant recursive solution has not been mentioned, although it has been around for a long time. Referring to Knuth's Art of Computer Programming,

mean_1 = x_1, variance_1 = 0;            //initial conditions; edge case;

//for k >= 2, 
mean_k     = mean_k-1 + (x_k - mean_k-1) / k;
variance_k = variance_k-1 + (x_k - mean_k-1) * (x_k - mean_k);

then for a list of n>=2 values, the estimate of the standard deviation is:

stddev = std::sqrt(variance_n / (n-1)). 

Hope this helps!

File to byte[] in Java

Basically you have to read it in memory. Open the file, allocate the array, and read the contents from the file into the array.

The simplest way is something similar to this:

public byte[] read(File file) throws IOException, FileTooBigException {
    if (file.length() > MAX_FILE_SIZE) {
        throw new FileTooBigException(file);
    }
    ByteArrayOutputStream ous = null;
    InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1) {
            ous.write(buffer, 0, read);
        }
    }finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
        }

        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }
    return ous.toByteArray();
}

This has some unnecessary copying of the file content (actually the data is copied three times: from file to buffer, from buffer to ByteArrayOutputStream, from ByteArrayOutputStream to the actual resulting array).

You also need to make sure you read in memory only files up to a certain size (this is usually application dependent) :-).

You also need to treat the IOException outside the function.

Another way is this:

public byte[] read(File file) throws IOException, FileTooBigException {
    if (file.length() > MAX_FILE_SIZE) {
        throw new FileTooBigException(file);
    }

    byte[] buffer = new byte[(int) file.length()];
    InputStream ios = null;
    try {
        ios = new FileInputStream(file);
        if (ios.read(buffer) == -1) {
            throw new IOException(
                    "EOF reached while trying to read the whole file");
        }
    } finally {
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }
    return buffer;
}

This has no unnecessary copying.

FileTooBigException is a custom application exception. The MAX_FILE_SIZE constant is an application parameters.

For big files you should probably think a stream processing algorithm or use memory mapping (see java.nio).

Convert a object into JSON in REST service by Spring MVC

You can always add the @Produces("application/json") above your web method or specify produces="application/json" to return json. Then on top of the Student class you can add @XmlRootElement from javax.xml.bind.annotation package.

Please note, it might not be a good idea to directly return model classes. Just a suggestion.

HTH.

How to delete files/subfolders in a specific directory at the command prompt in Windows

None of the answers as posted on 2018-06-01, with the exception of the single command line posted by foxidrive, really deletes all files and all folders/directories in %PathToFolder%. That's the reason for posting one more answer with a very simple single command line to delete all files and subfolders of a folder as well as a batch file with a more complex solution explaining why all other answers as posted on 2018-06-01 using DEL and FOR with RD failed to clean up a folder completely.


The simple single command line solution which of course can be also used in a batch file:

pushd "%PathToFolder%" 2>nul && ( rd /Q /S "%PathToFolder%" 2>nul & popd )

This command line contains three commands executed one after the other.

The first command PUSHD pushes current directory path on stack and next makes %PathToFolder% the current directory for running command process.

This works also for UNC paths by default because of command extensions are enabled by default and in this case PUSHD creates a temporary drive letter that points to that specified network resource and then changes the current drive and directory, using the newly defined drive letter.

PUSHD outputs following error message to handle STDERR if the specified directory does not exist at all:

The system cannot find the path specified.

This error message is suppressed by redirecting it with 2>nul to device NUL.

The next command RD is executed only if changing current directory for current command process to specified directory was successful, i.e. the specified directory exists at all.

The command RD with the options /Q and /S removes a directory quietly with all subdirectories even if the specified directory contains files or folders with hidden attribute or with read-only attribute set. The system attribute does never prevent deletion of a file or folder.

Not deleted are:

  1. Folders used as the current directory for any running process. The entire folder tree to such a folder cannot be deleted if a folder is used as the current directory for any running process.

  2. Files currently opened by any running process with file access permissions set on file open to prevent deletion of the file while opened by the running application/process. Such an opened file prevents also the deletion of entire folder tree to the opened file.

  3. Files/folders on which the current user has not the required (NTFS) permissions to delete the file/folder which prevents also the deletion of the folder tree to this file/folder.

The first reason for not deleting a folder is used by this command line to delete all files and subfolders of the specified folder, but not the folder itself. The folder is made temporarily the current directory for running command process which prevents the deletion of the folder itself. Of course this results in output of an error message by command RD:

The process cannot access the file because it is being used by another process.

File is the wrong term here as in reality the folder is being used by another process, the current command process which executed command RD. Well, in reality a folder is for the file system a special file with file attribute directory which explains this error message. But I don't want to go too deep into file system management.

This error message, like all other error messages, which could occur because of the three reasons written above, is suppressed by redirecting it with 2>nul from handle STDERR to device NUL.

The third command, POPD, is executed independently of the exit value of command RD.

POPD pops the directory path pushed by PUSHD from the stack and changes the current directory for running the command process to this directory, i.e. restores the initial current directory. POPD deletes the temporary drive letter created by PUSHD in case of a UNC folder path.

Note: POPD can silently fail to restore the initial current directory in case of the initial current directory was a subdirectory of the directory to clean which does not exist anymore. In this special case %PathToFolder% remains the current directory. So it is advisable to run the command line above not from a subdirectory of %PathToFolder%.

One more interesting fact: I tried the command line also using a UNC path by sharing local directory C:\Temp with share name Temp and using UNC path \\%COMPUTERNAME%\Temp\CleanTest assigned to environment variable PathToFolder on Windows 7. If the current directory on running the command line is a subdirectory of a shared local folder accessed using UNC path, i.e. C:\Temp\CleanTest\Subfolder1, Subfolder1 is deleted by RD, and next POPD fails silently in making C:\Temp\CleanTest\Subfolder1 again the current directory resulting in Z:\CleanTest remaining as the current directory for the running command process. So in this very, very special case the temporary drive letter remains until the current directory is changed for example with cd /D %SystemRoot% to a local directory really existing. Unfortunately POPD does not exit with a value greater 0 if it fails to restore the initial current directory making it impossible to detect this very special error condition using just the exit code of POPD. However, it can be supposed that nobody ever runs into this very special error case as UNC paths are usually not used for accessing local files and folders.

For understanding the used commands even better, open a command prompt window, execute there the following commands, and read the help displayed for each command very carefully.

  • pushd /?
  • popd /?
  • rd /?

Single line with multiple commands using Windows batch file explains the operators && and & used here.


Next let us look on the batch file solution using the command DEL to delete files in %PathToFolder% and FOR and RD to delete the subfolders in %PathToFolder%.

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Clean the folder for temporary files if environment variable
rem PathToFolder is not defined already outside this batch file.
if not defined PathToFolder set "PathToFolder=%TEMP%"

rem Remove all double quotes from folder path.
set "PathToFolder=%PathToFolder:"=%"

rem Did the folder path consist only of double quotes?
if not defined PathToFolder goto EndCleanFolder

rem Remove a backslash at end of folder path.
if "%PathToFolder:~-1%" == "\" set "PathToFolder=%PathToFolder:~0,-1%"

rem Did the folder path consist only of a backslash (with one or more double quotes)?
if not defined PathToFolder goto EndCleanFolder

rem Delete all files in specified folder including files with hidden
rem or read-only attribute set, except the files currently opened by
rem a running process which prevents deletion of the file while being
rem opened by the application, or on which the current user has not
rem the required permissions to delete the file.
del /A /F /Q "%PathToFolder%\*" >nul 2>nul

rem Delete all subfolders in specified folder including those with hidden
rem attribute set recursive with all files and subfolders, except folders
rem being the current directory of any running process which prevents the
rem deletion of the folder and all folders above, folders containing a file
rem opened by the application which prevents deletion of the file and the
rem entire folder structure to this file, or on which the current user has
rem not the required permissions to delete a folder or file in folder tree
rem to delete.
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul

:EndCleanFolder
endlocal

The batch file first makes sure that environment variable PathToFolder is really defined with a folder path without double quotes and without a backslash at the end. The backslash at the end would not be a problem, but double quotes in a folder path could be problematic because of the value of PathToFolder is concatenated with other strings during batch file execution.

Important are the two lines:

del /A /F /Q "%PathToFolder%\*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul

The command DEL is used to delete all files in the specified directory.

  • The option /A is necessary to process really all files including files with the hidden attribute which DEL would ignore without using option /A.
  • The option /F is necessary to force deletion of files with the read-only attribute set.
  • The option /Q is necessary to run a quiet deletion of multiple files without prompting the user if multiple files should be really deleted.
  • >nul is necessary to redirect the output of the file names written to handle STDOUT to device NUL of which can't be deleted because of a file is currently opened or user has no permission to delete the file.
  • 2>nul is necessary to redirect the error message output for each file which can't be deleted from handle STDERR to device NUL.

The commands FOR and RD are used to remove all subdirectories in specified directory. But for /D is not used because of FOR is ignoring in this case subdirectories with the hidden attribute set. For that reason for /F is used to run the following command line in a separate command process started in the background with %ComSpec% /c:

dir "%PathToFolder%\*" /AD /B 2>nul

DIR outputs in bare format because of /B the directory entries with attribute D, i.e. the names of all subdirectories in specified directory independent on other attributes like the hidden attribute without a path. 2>nul is used to redirect the error message output by DIR on no directory found from handle STDERR to device NUL.

The redirection operator > must be escaped with the caret character, ^, on the FOR command line to be interpreted as a literal character when the Windows command interpreter processes this command line before executing the command FOR which executes the embedded dir command line in a separate command process started in the background.

FOR processes the captured output written to handle STDOUT of a started command process which are the names of the subdirectories without path and never enclosed in double quotes.

FOR with option /F ignores empty lines which don't occur here as DIR with option /B does not output empty lines.

FOR would also ignore lines starting with a semicolon which is the default end of line character. A directory name can start with a semicolon. For that reason eol=| is used to define the vertical bar character as the end-of-line character which no directory or file can have in its name.

FOR would split up the line into substrings using space and horizontal tab as delimiters and would assign only the first space/tab delimited string to specified loop variable I. This splitting behavior is not wanted here because of a directory name can contain one or more spaces. Therefore delims= is used to define an empty list of delimiters to disable the line splitting behavior and get assigned to the loop variable, I, always the complete directory name.

Command FOR runs the command RD for each directory name without a path which is the reason why on the RD command line the folder path must be specified once again which is concatenated with the subfolder name.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • del /?
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rd /?
  • rem /?
  • set /?
  • setlocal /?

"SSL certificate verify failed" using pip to install packages

It seems that Scrapy fails because installing Twisted fails, which fails because incremental fails. Running pip install --upgrade pip && pip install --upgrade incremental fixed this for me.

Cannot implicitly convert type 'int' to 'short'

Adding two Int16 values result in an Int32 value. You will have to cast it to Int16:

Int16 answer = (Int16) (firstNo + secondNo);

You can avoid this problem by switching all your numbers to Int32.

jQuery remove special characters from string and more

Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:

str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');

The problem is that first code removes all the hyphens and then tries to replace them :) You should reverse the replace calls and also add hyphen to second replace regex. Like this:

str.replace(/[_\s]/g, '-').replace(/[^a-z0-9-\s]/gi, '');

Requested registry access is not allowed

If you don't need admin privs for the entire app, or only for a few infrequent changes you can do the changes in a new process and launch it using:

Process.StartInfo.UseShellExecute = true;
Process.StartInfo.Verb = "runas";

which will run the process as admin to do whatever you need with the registry, but return to your app with the normal priviledges. This way it doesn't prompt the user with a UAC dialog every time it launches.

What languages are Windows, Mac OS X and Linux written in?

  • windows: C++
  • linux: C
  • mac: Objective C
  • android: JAVA, C, C++
  • Solaris: C, C++
  • iOS 7: Objective-C,Swift,C, C++

How do I toggle an ng-show in AngularJS based on a boolean?

If based on click here it is:

ng-click="orderReverse = orderReverse ? false : true"

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

How do I get the localhost name in PowerShell?

You can just use the .NET Framework method:

[System.Net.Dns]::GetHostName()

also

$env:COMPUTERNAME

client denied by server configuration

For me the following worked which is copied from example in /etc/apache2/apache2.conf:

<Directory /srv/www/default>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Require all granted option is the solution for the first problem example in wiki.apache.org page dedicated for this issue for Apache version 2.4+.

More details about Require option can be found on official apache page for mod_authz module and on this page too. Namely:

Require all granted -> Access is allowed unconditionally.

Setting focus on an HTML input box on page load

This line:

<input type="password" name="PasswordInput"/>

should have an id attribute, like so:

<input type="password" name="PasswordInput" id="PasswordInput"/>

Use chrome as browser in C#?

OpenWebKitSharp gives you full control over WebKit Nightly, which is very close to webkit in terms of performance and compatibility. Chrome uses WebKit Chromium engine, while WebKit.NET uses Cairo and OpenWebKitSharp Nightly. Chromium should be the best of these builds, while at 2nd place should come Nightly and that's why I suggest OpenWebKitSharp.

http://gt-web-software.webs.com/libraries.htm at the OpenWebKitSharp section

How to set default vim colorscheme

Ubuntu 17.10 default doesn't have the ~/.vimrc file, we need create it and put the setting colorscheme color_scheme_name in it.

By the way, colorscheme desert is good scheme to choose.

In PHP, what is a closure and why does it use the "use" identifier?

Zupa did a great job explaining closures with 'use' and the difference between EarlyBinding and Referencing the variables that are 'used'.

So I made a code example with early binding of a variable (= copying):

<?php

$a = 1;
$b = 2;

$closureExampleEarlyBinding = function() use ($a, $b){
    $a++;
    $b++;
    echo "Inside \$closureExampleEarlyBinding() \$a = ".$a."<br />";
    echo "Inside \$closureExampleEarlyBinding() \$b = ".$b."<br />";    
};

echo "Before executing \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "Before executing \$closureExampleEarlyBinding() \$b = ".$b."<br />";  

$closureExampleEarlyBinding();

echo "After executing \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "After executing \$closureExampleEarlyBinding() \$b = ".$b."<br />";

/* this will output:
Before executing $closureExampleEarlyBinding() $a = 1
Before executing $closureExampleEarlyBinding() $b = 2
Inside $closureExampleEarlyBinding() $a = 2
Inside $closureExampleEarlyBinding() $b = 3
After executing $closureExampleEarlyBinding() $a = 1
After executing $closureExampleEarlyBinding() $b = 2
*/

?>

Example with referencing a variable (notice the '&' character before variable);

<?php

$a = 1;
$b = 2;

$closureExampleReferencing = function() use (&$a, &$b){
    $a++;
    $b++;
    echo "Inside \$closureExampleReferencing() \$a = ".$a."<br />";
    echo "Inside \$closureExampleReferencing() \$b = ".$b."<br />"; 
};

echo "Before executing \$closureExampleReferencing() \$a = ".$a."<br />";
echo "Before executing \$closureExampleReferencing() \$b = ".$b."<br />";   

$closureExampleReferencing();

echo "After executing \$closureExampleReferencing() \$a = ".$a."<br />";
echo "After executing \$closureExampleReferencing() \$b = ".$b."<br />";    

/* this will output:
Before executing $closureExampleReferencing() $a = 1
Before executing $closureExampleReferencing() $b = 2
Inside $closureExampleReferencing() $a = 2
Inside $closureExampleReferencing() $b = 3
After executing $closureExampleReferencing() $a = 2
After executing $closureExampleReferencing() $b = 3
*/

?>

How to convert string to Title Case in Python?

Why not write one? Something like this may satisfy your requirements:

def FixCase(st):
    return ' '.join(''.join([w[0].upper(), w[1:].lower()]) for w in st.split())

substring index range

For substring(startIndex, endIndex), startIndex is inclusive and endIndex are exclusive. The startIndex and endIndex are very confusing. I would understand substring(startIndex, length) to remember that.

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

All other answers may answer your query, but I faced same issue which was due to stray , which I added at the end of my json string like this:

{
 "key":"123sdf",
 "bus_number":"asd234sdf",
}

I finally got it working when I removed extra , like this:

{
 "key":"123sdf",
 "bus_number":"asd234sdf"
}

Hope this help! cheers.

How to implement a custom AlertDialog View

The simplest lines of code that works for me are are follows:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.layout_resource_id);
builder.show();

Whatever the type of layout(LinearLayout, FrameLayout, RelativeLayout) will work by setView and will just differ in the appearance and behavior.

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

The best way is to check the contects of the text box whenever it loses focus.

You can check whether the contents are a "number" using a regular expression.

Or you can use the Validation plugin, which basically does this automatically.

Check OS version in Swift?

Swift 5

func run() {
    let version = OperatingSystemVersion(majorVersion: 13, minorVersion: 0, patchVersion: 0)
    if ProcessInfo.processInfo.isOperatingSystemAtLeast(version) {
        runNewCode()
    } else {
        runLegacyCode()
    }
}

func runNewCode() {
    guard #available(iOS 13.0, *) else {
        fatalError()
    }
    // do new stuff
}

func runLegacyCode() {
    // do old stuff
}

How to make script execution wait until jquery is loaded

It's a common issue, imagine you use a cool PHP templating engine, so you have your base layout:

HEADER
BODY ==> dynamic CONTENT/PAGE
FOOTER

And of course, you read somewhere it's better to load Javascript at the bottom of the page, so your dynamic content doesnot know who is jQuery (or the $).

Also you read somewhere it's good to inline small Javascript, so imagine you need jQuery in a page, baboom, $ is not defined (.. yet ^^).

I love the solution Facebook provides

window.fbAsyncInit = function() { alert('FB is ready !'); }

So as a lazy programmer (I should say a good programmer ^^), you can use an equivalent (within your page):

window.jqReady = function() {}

And add at the bottom of your layout, after jQuery include

if (window.hasOwnProperty('jqReady')) $(function() {window.jqReady();});

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Bootstrap 4 (^beta) has changed the classes for responsive hiding/showing elements. See this link for correct classes to use: http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

can't multiply sequence by non-int of type 'float'

for i in growthRates:  
    fund = fund * (1 + 0.01 * growthRates) + depositPerYear

should be:

for i in growthRates:  
    fund = fund * (1 + 0.01 * i) + depositPerYear

You are multiplying 0.01 with the growthRates list object. Multiplying a list by an integer is valid (it's overloaded syntactic sugar that allows you to create an extended a list with copies of its element references).

Example:

>>> 2 * [1,2]
[1, 2, 1, 2]

Extracting extension from filename in Python

For funsies... just collect the extensions in a dict, and track all of them in a folder. Then just pull the extensions you want.

import os

search = {}

for f in os.listdir(os.getcwd()):
    fn, fe = os.path.splitext(f)
    try:
        search[fe].append(f)
    except:
        search[fe]=[f,]

extensions = ('.png','.jpg')
for ex in extensions:
    found = search.get(ex,'')
    if found:
        print(found)

JavaScript Chart Library

If you're using jQuery I've found flot to be very good - try out the examples to see if they suit your needs, but I've found them to do most of what I need for my current project.

Additionally ExtJS 4.0 has introduced a great set of charts - very powerful, and is designed to work with live data.

Object of class stdClass could not be converted to string - laravel

Try this simple in one line of code:-

$data= json_decode( json_encode($data), true);

Hope it helps :)

HTML button opening link in new tab

This worked for me.

onClick={() => {window.open('https://www.google.com/');}}

React: why child component doesn't update when prop changes

When create React components from functions and useState.

const [drawerState, setDrawerState] = useState(false);

const toggleDrawer = () => {
      // attempting to trigger re-render
      setDrawerState(!drawerState);
};

This does not work

         <Drawer
            drawerState={drawerState}
            toggleDrawer={toggleDrawer}
         />

This does work (adding key)

         <Drawer
            drawerState={drawerState}
            key={drawerState}
            toggleDrawer={toggleDrawer}
         />

Trim whitespace from a String

In addition to answer of @gjha:

inline std::string ltrim_copy(const std::string& str)
{
    auto it = std::find_if(str.cbegin(), str.cend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return std::string(it, str.cend());
}

inline std::string rtrim_copy(const std::string& str)
{
    auto it = std::find_if(str.crbegin(), str.crend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
}

inline std::string trim_copy(const std::string& str)
{
    auto it1 = std::find_if(str.cbegin(), str.cend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    if (it1 == str.cend()) {
        return std::string();
    }
    auto it2 = std::find_if(str.crbegin(), str.crend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
}

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

Brew only solution

Update:

From the comments (kudos to Maksim Luzik), I haven't tested but seems like a more elegant solution:

After installing ruby through brew, run following command to update the links to the latest ruby installation: brew link --overwrite ruby

Original answer:

Late to the party, but using brew is enough. It's not necessary to install rvm and for me it just complicated things.

By brew install ruby you're actually installing the latest (currently v2.4.0). However, your path finds 2.0.0 first. To avoid this just change precedence (source). I did this by changing ~/.profile and setting:

export PATH=/usr/local/bin:$PATH

After this I found that bundler gem was still using version 2.0.0, just install it again: gem install bundler

2D array values C++

int iArray[2][2] = {{1, 2}, {3, 4}};

Think of a 2D array as an array of arrays.

How to map atan2() to degrees 0-360

Or if you don't like branching, just negate the two parameters and add 180° to the answer.

(Adding 180° to the return value puts it nicely in the 0-360 range, but flips the angle. Negating both input parameters flips it back.)

Concrete Javascript Regex for Accented Characters (Diacritics)

The XRegExp library has a plugin named Unicode that helps solve tasks like this.

<script src="xregexp.js"></script>
<script src="addons/unicode/unicode-base.js"></script>
<script>
  var unicodeWord = XRegExp("^\\p{L}+$");

  unicodeWord.test("???????"); // true
  unicodeWord.test("???"); // true
  unicodeWord.test("???????"); // true
</script>

It's mentioned in the comments to the question, but it's easy to miss. I've noticed it only after I submitted this answer.

Can't load IA 32-bit .dll on a AMD 64-bit platform

Just go to install download jdk_x86 and it install in Program Files (x86) and set the jre path in your project. Thats it.

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;

Why can't C# interfaces contain fields?

A lot has been said already, but to make it simple, here's my take. Interfaces are intended to have method contracts to be implemented by the consumers or classes and not to have fields to store values.

You may argue that then why properties are allowed? So the simple answer is - properties are internally defined as methods only.

Rounding a number to the nearest 5 or 10 or X

To mimic in Visual Basic the way the round function works in Excel, you just have to use: WorksheetFunction.Round(number, decimals)

This way the banking or accounting rounding don't do the rounding.

I want to execute shell commands from Maven's pom.xml

2 Options:

  1. You want to exec a command from maven without binding to any phase, you just type the command and maven runs it, you just want to maven to run something, you don't care if we are in compile/package/... Let's say I want to run npm start with maven, you can achieve it with the below:

mvn exec:exec -Pstart-node

For that you need the below maven section

  <profiles>
    <profile>
      <id>start-node</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>npm</executable>
              <arguments><argument>start</argument></arguments>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

  </profiles>
  1. You want to run an arbitrary command from maven while you are at a specific phase, for example when I'm at install phase I want to run npm install you can do that with:

mvn install

And for that to work you would need the below section:

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.3.2</version>
    <executions>

      <execution>
        <id>npm install (initialize)</id>
        <goals>
          <goal>exec</goal>
        </goals>
        <phase>initialize</phase>
        <configuration>
          <executable>npm</executable>
          <arguments>
            <argument>install</argument>
          </arguments>
        </configuration>
      </execution>

Can I scale a div's height proportionally to its width using CSS?

One way usefull when you work with images, but can be used as workaround otherwise:

<html>
<head>
</head>
<style>
    #someContainer {
        width:50%;
        position: relative;
    }
    #par {
        width: 100%;
        background-color:red;
    }
    #image {
        width: 100%;
        visibility: hidden;
    }
    #myContent {
        position:absolute;
    }
</style>
<div id="someContainer">
    <div id="par">
        <div id="myContent">
            <p>
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            </p>    
        </div>
        <img src="yourImage" id="image"/>
    </div>
</div>
</html>

To use replace yourImage with your image url. You use image with width / height ratio you desire.

div id="myContent" is here as example of workaround where myContent will overlay over image.

This works like: Parent div will adopt to the height of image, image height will adopt to width of parent. However image is hidden.

How to detect idle time in JavaScript elegantly?

You asked for elegancy, and I created a simple class to also support a lazy check (which has an idle state), aside to the imperative way (with callbacks). In addition, this class supports "backToActive" when the idle time is violated.

class Idle {
    constructor(timeout = 10, idleCallback = null, backToActiveCallback = null, autoStart = true, backToActiveOnXHR = false) {
        this.timeout = timeout
        this.idleCallback = idleCallback
        this.backToActiveCallback = backToActiveCallback
        this.autoStart = autoStart // only F5
        this.backToActiveOnXHR = backToActiveOnXHR
        this.idle = false
        this.timer = null
        this.events = ['scroll', 'mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart']
        this.init()
    }

    init() {
        if(this.backToActiveOnXHR) {
            this.events.push('load')
        }
        this.events.forEach(name => {
            window.addEventListener(name, this.backToActive, true)
        })
        if(this.autoStart) {
            this.backToActive()
        }
    }

    goIdle = () => {
        this.idle = true
        if(!!this.idleCallback) {
            this.idleCallback(this.timeout)
        }
    }

    backToActive = () => {
        if(this.idle) {
            this.backToActiveCallback()
        }
        this.idle = false
        clearTimeout(this.timer)
        this.timer = setTimeout(this.goIdle, this.timeout * 1000)
    }
}

Usage:

let idleCallback = timeout => { console.log(`Went idle after ${timeout} seconds`) }
let backToActiveCallback = () => { console.log('Back to active') }
let idle = new Idle(30, idleCallback, backToActiveCallback)

Result in devtools:

// Went idle after 30 seconds <--- goes idle when no activity is detected
// Back to active <--- when the user is detected again

The advantage of supporting laziness:

setInterval(() => {
    common.fetchApi('/api/v1/list', { status: idle.idle ? 'away' : 'online' }).then(/* show a list of elements */)
}, 1000 * 5)

Why would you want a lazy check? Sometimes we use a periodic XHR (with setInterval), i.e. when a user watch a list of flights, rides, movies, orders etc. With each XHR we then can add information about his activity status (online / away), so we have a sense of active users in our system.

My class is based on Equiman's & Frank Conijn's answers.

Intellij idea subversion checkout error: `Cannot run program "svn"`

I solved this by uncheking the "Use command-line client" option from Subversion settings.

This works with version 1.6 and 1.7 only. See @Vic's answer for SVN version 1.8.

What is aria-label and how should I use it?

The title attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).

As such, the mindful approach here would be to serve all users. I would add both title and aria-label attributes (serving different types of users and different types of usage of the web).

Here's a good article that explains aria-label in depth

Which passwordchar shows a black dot (•) in a winforms textbox?

You can use this one: You can type it by pressing Alt key and typing 0149.

How can I change an element's class with JavaScript?

Lots of answers, lots of good answers.

TL;DR :

document.getElementById('id').className = 'class'

OR

document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');

That's it.

And, if you really want to know the why and educate yourself then I suggest reading Peter Boughton's answer, it's perfect.

Note:
This is possible with (document or event):

  • getElementById()
  • getElementsByClassName()
  • querySelector()
  • querySelectorAll()

Resource u'tokenizers/punkt/english.pickle' not found

For me nothing of the above worked, so I just downloaded all the files by hand from the web site http://www.nltk.org/nltk_data/ and I put them also by hand in a file "tokenizers" inside of "nltk_data" folder. Not a pretty solution but still a solution.

Which JDK version (Language Level) is required for Android Studio?

Answer Clarification - Android Studio supports JDK8

The following is an answer to the question "What version of Java does Android support?" which is different from "What version of Java can I use to run Android Studio?" which is I believe what was actually being asked. For those looking to answer the 2nd question, you might find Using Android Studio with Java 1.7 helpful.

Also: See http://developer.android.com/sdk/index.html#latest for Android Studio system requirements. JDK8 is actually a requirement for PC and linux (as of 5/14/16).


Java 8 update (3/19/14)

Because I'd assume this question will start popping up soon with the release yesterday: As of right now, there's no set date for when Android will support Java 8.

Here's a discussion over at /androiddev - http://www.reddit.com/r/androiddev/comments/22mh0r/does_android_have_any_plans_for_java_8/

If you really want lambda support, you can checkout Retrolambda - https://github.com/evant/gradle-retrolambda. I've never used it, but it seems fairly promising.

Another Update: Android added Java 7 support

Android now supports Java 7 (minus try-with-resource feature). You can read more about the Java 7 features here: https://stackoverflow.com/a/13550632/413254. If you're using gradle, you can add the following in your build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Older response

I'm using Java 7 with Android Studio without any problems (OS X - 10.8.4). You need to make sure you drop the project language level down to 6.0 though. See the screenshot below.

enter image description here

What tehawtness said below makes sense, too. If they're suggesting JDK 6, it makes sense to just go with JDK 6. Either way will be fine.

enter image description here


Update: See this SO post -- https://stackoverflow.com/a/9567402/413254

Change the Bootstrap Modal effect

Here is pure Bootstrap 4 with CSS 3 solution.

<div class="modal fade2" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>
.fade2 {
    transform: scale(0.9);
    opacity: 0;
    transition: all .2s linear;
    display: block !important;
}

.fade2.show {
    opacity: 1;
    transform: scale(1);
}
$('#exampleModal').modal();

function afterModalTransition(e) {
  e.setAttribute("style", "display: none !important;");
}
$('#exampleModal').on('hide.bs.modal', function (e) {
    setTimeout( () => afterModalTransition(this), 200);
})

Full example here.

Maybe it will help someone.

--

Thank you @DavidDomain too.

How to change Navigation Bar color in iOS 7?

For swift change navigation bar color:

self.navigationController?.navigationBar.barTintColor = UIColor.red

change title font,size, color:

self.title = "title"
self.navigationController?.navigationBar.titleTextAttributes = [
        NSAttributedString.Key.foregroundColor : UIColor.white,
        NSAttributedString.Key.font : UIFont(name: "Futura", size: 30)!
    ]

Pass parameter to controller from @Html.ActionLink MVC 4

The problem must be with the value Model.Id which is null. You can confirm by assigning a value, e.g

@{         
     var blogPostId = 1;          
 }

If the error disappers, then u need to make sure that your model Id has a value before passing it to the view

How do I auto-hide placeholder text upon focus using css or jquery?

The same thing i have applied in angular 5.

i created a new string for storing placeholder

newPlaceholder:string;

then i have used focus and blur functions on input box(i am using prime ng autocomplete).

Above placeholder is being set from typescript

Two functions i am using -

/* Event fired on focus to textbox*/
Focus(data) {
    this.newPlaceholder = data.target.placeholder;
    this.placeholder = '';
}
/* Event fired on mouse out*/
Blur(data) {
    this.placeholder = this.newPlaceholder;
}

Unable to make the session state request to the session state server

I recently ran into this issue and none of the solutions proposed fixed it. The issue turned out to be an excessive use of datasets stored in the session. There was a flaw in the code that results in the session size to increase 10x.

There is an article on the msdn blog that also talks about this. http://blogs.msdn.com/b/johan/archive/2006/11/20/sessionstate-performance.aspx

I used a function to write custom trace messages to measure the size of the session data on the live site.

Server did not recognize the value of HTTP Header SOAPAction

I've decided to post my own answer here because I've lost a few hours on this and I think that, although the accepted answer is very good and pointed me in the right direction (yes, it got a voteup), it was not detailed enough to explain what was wrong with my application, at least in my case.

I'm running a BPEL module in OpenESB 2.2 and the Test Case of my Composite Application was failing with the following error:

Caused by: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: .

After doing some research I've noticed that the external WSDL has all the clues we need to fix this problem, e.g., I'm using the following web service to validate a credit card number through a orchestration of Web Services: http://www.webservicex.net/CreditCard.asmx?WSDL

If you check the <wsdl:operation elements you will see that it clearly states the soapAction for that operation:

<wsdl:binding name="CCCheckerSoap" type="tns:CCCheckerSoap">
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
  <wsdl:operation name="ValidateCardNumber">
    <soap:operation soapAction="http://www.webservicex.net/ValidateCardNumber" style="document"/>
    <wsdl:input>
  <soap:body use="literal"/>
</wsdl:input>
...

But, once you create the Composite Application and build the project with the BPEL that invokes this external WSDL service, for some reason (bug?), the XML of the Composite Application Service Assembly (CASA) binding is generated with an empty soapAction parameter:

<binding name="casaBinding1" type="ns:CCCheckerSoap">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="ValidateCardNumber">
            <soap:operation soapAction="" style="document"/>
            <input>
                <soap:body use="literal"/>
            </input>

Once you copy the proper soapAction (http://www.webservicex.net/ValidateCardNumber) into this parameter, the application's Test Case will correctly and return the expected Soap response.

<soap:operation soapAction="http://www.webservicex.net/ValidateCardNumber" style="document"/>

So, it's a more specific solution that I decided to document based on the information found in this blog post: http://bluebones.net/2003/07/server-did-not-recognize-http-header-soapaction/.

It means (at least in my case) that you are accessing a web service with SOAP and passing a SOAPAction parameter in the HTTP request that does not match what the service is expecting.

How to get current time and date in C++?

In C++ 11 you can use std::chrono::system_clock::now()

Example (copied from en.cppreference.com):

#include <iostream>
#include <chrono>
#include <ctime>    

int main()
{
    auto start = std::chrono::system_clock::now();
    // Some computation here
    auto end = std::chrono::system_clock::now();

    std::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s\n";
}

This should print something like this:

finished computation at Mon Oct  2 00:59:08 2017
elapsed time: 1.88232s

Fix footer to bottom of page

We can use FlexBox for Sticky Footer and Header without using POSITIONS in CSS.

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
  height: 50px;_x000D_
  flex-shrink: 0;_x000D_
  background-color: #037cf5;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  height: 50px;_x000D_
  flex-shrink: 0;_x000D_
  background-color: #134c7d;_x000D_
}_x000D_
_x000D_
main {_x000D_
  flex: 1 0 auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <header>HEADER</header>_x000D_
  <main class="content">_x000D_
_x000D_
  </main>_x000D_
  <footer>FOOTER</footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

DEMO - JSFiddle

Note : Check browser supports for FlexBox. caniuse

How to compare character ignoring case in primitive types

Generic methods to compare a char at a position between 2 strings with ignore case.

public static boolean isEqualIngoreCase(char one, char two){
    return Character.toLowerCase(one)==Character .toLowerCase(two);
}

public static boolean isEqualStringCharIgnoreCase(String one, String two, int position){
    char oneChar = one.charAt(position);
    char twoChar = two.charAt(position);
    return isEqualIngoreCase(oneChar, twoChar);
}

Function call

boolean isFirstCharEqual = isEqualStringCharIgnoreCase("abc", "ABC", 0)

Found conflicts between different versions of the same dependent assembly that could not be resolved

Obviously there's a lot of different causes and thus a lot of solutions for this problem. To throw mine into the mix, we upgraded an assembly (System.Net.Http) that was previously directly referenced in our Web project to a version managed by NuGet. This removed the direct reference within that project, but our Test project still contained the direct reference. Upgrading both projects to use the NuGet-managed assembly resolved the issue.

Combine or merge JSON on node.js without jQuery

You should use "Object.assign()"

There's no need to reinvent the wheel for such a simple use case of shallow merging.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, target object itself is changed

Even the folks from Node.js say so:

_extend was never intended to be used outside of internal NodeJS modules. The community found and used it anyway. It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign.


Update:

You could use the spread operator

Since version 8.6, it's possible to natively use the spread operator in Node.js. Example below:

let o1 = { a: 1 };
let o2 = { b: 2 };
let obj = { ...o1, ...o2 }; // { a: 1, b: 2 }

Object.assign still works, though.


PS1: If you are actually interested in deep merging (in which internal object data -- in any depth -- is recursively merged), you can use packages like deepmerge, assign-deep or lodash.merge, which are pretty small and simple to use.

PS2: Keep in mind that Object.assign doesn't work with 0.X versions of Node.js. If you are working with one of those versions (you really shouldn't by now), you could use require("util")._extend as shown in the Node.js link above -- for more details, check tobymackenzie's answer to this same question.

Why is Node.js single threaded?

The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.

Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).

The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.

In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.

If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

The most likely explanations for that error are:

  1. The file you are attempting to load is not an executable file. CreateProcess requires you to provide an executable file. If you wish to be able to open any file with its associated application then you need ShellExecute rather than CreateProcess.
  2. There is a problem loading one of the dependencies of the executable, i.e. the DLLs that are linked to the executable. The most common reason for that is a mismatch between a 32 bit executable and a 64 bit DLL, or vice versa. To investigate, use Dependency Walker's profile mode to check exactly what is going wrong.

Reading down to the bottom of the code, I can see that the problem is number 1.

How to get first item from a java.util.Set?

Or, using Java8:

Object firstElement = set.stream().findFirst().get();

And then you can do stuff with it straight away:

set.stream().findFirst().ifPresent(<doStuffHere>);

Or, if you want to provide an alternative in case the element is missing (my example returns new default string):

set.stream().findFirst().orElse("Empty string");

You can even throw an exception if the first element is missing:

set.stream().findFirst().orElseThrow(() -> new MyElementMissingException("Ah, blip, nothing here!"));

Kudos to Alex Vulaj for prompting me to provide more examples beyond the initial grabbing of the first element.

Right way to write JSON deserializer in Spring or extend it

I've searched a lot and the best way I've found so far is on this article:

Class to serialize

package net.sghill.example;

import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private ObjectId id;
    private String   username;
    private String   password;

    public User(ObjectId id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public ObjectId getId()       { return id; }
    public String   getUsername() { return username; }
    public String   getPassword() { return password; }
}

Deserializer class

package net.sghill.example;

import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
    }
}

Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.

How to get only the date value from a Windows Forms DateTimePicker control?

@Shoban It looks like the question is tagged c# so here is the appropriate snipped http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx

public MyClass()
{
    // Create a new DateTimePicker
    DateTimePicker dateTimePicker1 = new DateTimePicker();
    Controls.Add(dateTimePicker1);
    MessageBox.Show(dateTimePicker1.Value.ToString());

    dateTimePicker1.Value = DateTime.Now.AddDays(1);
    MessageBox.Show(dateTimePicker1.Value.ToString());
 } 

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

sqlcmd works, System.Data.SqlClient not working - Server not found in Kerberos database. You should add RestrictedKrbHost SPN

https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-kile/445e4499-7e49-4f2a-8d82-aaf2d1ee3c47

5.1.2 SPNs with Serviceclass Equal to "RestrictedKrbHost"

Supporting the "RestrictedKrbHost" service class allows client applications to use Kerberos authentication when they do not have the identity of the service but have the server name. This does not provide client-to-service mutual authentication, but rather client-to-server computer authentication. Services of different privilege levels have the same session key and could decrypt each other's data if the underlying service does not ensure that data cannot be accessed by higher services.

PHP ternary operator vs null coalescing operator

If you use the shortcut ternary operator like this, it will cause a notice if $_GET['username'] is not set:

$val = $_GET['username'] ?: 'default';

So instead you have to do something like this:

$val = isset($_GET['username']) ? $_GET['username'] : 'default';

The null coalescing operator is equivalent to the above statement, and will return 'default' if $_GET['username'] is not set or is null:

$val = $_GET['username'] ?? 'default';

Note that it does not check truthiness. It checks only if it is set and not null.

You can also do this, and the first defined (set and not null) value will be returned:

$val = $input1 ?? $input2 ?? $input3 ?? 'default';

Now that is a proper coalescing operator.

Android Webview gives net::ERR_CACHE_MISS message

Answers assembled! I wanted to just combine all the answers into one comprehensive one.

1. Check if <uses-permission android:name="android.permission.INTERNET" /> is present in manifest.xml. Make sure that it is nested under <manifest> and not <application>. Thanks to sajid45 and Liyanis Velazquez

2. Ensure that you are using <uses-permission android:name="android.permission.INTERNET"/> instead of the deprecated <uses-permission android:name="android.permission.internet"/>. Much thanks to alan_shi and creos.

3. If minimum version is below KK, check that you have

if (18 < Build.VERSION.SDK_INT ){
    //18 = JellyBean MR2, KITKAT=19
    mWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}

or

if (Build.VERSION.SDK_INT >= 19) {
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}

because proper webview is only added in KK (SDK 19). Thanks to Devavrata, Mike ChanSeong Kim and Liyanis Velazquez

4. Ensure that you don't have webView.getSettings().setBlockNetworkLoads (false);. Thanks to TechNikh for pointing this out.

5. If all else fails, make sure that your Android Studio, Android SDK and the emulator image (if you are using one) is updated. And if you are still meeting the problem, just open a new question and make a comment below to your URL.

Make a negative number positive

The easiest, if verbose way to do this is to wrap each number in a Math.abs() call, so you would add:

Math.abs(1) + Math.abs(2) + Math.abs(1) + Math.abs(-1)

with logic changes to reflect how your code is structured. Verbose, perhaps, but it does what you want.

Create a Cumulative Sum Column in MySQL

Using a correlated query:


  SELECT t.id,
         t.count,
         (SELECT SUM(x.count)
            FROM TABLE x
           WHERE x.id <= t.id) AS cumulative_sum
    FROM TABLE t
ORDER BY t.id

Using MySQL variables:


  SELECT t.id,
         t.count,
         @running_total := @running_total + t.count AS cumulative_sum
    FROM TABLE t
    JOIN (SELECT @running_total := 0) r
ORDER BY t.id

Note:

  • The JOIN (SELECT @running_total := 0) r is a cross join, and allows for variable declaration without requiring a separate SET command.
  • The table alias, r, is required by MySQL for any subquery/derived table/inline view

Caveats:

  • MySQL specific; not portable to other databases
  • The ORDER BY is important; it ensures the order matches the OP and can have larger implications for more complicated variable usage (IE: psuedo ROW_NUMBER/RANK functionality, which MySQL lacks)

POST data with request module on Node.JS

If you're posting a json body, dont use the form parameter. Using form will make the arrays into field[0].attribute, field[1].attribute etc. Instead use body like so.

var jsonDataObj = {'mes': 'hey dude', 'yo': ['im here', 'and here']};
request.post({
    url: 'https://api.site.com',
    body: jsonDataObj,
    json: true
  }, function(error, response, body){
  console.log(body);
});

Unresolved external symbol in object files

One possible cause of this linker error can also be inline functions that are declared but not defined in a header file that is then included somewhere else. Inline functions have to be defined in every translation unit they are used in.

How to get length of a list of lists in python

if the name of your list is listlen then just type len(listlen). This will return the size of your list in the python.

How to specify function types for void (not Void) methods in Java8?

I feel you should be using the Consumer interface instead of Function<T, R>.

A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)

In your case, you can create a consumer elsewhere in your code like this:

Consumer<Integer> myFunction = x -> {
    System.out.println("processing value: " + x);    
    .... do some more things with "x" which returns nothing...
}

Then you can replace your myForEach code with below snippet:

public static void myForEach(List<Integer> list, Consumer<Integer> myFunction) 
{
  list.forEach(x->myFunction.accept(x));
}

You treat myFunction as a first-class object.

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

How to do if-else in Thymeleaf?

In simpler case (when html tags is the same):

<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

Since your local repository is few commits ahead, git tries to merge your remote to your local repo. This can be handled via merge, but in your case, perhaps you are looking for rebase, i.e. add your commit to the top. You can do this with

git rebase or git pull --rebase

Here is a good article explaining the difference between git pull & git pull --rebase.

https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/

How to specify the bottom border of a <tr>?

What I want to say here is like some kind of add-on on @Suciu Lucian's answer.

The weird situation I ran into is that when I apply the solution of @Suciu Lucian in my file, it works in Chrome but not in Safari (and did not try in Firefox). After I studied the guide of styling table border published by w3.org, I found something alternative:

table.myTable{
  border-spacing: 0;
}

table.myTable td{
  border-bottom:1px solid red;
}

Yes you have to style the td instead of the tr.

Merging two images in C#/.NET

basically i use this in one of our apps: we want to overlay a playicon over a frame of a video:

Image playbutton;
try
{
    playbutton = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

Image frame;
try
{
    frame = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

using (frame)
{
    using (var bitmap = new Bitmap(width, height))
    {
        using (var canvas = Graphics.FromImage(bitmap))
        {
            canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            canvas.DrawImage(frame,
                             new Rectangle(0,
                                           0,
                                           width,
                                           height),
                             new Rectangle(0,
                                           0,
                                           frame.Width,
                                           frame.Height),
                             GraphicsUnit.Pixel);
            canvas.DrawImage(playbutton,
                             (bitmap.Width / 2) - (playbutton.Width / 2),
                             (bitmap.Height / 2) - (playbutton.Height / 2));
            canvas.Save();
        }
        try
        {
            bitmap.Save(/*somekindofpath*/,
                        System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception ex) { }
    }
}

Limit the size of a file upload (html input element)

<script type="text/javascript">
    $(document).ready(function () {

        var uploadField = document.getElementById("file");

        uploadField.onchange = function () {
            if (this.files[0].size > 300000) {
                this.value = "";
                swal({
                    title: 'File is larger than 300 KB !!',
                    text: 'Please Select a file smaller than 300 KB',
                    type: 'error',
                    timer: 4000,
                    onOpen: () => {
                        swal.showLoading()
                        timerInterval = setInterval(() => {
                            swal.getContent().querySelector('strong')
                                .textContent = swal.getTimerLeft()
                        }, 100)
                    },
                    onClose: () => {
                        clearInterval(timerInterval)

                    }
                }).then((result) => {
                    if (
                        // Read more about handling dismissals
                        result.dismiss === swal.DismissReason.timer


                    ) {

                        console.log('I was closed by the timer')
                    }
                });

            };
        };



    });
</script>

Release generating .pdb files, why?

In a multi-project solution, you usually want to have one configuration that generates no PDB or XML files at all. Instead of changing the Debug Info property of every project to none, I thought it would be more expedient to add a post-build event that only works in a specific configuration.

Unfortunately, Visual Studio doesn't allow you to specify different post-build events for different configurations. So I decided to do this manually, by editing the csproj file of the startup project and adding the following (instead of any existing PostBuildEvent tag):

  <PropertyGroup Condition="'$(Configuration)' == 'Publish'">
    <PostBuildEvent>
        del *.pdb
        del *.xml
    </PostBuildEvent>
  </PropertyGroup>

Unfortunately, this will make the post build event textbox blank and putting anything in it can have unpredictable results.

How to make sure that a certain Port is not occupied by any other process

You can use "netstat" to check whether a port is available or not.

Use the netstat -anp | find "port number" command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.

You have to put : before port number to get the actual output

Ex netstat -anp | find ":8080"

extra qualification error in C++

I saw this error when my header file was missing closing brackets.

Causing this error:

// Obj.h
class Obj {
public:
    Obj();

Fixing this error:

// Obj.h
class Obj {
public:
    Obj();
};

SQL to Entity Framework Count Group-By

A useful extension is to collect the results in a Dictionary for fast lookup (e.g. in a loop):

var resultDict = _dbContext.Projects
    .Where(p => p.Status == ProjectStatus.Active)
    .GroupBy(f => f.Country)
    .Select(g => new { country = g.Key, count = g.Count() })
    .ToDictionary(k => k.country, i => i.count);

Originally found here: http://www.snippetsource.net/Snippet/140/groupby-and-count-with-ef-in-c

How to parse JSON in Java

You can use JsonNode for a structured tree representation of your JSON string. It's part of the rock solid jackson library which is omnipresent.

ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{\"k\":\"v\"}");

Path to Powershell.exe (v 2.0)

It is always C:\Windows\System32\WindowsPowershell\v1.0. It was left like that for backward compability is what I heard or read somewhere.

Read data from SqlDataReader

For a single result:

if (reader.Read())
{
    Response.Write(reader[0].ToString());
    Response.Write(reader[1].ToString());
}

For multiple results:

while (reader.Read())
{
    Response.Write(reader[0].ToString());
    Response.Write(reader[1].ToString());
}

Get the records of last month in SQL server

SELECT * 
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, date_created) = DATEPART(yyyy, DATEADD(m, -1, getdate()))

You need to check the month and year.

How to calculate mean, median, mode and range from a set of numbers

    public static Set<Double> getMode(double[] data) {
            if (data.length == 0) {
                return new TreeSet<>();
            }
            TreeMap<Double, Integer> map = new TreeMap<>(); //Map Keys are array values and Map Values are how many times each key appears in the array
            for (int index = 0; index != data.length; ++index) {
                double value = data[index];
                if (!map.containsKey(value)) {
                    map.put(value, 1); //first time, put one
                }
                else {
                    map.put(value, map.get(value) + 1); //seen it again increment count
                }
            }
            Set<Double> modes = new TreeSet<>(); //result set of modes, min to max sorted
            int maxCount = 1;
            Iterator<Integer> modeApperance = map.values().iterator();
            while (modeApperance.hasNext()) {
                maxCount = Math.max(maxCount, modeApperance.next()); //go through all the value counts
            }
            for (double key : map.keySet()) {
                if (map.get(key) == maxCount) { //if this key's value is max
                    modes.add(key); //get it
                }
            }
            return modes;
        }

        //std dev function for good measure
        public static double getStandardDeviation(double[] data) {
            final double mean = getMean(data);
            double sum = 0;
            for (int index = 0; index != data.length; ++index) {
                sum += Math.pow(Math.abs(mean - data[index]), 2);
            }
            return Math.sqrt(sum / data.length);
        }


        public static double getMean(double[] data) {
        if (data.length == 0) {
            return 0;
        }
        double sum = 0.0;
        for (int index = 0; index != data.length; ++index) {
            sum += data[index];
        }
        return sum / data.length;
    }

//by creating a copy array and sorting it, this function can take any data.
    public static double getMedian(double[] data) {
        double[] copy = Arrays.copyOf(data, data.length);
        Arrays.sort(copy);
        return (copy.length % 2 != 0) ? copy[copy.length / 2] : (copy[copy.length / 2] + copy[(copy.length / 2) - 1]) / 2;
    }

Make a td fixed size (width,height) while rest of td's can expand

just set the width of the td/column you want to be fixed and the rest will expand.

<td width="200"></td>

How to check visibility of software keyboard in Android?

if (keyopen())
{
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);            
}

The above function is what I use to check if a Keyboard is visible. If it is, then I close it.

Below shows the two methods required.

First, define the workable Window height in onCreate.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//  add to onCreate method
    Rect rectgle= new Rect();
    Window window= getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
    sheight= rectgle.bottom;
//

} 

Then, add a boolean method that gets the Window height at that instance. If it does not match the original (assuming you are not changing it along the way...) then, the keyboard is open.

public boolean keyopen()
{
    Rect rectgle= new Rect();
    Window window= getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
    int curheight= rectgle.bottom;

    if (curheight!=sheight)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Frotz!

Is it safe to use Project Lombok?

I read some opinions about the Lombok and actually I'm using it in some projects.

Well, in the first contact with Lombok I had a bad impression. After some weeks, I started to like it. But after some months I figure out a lot of tiny problems using it. So, my final impression about Lombok is not so positive.

My reasons to think in this way:

  • IDE plugin dependency. The IDE support for Lombok is through plugins. Even working good in most part of the time, you are always a hostage from this plugins to be maintained in the future releases of the IDEs and even the language version (Java 10+ will accelerate the development of the language). For example, I tried to update from Intellij IDEA 2017.3 to 2018.1 and I couldn't do that because there was some problem on the actual lombok plugin version and I needed to wait the plugin be updated... This also is a problem if you would like to use a more alternative IDE that don't have any Lombok plugin support.
  • 'Find usages' problem.. Using Lombok you don't see the generated getter, setter, constructor, builder methods and etc. So, if you are planning to find out where these methods are being used in your project by your IDE, you can't do this only looking for the class that owns this hidden methods.
  • So easy that the developers don't care to break the encapsulation. I know that it's not really a problem from Lombok. But I saw a bigger tendency from the developers to not control anymore what methods needs to be visible or not. So, many times they are just copying and pasting @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor annotations block without thinking what methods the class really need to be exposed.
  • Builder Obssession ©. I invented this name (get off, Martin Fowler). Jokes apart, a Builder is so easy to create that even when a class have only two parameters the developers prefer to use @Builder instead of constructor or a static constructor method. Sometimes they even try to create a Builder inside the lombok Builder, creating weird situations like MyClass.builder().name("Name").build().create().
  • Barriers when refactoring. If you are using, for example, a @AllArgsConstructor and need to add one more parameter on the constructor, the IDE can't help you to add this extra parameter in all places (mostly, tests) that are instantiating the class.
  • Mixing Lombok with concrete methods. You can't use Lombok in all scenarios to create a getter/setter/etc. So, you will see these two approaches mixed in your code. You get used to this after some time, but feels like a hack on the language.

Like another answer said, if you are angry about the Java verbosity and use Lombok to deal with it, try Kotlin.

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4.x the log level is configured a bit different than in Rails 3.x

Add this to config/environment/test.rb

# Enable stdout logger
config.logger = Logger.new(STDOUT)

# Set log level
config.log_level = :ERROR

The logger level is set on the logger instance from config.log_level at: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application/bootstrap.rb#L70

Environment variable

As a bonus, you can allow overwriting the log level using an environment variable with a default value like so:

# default :ERROR
config.log_level = ENV.fetch("LOG_LEVEL", "ERROR")

And then running tests from shell:

# Log level :INFO (the value is uppercased in bootstrap.rb)
$ LOG_LEVEL=info rake test

# Log level :ERROR
$ rake test

PHP check if file is an image

The getimagesize() should be the most definite way of working out whether the file is an image:

if(@is_array(getimagesize($mediapath))){
    $image = true;
} else {
    $image = false;
}

because this is a sample getimagesize() output:

Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)

How does "make" app know default target to build if no target is specified?

GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target.

Ref: The Gnu Make manual - Special Variables

How do I create directory if it doesn't exist to create a file?

To Create

(new FileInfo(filePath)).Directory.Create() Before writing to the file.

....Or, If it exists, then create (else do nothing)

System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);

How to add image for button in android?

You should try something like this

    <Button
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/qrcode"/>

the android:background="@drawable/qrcode" will do it

I'm getting favicon.ico error

I have had this error for some time as well. It might be some kind of netbeans bug that has to do with netbeans connector. I can't find any mention of favicon.ico in my code or in the project settings.

I was able to fix it by putting the following line in the head section of my html file

<link rel="shortcut icon" href="#">

I am currently using this in my testing environment, but I would remove it for any production environment.

CURL to pass SSL certifcate and password

Addition to previous answer make sure that your curl installation supports https.
You can use curl --version to get information about supported protocols.

If your curl supports https follow the previous answer.

curl --cert certificate_path:password https://www.example.com

If it does not support https, you need to install a cURL version that supports https.

Can't access to HttpContext.Current

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

How do I make a div full screen?

CSS way:

#foo {
   position: absolute;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
}

JS way:

$(function() {
    function abso() {
        $('#foo').css({
            position: 'absolute',
            width: $(window).width(),
            height: $(window).height()
        });
    }

    $(window).resize(function() {
        abso();         
    });

    abso();
});