Programs & Examples On #Scp

GENERAL SCP SUPPORT IS OFF-TOPIC. Support questions may be asked on https://superuser.com. Secure Copy or SCP is a means of securely transferring computer files between a local and a remote host or between two remote hosts over an SSH protocol.

Using putty to scp from windows to Linux

You can use PSCP to copy files from Windows to Linux.

  1. Download PSCP from putty.org
  2. Open cmd in the directory with pscp.exe file
  3. Type command pscp source_file user@host:destination_file

Reference

How to filter files when using scp to copy dir recursively?

To exclude dotfiles in base directory:

scp -r [!.]* server:/path/to/something

[!.]* is a shell glob that expands to all files in working directory not starting with a dot.

recursively use scp but excluding some folders

You can specify GLOBIGNORE and use the pattern *

GLOBIGNORE='ignore1:ignore2' scp -r source/* remoteurl:remoteDir

You may wish to have general rules which you combine or override by using export GLOBIGNORE, but for ad-hoc usage simply the above will do. The : character is used as delimiter for multiple values.

How to pass password to scp?

You can script it with a tool like expect (there are handy bindings too, like Pexpect for Python).

scp via java

plug: sshj is the only sane choice! See these examples to get started: download, upload.

How to copy a file from remote server to local machine?

When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:

scp -P[portnumber] myfile_at_remote_host [user]@[your_ip_address]:/your/path/

Example:

scp -P22 table [email protected]:/home/me/Desktop/

On the other hand, if you are at your are actually on your machine you may use something like this:

scp -P[portnumber] [remote_login]@[remote's_ip_address]:/remote/path/myfile_at_remote_host /your/path/

Example:

scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/

scp files from local to remote machine error: no such file or directory

Be sure the folder from where you send the file does not contain space !

I was trying to send a file to a remote server from my windows machine from VS code terminal, and I got this error even if the file was here.

It's because the folder where the file was contained space in its name...

Copying a local file from Windows to a remote server using scp

Drive letters can be used in the target like

scp some_file user@host:/c/temp

where c is the drive letter. It's treated like a directory.

Maybe this works on the source, too.

How do I copy a folder from remote to local using scp?

Typical scenario,

scp -r -P port username@ip:/path-to-folder  .

explained with an sample,

scp -r -P 27000 [email protected]:/tmp/hotel_dump .

where,

port = 27000
username = "abc" , remote server username
path-to-folder = tmp/hotel_dump
. = current local directory

SSH SCP Local file to Remote in Terminal Mac Os X

Watch that your file name doesn't have : in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt and then scp no-colons.txt server: then don't forget to mv back on the server. Just in case this was an issue.

scp from remote host to local host

There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.

And then you can copy for example the file "test.txt" from a remote host to the local host

scp [email protected]:test.txt /local/dir


@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.

In UNIX, absolute paths must start with '/'.

How do I escape spaces in path for scp copy in Linux?

Sorry for using this Linux question to put this tip for Powershell on Windows 10: the space char escaping with backslashes or surrounding with quotes didn't work for me in this case. Not efficient, but I solved it using the "?" char instead:

for the file "tasks.txt Jun-22.bkp" I downloaded it using "tasks.txt?Jun-22.bkp"

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

One of the ways to get around login issues with ssh, scp, and sftp (all use the same protocol and sshd server) is to create public/private key pairings.

Some servers may disallow this, but most sites don't. These directions are for Unix/Linux/Mac. As always, Windows is a wee bit different although the cygwin environment on Windows does follow these steps.

  • On your machine, create your public/private key using ssh-keygen. This can vary from system to system, but the program should lead you through this.
  • When ssh-keygen is finished, you will have a $HOME/.ssh directory on your machine. This directory will contain a public key and a private key. There will be two more files that are generated as you go along. One is known_hosts which contains the fingerprints of all known hosts you've logged into. The second will be called either authorized_keys or authorized_keys2 depending upon your implementation.
  • If it's not there already, log into the remote host, and run ssh-keygen there too. This will generate a $HOME/.ssh directory there as well as a private/public key pair. Don't do this if the $HOME/.ssh directory already exists and has a public and private key file. You don't want to regenerate it.
  • On the remote server in the $HOME/.ssh directory, create a file called authorized_keys. In this file, put your public key. This public key is found on your $HOME/.ssh directory on your local machine. It will end with *.pub. Paste the contents of that into authorized_keys. If authorized_keys already exists, paste your public key in the next line.

Now, when you log in using ssh, or you use scp or sftp, you will not be required to enter a password. By the way, the user IDs on the two machines do not have to agree. I've logged into many remote servers as a different user and setup my public key in authorized_keys and have no problems logging directly into that user.

Doing Private Public Key Authentication on Windows

If you use Windows, you will need something that can do ssh. Most people I know use PuTTY which can generate public/private keys, and do the key pairing when you login remotely. I can't remember all of the steps, but you generate two files (one contains the public key, one contains the private key), and configure PuTTY to use both of those when logging into a remote site. If that remote site is Linux/Unix/Mac, you can copy your public key and put it into the authorized_keys file.

If you can use SSH Public/Private keys, you can eliminate the need for passwords in your scripts. Otherwise, you will have to use something like Expect or Perl with Net::SSH which can watch the remote host and enter the password when prompted.

Is there any WinSCP equivalent for linux?

Filezilla is available for Linux. If you are using Ubuntu:

sudo apt-get install filezilla

Otherwise, you can download it from the Filezilla website.

Transferring files over SSH

You need to scp something somewhere. You have scp ./styles/, so you're saying secure copy ./styles/, but not where to copy it to.

Generally, if you want to download, it will go:

# download: remote -> local
scp user@remote_host:remote_file local_file 

where local_file might actually be a directory to put the file you're copying in. To upload, it's the opposite:

# upload: local -> remote
scp local_file user@remote_host:remote_file

If you want to copy a whole directory, you will need -r. Think of scp as like cp, except you can specify a file with user@remote_host:file as well as just local files.

Edit: As noted in a comment, if the usernames on the local and remote hosts are the same, then the user can be omitted when specifying a remote file.

how to execute a scp command with the user name and password in one line

Using sshpass works best. To just include your password in scp use the ' ':

scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/

Using scp to copy a file to Amazon EC2 instance?

Send file from Local to Server:

scp -i .ssh/awsinstance.pem my_local_file [email protected]:/home/ubuntu

Download file from Server to Local:

scp -i .ssh/awsinstance.pem [email protected]:/home/ubuntu/server_file .

How to download a file from my server using SSH (using PuTTY on Windows)

if you install git with git bash, you get SCP available on windows.

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

The -i flag specifies the private key (.pem file) to use. If you don't specify that flag (as in your first command) it will use your default ssh key (usually under ~/.ssh/).

So in your first command, you are actually asking scp to upload the .pem file itself using your default ssh key. I don't think that is what you want.

Try instead with:

scp -r -i /Applications/XAMPP/htdocs/keypairfile.pem uploads/* ec2-user@publicdns:/var/www/html/uploads

How does `scp` differ from `rsync`?

rysnc can be useful to run on slow and unreliable connections. So if your download aborts in the middle of a large file rysnc will be able to continue from where it left off when invoked again.

Use rsync -vP username@host:/path/to/file .

The -P option preserves partially downloaded files and also shows progress.

As usual check man rsync

Copying files from server to local computer using SSH

Your question is a bit confusing, but I am assuming - you are first doing 'ssh' to find out which files or rather specifically directories are there and then again on your local computer, you are trying to scp 'all' files in that directory to local path. you should simply do scp -r.

So here in your case it'd be something like

local> scp -r [email protected]:/path/to/dir local/path 

If youare using some other executable that provides 'scp like functionality', refer to it's manual for recursively copying files.

scp from Linux to Windows

Try this:

scp /home/ubuntu/myfile C:\users\Anshul\Desktop

Error when using scp command "bash: scp: command not found"

Make sure the scp command is available on both sides - both on the client and on the server.

If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:

    yum -y install openssh-clients

If you work with Debian or Ubuntu and clones, install this package:

    apt-get install openssh-client

Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found or similar although you have it locally. This already confused thousands of people, I guess :)

Single line sftp from terminal

A minor modification like below worked for me when using it from within perl and system() call:

sftp {user}@{host} <<< $'put {local_file_path} {remote_file_path}'

scp or sftp copy multiple files with single command

Copy multiple files from remote to local:

$ scp [email protected]:/some/remote/directory/\{a,b,c\} ./

Copy multiple files from local to remote:

$ scp foo.txt bar.txt [email protected]:~
$ scp {foo,bar}.txt [email protected]:~
$ scp *.txt [email protected]:~

Copy multiple files from remote to remote:

$ scp [email protected]:/some/remote/directory/foobar.txt \
[email protected]:/some/remote/directory/

Source: http://www.hypexr.org/linux_scp_help.php

scp copy directory to another server with private key auth

Putty doesn't use openssh key files - there is a utility in putty suite to convert them.

edit: it is called puttygen

scp (secure copy) to ec2 instance without password

scp -i /path/to/your/.pemkey -r /copy/from/path user@server:/copy/to/path

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

Automate scp file transfer using a shell script

here's bash code for SCP with a .pem key file. Just save it to a script.sh file then run with 'sh script.sh'

Enjoy

#!/bin/bash
#Error function
function die(){
echo "$1"
exit 1
}

Host=ec2-53-298-45-63.us-west-1.compute.amazonaws.com
User=ubuntu
#Directory at sent destination
SendDirectory=scp
#File to send at host
FileName=filetosend.txt
#Key file
Key=MyKeyFile.pem

echo "Aperture in Process...";

#The code that will send your file scp
scp -i $Key $FileName $User@$Host:$SendDirectory || \
die "@@@@@@@Houston we have problem"

echo "########Aperture Complete#########";

How to copy a file to a remote server in Python using SCP or SSH?

To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the Paramiko library, you would do something like this:

import os
import paramiko

ssh = paramiko.SSHClient() 
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()

(You would probably want to deal with unknown hosts, errors, creating any directories necessary, and so on).

How to scp in Python?

You could also check out paramiko. There's no scp module (yet), but it fully supports sftp.

[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.

scp.py for paramiko

Run local python script on remote server

It is possible using ssh. Python accepts hyphen(-) as argument to execute the standard input,

cat hello.py | ssh [email protected] python -

Run python --help for more info.

Transfer files to/from session I'm logged in with PuTTY

Look here:

http://web.archive.org/web/20170106202838/https://it.cornell.edu/services/managed_servers/howto/file_transfer/fileputty.cfm#puttytrans

It recommends using pscp.exe from PuTTY, which can be found here: https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html

A direct transfer like FTP is not possible, because all commands during your session are send to the server.

scp with port number specified

if you need copy local file to server (specify port )

scp -P 3838 /the/source/file [email protected]:/destination/file

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you wrap each template in a script tag, eg:

<script id="about.html" type="text/ng-template">
<div>
    <h3>About</h3>
    This is the About page
    Its cool!
</div>
</script>

Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials - it adds a right click menu to create an HTML Bundle.

Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works: Vojta Jina's Gist

Its the $http.get that should be changed to use your bundle file:

allTplPromise = $http.get('templates/templateBundle.min.html').then(

Your routes templateUrl should look like this:

        $routeProvider.when(
            "/about", {
                controller: "",
                templateUrl: "about.html"
            }
        );

AngularJS : Custom filters and ng-repeat

You can call more of 1 function filters in the same ng-repeat filter

<article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">

c# dictionary How to add multiple values for single key?

Here are many variations of the one answer :) My is another one and it uses extension mechanism as comfortable way to execute (handy):

public static void AddToList<T, U>(this IDictionary<T, List<U>> dict, T key, U elementToList)
{

    List<U> list;

    bool exists = dict.TryGetValue(key, out list);

    if (exists)
    {
        dict[key].Add(elementToList);
    }
    else
    {
        dict[key] = new List<U>();
        dict[key].Add(elementToList);
    }

}

Then you use it as follows:

Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();

dict.AddToList(4, "test1");
dict.AddToList(4, "test2");
dict.AddToList(4, "test3");

dict.AddToList(5, "test4");

CSS text-align: center; is not centering things

I assume you want all the items next to each other, and the whole thing to be centered horizontally.

li elements are display: block by default, taking up all the horizontal space.

Add

div#footer ul li { display: inline }

once you've done that, you probably want to get rid of the list's bullets:

div#footer ul { list-style-type: none; padding: 0px; margin: 0px }

Is it possible to force row level locking in SQL Server?

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

Yahoo Finance API

Yahoo is very easy to use and provides customized data. Use the following page to learn more.

finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT=pder=.csv

WARNING - there are a few tutorials out there on the web that show you how to do this, but the region where you put in the stock symbols causes an error if you use it as posted. You will get a "MISSING FORMAT VALUE". The tutorials I found omits the commentary around GOOG.

Example URL for GOOG: http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,GOOG&f=nsl1op&e=.csv

How to activate a specific worksheet in Excel?

An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link. You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab 'Place in this document' and select the tab you want to activate. If you would click the text (that is now a link) the configured sheet will become active/selected.

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

SUBSTRING may help for some cases, you can limit the size of the int.

SELECT CAST(SUBSTRING('X12312333333333', '([\d]{1,9})') AS integer);

What are the differences in die() and exit() in PHP?

Something I have noticed in my scripts at least is that exit() will stop the currently executing script and pass control back to any calling script, while die will stop php in its tracks. I would say that is quite a big difference?

How can I check Drupal log files?

Make sure drush is installed (you may also need to make sure the dblog module is enabled) and use:

drush watchdog-show --tail

Available in drush v8 and below.

This will give you a live look at the logs from your console.

Detecting when the 'back' button is pressed on a navbar

Those who claim that this doesn't work are mistaken:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParent {
        print("we are being popped")
    }
}

That works fine. So what is causing the widespread myth that it doesn’t?

The problem seems to be due to an incorrect implementation of a different method, namely that the implementation of willMove(toParent:) forgot to call super.

If you implement willMove(toParent:) without calling super, then self.isMovingFromParent will be false and the use of viewWillDisappear will appear to fail. It didn't fail; you broke it.

NOTE: The real problem is usually the second view controller detecting that the first view controller was popped. Please see also the more general discussion here: Unified UIViewController "became frontmost" detection?

EDIT A comment suggests that this should be viewDidDisappear rather than viewWillDisappear.

Free tool to Create/Edit PNG Images?

Paint.NET will create and edit PNGs with gusto. It's an excellent program in many respects. It's free as in beer and speech.

gulp command not found - error after installing gulp

  1. Install gulp globally.

    npm install -g gulp

  2. Install gulp locally in the project.

    npm install gulp

  3. Add below line in your package.json

    "scripts": { "gulp": "gulp" }

  4. Run gulp.

    npm run gulp

This worked for me.

Rails: How to reference images in CSS within Rails 4

The hash is because the asset pipeline and server Optimize caching http://guides.rubyonrails.org/asset_pipeline.html

Try something like this:

 background-image: url(image_path('check.png'));

Goodluck

Is "&#160;" a replacement of "&nbsp;"?

  • &nbsp; is the character entity reference (meant to be easily parseable by humans).
  • &#160; is the numeric entity reference (meant to be easily parseable by machines).

They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.

You can read more about character entity references in the offical W3C documents.

How to read pickle file?

The following is an example of how you might write and read a pickle file. Note that if you keep appending pickle data to the file, you will need to continue reading from the file until you find what you want or an exception is generated by reaching the end of the file. That is what the last function does.

import os
import pickle


PICKLE_FILE = 'pickle.dat'


def main():
    # append data to the pickle file
    add_to_pickle(PICKLE_FILE, 123)
    add_to_pickle(PICKLE_FILE, 'Hello')
    add_to_pickle(PICKLE_FILE, None)
    add_to_pickle(PICKLE_FILE, b'World')
    add_to_pickle(PICKLE_FILE, 456.789)
    # load & show all stored objects
    for item in read_from_pickle(PICKLE_FILE):
        print(repr(item))
    os.remove(PICKLE_FILE)


def add_to_pickle(path, item):
    with open(path, 'ab') as file:
        pickle.dump(item, file, pickle.HIGHEST_PROTOCOL)


def read_from_pickle(path):
    with open(path, 'rb') as file:
        try:
            while True:
                yield pickle.load(file)
        except EOFError:
            pass


if __name__ == '__main__':
    main()

CSS file not refreshing in browser

Is this a local custom CSS file? Is this your website? Maybe you should clear your cache.

Also the last CSS declaration takes precedence.

env: node: No such file or directory in mac

NOTE: Only mac users!

  1. uninstall node completely with the commands
curl -ksO https://gist.githubusercontent.com/nicerobot/2697848/raw/uninstall-node.sh
chmod +x ./uninstall-node.sh
./uninstall-node.sh
rm uninstall-node.sh

Or you could check out this website: How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

if this doesn't work, you need to remove node via control panel or any other method. As long as it gets removed.

  1. Install node via this website: https://nodejs.org/en/download/

If you use nvm, you can use:

nvm install node

You can already check if it works, then you don't need to take the following steps with: npm -v and then node -v

if you have nvm installed: command -v nvm

  1. Uninstall npm using the following command:

sudo npm uninstall npm -g

Or, if that fails, get the npm source code, and do:

sudo make uninstall

If you have nvm installed, then use: nvm uninstall npm

  1. Install npm using the following command: npm install -g grunt

How to solve java.lang.OutOfMemoryError trouble in Android

I see only two options:

  1. You have memory leaks in your application.
  2. Devices do not have enough memory when running your application.

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

As of Oct 2019, SQL Server Management Studio, they did not upgraded the SSMS to add create ER Diagram feature.

I would suggest try using DBWeaver from here :

https://dbeaver.io/download/

I am using Mac and Windows both and I was able to download the community edition and logged into my SQL server database and was able to create the ER diagram using the DB Weaver.

ER Diagram using the Community Version Db Viewer

What is the difference between Views and Materialized Views in Oracle?

Adding to Mike McAllister's pretty-thorough answer...

Materialized views can only be set to refresh automatically through the database detecting changes when the view query is considered simple by the compiler. If it's considered too complex, it won't be able to set up what are essentially internal triggers to track changes in the source tables to only update the changed rows in the mview table.

When you create a materialized view, you'll find that Oracle creates both the mview and as a table with the same name, which can make things confusing.

Writing a new line to file in PHP (line feed)

You can also use file_put_contents():

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);

Install Node.js on Ubuntu

You can also compile it from source like this

git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install

Find detailed instructions here http://howtonode.org/how-to-install-nodejs

How to query all the GraphQL type fields without writing a long query?

Package graphql-type-json supports custom-scalars type JSON. Use it can show all the field of your json objects. Here is the link of the example in ApolloGraphql Server. https://www.apollographql.com/docs/apollo-server/schema/scalars-enums/#custom-scalars

How to read strings from a Scanner in a Java console application?

You are entering a null value to nextInt, it will fail if you give a null value...

i have added a null check to the piece of code

Try this code:

import java.util.Scanner;
class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                     eid=(scanner.nextInt());
                System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
                System.out.println("Enter SupervisiorId:");
                    if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                     sid=scanner.nextInt();
                     }//null check
        }
}

Comparing Arrays of Objects in JavaScript

I have worked a bit on a simple algorithm to compare contents of two objects and return an intelligible list of difference. Thought I would share. It borrows some ideas for jQuery, namely the map function implementation and the object and array type checking.

It returns a list of "diff objects", which are arrays with the diff info. It's very simple.

Here it is:

// compare contents of two objects and return a list of differences
// returns an array where each element is also an array in the form:
// [accessor, diffType, leftValue, rightValue ]
//
// diffType is one of the following:
//   value: when primitive values at that index are different
//   undefined: when values in that index exist in one object but don't in 
//              another; one of the values is always undefined
//   null: when a value in that index is null or undefined; values are
//         expressed as boolean values, indicated wheter they were nulls
//   type: when values in that index are of different types; values are 
//         expressed as types
//   length: when arrays in that index are of different length; values are
//           the lengths of the arrays
//

function DiffObjects(o1, o2) {
    // choose a map() impl.
    // you may use $.map from jQuery if you wish
    var map = Array.prototype.map?
        function(a) { return Array.prototype.map.apply(a, Array.prototype.slice.call(arguments, 1)); } :
        function(a, f) { 
            var ret = new Array(a.length), value;
            for ( var i = 0, length = a.length; i < length; i++ ) 
                ret[i] = f(a[i], i);
            return ret.concat();
        };

    // shorthand for push impl.
    var push = Array.prototype.push;

    // check for null/undefined values
    if ((o1 == null) || (o2 == null)) {
        if (o1 != o2)
            return [["", "null", o1!=null, o2!=null]];

        return undefined; // both null
    }
    // compare types
    if ((o1.constructor != o2.constructor) ||
        (typeof o1 != typeof o2)) {
        return [["", "type", Object.prototype.toString.call(o1), Object.prototype.toString.call(o2) ]]; // different type

    }

    // compare arrays
    if (Object.prototype.toString.call(o1) == "[object Array]") {
        if (o1.length != o2.length) { 
            return [["", "length", o1.length, o2.length]]; // different length
        }
        var diff =[];
        for (var i=0; i<o1.length; i++) {
            // per element nested diff
            var innerDiff = DiffObjects(o1[i], o2[i]);
            if (innerDiff) { // o1[i] != o2[i]
                // merge diff array into parent's while including parent object name ([i])
                push.apply(diff, map(innerDiff, function(o, j) { o[0]="[" + i + "]" + o[0]; return o; }));
            }
        }
        // if any differences were found, return them
        if (diff.length)
            return diff;
        // return nothing if arrays equal
        return undefined;
    }

    // compare object trees
    if (Object.prototype.toString.call(o1) == "[object Object]") {
        var diff =[];
        // check all props in o1
        for (var prop in o1) {
            // the double check in o1 is because in V8 objects remember keys set to undefined 
            if ((typeof o2[prop] == "undefined") && (typeof o1[prop] != "undefined")) {
                // prop exists in o1 but not in o2
                diff.push(["[" + prop + "]", "undefined", o1[prop], undefined]); // prop exists in o1 but not in o2

            }
            else {
                // per element nested diff
                var innerDiff = DiffObjects(o1[prop], o2[prop]);
                if (innerDiff) { // o1[prop] != o2[prop]
                    // merge diff array into parent's while including parent object name ([prop])
                    push.apply(diff, map(innerDiff, function(o, j) { o[0]="[" + prop + "]" + o[0]; return o; }));
                }

            }
        }
        for (var prop in o2) {
            // the double check in o2 is because in V8 objects remember keys set to undefined 
            if ((typeof o1[prop] == "undefined") && (typeof o2[prop] != "undefined")) {
                // prop exists in o2 but not in o1
                diff.push(["[" + prop + "]", "undefined", undefined, o2[prop]]); // prop exists in o2 but not in o1

            }
        }
        // if any differences were found, return them
        if (diff.length)
            return diff;
        // return nothing if objects equal
        return undefined;
    }
    // if same type and not null or objects or arrays
    // perform primitive value comparison
    if (o1 != o2)
        return [["", "value", o1, o2]];

    // return nothing if values are equal
    return undefined;
}

Matplotlib make tick labels font size smaller

For smaller font, I use

ax1.set_xticklabels(xticklabels, fontsize=7)

and it works!

database attached is read only

Another Way which worked for me is:

After dettaching before you attach

  • -> go to the .mdf file -> right click & select properties on the file -> security tab -> Check Group or usernames:

    for your name\account (optional) and for "NT SERVICE\MSSQLSERVER"(NB)

List item

-> if not there than click on edit button -> click on add button

  and enter\search NT SERVICE\MSSQLSERVER
  • -> click on OK -> give full rights -> apply then ok

    then ok again do this for .ldf file too.

then attach

Laravel Eloquent LEFT JOIN WHERE NULL

I would be using laravel whereDoesntHave to achieve this.

Customer::whereDoesntHave('orders')->get();

apache server reached MaxClients setting, consider raising the MaxClients setting

When you use Apache with mod_php apache is enforced in prefork mode, and not worker. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).

So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :

StartServers       20
MinSpareServers    5
MaxSpareServers    10
MaxClients         1024
MaxRequestsPerChild  0

This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.

See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.

Now you set 1024 MaxClients. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.

So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:

<IfModule prefork.c>
  StartServers       12
  MinSpareServers    12
  MaxSpareServers    12
  MaxClients         12
  MaxRequestsPerChild  300
</IfModule>

That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300 means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the ListenBacklog queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).

And yes, that means you cannot handle more than 12 parallel requests.

If you want to handle more requests:

  • buy some more RAM
  • try to use apache in worker mode, but remove mod_php and use php as a parallel daemon with his own pooler settings (this is called php-fpm), connect it with fastcgi. Note that you will certainly need to buy some RAM to allow a big number of parallel php-fpm process, but maybe less than with mod_php
  • Reduce the time spent in your php process. From your cacti graphs you have to potential problems: a real traffic peak around 11:25-11:30 or some php code getting very slow. Fast requests will reduce the number of parallel requests.

If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?

And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.

Update: About internal dummy connections (if it's your problem, but maybe not).

Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.

If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:

  RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
  RewriteRule .* - [F,L]

Update:

Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.

Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l or apache2 -l on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:

<IfModule worker.c>
  StartServers           3
  MaxClients           500
  MinSpareThreads       75
  MaxSpareThreads      250 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:

<IfModule worker.c>
  StartServers           2
  MaxClients           250
  MinSpareThreads       50
  MaxSpareThreads      150 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

SQL query for finding records where count > 1

I wouldn't recommend the HAVING keyword for newbies, it is essentially for legacy purposes.

I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:

I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.

So I've taken a literal interpretation.

The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES but it could be a VIEW:

WITH PAYMENT_TALLIES (user_id, zip, tally)
     AS
     (
      SELECT user_id, zip, COUNT(*) AS tally
        FROM PAYMENT
       GROUP 
          BY user_id, zip
     )
SELECT DISTINCT *
  FROM PAYMENT AS P
 WHERE EXISTS (
               SELECT * 
                 FROM PAYMENT_TALLIES AS PT
                WHERE P.user_id = PT.user_id
                      AND PT.tally > 1
              );

How to Validate on Max File Size in Laravel?

According to the documentation:

$validator = Validator::make($request->all(), [
    'file' => 'max:500000',
]);

The value is in kilobytes. I.e. max:10240 = max 10 MB.

Show DataFrame as table in iPython Notebook

To display dataframes contained in a list:

display(*dfs)

Add ... if string is too long PHP

<?php
function truncate($string, $length, $stopanywhere=false) {
    //truncates a string to a certain char length, stopping on a word if not specified otherwise.
    if (strlen($string) > $length) {
        //limit hit!
        $string = substr($string,0,($length -3));
        if ($stopanywhere) {
            //stop anywhere
            $string .= '...';
        } else{
            //stop on a word.
            $string = substr($string,0,strrpos($string,' ')).'...';
        }
    }
    return $string;
}
?>

I use the above code snippet many-a-times..

Difference between a Seq and a List in Scala

Seq is a trait that List implements.

If you define your container as Seq, you can use any container that implements Seq trait.

scala> def sumUp(s: Seq[Int]): Int = { s.sum }
sumUp: (s: Seq[Int])Int

scala> sumUp(List(1,2,3))
res41: Int = 6

scala> sumUp(Vector(1,2,3))
res42: Int = 6

scala> sumUp(Seq(1,2,3))
res44: Int = 6

Note that

scala> val a = Seq(1,2,3)
a: Seq[Int] = List(1, 2, 3)

Is just a short hand for:

scala> val a: Seq[Int] = List(1,2,3)
a: Seq[Int] = List(1, 2, 3)

if the container type is not specified, the underlying data structure defaults to List.

how to use sqltransaction in c#

First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like

sqlCommand.Transaction = transaction;

And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like

sqlCommand.CommandText = "select * from table1";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = "select * from table2";
sqlCommand.ExecuteNonQuery();

What is the best way to initialize a JavaScript Date to midnight?

You can probably use

new Date().setUTCHours(0,0,0,0)

if you need the value only once.

how to use DEXtoJar

  1. Download Dex2jar and Extract it.
  2. Go to Download path ./d2j-dex2jar.sh /path-to-your/someApk.apk if .sh is not compilable, update the permission: chmod a+x d2j-dex2jar.sh.
  3. It will generate .jar file.
  4. Now use the jar with JD-GUI to decompile it

npm - EPERM: operation not permitted on Windows

I updated my node version to 8.9.4 and ran the necessary install command again from administrator command prompt. It worked for me!

Convert list to tuple in Python

I find many answers up to date and properly answered but will add something new to stack of answers.

In python there are infinite ways to do this, here are some instances
Normal way

>>> l= [1,2,"stackoverflow","python"]
>>> l
[1, 2, 'stackoverflow', 'python']
>>> tup = tuple(l)
>>> type(tup)
<type 'tuple'>
>>> tup
(1, 2, 'stackoverflow', 'python')

smart way

>>>tuple(item for item in l)
(1, 2, 'stackoverflow', 'python')

Remember tuple is immutable ,used for storing something valuable. For example password,key or hashes are stored in tuples or dictionaries. If knife is needed why to use sword to cut apples. Use it wisely, it will also make your program efficient.

Where value in column containing comma delimited values

Since you don't know how many comma-delimited entries you can find, you may need to create a function with 'charindex' and 'substring' SQL Server functions. Values, as returned by the function could be used in a 'in' expression.

You function can be recursively invoked or you can create loop, searching for entries until no more entries are present in the string. Every call to the function uses the previous found index as the starting point of the next call. The first call starts at 0.

How to update Identity Column in SQL Server?

DBCC CHECKIDENT(table_name, RESEED, value)

table_name = give the table you want to reset value

value=initial value to be zero,to start identity column with 1

Parsing xml using powershell

[xml]$xmlfile = '<xml> <Section name="BackendStatus"> <BEName BE="crust" Status="1" /> <BEName BE="pizza" Status="1" /> <BEName BE="pie" Status="1" /> <BEName BE="bread" Status="1" /> <BEName BE="Kulcha" Status="1" /> <BEName BE="kulfi" Status="1" /> <BEName BE="cheese" Status="1" /> </Section> </xml>'

foreach ($bename in $xmlfile.xml.Section.BEName) {
    if($bename.Status -eq 1){
        #Do something
    }
}

How to format numbers as currency string?

If amount is a number, say -123, then

amount.toLocaleString('en-US', { style: 'currency', currency: 'USD' });

will produce the string "-$123.00".

Here's a complete working example.

Renaming branches remotely in Git

TL;DR

"Renaming" a remote branch is actually a 2 step process (not necessarily ordered):

  • deletion of the old remote branch (git push [space]:<old_name> as ksrb explained);
  • push into a new remote branch (difference between a couple of answers commands below).

Deleting

I use TortoiseGit and when I first tried to delete the branch through the command line, I got this:

$ git push origin :in
  • fatal: 'origin' does not appear to be a git repository

  • fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

This was likely due to pageant not having the private key loaded (which TortoiseGit loads automatically into pageant). Moreover, I noticed that TortoiseGit commands do not have the origin ref in them (e.g. git.exe push --progress "my_project" interesting_local:interesting).

I am also using Bitbucket and, as others web-based online git managers of the sort (GitHub, GitLab), I was able to delete the remote branch directly through their interface (branches page):

Delete branch Bitbucket

However, in TortoiseGit you may also delete remote branches through Browse References:

Browse References menu

By right-clicking on a remote branch (remotes list) the Delete remote branch option shows up:

TortoiseGit remote branch delete

Pushing

After deleting the old remote branch I pushed directly into a new remote branch through TortoiseGit just by typing the new name in the Remote: field of the Push window and this branch was automatically created and visible in Bitbucket.

However, if you still prefer to do it manually, a point that has not been mentioned yet in this thread is that -u = --set-upstream.

From git push docs, -u is just an alias of --set-upstream, so the commands in the answers of Sylvain (-set-upstream new-branch) and Shashank (-u origin new_branch) are equivalent, since the remote ref defaults to origin if no other ref was previously defined:

  • git push origin -u new_branch = git push -u new_branch from the docs description:

    If the configuration is missing, it defaults to origin.

In the end, I did not manually type in or used any of the commands suggested by the other answers in here, so perhaps this might be useful to others in a similar situation.

Can't connect to docker from docker-compose

$sudo docker-compose up

I did follow the steps as it is in the above answer to add $USER to group docker. i didn't want to add a new group docker because in my docker installation a group named docker automatically created.

Docker CE is installed and running. The docker group is created but no users are added to it. You need to use sudo to run Docker commands. Continue to Linux postinstall to allow non-privileged users to run Docker commands and for other optional configuration steps.

but using docker-compose up didn't work either. It gave the same previous error. So in my case(Ubuntu 18.10) sudo docker-compose up fixed the issue.

ps: @Tiw thanks for the advice.

Generating a WSDL from an XSD file

You cannot - a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.

These are really two separate, distinctive parts of the equation. For simplicity's sake you would often import your XSD definitions into the WSDL in the <wsdl:types> tag.

(thanks to Cheeso for pointing out my inaccurate usage of terms)

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

This is a helper function for mustacheJS, without pre-formatting the data and instead getting it during render.

var data = {
    valueFromMap: function() {
        return function(text, render) {
            // "this" will be an object with map key property
            // text will be color that we have between the mustache-tags
            // in the template
            // render is the function that mustache gives us

            // still need to loop since we have no idea what the key is
            // but there will only be one
            for ( var key in this) {
                if (this.hasOwnProperty(key)) {
                    return render(this[key][text]);
                }
            }
        };
    },

    list: {
        blueHorse: {
            color: 'blue'
        },

        redHorse: {
            color: 'red'
        }
    }
};

Template:

{{#list}}
    {{#.}}<span>color: {{#valueFromMap}}color{{/valueFromMap}}</span> <br/>{{/.}}
{{/list}}

Outputs:

color: blue
color: red

(order might be random - it's a map) This might be useful if you know the map element that you want. Just watch out for falsy values.

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

This is the script I use. A bit tricky but it works. Tested on SQL Server 2012.

DECLARE @backupPath nvarchar(400);
DECLARE @sourceDb nvarchar(50);
DECLARE @sourceDb_log nvarchar(50);
DECLARE @destDb nvarchar(50);
DECLARE @destMdf nvarchar(100);
DECLARE @destLdf nvarchar(100);
DECLARE @sqlServerDbFolder nvarchar(100);

SET @sourceDb = 'db1'
SET @sourceDb_log = @sourceDb + '_log'
SET @backupPath = 'E:\tmp\' + sourceDb + '.bak' --ATTENTION: file must already exist and SQL Server must have access to it
SET @sqlServerDbFolder = 'E:\DB SQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\'
SET @destDb = 'db2'
SET @destMdf = @sqlServerDbFolder + @destDb + '.mdf'
SET @destLdf = @sqlServerDbFolder + @destDb + '_log' + '.ldf'

BACKUP DATABASE @sourceDb TO DISK = @backupPath

RESTORE DATABASE @destDb FROM DISK = @backupPath
WITH REPLACE,
   MOVE @sourceDb     TO @destMdf,
   MOVE @sourceDb_log TO @destLdf

How to subtract 30 days from the current datetime in mysql?

another way

SELECT COUNT(*) FROM tbl_debug WHERE TO_DAYS(`when`) < TO_DAYS(NOW())-30 ;

C# 'or' operator?

Also worth mentioning, in C# the OR operator is short-circuiting. In your example, Close seems to be a property, but if it were a method, it's worth noting that:

if (ActionsLogWriter.Close() || ErrorDumpWriter.Close())

is fundamentally different from

if (ErrorDumpWriter.Close() || ActionsLogWriter.Close())

In C#, if the first expression returns true, the second expression will not be evaluated at all. Just be aware of this. It actually works to your advantage most of the time.

INSERT INTO @TABLE EXEC @query with SQL Server 2000

N.B. - this question and answer relate to the 2000 version of SQL Server. In later versions, the restriction on INSERT INTO @table_variable ... EXEC ... were lifted and so it doesn't apply for those later versions.


You'll have to switch to a temp table:

CREATE TABLE #tmp (code varchar(50), mount money)
DECLARE @q nvarchar(4000)
SET @q = 'SELECT coa_code, amount FROM T_Ledger_detail'

INSERT INTO  #tmp (code, mount)
EXEC sp_executesql (@q)

SELECT * from #tmp

From the documentation:

A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared.

Within its scope, a table variable may be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table may not be used in the following statements:

INSERT INTO table_variable EXEC stored_procedure

SELECT select_list INTO table_variable statements.

Why does Google prepend while(1); to their JSON responses?

As this is a High traffic post i hope to provide here an answer slightly more undetermined to the original question and thus to provide further background on a JSON Hijacking attack and its consequences

JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:

[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"}, 
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"}, 
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]

This attack can be achieved in 3 major steps:

Step 1: Get an authenticated user to visit a malicious page. Step 2: The malicious page will try and access sensitive data from the application that the user is logged into.This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.

<script src="http://<jsonsite>/json_server.php"></script>

The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request. Step 3: At this point while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.

Object.prototype.__defineSetter__('ccnum',function(obj){

secrets =secrets.concat(" ", obj);

});

At this point the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php JSON

It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.

There are several ways in which JSON Hijacking can be prevented:

  • Since SCRIPT tags can only generate HTTP GET requests, only return JSON objects to POST requests.

  • Prevent the web browser from interpreting the JSON object as valid JavaScript code.

  • Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.

so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop which will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed.Alas, If you read the JSON block with a parser, the while(1) loop is ignored.

So in conclusion, the while(1) loop can more easily visualised as a simple break statement cipher that google can use to control flow of data.

However the key word in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has preventative measures embedded and the system is not crucial nor effective anymore. (part of this is the move away from JSON Hijacking to more fruitful datafarming techniques that i wont go into at present)

*

Table Height 100% inside Div element

You need to have a height in the div <div style="overflow:hidden"> else it doesnt know what 100% is.

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

Give this a try

<style type="text/css">

form {width:400px;}

#text1 {float:right;}

#text2 {float:left;}

</style>

then

<form id="form1" name="form1" method="post" action="">


 <label id="text1">Company Name<br />
   <input type="text" name="textfield2" id="textfield2" />
 </label>

 <label id="text2">Contact Name<br />
   <input type="text" name="textfield" id="textfield" />
 </label>


</form>

Test Page: http://jsbin.com/ahelo4

Works for me in the latest versions of Firefox, Safari, Chrome, Opera. Not 100% sure about IE though as im on a Mac, but I cant see why it wouldn't :)

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

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

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

An example CSS could be as simple as this:

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

  body .printable {
    display:block;
  }
}

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

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

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

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

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

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

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

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

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

UPDATE: 2019-12-30

It seem that this tool is no longer working! [Request for update!]

UPDATE 2019-01-06: You can bypass X-Frame-Options in an <iframe> using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.

You can use it as follows:

  1. (Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:

    <script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
    
  2. Include the X-Frame-Bypass JS module:

    <script type="module" src="x-frame-bypass.js"></script>
    
  3. Insert the X-Frame-Bypass Custom Element:

    <iframe is="x-frame-bypass" src="https://example.org/"></iframe>
    

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

Is there a difference between using a dict literal and a dict constructor?

From python 2.7 tutorial:

A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

tel = {'jack': 4098, 'sape': 4139}
data = {k:v for k,v in zip(xrange(10), xrange(10,20))}

While:

The dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples. When the pairs form a pattern, list comprehensions can compactly specify the key-value list.

tel = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
data = dict((k,v) for k,v in zip(xrange(10), xrange(10,20)))

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

dict(sape=4139, guido=4127, jack=4098)
>>>  {'sape': 4139, 'jack':4098, 'guido': 4127}

So both {} and dict() produce dictionary but provide a bit different ways of dictionary data initialization.

Log4j: How to configure simplest possible file logging?

Here is a log4j.properties file that I've used with great success.

logDir=/var/log/myapp

log4j.rootLogger=INFO, stdout
#log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM/dd/yyyy hh:mm:ss a}|%-5p|%-30c{1}| %m%n
log4j.appender.stdout.DatePattern='.'yyyy-MM-dd
log4j.appender.stdout.File=${logDir}/myapp.log
log4j.appender.stdout.append=true

The DailyRollingFileAppender will create new files each day with file names that look like this:

myapp.log.2017-01-27
myapp.log.2017-01-28
myapp.log.2017-01-29
myapp.log  <-- today's log

Each entry in the log file will will have this format:

01/30/2017 12:59:47 AM|INFO |Component1   | calling foobar(): userId=123, returning totalSent=1
01/30/2017 12:59:47 AM|INFO |Component2   | count=1 > 0, calling fooBar()

Set the location of the above file by using -Dlog4j.configuration, as mentioned in this posting:

java -Dlog4j.configuration=file:/home/myapp/config/log4j.properties com.foobar.myapp

In your Java code, be sure to set the name of each software component when you instantiate your logger object. I also like to log to both the log file and standard output, so I wrote this small function.

private static final Logger LOGGER = Logger.getLogger("Component1");

public static void log(org.apache.log4j.Logger logger, String message) {

    logger.info(message);
    System.out.printf("%s\n", message);
}

public static String stackTraceToString(Exception ex) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ex.printStackTrace(pw);
    return sw.toString();
}

And then call it like so:

LOGGER.info(String.format("Exception occurred: %s", stackTraceToString(ex)));

How to pass an array into a function, and return the results with an array

I always return multiple values by using a combination of list() and array()s:

function DecideStuffToReturn() {
    $IsValid = true;
    $AnswerToLife = 42;

    // Build the return array.
    return array($IsValid, $AnswerToLife);
}

// Part out the return array in to multiple variables.
list($IsValid, $AnswerToLife) = DecideStuffToReturn();

You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.

See list() for more information.

How to check whether an array is empty using PHP?

If you want to ascertain whether the variable you are testing is actually explicitly an empty array, you could use something like this:

if ($variableToTest === array()) {
    echo 'this is explicitly an empty array!';
}

Function not defined javascript

I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.

Returning JSON from a PHP Script

In case you're doing this in WordPress, then there is a simple solution:

add_action( 'parse_request', function ($wp) {
    $data = /* Your data to serialise. */
    wp_send_json_success($data); /* Returns the data with a success flag. */
    exit(); /* Prevents more response from the server. */
})

Note that this is not in the wp_head hook, which will always return most of the head even if you exit immediately. The parse_request comes a lot earlier in the sequence.

Git diff between current branch and master but not including unmerged master commits

According to Documentation

git diff Shows changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, changes resulting from a merge, changes between two blob objects, or changes between two files on disk.

In git diff - There's a significant difference between two dots .. and 3 dots ... in the way we compare branches or pull requests in our repository. I'll give you an easy example which demonstrates it easily.

Example: Let's assume we're checking out new branch from master and pushing some code in.

  G---H---I feature (Branch)
 /
A---B---C---D master (Branch)
  • Two dots - If we want to show the diffs between all changes happened in the current time on both sides, We would use the git diff origin/master..feature or just git diff origin/master
    ,output: ( H, I against A, B, C, D )

  • Three dots - If we want to show the diffs between the last common ancestor (A), aka the check point we started our new branch ,we use git diff origin/master...feature,output: (H, I against A ).

  • I'd rather use the 3 dots in most circumstances.

What is the attribute property="og:title" inside meta tag?

og:title is one of the open graph meta tags. og:... properties define objects in a social graph. They are used for example by Facebook.

og:title stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )

Django set field value after a form is initialized

Just change your Form.data field:

class ChooseProjectForm(forms.Form):
    project = forms.ModelChoiceField(queryset=project_qs)
    my_projects = forms.BooleanField()

    def __init__(self, *args, **kwargs):
        super(ChooseProjectForm, self).__init__(*args, **kwargs)
        self.data = self.data.copy()  # IMPORTANT, self.data is immutable
        # any condition:
        if self.data.get('my_projects'):
            my_projects = self.fields['project'].queryset.filter(my=True)
            self.fields['project'].queryset = my_projects
            self.fields['project'].initial = my_projects.first().pk
            self.fields['project'].empty_label = None  # disable "-----"
            self.data.update(project=my_projects.first().pk)  # Update Form data
            self.fields['project'].widget = forms.HiddenInput()  # Hide if you want

How to delete a file after checking whether it exists

You could import the System.IO namespace using:

using System.IO;

If the filepath represents the full path to the file, you can check its existence and delete it as follows:

if(File.Exists(filepath))
{
     try
    {
         File.Delete(filepath);
    } 
    catch(Exception ex)
    {
      //Do something
    } 
}  

Why doesn't logcat show anything in my Android?

This is simple.

Just close the Logcat from eclipse.

Then reopen it by following steps in Eclipse.

Window - Show View - Other - Android - LogCat - ok

Hope this solves your problem.

Converting a float to a string without rounding it

Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.

Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:

http://docs.python.org/library/decimal.html

Among other things you can explicitly specify the precision that you wish to obtain (from the docs):

>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

A simple example from my prompt (python 2.6):

>>> import decimal
>>> a = decimal.Decimal('10.000000001')
>>> a
Decimal('10.000000001')
>>> print a
10.000000001
>>> b = decimal.Decimal('10.00000000000000000000000000900000002')
>>> print b
10.00000000000000000000000000900000002
>>> print str(b)
10.00000000000000000000000000900000002
>>> len(str(b/decimal.Decimal('3.0')))
29

Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.

Hope this helps, Francesco

What causes a TCP/IP reset (RST) flag to be sent?

Run a packet sniffer (e.g., Wireshark) also on the peer to see whether it's the peer who's sending the RST or someone in the middle.

How to change button background image on mouseOver?

I think something like this:

btn.BackgroundImage = Properties.Resources.*Image_Identifier*;

Where *Image_Identifier* is an identifier of the image in your resources.

Opening Android Settings programmatically

You can make another class for doing this kind of activities.

public class Go {

   public void Setting(Context context)
    {
        Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}

How can I permanently enable line numbers in IntelliJ?

Android Studio

Go to Android Studio => Preferences => Editor => General => Appearance => set Checked "Show line numbers"

enter image description here

StringBuilder vs String concatenation in toString() in Java

I also had clash with my boss on the fact whether to use append or +.As they are using Append(I still cant figure out as they say every time a new object is created). So I thought to do some R&D.Although I love Michael Borgwardt explaination but just wanted to show an explanation if somebody will really need to know in future.

/**
 *
 * @author Perilbrain
 */
public class Appc {
    public Appc() {
        String x = "no name";
        x += "I have Added a name" + "We May need few more names" + Appc.this;
        x.concat(x);
        // x+=x.toString(); --It creates new StringBuilder object before concatenation so avoid if possible
        //System.out.println(x);
    }

    public void Sb() {
        StringBuilder sbb = new StringBuilder("no name");
        sbb.append("I have Added a name");
        sbb.append("We May need few more names");
        sbb.append(Appc.this);
        sbb.append(sbb.toString());
        // System.out.println(sbb.toString());
    }
}

and disassembly of above class comes out as

 .method public <init>()V //public Appc()
  .limit stack 2
  .limit locals 2
met001_begin:                                  ; DATA XREF: met001_slot000i
  .line 12
    aload_0 ; met001_slot000
    invokespecial java/lang/Object.<init>()V
  .line 13
    ldc "no name"
    astore_1 ; met001_slot001
  .line 14

met001_7:                                      ; DATA XREF: met001_slot001i
    new java/lang/StringBuilder //1st object of SB
    dup
    invokespecial java/lang/StringBuilder.<init>()V
    aload_1 ; met001_slot001
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lan\
g/StringBuilder;
    ldc "I have Added a nameWe May need few more names"
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lan\
g/StringBuilder;
    aload_0 ; met001_slot000
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/Object;)Ljava/lan\
g/StringBuilder;
    invokevirtual java/lang/StringBuilder.toString()Ljava/lang/String;
    astore_1 ; met001_slot001
  .line 15
    aload_1 ; met001_slot001
    aload_1 ; met001_slot001
    invokevirtual java/lang/String.concat(Ljava/lang/String;)Ljava/lang/Strin\
g;
    pop
  .line 18
    return //no more SB created
met001_end:                                    ; DATA XREF: met001_slot000i ...

; ===========================================================================

;met001_slot000                                ; DATA XREF: <init>r ...
    .var 0 is this LAppc; from met001_begin to met001_end
;met001_slot001                                ; DATA XREF: <init>+6w ...
    .var 1 is x Ljava/lang/String; from met001_7 to met001_end
  .end method
;44-1=44
; ---------------------------------------------------------------------------


; Segment type: Pure code
  .method public Sb()V //public void Sb
  .limit stack 3
  .limit locals 2
met002_begin:                                  ; DATA XREF: met002_slot000i
  .line 21
    new java/lang/StringBuilder
    dup
    ldc "no name"
    invokespecial java/lang/StringBuilder.<init>(Ljava/lang/String;)V
    astore_1 ; met002_slot001
  .line 22

met002_10:                                     ; DATA XREF: met002_slot001i
    aload_1 ; met002_slot001
    ldc "I have Added a name"
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lan\
g/StringBuilder;
    pop
  .line 23
    aload_1 ; met002_slot001
    ldc "We May need few more names"
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lan\
g/StringBuilder;
    pop
  .line 24
    aload_1 ; met002_slot001
    aload_0 ; met002_slot000
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/Object;)Ljava/lan\
g/StringBuilder;
    pop
  .line 25
    aload_1 ; met002_slot001
    aload_1 ; met002_slot001
    invokevirtual java/lang/StringBuilder.toString()Ljava/lang/String;
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lan\
g/StringBuilder;
    pop
  .line 28
    return
met002_end:                                    ; DATA XREF: met002_slot000i ...


;met002_slot000                                ; DATA XREF: Sb+25r
    .var 0 is this LAppc; from met002_begin to met002_end
;met002_slot001                                ; DATA XREF: Sb+9w ...
    .var 1 is sbb Ljava/lang/StringBuilder; from met002_10 to met002_end
  .end method
;96-49=48
; ---------------------------------------------------------------------------

From the above two codes you can see Michael is right.In each case only one SB object is created.

How to convert rdd object to dataframe in spark

I tried to explain the solution using the word count problem. 1. Read the file using sc

  1. Produce word count
  2. Methods to create DF

    • rdd.toDF method
    • rdd.toDF("word","count")
      • spark.createDataFrame(rdd,schema)

    Read file using spark

    val rdd=sc.textFile("D://cca175/data/")  
    

    Rdd to Dataframe

    val df=sc.textFile("D://cca175/data/").toDF("t1") df.show

    Method 1

    Create word count RDD to Dataframe

    val df=rdd.flatMap(x=>x.split(" ")).map(x=>(x,1)).reduceByKey((x,y)=>(x+y)).toDF("word","count")
    

    Method2

    Create Dataframe from Rdd

    val df=spark.createDataFrame(wordRdd) 
    # with header   
    val df=spark.createDataFrame(wordRdd).toDF("word","count")  df.show
    

    Method3

    Define Schema

    import org.apache.spark.sql.types._

    val schema=new StructType(). add(StructField("word",StringType,true)). add(StructField("count",StringType,true))

    Create RowRDD

    import org.apache.spark.sql.Row
    val rowRdd=wordRdd.map(x=>(Row(x._1,x._2)))     
    

    Create DataFrame from RDD with schema

    val df=spark.createDataFrame(rowRdd,schema)
    df.show

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

I am quoting this answer from official tensorflow docs https://www.tensorflow.org/api_guides/python/nn#Convolution For the 'SAME' padding, the output height and width are computed as:

out_height = ceil(float(in_height) / float(strides[1]))
out_width  = ceil(float(in_width) / float(strides[2]))

and the padding on the top and left are computed as:

pad_along_height = max((out_height - 1) * strides[1] +
                    filter_height - in_height, 0)
pad_along_width = max((out_width - 1) * strides[2] +
                   filter_width - in_width, 0)
pad_top = pad_along_height // 2
pad_bottom = pad_along_height - pad_top
pad_left = pad_along_width // 2
pad_right = pad_along_width - pad_left

For the 'VALID' padding, the output height and width are computed as:

out_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))
out_width  = ceil(float(in_width - filter_width + 1) / float(strides[2]))

and the padding values are always zero.

Style bottom Line in Android

it is completely transparent Edittext with transparent background.

<item>
    <shape android:shape="rectangle" >
        <solid android:color="@color/transparent" />
    </shape>
</item>

<item android:top="-3dp" android:right="-3dp" android:left="-3dp">
    <shape>
        <solid android:color="@android:color/transparent" />
        <stroke

            android:width="2dp"
            android:color="@color/bottomline" />
    </shape>
</item>

How to change the docker image installation directory?

For Mac users in the 17.06.0-ce-mac19 version you can simply move the Disk Image location from the user interface in the preferences option Just change the location of the disk image and it will work (by clicking Move disk Image) and restarting the docker. Using this approach I was able to use my external hardisk for storing docker images.

Can't load IA 32-bit .dll on a AMD 64-bit platform

I had a problem when run red5(tomcat) on Windows x64 that previous worked under Windows x32, got next error:

 INFO pool-15-thread-1 com.home.launcher.CommandLauncher - Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\....\lib\Data Samolet.dll: Can't find dependent libraries
INFO pool-15-thread-1 com.home.launcher.CommandLauncher - at java.lang.ClassLoader$NativeLibrary.load(Native Method)

Problem solved when I installed Java x32 version and set next

"Environment variables"

"User variables for Home"

JAVA_HOME => C:\Program Files (x86)\Java\jdk.1.6.0_45

"System variables"

Path[at the beginning] => C:\Program Files\Java\jdk.1.8.0_60;..

Is it possible to run a .NET 4.5 app on XP?

Sadly, no, you can't run 4.5 programs on XP.

And the relevant post from that Connect page:

Posted by Microsoft on 23/03/2012 at 10:39
Thanks for the report. This behavior is by design in .NET Framework 4.5 Beta. The minimum supported operating systems are Windows 7, Windows Server 2008 SP2 and Windows Server 2008 R2 SP1. Windows XP is not a supported operating system for the Beta release.

How to convert currentTimeMillis to a date in Java?

Below is my solution to get date from miliseconds to date format. You have to use Joda Library to get this code run.

import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class time {

    public static void main(String args[]){

        String str = "1431601084000";
        long geTime= Long.parseLong(str);
        GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
        calendar.setTimeInMillis(geTime);
        DateTime jodaTime = new DateTime(geTime, 
               DateTimeZone.forTimeZone(TimeZone.getTimeZone("US/Central")));
        DateTimeFormatter parser1 = DateTimeFormat.forPattern("yyyy-MM-dd");
        System.out.println("Get Time : "+parser1.print(jodaTime));

   }
}

How to asynchronously call a method in Java

There is also nice library for Async-Await created by EA: https://github.com/electronicarts/ea-async

From their Readme:

With EA Async

import static com.ea.async.Async.await;
import static java.util.concurrent.CompletableFuture.completedFuture;

public class Store
{
    public CompletableFuture<Boolean> buyItem(String itemTypeId, int cost)
    {
        if(!await(bank.decrement(cost))) {
            return completedFuture(false);
        }
        await(inventory.giveItem(itemTypeId));
        return completedFuture(true);
    }
}

Without EA Async

import static java.util.concurrent.CompletableFuture.completedFuture;

public class Store
{
    public CompletableFuture<Boolean> buyItem(String itemTypeId, int cost)
    {
        return bank.decrement(cost)
            .thenCompose(result -> {
                if(!result) {
                    return completedFuture(false);
                }
                return inventory.giveItem(itemTypeId).thenApply(res -> true);
            });
    }
}

Difference between array_map, array_walk and array_filter

The idea of mapping an function to array of data comes from functional programming. You shouldn't think about array_map as a foreach loop that calls a function on each element of the array (even though that's how it's implemented). It should be thought of as applying the function to each element in the array independently.

In theory such things as function mapping can be done in parallel since the function being applied to the data should ONLY affect the data and NOT the global state. This is because an array_map could choose any order in which to apply the function to the items in (even though in PHP it doesn't).

array_walk on the other hand it the exact opposite approach to handling arrays of data. Instead of handling each item separately, it uses a state (&$userdata) and can edit the item in place (much like a foreach loop). Since each time an item has the $funcname applied to it, it could change the global state of the program and therefor requires a single correct way of processing the items.

Back in PHP land, array_map and array_walk are almost identical except array_walk gives you more control over the iteration of data and is normally used to "change" the data in-place vs returning a new "changed" array.

array_filter is really an application of array_walk (or array_reduce) and it more-or-less just provided for convenience.

how to add jquery in laravel project

you can use online library

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

or else download library and add css in css folder and jquery in js folder.both folder you keep in laravel public folder then you can link like below

<link rel="stylesheet" href="{{asset('css/bootstrap-theme.min.css')}}">
<script src="{{asset('js/jquery.min.js')}}"></script>

or else

{{ HTML::style('css/style.css') }}
{{ HTML::script('js/functions.js') }}

Can I style an image's ALT text with CSS?

Sure you can!

http://jsfiddle.net/VfTGW/

I do this as a fallback for header logo images, I think some versions of IE will not abide. Edit: Or Chrome apparently - I don't even see alt text in the demo(?). Firefox works well however.

_x000D_
_x000D_
img {_x000D_
  color: green;_x000D_
  font: 40px Impact;_x000D_
}
_x000D_
<img src="404" alt="Alt Text">
_x000D_
_x000D_
_x000D_

Set custom HTML5 required field validation message

you can just simply using the oninvalid=" attribute, with the bingding the this.setCustomValidity() eventListener!

Here is my demo codes!(you can run it to check out!) enter image description here

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <title>oninvalid</title>_x000D_
</head>_x000D_
<body>_x000D_
    <form action="https://www.google.com.hk/webhp?#safe=strict&q=" method="post" >_x000D_
        <input type="email" placeholder="[email protected]" required="" autocomplete="" autofocus="" oninvalid="this.setCustomValidity(`This is a customlised invalid warning info!`)">_x000D_
        <input type="submit" value="Submit">_x000D_
    </form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

reference link

http://caniuse.com/#feat=form-validation

https://www.w3.org/TR/html51/sec-forms.html#sec-constraint-validation

Simple division in Java - is this a bug or a feature?

Please do not take this as an answer to the question. It is not, but an advice related to exploiting the difference of int and float. I would have put this under a comment except that the answer box allows me to format this comment.

This feature has been used in every respectable programming language since the days of fortran (or earlier) - I must confess I was once a Fortran and Cobol punch card programmer.

As an example, integer division of 10/3 yields integer value 3 since an integer has no facility to hold fractional residual .3333.. .

One of the ways we (old time ancient programmers) had been using this feature is loop control.

Let's say we wish to print an array of 1000 strings, but we wish to insert a line break after every 15th string, to insert some prettyfying chars at the end of the line and at the beginning of the next line. We exploit this, given that integer k is the position of a string in that array.

int(k/15)*15 == k

is true only when k is divisible by 15, an occurrence at a frequency of every 15th cell. Which is akin to what my friend said about his grandfather's dead watch being accurate twice a day.

int(1/15) = 0 -> int(1/15)*15 = 0
int(2/15) = 0 -> int(2/15)*15 = 0
...
int(14/15) = 0 -> int(14/15)*15 = 0
int(15/15) = 1 -> int(15/15)*15 = 15

int(16/15) = 1 -> int(16/15)*15 = 15
int(17/15) = 1 -> int(17/15)*15 = 15
...
int(29/15) = 1 -> int(29/15)*15 = 15
int(30/15) = 2 -> int(30/15)*15 = 30

Therefore, the loop,

leftPrettyfy();
for(int k=0; k<sa.length; k++){
  print(sa[k]);
  int z = k + 1;
  if ((z/15)*15 == z){
    rightPrettyfy();
    leftPrettyfy();
  }
}

By varying k in a fanciful way in the loop, we could print a triangular printout

1
2  3
4  5  6
7  8  9  10
11 12 13 14 15

That is to demonstrate that, if you consider this a bug, this "bug" is a useful feature that we would not want to be removed from any of the various languages that we have used thus far.

Download pdf file using jquery ajax

I am newbie and most of the code is from google search. I got my pdf download working with the code below (trial and error play). Thank you for code tips (xhrFields) above.

$.ajax({
            cache: false,
            type: 'POST',
            url: 'yourURL',
            contentType: false,
            processData: false,
            data: yourdata,
             //xhrFields is what did the trick to read the blob to pdf
            xhrFields: {
                responseType: 'blob'
            },
            success: function (response, status, xhr) {

                var filename = "";                   
                var disposition = xhr.getResponseHeader('Content-Disposition');

                 if (disposition) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                } 
                var linkelem = document.createElement('a');
                try {
                                           var blob = new Blob([response], { type: 'application/octet-stream' });                        

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        //   IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) { 
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");

                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.target = "_blank";
                                a.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }
                    }   

                } catch (ex) {
                    console.log(ex);
                } 
            }
        });

Error handling with PHPMailer

In PHPMailer.php, there are lines as below:

echo $e->getMessage()

Just comment these lines and you will be good to go.

What is a wrapper class?

Just what it sounds like: a class that "wraps" the functionality of another class or API in a simpler or merely different API.

See: Adapter pattern, Facade pattern

Import Certificate to Trusted Root but not to Personal [Command Line]

The below 'd help you to add the cert to the Root Store-

certutil -enterprise -f -v -AddStore "Root" <Cert File path>

This worked for me perfectly.

XAMPP Object not found error

Check if you have the correct file mentioned in form statement in HTML:

For eg:

form action="insert.php" method="POST">
</form>

when you are in trial.php but instead you give another fileName

Why do we need virtual functions in C++?

You need at least 1 level of inheritance and an upcast to demonstrate it. Here is a very simple example:

class Animal
{        
    public: 
      // turn the following virtual modifier on/off to see what happens
      //virtual   
      std::string Says() { return "?"; }  
};

class Dog: public Animal
{
    public: std::string Says() { return "Woof"; }
};

void test()
{
    Dog* d = new Dog();
    Animal* a = d;       // refer to Dog instance with Animal pointer

    std::cout << d->Says();   // always Woof
    std::cout << a->Says();   // Woof or ?, depends on virtual
}

Check image width and height before upload with Javascript

You can do the steps for previewing the image without showing it which is supported on all browsers. Following js code shows you how to check the width and height :

var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
    var reader = new FileReader();
    reader.addEventListener("load", function () {
        var image = new Image();
        image.src = this.result as string;
        image.addEventListener('load', function () {
            console.log(`height: ${this.height}, width: ${this.width}`);
        });
                
    }, false);
            
    reader.readAsDataURL(file);
}

Based on Mozilla docs:

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.

And the browser compatibility is listed too.

declaring a priority_queue in c++ with a custom comparator

You have to define the compare first. There are 3 ways to do that:

  1. use class
  2. use struct (which is same as class)
  3. use lambda function.

It's easy to use class/struct because easy to declare just write this line of code above your executing code

struct compare{
  public:
  bool operator()(Node& a,Node& b) // overloading both operators 
  {
      return a.w < b.w: // if you want increasing order;(i.e increasing for minPQ)
      return a.w > b.w // if you want reverse of default order;(i.e decreasing for minPQ)
   }
};

Calling code:

priority_queue<Node,vector<Node>,compare> pq;

Convert .pem to .crt and .key

A .crt stores the certificate.. in pem format. So a .pem, while it can also have other things like a csr (Certificate signing request), a private key, a public key, or other certs, when it is storing just a cert, is the same thing as a .crt.

A pem is a base 64 encoded file with a header and a footer between each section.

To extract a particular section, a perl script such as the following is totally valid, but feel free to use some of the openssl commands.

 perl -ne "\$n++ if /BEGIN/; print if \$n == 1 && /BEGIN/.../END/;" mydomain.pem

where ==1 can be changed to which ever section you need. Obviously if you know exactly the header and footer you require and there is only one of those in the file (usually the case if you keep just the cert and the key in there), you can simplify it:

 perl -ne "print if /^-----BEGIN CERTIFICATE-----\$/.../END/;" mydomain.pem

Pick any kind of file via an Intent in Android

If you want to know this, it exists an open source library called aFileDialog that it is an small and easy to use which provides a file picker.

The difference with another file chooser's libraries for Android is that aFileDialog gives you the option to open the file chooser as a Dialog and as an Activity.

It also lets you to select folders, create files, filter files using regular expressions and show confirmation dialogs.

How to compare files from two different branches?

In order to compare two files in the git bash you need to use the command:

git diff <Branch name>..master -- Filename.extension   

This command will show the difference between the two files in the bash itself.

What's the u prefix in a Python string?

The u in u'Some String' means that your string is a Unicode string.

Q: I'm in a terrible, awful hurry and I landed here from Google Search. I'm trying to write this data to a file, I'm getting an error, and I need the dead simplest, probably flawed, solution this second.

A: You should really read Joel's Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) essay on character sets.

Q: sry no time code pls

A: Fine. try str('Some String') or 'Some String'.encode('ascii', 'ignore'). But you should really read some of the answers and discussion on Converting a Unicode string and this excellent, excellent, primer on character encoding.

How do I set the rounded corner radius of a color drawable using xml?

Use the <shape> tag to create a drawable in XML with rounded corners. (You can do other stuff with the shape tag like define a color gradient as well).

Here's a copy of a XML file I'm using in one of my apps to create a drawable with a white background, black border and rounded corners:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#ffffffff"/>    
             
    <stroke android:width="3dp"
            android:color="#ff000000" />

    <padding android:left="1dp"
             android:top="1dp"
             android:right="1dp"
             android:bottom="1dp" /> 
             
    <corners android:radius="7dp" /> 
</shape>

read input separated by whitespace(s) or newline...?

the user pressing enter or spaces is the same.

int count = 5;
int list[count]; // array of known length
cout << "enter the sequence of " << count << " numbers space separated: ";
// user inputs values space separated in one line.  Inputs more than the count are discarded.
for (int i=0; i<count; i++) {
    cin >> list[i];
}

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

static synchronized means holding lock on the the class's Class object where as synchronized means holding lock on that class's object itself. That means, if you are accessing a non-static synchronized method in a thread (of execution) you still can access a static synchronized method using another thread.

So, accessing two same kind of methods(either two static or two non-static methods) at any point of time by more than a thread is not possible.

How to create a secure random AES key in Java?

I would use your suggested code, but with a slight simplification:

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // for example
SecretKey secretKey = keyGen.generateKey();

Let the provider select how it plans to obtain randomness - don't define something that may not be as good as what the provider has already selected.

This code example assumes (as Maarten points out below) that you've configured your java.security file to include your preferred provider at the top of the list. If you want to manually specify the provider, just call KeyGenerator.getInstance("AES", "providerName");.

For a truly secure key, you need to be using a hardware security module (HSM) to generate and protect the key. HSM manufacturers will typically supply a JCE provider that will do all the key generation for you, using the code above.

Regular expression for first and last name

Simplest way. Just check almost 2 words.

/^[^\s]+( [^\s]+)+$/

Valid names

  • John Doe
  • pedro alberto ch
  • Ar. Gen
  • Mathias d'Arras
  • Martin Luther King, Jr.

No valid names

  • John
  • ???

Calling a particular PHP function on form submit

Assuming that your script is named x.php, try this

<?php 
   function display($s) {
      echo $s;
   }
?>
<html>
    <body>
        <form method="post" action="x.php">
            <input type="text" name="studentname">
            <input type="submit" value="click">
        </form>
        <?php
           if($_SERVER['REQUEST_METHOD']=='POST')
           {
               display();
           } 
        ?>
    </body>
</html>

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

@mohammed, this is usually attributed to the authentication plugin that your mysql database is using.

By default and for some reason, mysql 8 default plugin is auth_socket. Applications will most times expect to log in to your database using a password.

If you have not yet already changed your mysql default authentication plugin, you can do so by:
1. Log in as root to mysql
2. Run this sql command:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
BY 'password';  

Replace 'password' with your root password. In case your application does not log in to your database with the root user, replace the 'root' user in the above command with the user that your application uses.

Digital ocean expounds some more on this here Installing Mysql

React component initialize state from props

If you directly init state from props, it will shows warning in React 16.5 (5th September 2018)

How to select a CRAN mirror in R

You should either get a window with a list of repositories or a text menu with some options. But if that is not appearing, you can always specify the mirror from where to download the packages yourself by using repos parameter. By doing that, R will not ask you anymore about the repository. Example:

install.packages('RMySQL', repos='http://cran.us.r-project.org')

Here you have a list of mirrors for R.

How do I autoindent in Netbeans?

To format all the code in NetBeans, press Alt + Shift + F. If you want to indent lines, select the lines and press Alt + Shift + right arrow key, and to unindent, press Alt + Shift + left arrow key.

Creating a UITableView Programmatically

Creating a tableview using tableViewController .

import UIKit

class TableViewController: UITableViewController
{
    let tableViewModel = TableViewModel()
    var product: [String] = []
    var price: [String] = []
    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.tableView.contentInset = UIEdgeInsetsMake( 20, 20 , 0, 0)
        let priceProductDetails = tableViewModel.dataProvider()

        for (key, value) in priceProductDetails
        {
            product.append(key)
            price.append(value)
        }
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return product.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style: .Value1, reuseIdentifier: "UITableViewCell")
        cell.textLabel?.text = product[indexPath.row]
        cell.detailTextLabel?.text = price[indexPath.row]
        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        print("You tapped cell number \(indexPath.row).")
    }
}

Difference between npx and npm?

npx is a npm package runner (x probably stands for eXecute). The typical use is to download and run a package temporarily or for trials.

create-react-app is an npm package that is expected to be run only once in a project's lifecycle. Hence, it is preferred to use npx to install and run it in a single step.

As mentioned in the man page https://www.npmjs.com/package/npx, npx can run commands in the PATH or from node_modules/.bin by default.

Note: With some digging, we can find that create-react-app points to a Javascript file (possibly to /usr/lib/node_modules/create-react-app/index.js on Linux systems) that is executed within the node environment. This is simply a global tool that does some checks. The actual setup is done by react-scripts, whose latest version is installed in the project. Refer https://github.com/facebook/create-react-app for more info.

SQL query for today's date minus two months

SELECT COUNT(1)
FROM FB
WHERE
    Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
        AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'

How do I deserialize a complex JSON object in C# .NET?

Should just be this:

var jobject = JsonConvert.DeserializeObject<RootObject>(jsonstring);

You can paste the json string to here: http://json2csharp.com/ to check your classes are correct.

How to restart a rails server on Heroku?

Go into your application directory on terminal and run following command:

heroku restart

How to set JAVA_HOME in Linux for all users

It's Very easy to set a path in Linux. Do as follows :

Step-1 Open terminal and type sudo gedit .bashrc

Step-2 It will ask you your password. After typing the password ,it will open the bash file. Then go to end and type below

step-3

   export JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64/"
   export PATH=$PATH:$JAVA_HOME/bin

step-4 Then save the file and exit from file

Above is for a single user. For all users, you have to follow below steps

Step-1 gedit /etc/profile

Step-2 export JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64/"

Step-3 export PATH=$PATH:$JAVA_HOME/bin

Hope this helps. Thanks!

Take n rows from a spark dataframe and pass to toPandas()

You can use the limit(n) function:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()

Or:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()

Filter Pyspark dataframe column with None value

To obtain entries whose values in the dt_mvmt column are not null we have

df.filter("dt_mvmt is not NULL")

and for entries which are null we have

df.filter("dt_mvmt is NULL")

How can I use custom fonts on a website?

Yes, there is a way. Its called custom fonts in CSS.Your CSS needs to be modified, and you need to upload those fonts to your website.

The CSS required for this is:

@font-face {
     font-family: Thonburi-Bold;
     src: url('pathway/Thonburi-Bold.otf'); 
}

Can't find System.Windows.Media namespace?

The System.Windows.Media.Imaging namespace is part of PresentationCore.dll (if you are using Visual Studio 2008 then the WPF application template will automatically add this reference). Note that this namespace is not a direct wrapping of the WIC library, although a large proportion of the more common uses are still available and it is relatively obvious how these map to the WIC versions. For more information on the classes in this namespace check out

http://msdn2.microsoft.com/en-us/library/system.windows.media.imaging.aspx

How to launch an application from a browser?

The correct method is to register your custom URL Protocol in windows registry as follows:

[HKEY_CLASSES_ROOT\customurl]
@="Description here"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\customurl\shell]

[HKEY_CLASSES_ROOT\customurl\shell\open]

[HKEY_CLASSES_ROOT\customurl\shell\open\command]
@="\"C:\\Path To Your EXE\\ExeName.exe\" \"%1\""

Once the above keys and values are added, from the web page, just call "customurl:\\parameter1=xxx&parameter2=xxx" . You will receive the entire url as the argument in exe, which you need to process inside your exe. Change 'customurl' with the text of your choice.

Python RuntimeWarning: overflow encountered in long scalars

Here's an example which issues the same warning:

import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a

yields

RuntimeWarning: overflow encountered in long_scalars

In the example above it happens because a is of dtype int32, and the maximim value storable in an int32 is 2**31-1. Since 10**10 > 2**32-1, the exponentiation results in a number that is bigger than that which can be stored in an int32.

Note that you can not rely on np.seterr(all='warn') to catch all overflow errors in numpy. For example, on 32-bit NumPy

>>> np.multiply.reduce(np.arange(21)+1)
-1195114496

while on 64-bit NumPy:

>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848

Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals

In [47]: import math

In [48]: math.factorial(21)
Out[50]: 51090942171709440000L

According to numpy developer, Robert Kern,

Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays.

So the burden is on you to choose appropriate dtypes so that no operation overflows.

What properties does @Column columnDefinition make redundant?

My Answer: All of the following should be overridden (i.e. describe them all within columndefinition, if appropriate):

  • length
  • precision
  • scale
  • nullable
  • unique

i.e. the column DDL will consist of: name + columndefinition and nothing else.

Rationale follows.


  1. Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.

  2. Other annotation purely logical - properties used in-memory in java to control JPA processing.

  3. That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true) and once via @Column(...,nullable=true). Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.

In your example, length and nullable properties are overridden and redundant.


So, when specifying columnDefinition, what other properties of @Column are made redundant?

  1. In JPA Spec & javadoc:

    • columnDefinition definition: The SQL fragment that is used when generating the DDL for the column.

    • columnDefinition default: Generated SQL to create a column of the inferred type.

    • The following examples are provided:

      @Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
      @Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
      
    • And, err..., that's it really. :-$ ?!

    Does columnDefinition override other properties provided in the same annotation?

    The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.

  2. The following can be safely implied from examples provided in the JPA spec

    • name & table can be used in conjunction with columnDefinition, neither are overridden
    • nullable is overridden/made redundant by columnDefinition
  3. The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):

    • length, precision, scale are overridden/made redundant by the columnDefinition - they are integral to the type
    • insertable and updateable are provided separately and never included in columnDefinition, because they control SQL generation in-memory, before it is emmitted to the database.
  4. That leaves just the "unique" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.


Test My Answer For columns "A" & "B", respectively:

  @Column(name="...", table="...", insertable=true, updateable=false,
          columndefinition="NUMBER(5,2) NOT NULL UNIQUE"

  @Column(name="...", table="...", insertable=false, updateable=true,
          columndefinition="NVARCHAR2(100) NULL"
  • confirm generated table has correct type/nullability/uniqueness
  • optionally, do JPA insert & update: former should include column A, latter column B

Calculate the execution time of a method

 using System.Diagnostics;
 class Program
 {
    static void Test1()
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine("Test1 " + i);
        }
    }
  static void Main(string[] args)
    {

        Stopwatch sw = new Stopwatch();
        sw.Start();
        Test1();
        sw.Stop();
        Console.WriteLine("Time Taken-->{0}",sw.ElapsedMilliseconds);
   }
 }

There has been an error processing your request, Error log record number

A common solution is to upgrade magento setup by running this command

php bin/magento setup:upgrade && php bin/magento setup:di:compile

Otherwise just check var/report/{error number}

How to fill Matrix with zeros in OpenCV?

use cv::mat::setto

img.setTo(cv::Scalar(redVal,greenVal,blueVal))

Where does Internet Explorer store saved passwords?

No guarantee, but I suspect IE uses the older Protected Storage API.

Arduino error: does not name a type?

I found the solution to this problem in a "}". I did some changes to my sketch and forgot to check for "}" and I had an extra one. As soon as I deleted it and compiled everything was fine.

Where does the @Transactional annotation belong?

In general I agree with the others stating that transactions are usually started on the service level (depending on the granularity that you require of course).

However, in the mean time I also started adding @Transactional(propagation = Propagation.MANDATORY) to my DAO layer (and other layers that are not allowed to start transactions but require existing ones) because it is much easier to detect errors where you have forgotten to start a transaction in the caller (e.g. the service). If your DAO is annotated with mandatory propagation you will get an exception stating that there is no active transaction when the method is invoked.

I also have an integration test where I check all beans (bean post processor) for this annotation and fail if there is a @Transactional annotation with propagation other than Mandatory in a bean that does not belong to the services layer. This way I make sure we do not start transactions on the wrong layer.

Value cannot be null. Parameter name: source

This exception will be returned if you attempt to count values in a null collection.

For example the below works when Errors is not null, however if Errors is null then the Value cannot be null. Parameter name: source exception occurs.

if (graphQLResponse.Errors.Count() > 0)

This exception can be avoided by checking for null instead.

if (graphQLResponse.Errors != null)

Rails 4: List of available datatypes

Here are all the Rails 4 (ActiveRecord migration) datatypes:

  • :binary
  • :boolean
  • :date
  • :datetime
  • :decimal
  • :float
  • :integer
  • :bigint
  • :primary_key
  • :references
  • :string
  • :text
  • :time
  • :timestamp

Source: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column
These are the same as with Rails 3.

If you use PostgreSQL, you can also take advantage of these:

  • :hstore
  • :json
  • :jsonb
  • :array
  • :cidr_address
  • :ip_address
  • :mac_address

They are stored as strings if you run your app with a not-PostgreSQL database.

Edit, 2016-Sep-19:

There's a lot more postgres specific datatypes in Rails 4 and even more in Rails 5.

How do I return a string from a regex match in python?

imgtag.group(0) or imgtag.group(). This returns the entire match as a string. You are not capturing anything else either.

http://docs.python.org/release/2.5.2/lib/match-objects.html

Parameterize an SQL IN clause

You can parameterize each value, so something like:

string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
string cmdText = "SELECT * FROM Tags WHERE Name IN ({0})";

string[] paramNames = tags.Select(
    (s, i) => "@tag" + i.ToString()
).ToArray();

string inClause = string.Join(", ", paramNames);
using (SqlCommand cmd = new SqlCommand(string.Format(cmdText, inClause))) {
    for(int i = 0; i < paramNames.Length; i++) {
       cmd.Parameters.AddWithValue(paramNames[i], tags[i]);
    }
}

Which will give you:

cmd.CommandText = "SELECT * FROM Tags WHERE Name IN (@tag0, @tag1, @tag2, @tag3)"
cmd.Parameters["@tag0"] = "ruby"
cmd.Parameters["@tag1"] = "rails"
cmd.Parameters["@tag2"] = "scruffy"
cmd.Parameters["@tag3"] = "rubyonrails"

No, this is not open to SQL injection. The only injected text into CommandText is not based on user input. It's solely based on the hardcoded "@tag" prefix, and the index of an array. The index will always be an integer, is not user generated, and is safe.

The user inputted values are still stuffed into parameters, so there is no vulnerability there.

Edit:

Injection concerns aside, take care to note that constructing the command text to accomodate a variable number of parameters (as above) impede's SQL server's ability to take advantage of cached queries. The net result is that you almost certainly lose the value of using parameters in the first place (as opposed to merely inserting the predicate strings into the SQL itself).

Not that cached query plans aren't valuable, but IMO this query isn't nearly complicated enough to see much benefit from it. While the compilation costs may approach (or even exceed) the execution costs, you're still talking milliseconds.

If you have enough RAM, I'd expect SQL Server would probably cache a plan for the common counts of parameters as well. I suppose you could always add five parameters, and let the unspecified tags be NULL - the query plan should be the same, but it seems pretty ugly to me and I'm not sure that it'd worth the micro-optimization (although, on Stack Overflow - it may very well be worth it).

Also, SQL Server 7 and later will auto-parameterize queries, so using parameters isn't really necessary from a performance standpoint - it is, however, critical from a security standpoint - especially with user inputted data like this.

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

Adding a Method to an Existing Object Instance

If it can be of any help, I recently released a Python library named Gorilla to make the process of monkey patching more convenient.

Using a function needle() to patch a module named guineapig goes as follows:

import gorilla
import guineapig
@gorilla.patch(guineapig)
def needle():
    print("awesome")

But it also takes care of more interesting use cases as shown in the FAQ from the documentation.

The code is available on GitHub.

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

oracle SQL how to remove time from date

You can use TRUNC on DateTime to remove Time part of the DateTime. So your where clause can be:

AND TRUNC(p1.PA_VALUE) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')

The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model.

<Django object > is not JSON serializable

I found that this can be done rather simple using the ".values" method, which also gives named fields:

result_list = list(my_queryset.values('first_named_field', 'second_named_field'))
return HttpResponse(json.dumps(result_list))

"list" must be used to get data as iterable, since the "value queryset" type is only a dict if picked up as an iterable.

Documentation: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#values

Stylesheet not loaded because of MIME-type

Incase, you're working with a Node application, make sure that the \public folder is immediately below the root folder, and not within the views folder. This can become troublesome. Move the \public immediately below the root and then restart the server and witness the changes.

How do I URl encode something in Node.js?

Note that URI encoding is good for the query part, it's not good for the domain. The domain gets encoded using punycode. You need a library like URI.js to convert between a URI and IRI (Internationalized Resource Identifier).

This is correct if you plan on using the string later as a query string:

> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")
'http%3A%2F%2Fexampl%C3%A9.org%2Fros%C3%A9%3Fros%C3%A9%3Dros%C3%A9'

If you don't want ASCII characters like /, : and ? to be escaped, use encodeURI instead:

> encodeURI("http://examplé.org/rosé?rosé=rosé")
'http://exampl%C3%A9.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'

However, for other use-cases, you might need uri-js instead:

> var URI = require("uri-js");
undefined
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))
'http://xn--exampl-gva.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'

WebView link click open default browser

You only need to add the following line

yourWebViewName.setWebViewClient(new WebViewClient());

Check this for official documentation.

Change DIV content using ajax, php and jQuery

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",
     url: 'Your URL',
     data: "id=" + id, // appears as $_GET['id'] @ your backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

And add onclick event in your lists

<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>

T-sql - determine if value is integer

WHERE IsNumeric(value + 'e0') = 1 AND CONVERT(FLOAT, value) BETWEEN -2147483648 AND 2147483647

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

If you're using mod_php, you could put (either in a .htaccess in /USERS or in your httpd.conf for the USERS directory)

RemoveHandler .php

or

RemoveType .php

(depending on whether PHP is enabled using AddHandler or AddType)

PHP files run from another directory will be still able to include files in /USERS (assuming that there is no open_basedir restriction), because this does not go through Apache. If a php file is accessed using apache it will be serverd as plain text.

Edit

Lance Rushing's solution of just denying access to the files is probably better

Regex Last occurrence?

What about this regex: \\[^\\]+$

CSS /JS to prevent dragging of ghost image?

In React all you need is:

  <img
    src={}
    onMouseDown={(e) => {
      e.preventDefault();
      // other code
    }}
  />

How do I horizontally center an absolute positioned element inside a 100% width div?

Its easy, just wrap it in a relative box like so:

<div class="relative">
 <div class="absolute">LOGO</div>
</div>

The relative box has a margin: 0 Auto; and, important, a width...

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

The above solutions explain clearly what the problem is; when you don't have control over the repo, the best way to submit your code is to create a Fork of the original repo and submit your code to this new repo so later you can push it to the original one.

Real-world examples of recursion

Recursion is used in things like BSP trees for collision detection in game development (and other similar areas).

Why are you not able to declare a class as static in Java?

if the benefit of using a static-class was not to instantiate an object and using a method then just declare the class as public and this method as static.

In plain English, what does "git reset" do?

TL;DR

git reset resets Staging to the last commit. Use --hard to also reset files in your Working directory to the last commit.

LONGER VERSION

But that's obviously simplistic hence the many rather verbose answers. It made more sense for me to read up on git reset in the context of undoing changes. E.g. see this:

If git revert is a “safe” way to undo changes, you can think of git reset as the dangerous method. When you undo with git reset(and the commits are no longer referenced by any ref or the reflog), there is no way to retrieve the original copy—it is a permanent undo. Care must be taken when using this tool, as it’s one of the only Git commands that has the potential to lose your work.

From https://www.atlassian.com/git/tutorials/undoing-changes/git-reset

and this

On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.

From https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting/commit-level-operations

JQuery, select first row of table

Actually, if you try to use function "children" it will not be succesfull because it's possible to the table has a first child like 'th'. So you have to use function 'find' instead.

Wrong way:

var $row = $(this).closest('table').children('tr:first');

Correct way:

 var $row = $(this).closest('table').find('tr:first');

SQL: how to use UNION and order by a specific select?

@Adrien's answer is not working. It gives an ORA-01791.

The correct answer (for the question that is asked) should be:

select id
from 
 (SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
  UNION ALL
  SELECT id, 1 as ordered FROM b -- returns 2,1
  )
group by id
order by min(ordered)

Explanation:

  1. The "UNION ALL" is combining the 2 sets. A "UNION" is wastefull because the 2 sets could not be the same, because the ordered field is different.
  2. The "group by" is then eliminating duplicates
  3. The "order by min (ordered)" is assuring the elements of table b are first

This solves all the cases, even when table b has more or different elements then table a

How to add scroll bar to the Relative Layout?

The following code should do the trick:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="638dp" >

<TextView
    android:id="@+id/textView1"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="64dp"
    android:text="Email" />

<TextView
    android:id="@+id/textView2"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="41dp"
    android:text="Password" />

<TextView
    android:id="@+id/textView3"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView2"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="47dp"
    android:text="Confirm Password" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView1"
    android:layout_alignBottom="@+id/textView1"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/textView4"
    android:inputType="textEmailAddress" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView2"
    android:layout_alignBottom="@+id/textView2"
    android:layout_alignLeft="@+id/editText1"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignLeft="@+id/editText2"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />


<TextView
    android:id="@+id/textView4"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView3"
    android:layout_marginTop="42dp"
    android:text="Date of Birth" />

<DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/textView4" />

<TextView
    android:id="@+id/textView5"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/datePicker1"
    android:layout_marginTop="60dp"
    android:layout_toLeftOf="@+id/datePicker1"
    android:text="Gender" />

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView5"
    android:layout_alignBottom="@+id/textView5"
    android:layout_alignLeft="@+id/editText3"
    android:layout_marginLeft="24dp"
    android:text="Male" />

<RadioButton
    android:id="@+id/radioButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/radioButton1"
    android:layout_below="@+id/radioButton1"
    android:layout_marginTop="14dp"
    android:text="Female" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="23dp"
    android:layout_toLeftOf="@+id/radioButton2"
    android:background="@drawable/rectbutton"
    android:text="Sign Up" />

Autocompletion of @author in Intellij

One more option, not exactly what you asked, but can be useful:

Go to Settings -> Editor -> File and code templates -> Includes tab (on the right). There is a template header for the new files, you can use the username here:

/**
 * @author myname
 */

For system username use:

/**
 * @author ${USER}
 */

Screen shot from Intellij 2016.02

Regular expression containing one word or another

You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:

([0-9]+)\s+((\bseconds\b)|(\bminutes\b))

Without those you were either matching a number followed by seconds OR just the word minutes

Fix footer to bottom of page

This code working for me :

footer{
    background-color: #333;
    color: #EEE;
    padding: 20px;
    left: 0;
    width: 100%;
    bottom: 0;
    position: fixed;
}

Important thing you should added bottom:0; and position: fixed;

FPDF utf-8 encoding (HOW-TO)

Don't use UTF-8 encoding. Standard FPDF fonts use ISO-8859-1 or Windows-1252. It is possible to perform a conversion to ISO-8859-1 with utf8_decode(): $str = utf8_decode($str); But some characters such as Euro won't be translated correctly. If the iconv extension is available, the right way to do it is the following: $str = iconv('UTF-8', 'windows-1252', $str);

Increase number of axis ticks

Based on Daniel Krizian's comment, you can also use the pretty_breaks function from the scales library, which is imported automatically:

ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 10))

All you have to do is insert the number of ticks wanted for n.


A slightly less useful solution (since you have to specify the data variable again), you can use the built-in pretty function:

ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = pretty(dat$x, n = 10)) +
scale_y_continuous(breaks = pretty(dat$y, n = 10))

No more data to read from socket error

In our case we had a query which loads multiple items with select * from x where something in (...) The in part was so long for benchmark test.(17mb as text query). Query is valid but text so long. Shortening the query solved the problem.

Where is android studio building my .apk file?

You can find it in the

project -> app (or your main app module) -> build -> outputs -> apk

Parsing XML with namespace in Python via 'ElementTree'

ElementTree is not too smart about namespaces. You need to give the .find(), findall() and iterfind() methods an explicit namespace dictionary. This is not documented very well:

namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed

root.findall('owl:Class', namespaces)

Prefixes are only looked up in the namespaces parameter you pass in. This means you can use any namespace prefix you like; the API splits off the owl: part, looks up the corresponding namespace URL in the namespaces dictionary, then changes the search to look for the XPath expression {http://www.w3.org/2002/07/owl}Class instead. You can use the same syntax yourself too of course:

root.findall('{http://www.w3.org/2002/07/owl#}Class')

If you can switch to the lxml library things are better; that library supports the same ElementTree API, but collects namespaces for you in a .nsmap attribute on elements.

How do I debug "Error: spawn ENOENT" on node.js?

As @DanielImfeld pointed it, ENOENT will be thrown if you specify "cwd" in the options, but the given directory does not exist.

Reportviewer tool missing in visual studio 2017 RC

If you're like me and tried a few of these methods and are stuck at the point that you have the control in the toolbox and can draw it on the form but it disappears from the form and puts it down in the components, then simply edit the designer and add the following in the appropriate area of InitializeComponent() to make it visible:

this.Controls.Add(this.reportViewer1);

or

[ContainerControl].Controls.Add(this.reportViewer1);

You'll also need to make adjustments to the location and size manually after you've added the control.

Not a great answer for sure, but if you're stuck and just need to get work done for now until you have more time to figure it out, it should help.

How do I format currencies in a Vue component?

You can use this example

formatPrice(value) {
  return value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
},

Prevent direct access to a php include file

Do something like:

<?php
if ($_SERVER['SCRIPT_FILENAME'] == '<path to php include file>') {
    header('HTTP/1.0 403 Forbidden');
    exit('Forbidden');
}
?>

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

Python Image Library fails with message "decoder JPEG not available" - PIL

For Fedora

Install pre-requisite
sudo dnf install make automake gcc gcc-c++ kernel-devel rpm-build libjpeg-devel zlib-devel python-devel
Now install Pillow

sudo pip install pillow

Note - For libjpeg and zlib we are installing libjpeg-devel and zlib-devel packages in Fedora/CentOS/Red Hat

Setting a max character length in CSS

This post is for a CSS solution, but the post is quite old, so just in case others stumble on this and are using a modern JS framework such as Angular 4+, there is a simple way to do this through Angular Pipes without having to mess around with CSS.

There are probably "React" or "Vue" ways of doing this as well. This is just to showcase how it could be done within a framework.

truncate-text.pipe.ts

/**
 * Helper to truncate text using JS in view only.
 *
 * This is pretty difficult to do reliably with CSS, especially when there are
 * multiple lines.
 *
 * Example: {{ value | truncateText:maxLength }} or {{ value | truncateText:45 }}
 *
 * If maxLength is not provided, the value will be returned without any truncating. If the
 * text is shorter than the maxLength, the text will be returned untouched. If the text is greater
 * than the maxLength, the text will be returned with 3 characters less than the max length plus
 * some ellipsis at the end to indicate truncation.
 *
 * For example: some really long text I won't bother writing it all ha...
 */
@Pipe({ name: 'truncateText' })
export class TruncateTextPipe implements PipeTransform {
  transform(value: string, ...args: any[]): any {
    const maxLength = args[0]
    const maxLengthNotProvided = !maxLength
    const isShorterThanMaximumLength = value.length < maxLength
    if (maxLengthNotProvided || isShorterThanMaximumLength) {
      return value
    }
    const shortenedString = value.substr(0, maxLength - 3)
    return `${shortenedString}...`
  }
}

app.component.html

<h1>{{ application.name | truncateText:45 }}</h1>

Empty brackets '[]' appearing when using .where

You can use the lower function:

Guide.where("lower(title)='attack'") 

As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.

Removing an item from a select box

If somebody need delete ALL options inside a select, i did a litle function.

I hope you find it useful

var removeAllOptionsSelect = function(element_class_or_id){
    var element = $(element_class_or_id+" option");
    $.each(element,function(i,v){
        value = v.value;
        $(element_class_or_id+" option[value="+value+"]").remove(); 
    })
}

Only have to run

removeAllOptionsSelect("#contenedor_modelos");

How to count number of unique values of a field in a tab-delimited text file?

# COLUMN is integer column number
# INPUT_FILE is input file name

cut -f ${COLUMN} < ${INPUT_FILE} | sort -u | wc -l

latex large division sign in a math formula

I found the answer I was looking for. The thing to use here is the construct of

\left \middle \right

For example, in this case, two possible solutions are:

$\left( {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right) $

Or, in case the brackets are not necessary:

$\left. {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right. $

Android basics: running code in the UI thread

As of Android P you can use getMainExecutor():

getMainExecutor().execute(new Runnable() {
  @Override public void run() {
    // Code will run on the main thread
  }
});

From the Android developer docs:

Return an Executor that will run enqueued tasks on the main thread associated with this context. This is the thread used to dispatch calls to application components (activities, services, etc).

From the CommonsBlog:

You can call getMainExecutor() on Context to get an Executor that will execute its jobs on the main application thread. There are other ways of accomplishing this, using Looper and a custom Executor implementation, but this is simpler.

What's the difference between ViewData and ViewBag?

Can I recommend to you to not use either?

If you want to "send" data to your screen, send a strongly typed object (A.K.A. ViewModel) because it's easier to test.

If you bind to some sort of "Model" and have random "viewbag" or "viewdata" items then it makes automated testing very difficult.

If you are using these consider how you might be able to restructure and just use ViewModels.

How to set Oracle's Java as the default Java in Ubuntu?

If you want to change it globally and at system level;

In

/etc/environment

add this line:

JAVA_HOME=/usr/lib/jvm/java-7-oracle

Count length of array and return 1 if it only contains one element

Maybe I am missing something (lots of many-upvotes-members answers here that seem to be looking at this different to I, which would seem implausible that I am correct), but length is not the correct terminology for counting something. Length is usually used to obtain what you are getting, and not what you are wanting.

$cars.count should give you what you seem to be looking for.

Compare two files line by line and generate the difference in another file

If you have a CSV file with single or even multiple columns, you can do these line by line "diff" operations using the sqlite3 embedded db. It comes with python, so should be available on most linux/macs. You can script the sqlite3 commands on the bash shell without needing to write python.

  1. Create your a.csv and b.csv files
  2. Ensure sqlite3 is installed using the command "sqlite3 -help"
  3. Run the below commands directly on the Linux/Mac shell (or put it in a script)
echo "
.mode csv
.import a.csv atable
.import b.csv btable
create table result as select * from atable EXCEPT select * from btable;
.output result.csv
select * from result ;
.quit
" | sqlite3 temp.db

Note : Ensure there is a newline for each of the sqlite3 commands.

How it works

  1. Import the 2 csvs into "atable" and "btable" respectively.
  2. Use the "except" sql operator to select the data available in "atable" but missing in "btable". Create a "result" table using the select query statement
  3. Output the result table to result.csv by running "select * from result;"

If you need to operate on specific columns, sqlite3 or any db is the way to go.

I have tried diff'ing on multiple GB files using the builtin diff and comm tools. Sqlite beats linux utilities by a mile.

How to always show the vertical scrollbar in a browser?

Just use CSS.

body {
  overflow-y: scroll;
}

error: ‘NULL’ was not declared in this scope

NULL is not a keyword. It's an identifier defined in some standard headers. You can include

#include <cstddef>

To have it in scope, including some other basics, like std::size_t.

How should I do integer division in Perl?

Integer division $x divided by $y ...

$z = -1 & $x / $y

How does it work?

$x / $y

return the floating point division

&

perform a bit-wise AND

-1

stands for

&HFFFFFFFF

for the largest integer ... whence

$z = -1 & $x / $y

gives the integer division ...

Incrementing a variable inside a Bash loop

USCOUNTER=$(grep -c "^US " "$FILE")

Preprocessor check if multiple defines are not defined

FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.

main.c has a main wrapper like this:

#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
  // the true main() routine.
}

spi.c, serial.c and usb.c have main wrappers for their respective test code like this:

#ifdef TEST_USB
int main(int argc, char *argv[]) {
  // the  main() routine for testing the usb code.
}

config.h Which is included by all the c files has an entry like this:

// Uncomment below to test the serial
//#define TEST_SERIAL


// Uncomment below to test the spi code
//#define TEST_SPI

// Uncomment below to test the usb code
#define TEST_USB

mysql delete under safe mode

Googling around, the popular answer seems to be "just turn off safe mode":

SET SQL_SAFE_UPDATES = 0;
DELETE FROM instructor WHERE salary BETWEEN 13000 AND 15000;
SET SQL_SAFE_UPDATES = 1;

If I'm honest, I can't say I've ever made a habit of running in safe mode. Still, I'm not entirely comfortable with this answer since it just assumes you should go change your database config every time you run into a problem.

So, your second query is closer to the mark, but hits another problem: MySQL applies a few restrictions to subqueries, and one of them is that you can't modify a table while selecting from it in a subquery.

Quoting from the MySQL manual, Restrictions on Subqueries:

In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms:

DELETE FROM t WHERE ... (SELECT ... FROM t ...);
UPDATE t ... WHERE col = (SELECT ... FROM t ...);
{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);

Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:

UPDATE t ... WHERE col = (SELECT * FROM (SELECT ... FROM t...) AS _t ...);

Here the result from the subquery in the FROM clause is stored as a temporary table, so the relevant rows in t have already been selected by the time the update to t takes place.

That last bit is your answer. Select target IDs in a temporary table, then delete by referencing the IDs in that table:

DELETE FROM instructor WHERE id IN (
  SELECT temp.id FROM (
    SELECT id FROM instructor WHERE salary BETWEEN 13000 AND 15000
  ) AS temp
);

SQLFiddle demo.

Sockets: Discover port availability using Java

This is the implementation coming from the Apache camel project:

/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 */
public static boolean available(int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

    return false;
}

They are checking the DatagramSocket as well to check if the port is avaliable in UDP and TCP.

Hope this helps.

Lollipop : draw behind statusBar with its color set to transparent

The accepted answer worked for me using a CollapsingToolbarLayout. It's important to note though, that setSytstemUiVisibility() overrides any previous calls to that function. So if you're using that function somewhere else for the same view, you need to include the View.SYSTEM_UI_FLAG_LAYOUT_STABLE and View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN flags, or they will be overridden with the new call.

This was the case for me, and once I added the two flags to the other place I was making a call to setSystemUiVisibility(), the accepted answer worked perfectly.

Sublime Text 2 - View whitespace characters

Here is an Offical tutorial of how to that!
http://sublimetexttips.com/show-whitespace-sublime-text/

just like this!

enter image description here
enter image description here

Hope help for your!

How do you copy and paste into Git Bash

Ctrl + insert did it for me in Windows.

MongoDB distinct aggregation

You can use $addToSet with the aggregation framework to count distinct objects.

For example:

db.collectionName.aggregate([{
    $group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
}])

MongoDB: update every document on one field

This code will be helpful for you

        Model.update({
            'type': "newuser"
        }, {
            $set: {
                email: "[email protected]",
                phoneNumber:"0123456789"
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  

splitting a string into an array in C++ without using vector

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main() {

    string s1="split on     whitespace";
    istringstream iss(s1);
    vector<string> result;
    for(string s;iss>>s;)
        result.push_back(s);
    int n=result.size();
    for(int i=0;i<n;i++)
        cout<<result[i]<<endl;
    return 0;
}

Output:-

split
on
whitespace

Using scp to copy a file to Amazon EC2 instance?

Your key must not be publicly viewable for SSH to work. Use this command if needed:

chmod 400 yourPublicKeyFile.pem

Switch/toggle div (jQuery)

This is how I toggle two divs at the same time:

$('#login-form, #recover-password').toggle();

It works!

What does the 'L' in front a string mean in C++?

It means it's an array of wide characters (wchar_t) instead of narrow characters (char).

It's a just a string of a different kind of character, not necessarily a Unicode string.