Programs & Examples On #Ssh

GENERAL SSH SUPPORT IS OFF-TOPIC. Support questions may be asked on https://superuser.com. Secure Shell (SSH) is a cryptographic network protocol for secure data communication. Use this tag for programming questions related to Secure Shell. Common authentication and configuration problems are off-topic for Stack Overflow.

How to download folder from putty using ssh client

I use both PuTTY and Bitvise SSH Client. PuTTY handles screen sessions better, but Bitvise automatically opens up a SFTP window so you can transfer files just like you would with an FTP client.

What are some good SSH Servers for windows?

You can run OpenSSH on Cygwin, and even install it as a Windows service.

I once used it this way to easily add backups of a Unix system - it would rsync a bunch of files onto the Windows server, and the Windows server had full tape backups.

Git's famous "ERROR: Permission to .git denied to user"

I had the same problem as you. After a long time spent Googling, I found out my error was caused by multiple users that had added the same key in their accounts.

So, here is my solution: delete the wrong-user's ssh-key (I can do it because the wrong-user is also my account). If the wrong-user isn't your account, you may need to change your ssh-key, but I don't think this gonna happen.

And I think your problem may be caused by a mistyping error in your accounts name.

Jenkins: Failed to connect to repository

Jenkins runs as another user, not as your ordinary login. So, do as this to solve the ssh problem:

  1. Log on as jenkins su jenkins (you may first have to do sudo passwd jenkins to be able to set the password for jenkins. I couldn't find the default...)
  2. Generate ssh key pair: ssh-keygen
  3. Copy the public key (id_rsa.pub) to your github account (or wherever)
  4. Clone the repo as jenkins in order to have the host added to jenkins known_hosts which is neccessary to do. Now you can remove the cloned repo again if you wish.

.ssh/config file for windows (git)

You can use multiple ssh keys on Windows 10 and specify the type of access allowed.

Assuming you have created the ssh secure keys already and they were stored in C:\Users\[User]\.ssh

  1. Open the folder C:\Users\[User]\.ssh

  2. Create the file config (no file extension)

  3. Open the file in a text editor like Notepad, and add these configuration details for the first remote host and user. Keep both CMD and BASH paths or only pick one format. Then copy-and-paste below it for the other host/user combinations and amend as required. Save the file.

    Host [git.domain.com]
    User [user]
    Port [number]
    IdentitiesOnly=yes
    PreferredAuthentications publickey
    PasswordAuthentication no
    # CMD
    IdentityFile C:\Users\[User]\.ssh\[name_of_PRIVATE_key_file]
    # BASH
    IdentityFile /c/Users/[User]/.ssh/[name_of_PRIVATE_key_file]
    
  4. Testing

  • Using Bash (Git for Windows)
    $ ssh -T git@[git.domain.com]
    Welcome to GitLab, @[User]!
    
  • Using Commandline (requires activation of Win 10 OpenSSH Client)
    C:\Users\[User]>ssh -T git@[git.domain.com]
    Welcome to GitLab, @[User]!
    
  1. For troubleshooting use ssh -Tv git@[git.domain.com] (or -Tvv or -Tvvv for higher verbosity levels).

Copying files from server to local computer using SSH

You need to name the file in both directory paths.

scp [email protected]:/dir/of/file.txt \local\dir\file.txt

Find and Replace Inside a Text File from a Bash Command

You may also use the ed command to do in-file search and replace:

# delete all lines matching foobar 
ed -s test.txt <<< $'g/foobar/d\nw' 

See more in "Editing files via scripts with ed".

Work on a remote project with Eclipse via SSH

For this case you can use ptp eclipse https://eclipse.org/ptp/ for source browsing and building.

You can use this pluging to debug your application

http://marketplace.eclipse.org/content/direct-remote-c-debugging

How do I verify/check/test/validate my SSH passphrase?

If your passphrase is to unlock your SSH key and you don't have ssh-agent, but do have sshd (the SSH daemon) installed on your machine, do:

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys;
ssh localhost -i ~/.ssh/id_rsa

Where ~/.ssh/id_rsa.pub is the public key, and ~/.ssh/id_rsa is the private key.

How to establish ssh key pair when "Host key verification failed"

Its means your remote host key was changed (May be host password change),

Your terminal suggested to execute this command as root user

$ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]:4231

You have to remove that host name from hosts list on your pc/server. Copy that suggested command and execute as a root user.

$ sudo su                                                            // Login as a root user

$ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]:4231   // Terminal suggested command execute here
Host [www.website.net]:4231 found: line 16 type ECDSA
/root/.ssh/known_hosts updated.
Original contents retained as /root/.ssh/known_hosts.old

$ exit                                                               // Exist from root user

$ sudo ssh [email protected] -p 4231                              // Try again

I Hope this works.

Displaying output of a remote command with Ansible

If you pass the -v flag to the ansible-playbook command, then ansible will show the output on your terminal.

For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.

What is the cleanest way to ssh and run multiple commands in Bash?

This works well for creating scripts, as you do not have to include other files:

#!/bin/bash
ssh <my_user>@<my_host> "bash -s" << EOF
    # here you just type all your commmands, as you can see, i.e.
    touch /tmp/test1;
    touch /tmp/test2;
    touch /tmp/test3;
EOF

# you can use '$(which bash) -s' instead of my "bash -s" as well
# but bash is usually being found in a standard location
# so for easier memorizing it i leave that out
# since i dont fat-finger my $PATH that bad so it cant even find /bin/bash ..

Git error: "Host Key Verification Failed" when connecting to remote repository

When asked:

Are you sure you want to continue connecting (yes/no)?

Type yes as the response

That is how I solved my issue. But if you try to just hit the enter button, it won't work!

How to execute a MySQL command from a shell script?

Use this syntax:

mysql -u $user -p$passsword -Bse "command1;command2;....;commandn"

Multiple GitHub Accounts & SSH Config

I have 2 accounts on github, and here is what I did (on linux) to make it work.

Keys

  • Create 2 pair of rsa keys, via ssh-keygen, name them properly, so that make life easier.
  • Add private keys to local agent via ssh-add path_to_private_key
  • For each github account, upload a (distinct) public key.

Configuration

~/.ssh/config

Host github-kc
    Hostname        github.com
    User git
    IdentityFile    ~/.ssh/github_rsa_kc.pub
    # LogLevel DEBUG3

Host github-abc
    Hostname        github.com
    User git
    IdentityFile    ~/.ssh/github_rsa_abc.pub
    # LogLevel DEBUG3

Set remote url for repo:

  • For repo in Host github-kc:

    git remote set-url origin git@github-kc:kuchaguangjie/pygtrans.git
    
  • For repo in Host github-abc:

    git remote set-url origin git@github-abc:abcdefg/yyy.git
    

Explaination

Options in ~/.ssh/config:

  • Host github-<identify_specific_user>
    Host could be any value that could identify a host plus an account, it don't need to be a real host, e.g github-kc identify one of my account on github for my local laptop,

    When set remote url for a git repo, this is the value to put after git@, that's how a repo maps to a Host, e.g git remote set-url origin git@github-kc:kuchaguangjie/pygtrans.git


  • [Following are sub options of Host]
  • Hostname
    specify the actual hostname, just use github.com for github,
  • User git
    the user is always git for github,
  • IdentityFile
    specify key to use, just put the path the a public key,
  • LogLevel
    specify log level to debug, if any issue, DEBUG3 gives the most detailed info.

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

Possible reasons for timeout when trying to access EC2 instance

Allow ssh and port 22 from ufw, then enable it and check with status command

sudo ufw allow ssh
sudo ufw allow 22
sudo ufw enable
sudo ufw status

How do I remove the passphrase for the SSH key without having to create a new key?

Short answer:

$ ssh-keygen -p

This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).


If you would like to do it all on one line without prompts do:

$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]

Important: Beware that when executing commands they will typically be logged in your ~/.bash_history file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.

Notice though that you can still use -f keyfile without having to specify -P nor -N, and that the keyfile defaults to ~/.ssh/id_rsa, so in many cases, it's not even needed.

You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.

Execute ssh with password authentication via windows command prompt

PowerShell solution

Using Posh-SSH:

New-SSHSession -ComputerName 0.0.0.0 -Credential $cred | Out-Null
Invoke-SSHCommand -SessionId 1 -Command "nohup sleep 5 >> abs.log &" | Out-Null

ssh_exchange_identification: Connection closed by remote host under Git bash

I just ran into this today and it was because the server I was trying to connect to was overloaded with processing. So it may be possible that the server is low on memory or CPU starved.

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

How to reset or change the passphrase for a GitHub SSH key?

In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.

Managing SSH keys within Jenkins for Git

According to this article, you may try following command:

   ssh-add -l

If your key isn't in the list, then

   ssh-add /var/lib/jenkins/.ssh/id_rsa_project

How to install sshpass on mac?

Solution provided by lukesUbuntu from github works for me:

Just use brew

$ brew install http://git.io/sshpass.rb

How to run the sftp command with a password from Bash script?

Combine sshpass with a locked-down credentials file and, in practice, it's as secure as anything - if you've got root on the box to read the credentials file, all bets are off anyway.

Delete newline in Vim

The problem is that multiples char 0A (\n) that are invisible may accumulate. Supose you want to clean up from line 100 to the end:

Typing ESC and : (terminal commander)

:110,$s/^\n//

In a vim script:

execute '110,$s/^\n//'

Explanation: from 110 till the end search for lines that start with new line (are blank) and remove them

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.

OS X Terminal UTF-8 issues

My terminal was just acting silly, not printing out åäö. I found (and set) this setting: enter image description here

Under Terminal -> Preferences... -> Profiles -> Advanced.

Seems to have fixed my problem.

SSH to Elastic Beanstalk instance

I also ran into the same problem awhile ago. I wanted to use the key file, but Amazon says somewhere that you cannot add a key file to an existing EC2 server. For the first Beanstalk application, Amazon preconfigures the application for you. You need to create a new application, and you can configure the EC2 server that runs the Beanstalk app to use an old pem file (ppk if using Putty), or you can create a new one. Now you should be able to SSH.

enter image description here

Then configure, then delete your old app.

List of all users that can connect via SSH

Any user with a valid shell in /etc/passwd can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.

To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.

SSH to Vagrant box in Windows?

Personally, I just use Cygwin. Which allows you to use many common *nix commands in Windows. SSH being one of them.

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

After trying a lot of passwords and becoming totally confused why my public key password is not working I found out that I have to use vagrant as password.

Maybe this info helps someone else too - that's because I've written it down here.

Edit:
According to the Vagrant documentation, there is usually a default password for the user vagrant which is vagrant.
Read more on here: official website

In recent versions however, they have moved to generating keypairs for each machine. If you would like to find out where that key is, you can run vagrant ssh -- -v. This will show the verbose output of the ssh login process. You should see a line like

debug1: Trying private key: /home/aaron/Documents/VMs/.vagrant/machines/default/virtualbox/private_key

How to ignore ansible SSH authenticity checking?

I found the answer, you need to set the environment variable ANSIBLE_HOST_KEY_CHECKING to False. For example:

ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook ...

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

How to restrict SSH users to a predefined set of commands after login?

GNU Rush may be the most flexible and secure way to accomplish this:

GNU Rush is a Restricted User Shell, designed for sites that provide limited remote access to their resources, such as svn or git repositories, scp, or the like. Using a sophisticated configuration file, GNU Rush gives you complete control over the command lines that users execute, as well as over the usage of system resources, such as virtual memory, CPU time, etc.

Specify an SSH key for git push for a given domain

you most specified in the file config key ssh:

# Default GitHub user
Host one
 HostName gitlab.com
 User git
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/key-one
 IdentitiesOnly yes

#two user
Host two
 HostName gitlab.com
 User git
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/key-two
 IdentitiesOnly yes

How to run a script file remotely using SSH

Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.

Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.

ssh kev@server1 './test/foo.sh'

Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).

Use Expect in a Bash script to provide a password to an SSH command

Another way that I found useful to use a small Expect script from a Bash script is as follows.

...
Bash script start
Bash commands
...
expect - <<EOF
spawn your-command-here
expect "some-pattern"
send "some-command"
...
...
EOF
...
More Bash commands
...

This works because ...If the string "-" is supplied as a filename, standard input is read instead...

Automatically enter SSH password with script

If you are doing this on a Windows system, you can use Plink (part of PuTTY).

plink your_username@yourhost -pw your_password

Why can I ping a server but not connect via SSH?

On the server, try:

netstat -an 

and look to see if tcp port 22 is opened (use findstr in Windows or grep in Unix).

Best way to script remote SSH commands in Batch (Windows)

You can also use Bash on Ubuntu on Windows directly. E.g.,

bash -c "ssh -t user@computer 'cd /; sudo my-command'"

Per Martin Prikryl's comment below:

The -t enables terminal emulation. Whether you need the terminal emulation for sudo depends on configuration (and by default you do no need it, while many distributions override the default). On the contrary, many other commands need terminal emulation.

How can I remove an SSH key?

If you're trying to perform an SSH-related operation and get the following error:

$ git fetch
no such identity: <ssh key path>: No such file or directory

You can remove the missing SSH key from your SSH agent with the following:

$ eval `ssh-agent -s`  # start ssh agent
$ ssh-add -D <ssh key path>  # delete ssh key

Add Keypair to existing EC2 instance

You can just add a new key to the instance by the following command:

ssh-copy-id -i ~/.ssh/id_rsa.pub domain_alias

You can configure domain_alias in ~/.ssh config

host domain_alias
  User ubuntu
  Hostname domain.com
  IdentityFile ~/.ssh/ec2.pem

How to specify the private SSH-key to use when executing shell command on Git?

You could use GIT_SSH environment variable. But you will need to wrap ssh and options into a shell script.

See git manual: man git in your command shell.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

Please follow this guide: https://gist.github.com/feczo/7282a6e00181fde4281b with pictures.

In short:

Using Puttygen, click 'Generate' move the mouse around as instructed and wait

  • Enter your desired username

  • Enter your password

  • Save the private key

Copy the entire content of the 'Public key for pasting into OpenSSH authorized_keys file' window. Make sure to copy every single character from the beginning to the very end!

Go to the Create instances page in the Google Cloud Platform Console and in the advanced options link paste the contents of your public key.

Note the IP address of the instance once it is complete. Open putty, from the left hand menu go to Connection / SSH / Auth and define the key file location which was saved.

From the left hand menu go to Connection / Data and define the same username

  • Enter the IP address of your instance
  • name the connection below saved Sessions as 'GCE' click on 'Save'
  • double click the 'GCE' entry you just created
  • accept the identy of the host

Now login with the password you specified earlier and run sudo su - and you are all set.

scp (secure copy) to ec2 instance without password

copy a file from a local server to a remote server

sudo scp -i my-pem-file.pem ./source/test.txt [email protected]:~/destination/

copy a file from a remote server to a local machine

sudo scp -i my-pem-file.pem [email protected]:~/source/of/remote/test.txt ./where/to/put

So the basically syntax is:-

scp -i my-pem-file.pem username@source:/location/to/file username@destination:/where/to/put

-i is for the identity_file

Use PPK file in Mac Terminal to connect to remote connection over SSH

Convert PPK to OpenSSh

OS X: Install Homebrew, then run

brew install putty

Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search

To generate the private key:

cd ~

puttygen id_dsa.ppk -O private-openssh -o id_dsa

and to generate the public key:

puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub

Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:

mkdir -p ~/.ssh
mv -i ~/id_dsa* ~/.ssh
chmod 600 ~/.ssh/id_dsa
chmod 666 ~/.ssh/id_dsa.pub

connect with ssh server

ssh -i ~/.ssh/id_dsa username@servername

Port Forwarding to connect mysql remote server

ssh -i ~/.ssh/id_dsa -L 9001:127.0.0.1:3306 username@serverName

git - Server host key not cached

For those of you who are setting up MSYS Git on Windows using PuTTY via the standard command prompt, the way to add a host to PuTTY's cache is to run

> plink.exe <host>

For example:

> plink.exe codebasehq.com

The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 2e:db:b6:22:f7:bd:48:f6:da:72:bf:59:d7:75:d7:4e
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)

Just answer y, and then Ctrl+C the rest.

Do check the fingerprint though. This warning is there for a good reason. Fingerprints for some git services (please edit to add more):

How to fix request failed on channel 0

rebooting the instance from AWS console worked for me. There was a service that was leaking file connections that lsof helped find.

How to pass the password to su/sudo/ssh without overriding the TTY?

Take a look at expect linux utility.

It allows you to send output to stdio based on simple pattern matching on stdin.

Perform commands over ssh with Python

I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called spur that uses paramiko to implement a slightly nicer interface:

import spur

shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello

If you need to run inside a shell:

shell.run(["sh", "-c", "echo -n hello"])

Trying to SSH into an Amazon Ec2 instance - permission error

.400 protects it by making it read only and only for the owner.
You can find the answer from the ASW guide.

chmod 400 yourPrivateKey.pem

enter image description here

SSH to AWS Instance without key pairs

1) You should be able to change the ssh configuration (on Ubuntu this is typically in /etc/ssh or /etc/sshd) and re-enable password logins.

2) There's nothing really AWS specific about this - Apache can handle VHOSTS (virtual hosts) out-of-the-box - allowing you to specify that a certain domain is served from a certain directory. I'd Google that for more info on the specifics.

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

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

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

Putty: Getting Server refused our key Error

Another reason could be UTF-8 BOM in the authorized_keys file.

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

In my case it's because the user's group is not set in AllowGroups of configuration file /etc/ssh/sshd_config. After adding it, everything works fine.

SSH Key - Still asking for password and passphrase

Same problem to me and the solution was:

See this github doc to convert remote's URL from https to ssh. To check if remote's URL is ssh or https, use git remote -v. To switch from https to ssh: git remote set-url origin [email protected]:USERNAME/REPOSITORY.git @jeeYem

Permissions error when connecting to EC2 via SSH on Mac OSx

After about a half hour of searching and trying to debug this I was able to figure it out. My situation involved me using the same pem file for two different ec2 instance and it working for one and not the other.

My first instance it worked on was the standard aws linux ami amzn-ami-hvm-2014.03.2.x86_64-ebs. I simply used

ssh -i mypemfile.pem ec2-user@myec2ipaddress 

and it worked.

I then launched a fedora instance Fedora-x86_64-19-20140407-sda and tried the same command but kept getting:

Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

After changing my username from ec2-user to fedora it worked!

ssh -i mypemfile.pem fedora@myec2address

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

If you are using a Ubuntu system, use the following to Store Password Permanently:

git config --global credential.helper store

key_load_public: invalid format

Instead of directly saving the private key Go to Conversions and Export SSh Key. Had the same issue and this worked for me

find . -type f -exec chmod 644 {} ;

Piping to xargs is a dirty way of doing that which can be done inside of find.

find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;

You can be even more controlling with other options, such as:

find . -type d -user harry -exec chown daisy {} \;

You can do some very cool things with find and you can do some very dangerous things too. Have a look at "man find", it's long but is worth a quick read. And, as always remember:

  • If you are root it will succeed.
  • If you are in root (/) you are going to have a bad day.
  • Using /path/to/directory can make things a lot safer as you are clearly defining where you want find to run.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

I faced a similar issue. I checked for the below:

  1. if ssh is not installed on your machine, you will have to install it firstly. (You will get a message saying ssh is not recognized as a command).
  2. Port 22 is open or not on the server you are trying to ssh.
  3. If the control of remote server is in your hands and you have permissions, try to disable firewall on it.
  4. Try to ssh again.

If port is not an issue then you would have to check for firewall settings as it is the one that is blocking your connection.

For me too it was a firewall issue between my machine and remote server.I disabled the firewall on the remote server and I was able to make a connection using ssh.

How to ssh connect through python Paramiko with ppk public key

For me I doing this:

import paramiko
hostname = 'my hostname or IP' 
myuser   = 'the user to ssh connect'
mySSHK   = '/path/to/sshkey.pub'
sshcon   = paramiko.SSHClient()  # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed

works for me pretty ok

Checkout Jenkins Pipeline Git SCM with credentials?

To explicitly checkout using a specific credentials

    stage('Checkout external proj') {
        steps {
            git branch: 'my_specific_branch',
                credentialsId: 'my_cred_id',
                url: 'ssh://[email protected]/proj/test_proj.git'

            sh "ls -lat"
        }
    }

To checkout based on the configred credentials in the current Jenkins Job

    stage('Checkout code') {
        steps {
            checkout scm
        }
    }

You can use both of the stages within a single Jenkins file.

Git Bash: Could not open a connection to your authentication agent

I was struggling with the problem as well.

After I typed $ eval 'ssh-agent -s' followed by $ssh-add ~/.ssh/id_rsa

I got the same complain: "Could not open a connection to your authentication agent". Then I realize there are two different kind of quotation on my computer's keyboard. So I tried the one at the same position as "~": $ eval ssh-agent -s $ ssh-add ~/.ssh/id_rsa

And bang it worked.

Vagrant ssh authentication failure

Just for those people that have been idiots like me, or have had something odd happen to their vagrant machine. This error can also occur when you changed the permissions of the vagrant user's home directory (deliberately or by accident).

You can log in instead (as described in other posts) using the password ('vagrant') and then run the following command to fix the permissions.

sudo chown -R vagrant:vagrant /home/vagrant

Then you should be able to log in again without entering the password.

TL;DR: The permissions on your vagrant home folder are wrong.

.bashrc: Permission denied

.bashrc is not meant to be executed but sourced. Try this instead:

. ~/.bashrc

Cheers!

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

quick note for those recently upgrading to "modern" ssh version [OpenSSH_8.1p1, OpenSSL 1.1.1d FIPS 10 Sep 2019] - supplied with fedora 31, seems not to be anymore accepting old DSA SHA256 keys (mine are dated 2006!) - created a new rsa key, public added to authorized, private on client, and everything works perfectly.

thanks for previous suggestions, especially the ssh -v has been very useful

python paramiko ssh

There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me:

import paramiko

ip='server ip'
port=22
username='username'
password='password'

cmd='some useful command' 

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)

stdin,stdout,stderr=ssh.exec_command('some really useful command')
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)

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

If your drive letter is C, you should be able to use

scp -r \desktop\myfolder\deployments\ user@host:/path/to/whereyouwant/thefile

without drive letter and backslashes instead of forward slashes.

You are using putty, so you can use pscp. It is better adapted to Windows.

Git Remote: Error: fatal: protocol error: bad line length character: Unab

This might help someone. When I was trying to clone a project from an EC2 instance, I was getting the below error:

Cloning into 'repo1'...
fatal: protocol error: bad line length character: logi

The resolution for me includes the below steps:

  1. Ensure SSH key (public) is added/updated in the EC2 instance.
  2. Ensure authentication agent (in my case its Pageant=Putty Authentication Agent) is running and the corresponding private key is loaded.
  3. Use the EC2 SSH key ID for the public key for git clone. Example:

    git clone ssh://{SSH Key ID}@someaccount.amazonaws.com/v1/repos/repo1

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

I had this problem when I wanted to make a vnc connection via a tunnel. But the vncserver was not running. I solved it by opening the channel on the remote machine with vncserver :3.

How to upload files to server using Putty (ssh)

"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:

file.py will be uploaded into your HOME dir on remote server.

or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:

After connecting to the server pscp will ask for a password.

Passing variables in remote ssh command

As answered previously, you do not need to set the environment variable on the remote host. Instead, you can simply do the meta-expansion on the local host, and pass the value to the remote host.

ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'

If you really want to set the environment variable on the remote host and use it, you can use the env program

ssh [email protected] "env BUILD_NUMBER=$BUILD_NUMBER ~/tools/run_pvt.pl \$BUILD_NUMBER"

In this case this is a bit of an overkill, and note

  • env BUILD_NUMBER=$BUILD_NUMBER does the meta expansion on the local host
  • the remote BUILD_NUMBER environment variable will be used by
    the remote shell

How to solve Permission denied (publickey) error when using Git?

When ever I get a new computer at work or switch jobs these are steps I follow setup github access. Mac or Windows

-Go to https://github.[yourWorkDomain].com. navigate to Settings ? Developer Settings ? Personal access tokens
-Generate a new token
-Set the token description and only check the “repo” box for scope (this will give you repo:status, repo_deployment, public_repo, repo:invite access)

-After your are given the token, copy it (don't navigate away yet, confirm the next two steps work)
-Try to clone the repo again(using “https”)
-For the username use your Username
-For the password, paste the token you copied
-All future requests should work now without asking for your username and password.

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

You can do something like this, to handle the host key checking as well

import os
os.system("sshpass -p password scp -o StrictHostKeyChecking=no local_file_path username@hostname:remote_path")

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.

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.

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

My way on Windows 8

  1. Add a directory with ssh-keygen to the system PATH variable, usually C:\Program Files (x86)\Git\bin

  2. Open CMD, go to C:\Users\Me\

  3. Generate SSH key ssh-keygen -t rsa

    Enter file in which to save the key (//.ssh/id_rsa): .ssh/id_rsa (change a default incorrect path to .ssh/somegoodname_rsa)

  4. Add the key to Heroku heroku keys:add

    Select a created key from a list

  5. Go to your app directory, write some beautiful code

  6. Init a git repo git init git add . git commit -m 'chore(release): v0.0.1

  7. Create Heroku application heroku create

  8. Deploy your app git push heroku master

  9. Open your app heroku open

Find the IP address of the client in an SSH session

You can get it in a programmatic way via an SSH library (https://code.google.com/p/sshxcute)

public static String getIpAddress() throws TaskExecFailException{
    ConnBean cb = new ConnBean(host, username, password);
    SSHExec ssh = SSHExec.getInstance(cb);
    ssh.connect();
    CustomTask sampleTask = new ExecCommand("echo \"${SSH_CLIENT%% *}\"");
    String Result = ssh.exec(sampleTask).sysout;
    ssh.disconnect();   
    return Result;
}

How to permanently add a private key with ssh-add on Ubuntu?

very simple ^_^ two steps

1.yum install keychain

2.add code below to .bash_profile

/usr/bin/keychain $HOME/.ssh/id_dsa
source $HOME/.keychain/$HOSTNAME-sh

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

You can also add -oHostKeyAlgorithms=+ssh-dss in your ssh line:

ssh -oHostKeyAlgorithms=+ssh-dss user@host

ssh-copy-id no identities found error

Generating ssh keys on the client solved it for me

$ ssh-keygen -t rsa

Disable password authentication for SSH

Here's a script to do this automatically

# Only allow key based logins
sed -n 'H;${x;s/\#PasswordAuthentication yes/PasswordAuthentication no/;p;}' /etc/ssh/sshd_config > tmp_sshd_config
cat tmp_sshd_config > /etc/ssh/sshd_config
rm tmp_sshd_config

Why does an SSH remote command get fewer environment variables then when run manually?

How about sourcing the profile before running the command?

ssh user@host "source /etc/profile; /path/script.sh"

You might find it best to change that to ~/.bash_profile, ~/.bashrc, or whatever.

(As here (linuxquestions.org))

How do I access my SSH public key?

Open terminal nano ~/.ssh/id_rsa.pub

git-upload-pack: command not found, when cloning remote Git repo

For zsh you need to put it in this file: ~/.zshenv

For example, on OS X using the git-core package from MacPorts:

$ echo 'export PATH=/opt/local/sbin:/opt/local/bin:$PATH' > ~/.zshenv

How to use 'git pull' from the command line?

One more option is to add the path of the privatekey file like this in terminal:

ssh-add "path to the privatekeyfile"

and then execute the pull command

vagrant login as root by default

This works if you are on ubuntu/trusty64 box:

vagrant ssh

Once you are in the ubuntu box:

sudo su

Now you are root user. You can update root password as shown below:

sudo -i
passwd

Now edit the below line in the file /etc/ssh/sshd_config

PermitRootLogin yes

Also, it is convenient to create your own alternate username:

adduser johndoe

Wait until it asks for password.

How to SSH to a VirtualBox guest externally through a host?

In order to ssh to a Ubuntu VM running in VirtualBox from your host machine, you need to set up two network adapters for the VM.

First of all, stop the VM if not yet.

Then select the VM and click the Settings menu in the VirtualBox toolbar:

enter image description here

Set up Adapter 1

enter image description here

Set up Adapter 2

enter image description here

(Note: you don't need to set up any port forwarding.)

That's it. Once set up, you can start your VM. In your VM, the network configuration will look like below and you'll have Internet access too:

enter image description here

Also in your host machine, you can ssh to your VM:

enter image description here

Be sure that the SSH server has been installed and up running in the VM.

$ ps aux | grep sshd
root 864 0.1 0.5 65512 5392 ? Ss 22:10 0:00 /usr/sbin/sshd -D

If not, install it:

$ sudo apt-get install openssh-server

Also for your information:

  • My VirtualBox version: 5.2.6 r120293 (Qt5.6.2), 2018
  • My Ubuntu version: Ubuntu 16.04.3 LTS
  • My host machine: Windows 10

Verify host key with pysftp

Connect to the server first with a Windows ssh client that uses the known_hosts file. PuTTy stores the data in the windows registry,however OpenSSH uses the known_hosts file, and will add entries in there after you connect. Default location for the file is %USERPROFILE%.ssh. I hope this helps

Failed to add the host to the list of know hosts

In your specific case, your known_hosts is a folder, so you need to remove it first.

For other people which experiencing similar issue, please check the right permission to your ~/ssh/known_hosts as it may be owned by different user (e.g. root). So you may try to run:

sudo chown -v $USER ~/.ssh/known_hosts

to fix it.

How to ssh from within a bash script?

There's yet another way to do it using Shared Connections, ie: somebody initiates the connection, using a password, and every subsequent connection will multiplex over the same channel, negating the need for re-authentication. ( And its faster too )

# ~/.ssh/config 
ControlMaster auto
ControlPath ~/.ssh/pool/%r@%h

then you just have to log in, and as long as you are logged in, the bash script will be able to open ssh connections.

You can then stop your script from working when somebody has not already opened the channel by:

ssh ... -o KbdInteractiveAuthentication=no ....

How to enter ssh password using bash?

Create a new keypair: (go with the defaults)

ssh-keygen

Copy the public key to the server: (password for the last time)

ssh-copy-id [email protected]

From now on the server should recognize your key and not ask you for the password anymore:

ssh [email protected]

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I had the same problem on Windows XP just recently. I tried to chmod 700 on my ~/.ssh/id_rsa file but it did not seem to work. When I had a look at the permissions using ls -l on the ~/.ssh/id_rsa I could see that my effective permissions still was 644.

Then I remembered that windows permissions also inherit permissions from the folders, and the folder was still open to everyone. A solution could be to set permissions for the folder as well, but I think a better way would be to tell the system to ignore inheritance for this file. This can be done using the advanced option on the security tab in the properties of the file, and unchecking "inherit from parent permissions..."

This might be helpful for others with the same problem.

How to add bootstrap in angular 6 project?

using command

npm install bootstrap --save

open .angular.json old (.angular-cli.json ) file find the "styles" add the bootstrap css file

"styles": [
       "src/styles.scss",
       "node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Anaconda version with Python 3.5

It is very simple, first, you need to be inside the virtualenv you created, then to install a specific version of python say 3.5, use Anaconda, conda install python=3.5

In general you can do this for any python package you want

conda install package_name=package_version

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

sep='\t' is often used for Tab-delimited file.

AssertNull should be used or AssertNotNull

assertNotNull asserts that the object is not null. If it is null the test fails, so you want that.

Passing vector by reference

You don't need to use **arr, you can either use:

void do_something(int el, std::vector<int> *arr){
    arr->push_back(el);
}

or:

 void do_something(int el, std::vector<int> &arr){
    arr.push_back(el);
}

**arr makes no sense but if you insist using it, do it this way:

void do_something(int el, std::vector<int> **arr){
    (*arr)->push_back(el);
}

but again there is no reason to do so...

What does "javascript:void(0)" mean?

The void operator evaluates the given expression and then returns undefined. It avoids refreshing the page.

div inside table

It is allow as TD can contain inline- AND block-elements.

Here you can find it in the reference: http://xhtml.com/en/xhtml/reference/td/#td-contains

jQuery jump or scroll to certain position, div or target on the page from button onclick

$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used

Add list to set?

list objects are unhashable. you might want to turn them in to tuples though.

ASP.NET MVC controller actions that return JSON or partial html

To answer the other half of the question, you can call:

return PartialView("viewname");

when you want to return partial HTML. You'll just have to find some way to decide whether the request wants JSON or HTML, perhaps based on a URL part/parameter.

Use latest version of Internet Explorer in the webbrowser control

I know this has been posted but here is a current version for dotnet 4.5 above that I use. I recommend to use the default browser emulation respecting doctype

InternetExplorerFeatureControl.Instance.BrowserEmulation = DocumentMode.DefaultRespectDocType;

internal class InternetExplorerFeatureControl
{
    private static readonly Lazy<InternetExplorerFeatureControl> LazyInstance = new Lazy<InternetExplorerFeatureControl>(() => new InternetExplorerFeatureControl());
    private const string RegistryLocation = @"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl";
    private readonly RegistryView _registryView = Environment.Is64BitOperatingSystem && Environment.Is64BitProcess ? RegistryView.Registry64 : RegistryView.Registry32;
    private readonly string _processName;
    private readonly Version _version;

    #region Feature Control Strings (A)

    private const string FeatureRestrictAboutProtocolIe7 = @"FEATURE_RESTRICT_ABOUT_PROTOCOL_IE7";
    private const string FeatureRestrictAboutProtocol = @"FEATURE_RESTRICT_ABOUT_PROTOCOL";

    #endregion

    #region Feature Control Strings (B)

    private const string FeatureBrowserEmulation = @"FEATURE_BROWSER_EMULATION";

    #endregion

    #region Feature Control Strings (G)

    private const string FeatureGpuRendering = @"FEATURE_GPU_RENDERING";

    #endregion

    #region Feature Control Strings (L)

    private const string FeatureBlockLmzScript = @"FEATURE_BLOCK_LMZ_SCRIPT";

    #endregion

    internal InternetExplorerFeatureControl()
    {
        _processName = $"{Process.GetCurrentProcess().ProcessName}.exe";
        using (var webBrowser = new WebBrowser())
            _version = webBrowser.Version;
    }

    internal static InternetExplorerFeatureControl Instance => LazyInstance.Value;

    internal RegistryHive RegistryHive { get; set; } = RegistryHive.CurrentUser;

    private int GetFeatureControl(string featureControl)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", false))
            {
                if (key.GetValue(_processName) is int value)
                {
                    return value;
                }
                return -1;
            }
        }
    }

    private void SetFeatureControl(string featureControl, int value)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", true))
            {
                key.SetValue(_processName, value, RegistryValueKind.DWord);
            }
        }
    }

    #region Internet Feature Controls (A)

    /// <summary>
    /// Windows Internet Explorer 8 and later. When enabled, feature disables the "about:" protocol. For security reasons, applications that host the WebBrowser Control are strongly encouraged to enable this feature.
    /// By default, this feature is enabled for Windows Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool AboutProtocolRestriction
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            return Convert.ToBoolean(GetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol));
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            SetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (B)

    /// <summary>
    /// Windows Internet Explorer 8 and later. Defines the default emulation mode for Internet Explorer and supports the following values.
    /// </summary>
    internal DocumentMode BrowserEmulation
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var value = GetFeatureControl(FeatureBrowserEmulation);
            if (Enum.IsDefined(typeof(DocumentMode), value))
            {
                return (DocumentMode)value;
            }
            return DocumentMode.NotSet;
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var tmp = value;
            if (value == DocumentMode.DefaultRespectDocType)
                tmp = DefaultRespectDocType;
            else if (value == DocumentMode.DefaultOverrideDocType)
                tmp = DefaultOverrideDocType;
            SetFeatureControl(FeatureBrowserEmulation, (int)tmp);
        }
    }

    #endregion

    #region Internet Feature Controls (G)

    /// <summary>
    /// Internet Explorer 9. Enables Internet Explorer to use a graphics processing unit (GPU) to render content. This dramatically improves performance for webpages that are rich in graphics.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// Note: GPU rendering relies heavily on the quality of your video drivers. If you encounter problems running Internet Explorer with GPU rendering enabled, you should verify that your video drivers are up to date and that they support hardware accelerated graphics.
    /// </summary>
    internal bool GpuRendering
    {
        get
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureGpuRendering));
        }
        set
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            SetFeatureControl(FeatureGpuRendering, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (L)

    /// <summary>
    /// Internet Explorer 7 and later. When enabled, feature allows scripts stored in the Local Machine zone to be run only in webpages loaded from the Local Machine zone or by webpages hosted by sites in the Trusted Sites list. For more information, see Security and Compatibility in Internet Explorer 7.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool LocalScriptBlocking
    {
        get
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureBlockLmzScript));
        }
        set
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            SetFeatureControl(FeatureBlockLmzScript, Convert.ToInt16(value));
        }
    }

    #endregion


    private DocumentMode DefaultRespectDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11RespectDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10RespectDocType;
                case 9:
                    return DocumentMode.InternetExplorer9RespectDocType;
                case 8:
                    return DocumentMode.InternetExplorer8RespectDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    private DocumentMode DefaultOverrideDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11OverrideDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10OverrideDocType;
                case 9:
                    return DocumentMode.InternetExplorer9OverrideDocType;
                case 8:
                    return DocumentMode.InternetExplorer8OverrideDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}

internal enum DocumentMode
{
    NotSet = -1,
    [Description("Webpages containing standards-based !DOCTYPE directives are displayed in IE latest installed version mode.")]
    DefaultRespectDocType,
    [Description("Webpages are displayed in IE latest installed version mode, regardless of the declared !DOCTYPE directive.  Failing to declare a !DOCTYPE directive could causes the page to load in Quirks.")]
    DefaultOverrideDocType,
    [Description(
        "Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer11OverrideDocType = 11001,

    [Description(
        "IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11."
    )] InternetExplorer11RespectDocType = 11000,

    [Description(
        "Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive."
    )] InternetExplorer10OverrideDocType = 10001,

    [Description(
        "Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10."
    )] InternetExplorer10RespectDocType = 10000,

    [Description(
        "Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer9OverrideDocType = 9999,

    [Description(
        "Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer9RespectDocType = 9000,

    [Description(
        "Webpages are displayed in IE8 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer8OverrideDocType = 8888,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer8RespectDocType = 8000,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control."
    )] InternetExplorer7RespectDocType = 7000
}

How to scroll to top of long ScrollView layout?

Had the same issue, probably some kind of bug.

Even the fullScroll(ScrollView.FOCUS_UP) from the other answer didn't work.
Only thing that worked for me was calling scroll_view.smoothScrollTo(0,0) right after the dialog is shown.

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

this work for me

compile 'com.android.support:appcompat-v7:26.0.0'

change 26.0.0 to 26.0.1

compile 'com.android.support:appcompat-v7:26.0.1'

How to access ssis package variables inside script component

Accessing package variables in a Script Component (of a Data Flow Task) is not the same as accessing package variables in a Script Task. For a Script Component, you first need to open the Script Transformation Editor (right-click on the component and select "Edit..."). In the Custom Properties section of the Script tab, you can enter (or select) the properties you want to make available to the script, either on a read-only or read-write basis: screenshot of Script Transformation Editor properties page Then, within the script itself, the variables will be available as strongly-typed properties of the Variables object:

// Modify as necessary
public override void PreExecute()
{
    base.PreExecute();
    string thePath = Variables.FilePath;
    // Do something ...
}

public override void PostExecute()
{
    base.PostExecute();
    string theNewValue = "";
    // Do something to figure out the new value...
    Variables.FilePath = theNewValue;
}

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    string thePath = Variables.FilePath;
    // Do whatever needs doing here ...
}

One important caveat: if you need to write to a package variable, you can only do so in the PostExecute() method.

Regarding the code snippet:

IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;

XlsFile = varCollection["User::FilePath"].Value.ToString();

varCollection is initialized to null and never set to a valid value. Thus, any attempt to dereference it will fail.

Typescript: React event types

For those who are looking for a solution to get an event and store something, in my case a HTML 5 element, on a useState here's my solution:

const [anchorElement, setAnchorElement] = useState<HTMLButtonElement | null>(null);

const handleMenu = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : void => {
    setAnchorElement(event.currentTarget);
};

How do you increase the max number of concurrent connections in Apache?

change the MaxClients directive. it is now on 256.

Converting to upper and lower case in Java

I consider this simpler than any prior correct answer. I'll also throw in javadoc. :-)

/**
 * Converts the given string to title case, where the first
 * letter is capitalized and the rest of the string is in
 * lower case.
 * 
 * @param s a string with unknown capitalization
 * @return a title-case version of the string
 */
public static String toTitleCase(String s)
{
    if (s.isEmpty())
    {
        return s;
    }
    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}

Strings of length 1 do not needed to be treated as a special case because s.substring(1) returns the empty string when s has length 1.

Cache an HTTP 'Get' service response in AngularJS?

Angular's $http has a cache built in. According to the docs:

cache – {boolean|Object} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.

Boolean value

So you can set cache to true in its options:

$http.get(url, { cache: true}).success(...);

or, if you prefer the config type of call:

$http({ cache: true, url: url, method: 'GET'}).success(...);

Cache Object

You can also use a cache factory:

var cache = $cacheFactory('myCache');

$http.get(url, { cache: cache })

You can implement it yourself using $cacheFactory (especially handly when using $resource):

var cache = $cacheFactory('myCache');

var data = cache.get(someKey);

if (!data) {
   $http.get(url).success(function(result) {
      data = result;
      cache.put(someKey, data);
   });
}

Angular.js How to change an elements css class on click and to remove all others

I only change/remove the class:

   function removeClass() {
                    var element = angular.element('#nameInput');
          element.removeClass('nameClass');
   };

How to Convert the value in DataTable into a string array in c#

 
            string[] result = new string[table.Columns.Count];
            DataRow dr = table.Rows[0];
            for (int i = 0; i < dr.ItemArray.Length; i++)
            {
                result[i] = dr[i].ToString();
            }
            foreach (string str in result)
                Console.WriteLine(str);

The endpoint reference (EPR) for the Operation not found is

This can be solved by disabling validation

<proxy>
    <!-- . . . -->
    <parameter name="disableOperationValidation">true</parameter>
</proxy>

Generate a random number in a certain range in MATLAB

You can also use:

round(mod(rand.*max,max-1))+min

Conditional HTML Attributes using Razor MVC3

You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...

<input type="text" id="@strElementID" class="@strCSSClass" />

If strCSSClass is null then the class attribute won't render at all.

SSSHHH...don't tell. :)

How to compare two tags with git?

For a side-by-side visual representation, I use git difftool with openDiff set to the default viewer.

Example usage:

git difftool tags/<FIRST TAG> tags/<SECOND TAG>

If you are only interested in a specific file, you can use:

git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>

As a side-note, the tags/<TAG>s can be replaced with <BRANCH>es if you are interested in diffing branches.

No tests found with test runner 'JUnit 4'

I've had issues with this recently, which seem to be fixed in the latest Eclipse.

eclipse-java 4.11.0,2019-03:R -> 4.12.0,2019-06:R

React navigation goBack() and update parent state

With React Navigation v5, just use the navigate method. From the docs:

To achieve this, you can use the navigate method, which acts like goBack if the screen already exists. You can pass the params with navigate to pass the data back

Full example:

import React from 'react';
import { StyleSheet, Button, Text, View } from 'react-native';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function ScreenA ({ navigation, route }) {
  const { params } = route;

  return (
    <View style={styles.container}>
      <Text>Params: {JSON.stringify(params)}</Text>
      <Button title='Go to B' onPress={() => navigation.navigate('B')} />
    </View>
  );
}

function ScreenB ({ navigation }) {
  return (
    <View style={styles.container}>
      <Button title='Go to A'
        onPress={() => {
          navigation.navigate('A', { data: 'Something' })
        }}
      />
    </View>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator mode="modal">
        <Stack.Screen name="A" component={ScreenA} />
        <Stack.Screen name="B" component={ScreenB} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Parse JSON with R

Try below code using RJSONIO in console

library(RJSONIO)
library(RCurl)


json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")

json_file2 = RJSONIO::fromJSON(json_file)

head(json_file2)

How to use source: function()... and AJAX in JQuery UI autocomplete

Try this code. You can use $.get instead of $.ajax

$( "input.suggest-user" ).autocomplete({
    source: function( request, response ) {
        $.ajax({
            dataType: "json",
            type : 'Get',
            url: 'yourURL',
            success: function(data) {
                $('input.suggest-user').removeClass('ui-autocomplete-loading');  
                // hide loading image

                response( $.map( data, function(item) {
                    // your operation on data
                }));
            },
            error: function(data) {
                $('input.suggest-user').removeClass('ui-autocomplete-loading');  
            }
        });
    },
    minLength: 3,
    open: function() {},
    close: function() {},
    focus: function(event,ui) {},
    select: function(event, ui) {}
});

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

  1. Mount the centos live cd and boot
  2. Go into rescue mode and wait for it load up
  3. Read the terminal to see where it mounted the OS
  4. Go into OS
  5. vim or nano /etc/selinux/config
  6. Make sure SELINUX=enforcing or disabled

PHP sessions that have already been started

Only if you want to destroy previous session :

<?php
    if(!isset($_SESSION)) 
    { 
        session_start(); 
    }
    else
    {
        session_destroy();
        session_start(); 
    }
?>

or you can use

unset($_SESSION['variable_session _data'])

to destroy a particular session variable.

What exceptions should be thrown for invalid or unexpected parameters in .NET?

Short answer:
Neither

Longer answer:
using Argument*Exception (except in a library that is a product on its on, such as component library) is a smell. Exceptions are to handle exceptional situation, not bugs, and not user's (i.e. API consumer) shortfalls.

Longest answer:
Throwing exceptions for invalid arguments is rude, unless you write a library.
I prefer using assertions, for two (or more) reasons:

  • Assertions don't need to be tested, while throw assertions do, and test against ArgumentNullException looks ridiculous (try it).
  • Assertions better communicate the intended use of the unit, and is closer to being executable documentation than a class behavior specification.
  • You can change behavior of assertion violation. For example in debug compilation a message box is fine, so that your QA will hit you with it right away (you also get your IDE breaking on the line where it happens), while in unit test you can indicate assertion failure as a test failure.

Here is what handling of null exception looks like (being sarcastic, obviously):

try {
    library.Method(null);
}
catch (ArgumentNullException e) {
    // retry with real argument this time
    library.Method(realArgument);
}

Exceptions shall be used when situation is expected but exceptional (things happen that are outside of consumer's control, such as IO failure). Argument*Exception is an indication of a bug and shall be (my opinion) handled with tests and assisted with Debug.Assert

BTW: In this particular case, you could have used Month type, instead of int. C# falls short when it comes to type safety (Aspect# rulez!) but sometimes you can prevent (or catch at compile time) those bugs all together.

And yes, MicroSoft is wrong about that.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

You can use this, it works fine:

<input type="date" class="form1"  
  value="{{date | date:MM/dd/yyyy}}"
  ng-model="date" 
  name="id" 
  validatedateformat 
  data-date-format="mm/dd/yyyy"
  maxlength="10" 
  id="id" 
  calendar 
  maxdate="todays"
  ng-click="openCalendar('id')">
    <span class="input-group-addon">
      <span class="glyphicon glyphicon-calendar" ng-click="openCalendar('id')"></span>
    </span>
</input>

Can I use Homebrew on Ubuntu?

Because all previous answers doesn't work for me for ubuntu 14.04 here what I did, if any one get the same problem:

git clone https://github.com/Linuxbrew/brew.git ~/.linuxbrew
PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$(brew --prefix)/share/man:$MANPATH"
export INFOPATH="$(brew --prefix)/share/info:$INFOPATH"

then

sudo apt-get install gawk
sudo yum install gawk
brew install hello

you can follow this link for more information.

ShowAllData method of Worksheet class failed

This will work. Define this, then call it from when you need it. (Good for button logic if you are making a clear button):

Sub ResetFilters()
    On Error Resume Next
    ActiveSheet.ShowAllData
End Sub

Make footer stick to bottom of page using Twitter Bootstrap

It could be easily achieved with CSS flex. Having HTML markup as follows:

<html>
    <body>
        <div class="container"></div>
        <div class="footer"></div>
    </body>
</html>

Following CSS should be used:

html {
    height: 100%;
}
body {
    min-height: 100%;
   display: flex;
   flex-direction: column;
}
body > .container {
    flex-grow: 1;
}

Here's CodePen to play with: https://codepen.io/webdevchars/pen/GPBqWZ

Create a menu Bar in WPF?

<DockPanel>
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="_File">
            <MenuItem Header="_Open"/>
            <MenuItem Header="_Close"/>
            <MenuItem Header="_Save"/>
        </MenuItem>
    </Menu>
    <StackPanel></StackPanel>
</DockPanel>

Find an element in a list of tuples

The filter function can also provide an interesting solution:

result = list(filter(lambda x: x.count(1) > 0, a))

which searches the tuples in the list a for any occurrences of 1. If the search is limited to the first element, the solution can be modified into:

result = list(filter(lambda x: x[0] == 1, a))

php how to go one level up on dirname(__FILE__)

I use this, if there is an absolute path (this is an example):

$img = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT']."/Folder-B/image1.jpg");

if there is a picture to show, this is enough:

echo("<img src='/Folder-B/image1.jpg'>");

How to view the roles and permissions granted to any database user in Azure SQL server instance?

To view database roles assigned to users, you can use sys.database_role_members

The following query returns the members of the database roles.

SELECT DP1.name AS DatabaseRoleName,   
    isnull (DP2.name, 'No members') AS DatabaseUserName   
FROM sys.database_role_members AS DRM  
RIGHT OUTER JOIN sys.database_principals AS DP1  
    ON DRM.role_principal_id = DP1.principal_id  
LEFT OUTER JOIN sys.database_principals AS DP2  
    ON DRM.member_principal_id = DP2.principal_id  
WHERE DP1.type = 'R'
ORDER BY DP1.name;  

A cron job for rails: best practices?

In our project we first used whenever gem, but confronted some problems.

We then switched to RUFUS SCHEDULER gem, which turned out to be very easy and reliable for scheduling tasks in Rails.

We have used it for sending weekly & daily mails, and even for running some periodic rake tasks or any method.

The code used in this is like:

    require 'rufus-scheduler'

    scheduler = Rufus::Scheduler.new

    scheduler.in '10d' do
      # do something in 10 days
    end

    scheduler.at '2030/12/12 23:30:00' do
      # do something at a given point in time
    end

    scheduler.every '3h' do
      # do something every 3 hours
    end

    scheduler.cron '5 0 * * *' do
      # do something every day, five minutes after midnight
      # (see "man 5 crontab" in your terminal)
    end

To learn more: https://github.com/jmettraux/rufus-scheduler

How to make layout with View fill the remaining space?

In case if < TEXT VIEW > is placed in LinearLayout, set the Layout_weight proprty of < and > to 0 and 1 for TextView.
In case of RelativeLayout align < and > to left and right and set "Layout to left of" and "Layout to right of" property of TextView to ids of < and >

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

I had the same problem when switching from absolute to relative path for my xml file. The following solves both loading and using relative source path issues. Using a XmlDataProvider, which is defined in xaml (should be possible in code too) :

    <Window.Resources>
    <XmlDataProvider 
        x:Name="myDP"
        x:Key="MyData"
        Source=""
        XPath="/RootElement/Element"
        IsAsynchronous="False"
        IsInitialLoadEnabled="True"                         
        debug:PresentationTraceSources.TraceLevel="High"  /> </Window.Resources>

The data provider automatically loads the document once the source is set. Here's the code :

        m_DataProvider = this.FindResource("MyData") as XmlDataProvider;
        FileInfo file = new FileInfo("MyXmlFile.xml");

        m_DataProvider.Document = new XmlDocument();
        m_DataProvider.Source = new Uri(file.FullName);

How to convert String to DOM Document object in java?

you can try

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));

Document doc = db.parse(is);

refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

Java compile error: "reached end of file while parsing }"

It happens when you don't properly close the code block:

if (condition){
  // your code goes here*
  { // This doesn't close the code block

Correct way:

if (condition){
  // your code goes here
} // Close the code block

<div> cannot appear as a descendant of <p>

If this error occurs while using Material UI <Typography> https://material-ui.com/api/typography/, then you can easily change the <p> to a <span> by changing the value of the component attribute of the <Typography> element :

<Typography component={'span'} variant={'body2'}>

According to the typography docs:

component : The component used for the root node. Either a string to use a DOM element or a component. By default, it maps the variant to a good default headline component.

So Typography is picking <p> as a sensible default, which you can change. May come with side effects ... worked for me.

Run CRON job everyday at specific time

you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM

1 10 * * * php -f /var/www/package/index.php controller function

30 14 * * * php -f /var/www/package/index.php controller function

but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30 .

30 10,14 * * * php -f /var/www/package/index.php controller function

Location of the android sdk has not been setup in the preferences in mac os?

I saw this error after updating the Android SDK to r17. The solution was to go to Help -> Update and get the latest version of the Android SDK to match.

Error to run Android Studio

On ubuntu I have tried all the methods that are described here but none worked.

What I did in the end was to:

  • download JDK from oracle, extract the archive

  • edit android-studio/bin/studio.sh and add at the top

    export JAVA_HOME=/path/to/jdk

  • save the file and cd android-studio/bin and launch Android Studio: ./studio.sh

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

If the service is running in a background thread by extending IntentService, you can replace IntentService with JobIntentService which is provided as part of Android Support Library

The advantage of using JobIntentService is, it behaves as an IntentService on pre-O devices and on O and higher, it dispatches it as a job

JobScheduler can also be used for periodic/on demand jobs. But, ensure to handle backward compatibility as JobScheduler API is available only from API 21

How to use ADB in Android Studio to view an SQLite DB

You can use a very nice tool called Stetho by adding this to build.gradle file:

compile 'com.facebook.stetho:stetho:1.4.1'

And initialized it inside your Application or Activity onCreate() method:

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

Then you can view the db records in chrome in the address:

chrome://inspect/#devices

For more details you can read my post: How to view easily your db records

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

Subtracting two lists in Python

I know "for" is not what you want, but it's simple and clear:

for x in b:
  a.remove(x)

Or if members of b might not be in a then use:

for x in b:
  if x in a:
    a.remove(x)

How to remove elements from a generic list while iterating over it?

Using .ToList() will make a copy of your list, as explained in this question: ToList()-- Does it Create a New List?

By using ToList(), you can remove from your original list, because you're actually iterating over a copy.

foreach (var item in listTracked.ToList()) {    

        if (DetermineIfRequiresRemoval(item)) {
            listTracked.Remove(item)
        }

     }

Font Awesome 5 font-family issue

The problem is in the font-weight.
For Font Awesome 5 you have to use {font-weight:900}

how to use json file in html code

You can use JavaScript like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
        <script type="text/javascript" >
            function load() {
                var mydata = JSON.parse(data);
                alert(mydata.length);

                var div = document.getElementById('data');

                for(var i = 0;i < mydata.length; i++)
                {
                    div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                }
            }
        </script>
    </head>
    <body onload="load()">
        <div id="data">

        </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';

Functional, Declarative, and Imperative Programming

imperative and declarative describe two opposing styles of programming. imperative is the traditional "step by step recipe" approach while declarative is more "this is what i want, now you work out how to do it".

these two approaches occur throughout programming - even with the same language and the same program. generally the declarative approach is considered preferable, because it frees the programmer from having to specify so many details, while also having less chance for bugs (if you describe the result you want, and some well-tested automatic process can work backwards from that to define the steps then you might hope that things are more reliable than having to specify each step by hand).

on the other hand, an imperative approach gives you more low level control - it's the "micromanager approach" to programming. and that can allow the programmer to exploit knowledge about the problem to give a more efficient answer. so it's not unusual for some parts of a program to be written in a more declarative style, but for the speed-critical parts to be more imperative.

as you might imagine, the language you use to write a program affects how declarative you can be - a language that has built-in "smarts" for working out what to do given a description of the result is going to allow a much more declarative approach than one where the programmer needs to first add that kind of intelligence with imperative code before being able to build a more declarative layer on top. so, for example, a language like prolog is considered very declarative because it has, built-in, a process that searches for answers.

so far, you'll notice that i haven't mentioned functional programming. that's because it's a term whose meaning isn't immediately related to the other two. at its most simple, functional programming means that you use functions. in particular, that you use a language that supports functions as "first class values" - that means that not only can you write functions, but you can write functions that write functions (that write functions that...), and pass functions to functions. in short - that functions are as flexible and common as things like strings and numbers.

it might seem odd, then, that functional, imperative and declarative are often mentioned together. the reason for this is a consequence of taking the idea of functional programming "to the extreme". a function, in it's purest sense, is something from maths - a kind of "black box" that takes some input and always gives the same output. and that kind of behaviour doesn't require storing changing variables. so if you design a programming language whose aim is to implement a very pure, mathematically influenced idea of functional programming, you end up rejecting, largely, the idea of values that can change (in a certain, limited, technical sense).

and if you do that - if you limit how variables can change - then almost by accident you end up forcing the programmer to write programs that are more declarative, because a large part of imperative programming is describing how variables change, and you can no longer do that! so it turns out that functional programming - particularly, programming in a functional language - tends to give more declarative code.

to summarise, then:

  • imperative and declarative are two opposing styles of programming (the same names are used for programming languages that encourage those styles)

  • functional programming is a style of programming where functions become very important and, as a consequence, changing values become less important. the limited ability to specify changes in values forces a more declarative style.

so "functional programming" is often described as "declarative".

Create an instance of a class from a string

I've used this method successfully:

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)

You'll need to cast the returned object to your desired object type.

How to get the Android Emulator's IP address?

If you need to refer to your host computer's localhost, such as when you want the emulator client to contact a server running on the same host, use the alias 10.0.2.2 to refer to the host computer's loopback interface. From the emulator's perspective, localhost (127.0.0.1) refers to its own loopback interface.More details: http://developer.android.com/guide/faq/commontasks.html#localhostalias

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you follow your link, it tells you that the error results from the $injector not being able to resolve your dependencies. This is a common issue with angular when the javascript gets minified/uglified/whatever you're doing to it for production.

The issue is when you have e.g. a controller;

angular.module("MyApp").controller("MyCtrl", function($scope, $q) {
  // your code
})

The minification changes $scope and $q into random variables that doesn't tell angular what to inject. The solution is to declare your dependencies like this:

angular.module("MyApp")
  .controller("MyCtrl", ["$scope", "$q", function($scope, $q) {
  // your code
}])

That should fix your problem.

Just to re-iterate, everything I've said is at the link the error message provides to you.

No module named _sqlite3

you must be in centos or redhat and compile python yourself, it is python‘s bug do this in your python source code dir and do this below

curl -sk https://gist.github.com/msabramo/2727063/raw/59ea097a1f4c6f114c32f7743308a061698b17fd/gistfile1.diff | patch -p1

Good Java graph algorithm library?

JGraph from http://mmengineer.blogspot.com/2009/10/java-graph-floyd-class.html

Provides a powerfull software to work with graphs (direct or undirect). Also generates Graphivz code, you can see graphics representations. You can put your own code algorithms into pakage, for example: backtracking code. The package provide some algorithms: Dijkstra, backtracking minimun path cost, ect..

Can CSS force a line break after each word in an element?

In my case,

    word-break: break-all;

worked perfecly, hope it helps any other newcomer like me.

How to parse JSON and access results

If your $result variable is a string json like, you must use json_decode function to parse it as an object or array:

$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);

OUTPUT

Array
(
    [Cancelled] => 
    [MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
    [Queued] => 
    [SMSError] => 2
    [SMSIncomingMessages] => 
    [Sent] => 
    [SentDateTime] => /Date(-62135578800000-0500)/
)

Now you can work with $json variable as an array:

echo $json['MessageID'];
echo $json['SMSError'];
// other stuff

References:

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Also worth noting, for people who find this in their searches, is this...

<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
  <div class="bb-button-label">{{ button.label }}</div>
  <div class="bb-button-description">{{ button.description }}</div>
</div>

Note the value of ng-click. The parameter passed to goTo() is a string from a property of the binding object (the button), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.

Relationship between hashCode and equals method in Java

A contract is: If two objects are equal then they should have the same hashcode and if two objects are not equal then they may or may not have same hash code.

Try using your object as key in HashMap (edited after comment from joachim-sauer), and you will start facing trouble. A contract is a guideline, not something forced upon you.

Change the color of a checked menu item in a navigation drawer

I believe app:itemBackground expects a drawable. So follow the steps below :

Make a drawable file highlight_color.xml with following contents :

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
     <solid android:color="YOUR HIGHLIGHT COLOR"/>
</shape>

Make another drawable file nav_item_drawable.xml with following contents:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/highlight_color" android:state_checked="true"/>
</selector>

Finally add app:itemBackground tag in the NavView :

<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
app:itemBackground="@drawable/nav_item_drawable"
app:menu="@menu/menu_drawer">

here the highlight_color.xml file defines a solid color drawable for the background. Later this color drawable is assigned to nav_item_drawable.xml selector.

This worked for me. Hopefully this will help.

********************************************** UPDATED **********************************************

Though the above mentioned answer gives you fine control over some properties, but the way I am about to describe feels more SOLID and is a bit COOLER.

So what you can do is, you can define a ThemeOverlay in the styles.xml for the NavigationView like this :

    <style name="ThemeOverlay.AppCompat.navTheme">

        <!-- Color of text and icon when SELECTED -->
        <item name="colorPrimary">@color/color_of_your_choice</item> 

        <!-- Background color when SELECTED -->
        <item name="colorControlHighlight">@color/color_of_your_choice</item> 

    </style>

now apply this ThemeOverlay to app:theme attribute of NavigationView, like this:

<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:theme="@style/ThemeOverlay.AppCompat.navTheme"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/menu_drawer">

I hope this will help.

How to serve an image using nodejs

_x000D_
_x000D_
//This method involves directly integrating HTML Code in the res.write
//first time posting to stack ...pls be kind

const express = require('express');
const app = express();
const https = require('https');

app.get("/",function(res,res){
    res.write("<img src="+image url / src +">");
    res.send();
});

app.listen(3000, function(req, res) {
  console.log("the server is onnnn");
});
_x000D_
_x000D_
_x000D_

Adding a background image to a <div> element

<div id="image">Example to have Background Image</div>

We need to Add the below content in Style tag:

.image {
  background-image: url('C:\Users\ajai\Desktop\10.jpg');
}

Create PostgreSQL ROLE (user) if it doesn't exist

The accepted answer suffers from a race condition if two such scripts are executed concurrently on the same Postgres cluster (DB server), as is common in continuous-integration environments.

It's generally safer to try to create the role and gracefully deal with problems when creating it:

DO $$
BEGIN
  CREATE ROLE my_role WITH NOLOGIN;
  EXCEPTION WHEN DUPLICATE_OBJECT THEN
  RAISE NOTICE 'not creating role my_role -- it already exists';
END
$$;

keyword not supported data source

I had this problem when I started using Entity Framework, it happened when I did not change the old SQL server connection to EntityFrameWork connection.

Solution: in the file where connection is made through web.config file "add name="Entities" connectionString=XYZ", make sure you are referring to the correct connection, in my case I had to do this

        public static string MyEntityFrameworkConnection
    {
        get
        {
             return ConfigurationManager.ConnectionStrings["Entities"].ConnectionString;
        }

    }

call MyEntityFrameworkConnection whenever connection need to be established.

private string strConnection= Library.DataAccessLayer.DBfile.AdoSomething.MyEntityFrameworkConnection;

note: the connection in web.config file will be generated automatically when adding Entity model to the solution.

How to set the java.library.path from Eclipse

I'm using Mac OS X Yosemite and Netbeans 8.02, I got the same error and the simple solution I have found is like above, this is useful when you need to include native library in the project. So do the next for Netbeans:

1.- Right click on the Project
2.- Properties
3.- Click on RUN
4.- VM Options: java -Djava.library.path="your_path"
5.- for example in my case: java -Djava.library.path=</Users/Lexynux/NetBeansProjects/NAO/libs>
6.- Ok

I hope it could be useful for someone. The link where I found the solution is here: java.library.path – What is it and how to use

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

5 Jan 2021: link update thanks to @Sadap's comment.

Kind of a corollary answer: the people on this site have taken the time to make tables of macros defined for every OS/compiler pair.

For example, you can see that _WIN32 is NOT defined on Windows with Cygwin (POSIX), while it IS defined for compilation on Windows, Cygwin (non-POSIX), and MinGW with every available compiler (Clang, GNU, Intel, etc.).

Anyway, I found the tables quite informative and thought I'd share here.

Creating and throwing new exception

To call a specific exception such as FileNotFoundException use this format

if (-not (Test-Path $file)) 
{
    throw [System.IO.FileNotFoundException] "$file not found."
}

To throw a general exception use the throw command followed by a string.

throw "Error trying to do a task"

When used inside a catch, you can provide additional information about what triggered the error

Conversion from Long to Double in Java

Long i = 1000000;
String s = i + "";
Double d = Double.parseDouble(s);
Float f = Float.parseFloat(s);

This way we can convert Long type to Double or Float or Int without any problem because it's easy to convert string value to Double or Float or Int.

Add views below toolbar in CoordinatorLayout

As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView.

app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"

What is "overhead"?

The meaning of the word can differ a lot with context. In general, it's resources (most often memory and CPU time) that are used, which do not contribute directly to the intended result, but are required by the technology or method that is being used. Examples:

  • Protocol overhead: Ethernet frames, IP packets and TCP segments all have headers, TCP connections require handshake packets. Thus, you cannot use the entire bandwidth the hardware is capable of for your actual data. You can reduce the overhead by using larger packet sizes and UDP has a smaller header and no handshake.
  • Data structure memory overhead: A linked list requires at least one pointer for each element it contains. If the elements are the same size as a pointer, this means a 50% memory overhead, whereas an array can potentially have 0% overhead.
  • Method call overhead: A well-designed program is broken down into lots of short methods. But each method call requires setting up a stack frame, copying parameters and a return address. This represents CPU overhead compared to a program that does everything in a single monolithic function. Of course, the added maintainability makes it very much worth it, but in some cases, excessive method calls can have a significant performance impact.

Javascript Regexp dynamic generation from variables?

You have to forgo the regex literal and use the object constructor, where you can pass the regex as a string.

var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regex);

Android add placeholder text to EditText

In Android Studio you can add Hint (Place holder) through GUI. First select EditText field on designer view. Then Click on Component Tree Left side of IDE (Normally it's there, but it may be there minimized) There you can see Properties of selected EditText. Find Hint field as below Image

enter image description here

There you can add Hint(Place holder) to EditText

Resizing an Image without losing any quality

Here is a forum thread that provides a C# image resizing code sample. You could use one of the GD library binders to do resampling in C#.

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

$ mysqladmin -u root -p password
Enter password: 
New password: 
Confirm new password:

password is to be typed literally. It's a command. You don't have to substitute password with your actual password.

How to increase the gap between text and underlining in CSS

Getting into the details of the visual style of text-decoration:underline is pretty much futile, so you're going to have to go with some kind of hack the removes text-decoration:underline and replaces it with something else until a magical far-distant future version of CSS gives us more control.

This worked for me:

_x000D_
_x000D_
   a {_x000D_
    background-image: linear-gradient(_x000D_
        180deg, rgba(0,0,0,0),_x000D_
        rgba(0,0,0,0) 81%, _x000D_
        #222222 81.1%,_x000D_
        #222222 85%,_x000D_
        rgba(0,0,0,0) 85.1%,_x000D_
        rgba(0,0,0,0)_x000D_
    );_x000D_
    text-decoration: none;_x000D_
}
_x000D_
<a href="#">Lorem ipsum</a> dolor sit amet, <a href="#">consetetur sadipscing</a> elitr, sed diam nonumy eirmod tempor <a href="#">invidunt ut labore.</a>
_x000D_
_x000D_
_x000D_

  • Adjust the % values (81% and 85%) to change how far the line is from the text
  • Adjust the difference between the two % values to change the line thickness
  • adjust the color values (#222222) to change the underline color
  • works with multiple line inline elements
  • works with any background

Here's a version with all the proprietary properties for some backwards compatibility:

a {     
    /* This code generated from: http://colorzilla.com/gradient-editor/ */
    background: -moz-linear-gradient(top,  rgba(0,0,0,0) 0%, rgba(0,0,0,0) 81%, rgba(0,0,0,1) 81.1%, rgba(0,0,0,1) 85%, rgba(0,0,0,0) 85.1%, rgba(0,0,0,0) 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(0,0,0,0)), color-stop(81%,rgba(0,0,0,0)), color-stop(81.1%,rgba(0,0,0,1)), color-stop(85%,rgba(0,0,0,1)), color-stop(85.1%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,0))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* IE10+ */
    background: linear-gradient(to bottom,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* W3C */

    text-decoration: none;
}

Update: SASSY version

I made a scss mixin for this. If you don't use SASS, the regular version above still works great...

@mixin fake-underline($color: #666, $top: 84%, $bottom: 90%) {
    background-image: linear-gradient(
        180deg, rgba(0,0,0,0),
        rgba(0,0,0,0) $top,
        $color $top + 0.1%,
        $color $bottom,
        rgba(0,0,0,0) $bottom + 0.1%,
        rgba(0,0,0,0)
    );
    text-decoration: none;
}

then use it like so:

$blue = #0054a6;
a {
    color: $blue;
    @include fake-underline(lighten($blue,20%));
}
a.thick {
    color: $blue;
    @include fake-underline(lighten($blue,40%), 86%, 99%);
}

Update 2: Descenders Tip

If you have a solid background color, try adding a thin text-stroke or text-shadow in the same color as your background to make the descenders look nice.

Credit

This is simplified version of the technique I originally found at https://eager.io/app/smartunderline, but the article has since been taken down.

INNER JOIN ON vs WHERE clause

The implicit join ANSI syntax is older, less obvious, and not recommended.

In addition, the relational algebra allows interchangeability of the predicates in the WHERE clause and the INNER JOIN, so even INNER JOIN queries with WHERE clauses can have the predicates rearranged by the optimizer.

I recommend you write the queries in the most readable way possible.

Sometimes this includes making the INNER JOIN relatively "incomplete" and putting some of the criteria in the WHERE simply to make the lists of filtering criteria more easily maintainable.

For example, instead of:

SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
    AND c.State = 'NY'
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
    AND a.Status = 1

Write:

SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
WHERE c.State = 'NY'
    AND a.Status = 1

But it depends, of course.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

How to tell bash that the line continues on the next line

In general, you can use a backslash at the end of a line in order for the command to continue on to the next line. However, there are cases where commands are implicitly continued, namely when the line ends with a token than cannot legally terminate a command. In that case, the shell knows that more is coming, and the backslash can be omitted. Some examples:

# In general
$ echo "foo" \
> "bar"
foo bar

# Pipes
$ echo foo |
> cat
foo

# && and ||
$ echo foo &&
> echo bar
foo
bar
$ false ||
> echo bar
bar

Different, but related, is the implicit continuation inside quotes. In this case, without a backslash, you are simply adding a newline to the string.

$ x="foo
> bar"
$ echo "$x"
foo
bar

With a backslash, you are again splitting the logical line into multiple logical lines.

$ x="foo\
> bar"
$ echo "$x"
foobar

Add data to JSONObject

In order to have this result:

{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}

that holds the same data as:

  {
    "aoColumnDefs": [
     { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
     { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
     { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
   ]
  }

you could use this code:

    JSONObject jo = new JSONObject();
    Collection<JSONObject> items = new ArrayList<JSONObject>();

    JSONObject item1 = new JSONObject();
    item1.put("aDataSort", new JSONArray(0, 1));
    item1.put("aTargets", new JSONArray(0));
    items.add(item1);
    JSONObject item2 = new JSONObject();
    item2.put("aDataSort", new JSONArray(1, 0));
    item2.put("aTargets", new JSONArray(1));
    items.add(item2);
    JSONObject item3 = new JSONObject();
    item3.put("aDataSort", new JSONArray(2, 3, 4));
    item3.put("aTargets", new JSONArray(2));
    items.add(item3);

    jo.put("aoColumnDefs", new JSONArray(items));

    System.out.println(jo.toString());

How to get the position of a character in Python?

A character might appear multiple times in a string. For example in a string sentence, position of e is 1, 4, 7 (because indexing usually starts from zero). but what I find is both of the functions find() and index() returns first position of a character. So, this can be solved doing this:

def charposition(string, char):
    pos = [] #list to store positions for each 'char' in 'string'
    for n in range(len(string)):
        if string[n] == char:
            pos.append(n)
    return pos

s = "sentence"
print(charposition(s, 'e')) 

#Output: [1, 4, 7]

Write single CSV file using spark-csv

I'm using this in Python to get a single file:

df.toPandas().to_csv("/tmp/my.csv", sep=',', header=True, index=False)

Convert a String In C++ To Upper Case

std::string str = "STriNg oF mIxID CasE lETteRS"

C++ 11

  • Using for_each

    std::for_each(str.begin(), str.end(), [](char & c){ c = ::toupper(c); });

  • Using transform

    std::transform(str.begin(), str.end(), str.begin(), ::toupper);

C++ (Winodws Only)

_strupr_s(str, str.length());

C++ (Using Boost Library)

boost::to_upper_copy(str)

Unable to Install Any Package in Visual Studio 2015

You need to Clear All NuGet Caches; for this you need go to Options and click on it like this:

enter image description here

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

For Devs getting this error in Web API Project -

The GetOwinContext extension method is defined in System.Web.Http.Owin dll and one more package will be needed i.e. Microsoft.Owin.Host.SystemWeb. This package needs to be installed in your project from nuget.

Link To Package: OWIN Package Install Command -

Install-Package Microsoft.AspNet.WebApi.Owin    

Link To System.web Package : Package Install Command -

Install-Package Microsoft.Owin.Host.SystemWeb

In order to resolve this error you need to find why its occurring in your case. Please Cross check below points in your code -

  1. You must have reference to Microsoft.AspNet.Identity.Owin;

    using Microsoft.AspNet.Identity.Owin;

  2. Define GetOwinContext() Under HttpContext.Current as below -

     return _userManager1 ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
    

    OR

    return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
    

Complete Code Where GetOwinContext() is used -

 public ApplicationSignInManager SignInManager
 {
   get
   {
    return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
   }
    private set
    {
     _signInManager = value;
    }
  }

Namespace's I'm Using in Code File where GetOwinContext() Is used

using AngularJSAuthentication.API.Entities;
using AngularJSAuthentication.API.Models;
using HomeCinema.Common;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.DataProtection;

I got this error while moving my code from my one project to another.

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

How do I find out if first character of a string is a number?

To verify only first letter is number or character -- For number Character.isDigit(str.charAt(0)) --return true

For character Character.isLetter(str.charAt(0)) --return true

mysql delete under safe mode

You can trick MySQL into thinking you are actually specifying a primary key column. This allows you to "override" safe mode.

Assuming you have a table with an auto-incrementing numeric primary key, you could do the following:

DELETE FROM tbl WHERE id <> 0

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

You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.

On the other hand, you have PAGE that seems active and works in python 2.7 and py3k

As you indicate on your comment, none of these use the grid geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.

It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:

enter image description here

By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

JavaScript - Hide a Div at startup (load)

Using CSS you can just set display:none for the element in a CSS file or in a style attribute

#div { display:none; }
<div id="div"></div>



<div style="display:none"></div>

or having the js just after the div might be fast enough too, but not as clean

Adding headers to requests module

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

Select N random elements from a List<T> in C#

When N is very large, the normal method that randomly shuffles the N numbers and selects, say, first k numbers, can be prohibitive because of space complexity. The following algorithm requires only O(k) for both time and space complexities.

http://arxiv.org/abs/1512.00501

def random_selection_indices(num_samples, N):
    modified_entries = {}
    seq = []
    for n in xrange(num_samples):
        i = N - n - 1
        j = random.randrange(i)

        # swap a[j] and a[i] 
        a_j = modified_entries[j] if j in modified_entries else j 
        a_i = modified_entries[i] if i in modified_entries else i

        if a_i != j:
            modified_entries[j] = a_i   
        elif j in modified_entries:   # no need to store the modified value if it is the same as index
            modified_entries.pop(j)

        if a_j != i:
            modified_entries[i] = a_j 
        elif i in modified_entries:   # no need to store the modified value if it is the same as index
            modified_entries.pop(i)
        seq.append(a_j)
    return seq

Toggle display:none style with JavaScript

Others have answered your question perfectly, but I just thought I would throw out another way. It's always a good idea to separate HTML markup, CSS styling, and javascript code when possible. The cleanest way to hide something, with that in mind, is using a class. It allows the definition of "hide" to be defined in the CSS where it belongs. Using this method, you could later decide you want the ul to hide by scrolling up or fading away using CSS transition, all without changing your HTML or code. This is longer, but I feel it's a better overall solution.

Demo: http://jsfiddle.net/ThinkingStiff/RkQCF/

HTML:

<a id="showTags" href="#" title="Show Tags">Show All Tags</a>
<ul id="subforms" class="subforums hide"><li>one</li><li>two</li><li>three</li></ul>

CSS:

#subforms {
    overflow-x: visible; 
    overflow-y: visible;
}

.hide {
    display: none; 
}

Script:

document.getElementById( 'showTags' ).addEventListener( 'click', function () {
    document.getElementById( 'subforms' ).toggleClass( 'hide' );
}, false );

Element.prototype.toggleClass = function ( className ) {
    if( this.className.split( ' ' ).indexOf( className ) == -1 ) {
        this.className = ( this.className + ' ' + className ).trim();
    } else {
        this.className = this.className.replace( new RegExp( '(\\s|^)' + className + '(\\s|$)' ), ' ' ).trim();
    };
};

Correct way to find max in an Array in Swift

The other answers are all correct, but don't forget you could also use collection operators, as follows:

var list = [1, 2, 3, 4]
var max: Int = (list as AnyObject).valueForKeyPath("@max.self") as Int

you can also find the average in the same way:

var avg: Double = (list as AnyObject).valueForKeyPath("@avg.self") as Double

This syntax might be less clear than some of the other solutions, but it's interesting to see that -valueForKeyPath: can still be used :)

How to convert date to timestamp in PHP?

<?php echo date('U') ?>

If you want, put it in a MySQL input type timestamp. The above works very well (only in PHP 5 or later):

<?php $timestamp_for_mysql = date('c') ?>

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Actually, none of these answers reflect current state of the art with Git (v2.29 by time of writing this answer). In the latest versions of Git, cache, winstore, wincred are deprecated.


If you want to clone a Bitbucket repository via HTTPS, e.g.

git clone https://[email protected]/SomeOrganization/SomeRepo.git

You have to:

  1. Generate app password at Bitbucket user administration.
  2. Setup your credential method in .gitconfig accordingly (global or local)
[credential]
    helper = manager

You can locate your .gitconfig by executing this command.

git config --list --show-origin
  1. Execute
git clone https://[email protected]/SomeOrganization/SomeRepo.git

and wait until log on window appears. Use your user name from the url (kutlime in my case) and your generated app password as a password.

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

The cleanest way is to copy the following classes: ShareActionProvider, ActivityChooserView, ActivityChooserModel. Add the ability to filter the intents in the ActivityChooserModel, and the appropriate support methods in the ShareActionProvider. I created the necessary classes, you can copy them into your project (https://gist.github.com/saulpower/10557956). This not only adds the ability to filter the apps you would like to share with (if you know the package name), but also to turn off history.

private final String[] INTENT_FILTER = new String[] {
    "com.twitter.android",
    "com.facebook.katana"
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.journal_entry_menu, menu);

    // Set up ShareActionProvider's default share intent
    MenuItem shareItem = menu.findItem(R.id.action_share);

    if (shareItem instanceof SupportMenuItem) {
        mShareActionProvider = new ShareActionProvider(this);
        mShareActionProvider.setShareIntent(ShareUtils.share(mJournalEntry));
        mShareActionProvider.setIntentFilter(Arrays.asList(INTENT_FILTER));
        mShareActionProvider.setShowHistory(false);
        ((SupportMenuItem) shareItem).setSupportActionProvider(mShareActionProvider);
    }

    return super.onCreateOptionsMenu(menu);
}

When do I use the PHP constant "PHP_EOL"?

On some system may be useful to use this constant because if, for example, you are sending an email, you can use PHP_EOL to have a cross-system script working on more systems... but even if it's useful sometime you can find this constant undefined, modern hosting with latest php engine do not have this problem but I think that a good thing is write a bit code that saves this situation:

<?php
  if (!defined('PHP_EOL')) {
    if (strtoupper(substr(PHP_OS,0,3) == 'WIN')) {
      define('PHP_EOL',"\r\n");
    } elseif (strtoupper(substr(PHP_OS,0,3) == 'MAC')) {
      define('PHP_EOL',"\r");
    } elseif (strtoupper(substr(PHP_OS,0,3) == 'DAR')) {
      define('PHP_EOL',"\n");
    } else {
      define('PHP_EOL',"\n");
    }
  }
?>

So you can use PHP_EOL without problems... obvious that PHP_EOL should be used on script that should work on more systems at once otherwise you can use \n or \r or \r\n...

Note: PHP_EOL can be

1) on Unix    LN    == \n
2) on Mac     CR    == \r
3) on Windows CR+LN == \r\n

Hope this answer help.

How to remove line breaks from a file in Java?

I find it odd that (Apache) StringUtils wasn't covered here yet.

you can remove all newlines (or any other occurences of a substring for that matter) from a string using the .replace method

StringUtils.replace(myString, "\n", "");

This line will replace all newlines with the empty string.

because newline is technically a character you can optionally use the .replaceChars method that will replace characters

StringUtils.replaceChars(myString, '\n', '');

Editable text to string

Based on this code (which you provided in response to Alex's answer):

Editable newTxt=(Editable)userName1.getText(); 
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:

String newString = userName1.getText().toString(); 

jQuery - on change input text

This worked for me

var change_temp = "";
$('#url_key').bind('keydown keyup',function(e){
    if(e.type == "keydown"){
        change_temp = $(this).val();
        return;
    }
    if($(this).val() != change_temp){
        // add the code to on change here 
    }

});

Java finished with non-zero exit value 2 - Android Gradle

I had the same issue and I fixed removing the library that were unnecessary

compile fileTree(dir: 'libs', include: ['*.jar'])

I removed that library and I could run the project without any problem.

Get the Application Context In Fragment In Android?

Use

getActivity().getApplicationContext()

to obtain the context in any fragment

Stop an input field in a form from being submitted

You need to add onsubmit at your form:

<form action="YOUR_URL" method="post" accept-charset="utf-8" onsubmit="return validateRegisterForm();">

And the script will be like this:

        function validateRegisterForm(){
        if(SOMETHING IS WRONG)
        { 
            alert("validation failed");
            event.preventDefault();
            return false;

        }else{
            alert("validations passed");
            return true;
        }
    }

This works for me everytime :)

Delete with Join in MySQL

Try like below:

DELETE posts.*,projects.* 
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;

How do I render a shadow?

    viewStyle : {
    backgroundColor: '#F8F8F8',
    justifyContent: 'center',
    alignItems: 'center',
    height: 60,
    paddingTop: 15,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    marginBottom: 10,
    elevation: 2,
    position: 'relative'
},

Use marginBottom: 10

Oracle SQL escape character (for a '&')

The real answer is you need to set the escape character to '\': SET ESCAPE ON

The problem may have occurred either because escaping was disabled, or the escape character was set to something other than '\'. The above statement will enable escaping and set it to '\'.


None of the other answers previously posted actually answer the original question. They all work around the problem but don't resolve it.

What are some alternatives to ReSharper?

CodeRush. Also, Scott Hanselman has a nice post comparing them, ReSharper vs. CodeRush.

A more up-to-date comparison is in Coderush vs Resharper by Jason Irwin.

Fastest way to iterate over all the chars in a String

String.toCharArray() creates new char array, means allocation of memory of string length, then copies original char array of string using System.arraycopy() and then returns this copy to caller. String.charAt() returns character at position i from original copy, that's why String.charAt() will be faster than String.toCharArray(). Although, String.toCharArray() returns copy and not char from original String array, where String.charAt() returns character from original char array. Code below returns value at the specified index of this string.

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

code below returns a newly allocated character array whose length is the length of this string

public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

Using Jasmine to spy on a function without an object

TypeScript users:

I know the OP asked about javascript, but for any TypeScript users who come across this who want to spy on an imported function, here's what you can do.

In the test file, convert the import of the function from this:

import {foo} from '../foo_functions';

x = foo(y);

To this:

import * as FooFunctions from '../foo_functions';

x = FooFunctions.foo(y);

Then you can spy on FooFunctions.foo :)

spyOn(FooFunctions, 'foo').and.callFake(...);
// ...
expect(FooFunctions.foo).toHaveBeenCalled();

ORA-00979 not a group by expression

If you do grouping by virtue of including GROUP BY clause, any expression in SELECT, which is not group function (or aggregate function or aggregated column) such as COUNT, AVG, MIN, MAX, SUM and so on (List of Aggregate functions) should be present in GROUP BY clause.

Example (correct way) (here employee_id is not group function (non-aggregated column), so it must appear in GROUP BY. By contrast, sum(salary) is a group function (aggregated column), so it is not required to appear in the GROUP BYclause.

   SELECT employee_id, sum(salary) 
   FROM employees
   GROUP BY employee_id; 

Example (wrong way) (here employee_id is not group function and it does not appear in GROUP BY clause, which will lead to the ORA-00979 Error .

   SELECT employee_id, sum(salary) 
   FROM employees;

To correct you need to do one of the following :

  • Include all non-aggregated expressions listed in SELECT clause in the GROUP BY clause
  • Remove group (aggregate) function from SELECT clause.

Which terminal command to get just IP address and nothing else?

When looking up your external IP address on a NATed host, quite a few answers suggest using HTTP based methods like ifconfig.me eg:

$ curl ifconfig.me/ip

Over the years I have seen many of these sites come and go, I find this DNS based method more robust:

$ dig +short myip.opendns.com @resolver1.opendns.com

I have this handy alias in my ~/.bashrc:

alias wip='dig +short myip.opendns.com @resolver1.opendns.com'

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

This was the best solution I found after more time than I care to admit. Basically, add target="_self" to each link that you need to insure a page reload.

http://blog.panjiesw.com/posts/2013/09/angularjs-normal-links-with-html5mode/

Get list from pandas dataframe column or row?

Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist() on to turn them into a Python list. Alternatively you cast it with list(x).

import pandas as pd

data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
             'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(data_dict)

print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")

col_one_list = df['one'].tolist()

col_one_arr = df['one'].to_numpy()

print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")

Output:

DataFrame:
   one  two
a  1.0    1
b  2.0    2
c  3.0    3
d  NaN    4

column types:
one    float64
two      int64
dtype: object

col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>

col_one_arr:
[ 1.  2.  3. nan]
type:<class 'numpy.ndarray'>

How to get last inserted row ID from WordPress database?

just like this :

global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);

simply your selecting all the rows then order them DESC by id , and displaying only the first

Determine Pixel Length of String in Javascript/jQuery?

If you use Snap.svg, the following works:

var tPaper = Snap(300, 300);
var tLabelText = tPaper.text(100, 100, "label text");
var tWidth = tLabelText.getBBox().width;  // the width of the text in pixels.
tLabelText.attr({ x : 150 - (tWidth/2)});   // now it's centered in x

Displaying Image in Java

If you want to load/process/display images I suggest you use an image processing framework. Using Marvin, for instance, you can do that easily with just a few lines of source code.

Source code:

public class Example extends JFrame{

    MarvinImagePlugin prewitt           = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.prewitt");
    MarvinImagePlugin errorDiffusion    = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion");
    MarvinImagePlugin emboss            = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.emboss");

    public Example(){
        super("Example");

        // Layout
        setLayout(new GridLayout(2,2));

        // Load images
        MarvinImage img1 = MarvinImageIO.loadImage("./res/car.jpg");
        MarvinImage img2 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img3 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img4 = new MarvinImage(img1.getWidth(), img1.getHeight());

        // Image Processing plug-ins
        errorDiffusion.process(img1, img2);
        prewitt.process(img1, img3);
        emboss.process(img1, img4);

        // Set panels
        addPanel(img1);
        addPanel(img2);
        addPanel(img3);
        addPanel(img4);

        setSize(560,380);
        setVisible(true);
    }

    public void addPanel(MarvinImage image){
        MarvinImagePanel imagePanel = new MarvinImagePanel();
        imagePanel.setImage(image);
        add(imagePanel);
    }

    public static void main(String[] args) {
        new Example().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Output:

enter image description here

How to change RGB color to HSV?

There's a C implementation here:

http://www.cs.rit.edu/~ncs/color/t_convert.html

Should be very straightforward to convert to C#, as almost no functions are called - just calculations.

found via Google

How can I verify if one list is a subset of another?

one = [1, 2, 3]
two = [9, 8, 5, 3, 2, 1]

all(x in two for x in one)

Explanation: Generator creating booleans by looping through list one checking if that item is in list two. all() returns True if every item is truthy, else False.

There is also an advantage that all return False on the first instance of a missing element rather than having to process every item.

Best way to encode text data for XML

In .net 3.5+

new XText("I <want> to & encode this for XML").ToString();

Gives you:

I &lt;want&gt; to &amp; encode this for XML

Turns out that this method doesn't encode some things that it should (like quotes).

SecurityElement.Escape (workmad3's answer) seems to do a better job with this and it's included in earlier versions of .net.

If you don't mind 3rd party code and want to ensure no illegal characters make it into your XML, I would recommend Michael Kropat's answer.

How to delete/truncate tables from Hadoop-Hive?

Use the following to delete all the tables in a linux environment.

hive -e 'show tables' | xargs -I '{}' hive -e 'drop table {}'

Disable a Maven plugin defined in a parent POM

See if the plugin has a 'skip' configuration parameter. Nearly all do. if it does, just add it to a declaration in the child:

<plugin>
   <groupId>group</groupId>
   <artifactId>artifact</artifactId>
   <configuration>
     <skip>true</skip>
   </configuration>
</plugin>

If not, then use:

<plugin>    
<groupId>group</groupId>   
 <artifactId>artifact</artifactId>    
<executions>
     <execution>
       <id>TheNameOfTheRelevantExecution</id>
       <phase>none</phase>
     </execution>    
</executions>  
</plugin>

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

Make sure you have imported HttpClientModule instead of adding HttpClient direcly to the list of providers.

See https://angular.io/guide/http#setup for more info.

The HttpClientModule actually provides HttpClient for you. See https://angular.io/api/common/http/HttpClientModule:

Code sample:

import { HttpClientModule, /* other http imports */ } from "@angular/common/http";

@NgModule({
    // ...other declarations, providers, entryComponents, etc.
    imports: [
        HttpClientModule,
        // ...some other imports
    ],
})
export class AppModule { }

Can I get the name of the currently running function in JavaScript?

An updated answer to this can can be found over at this answer: https://stackoverflow.com/a/2161470/632495

and, if you don't feel like clicking:

function test() {
  var z = arguments.callee.name;
  console.log(z);
}

how to enable sqlite3 for php?

For Debian distributions. Nothing worked for until I added the debian main repositories on the apt sources (I don't know how were they removed): sudo vi /etc/apt/sources.list

and added

deb  http://deb.debian.org/debian  stretch main
deb-src  http://deb.debian.org/debian  stretch main

after that sudo apt-get update (you can upgrade too) and finally sudo apt-get install php-sqlite3

asp.net Button OnClick event not firing

Have you copied this method from other page/application ? if yes then it will not work, So you need to delete the event and event name assigned to the button then go to design and go to button even properties go to onClick event double click next to it, it will generate event and it automatically assigns event name to the button. this should work

Python: Find a substring in a string and returning the index of the substring

Here is a simple approach:

my_string = 'abcdefg'
print(text.find('def'))

Output:

3

I the substring is not there, you will get -1. For example:

my_string = 'abcdefg'
print(text.find('xyz'))

Output:

-1

Sometimes, you might want to throw exception if substring is not there:

my_string = 'abcdefg'
print(text.index('xyz')) # It returns an index only if it's present

Output:

Traceback (most recent call last):

File "test.py", line 6, in print(text.index('xyz'))

ValueError: substring not found

Having links relative to root?

A root-relative URL starts with a / character, to look something like <a href="/directoryInRoot/fileName.html">link text</a>.

The link you posted: <a href="fruits/index.html">Back to Fruits List</a> is linking to an html file located in a directory named fruits, the directory being in the same directory as the html page in which this link appears.

To make it a root-relative URL, change it to:

<a href="/fruits/index.html">Back to Fruits List</a>

Edited in response to question, in comments, from OP:

So doing / will make it relative to www.example.com, is there a way to specify what the root is, e.g what if i want the root to be www.example.com/fruits in www.example.com/fruits/apples/apple.html?

Yes, prefacing the URL, in the href or src attributes, with a / will make the path relative to the root directory. For example, given the html page at www.example.com/fruits/apples.html, the a of href="/vegetables/carrots.html" will link to the page www.example.com/vegetables/carrots.html.

The base tag element allows you to specify the base-uri for that page (though the base tag would have to be added to every page in which it was necessary for to use a specific base, for this I'll simply cite the W3's example:

For example, given the following BASE declaration and A declaration:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
 <HEAD>
   <TITLE>Our Products</TITLE>
   <BASE href="http://www.aviary.com/products/intro.html">
 </HEAD>

 <BODY>
   <P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?
 </BODY>
</HTML>

the relative URI "../cages/birds.gif" would resolve to:

http://www.aviary.com/cages/birds.gif

Example quoted from: http://www.w3.org/TR/html401/struct/links.html#h-12.4.

Suggested reading:

How to differ sessions in browser-tabs?

You shouldn't. If you want to do such a thing either you need to force user to use a single instance of your application by writing URLs on the fly use a sessionID alike (not sessionid it won't work) id and pass it in every URL.

I don't know why you need it but unless you need make a totally unusable application don't do it.

JavaScript: set dropdown selected item based on option text

A modern alternative:

const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);

Converting XML to JSON using Python?

Here's the code I built for that. There's no parsing of the contents, just plain conversion.

from xml.dom import minidom
import simplejson as json
def parse_element(element):
    dict_data = dict()
    if element.nodeType == element.TEXT_NODE:
        dict_data['data'] = element.data
    if element.nodeType not in [element.TEXT_NODE, element.DOCUMENT_NODE, 
                                element.DOCUMENT_TYPE_NODE]:
        for item in element.attributes.items():
            dict_data[item[0]] = item[1]
    if element.nodeType not in [element.TEXT_NODE, element.DOCUMENT_TYPE_NODE]:
        for child in element.childNodes:
            child_name, child_dict = parse_element(child)
            if child_name in dict_data:
                try:
                    dict_data[child_name].append(child_dict)
                except AttributeError:
                    dict_data[child_name] = [dict_data[child_name], child_dict]
            else:
                dict_data[child_name] = child_dict 
    return element.nodeName, dict_data

if __name__ == '__main__':
    dom = minidom.parse('data.xml')
    f = open('data.json', 'w')
    f.write(json.dumps(parse_element(dom), sort_keys=True, indent=4))
    f.close()

Forbidden You don't have permission to access / on this server

The problem lies in https.conf file!

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

The error occurs when hash(#) is removed or messed around with. These two lines should appear as shown above.

Order columns through Bootstrap4

Since column-ordering doesn't work in Bootstrap 4 beta as described in the code provided in the revisited answer above, you would need to use the following (as indicated in the codeply 4 Flexbox order demo - alpha/beta links that were provided in the answer).

<div class="container">
<div class="row">
    <div class="col-3 col-md-6">
        <div class="card card-block">1</div>
    </div>
    <div class="col-6 col-md-12  flex-md-last">
        <div class="card card-block">3</div>
    </div>
    <div class="col-3 col-md-6 ">
        <div class="card card-block">2</div>
    </div>
</div>

Note however that the "Flexbox order demo - beta" goes to an alpha codebase, and changing the codebase to Beta (and running it) results in the divs incorrectly displaying in a single column -- but that looks like a codeply issue since cutting and pasting the code out of codeply works as described.

how to deal with google map inside of a hidden div (Updated picture)

First post. My googleMap div was within a container div with {display:none} until tab clicked. Had the same problem as OP. This worked for me:

google.maps.event.addDomListener(window, 'load', setTimeout(initialize, 1));

Stick this code inside and at the end of your code where your container div tab is clicked and reveals your hidden div. The important thing is that your container div has to be visible before initialize can be called.

I tried a number of solutions proposed here and other pages and they didn't work for me. Let me know if this works for you. Thanks.

How to right-align and justify-align in Markdown?

As mentioned here, markdown do not support right aligned text or blocks. But the HTML result does it, via Cascading Style Sheets (CSS).

On my Jekyll Blog is use a syntax which works in markdown as well. To "terminate" a block use two spaces at the end or two times new line.

Of course you can also add a css-class with {: .right } instead of {: style="text-align: right" }.

Text to right

{: style="text-align: right" }
This text is on the right

Text as block

{: style="text-align: justify" }
This text is a block

syntax error near unexpected token `('

Try

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

c# search string in txt file

You have to use while since foreach does not know about index. Below is an example code.

int counter = 0;
string line;

Console.Write("Input your search text: ");
var text = Console.ReadLine();

System.IO.StreamReader file =
    new System.IO.StreamReader("SampleInput1.txt");

while ((line = file.ReadLine()) != null)
{
    if (line.Contains(text))
    {
        break;
    }

    counter++;
}

Console.WriteLine("Line number: {0}", counter);

file.Close();

Console.ReadLine();

How do I restart nginx only after the configuration test was successful on Ubuntu?

At least on Debian the nginx startup script has a reload function which does:

reload)
  log_daemon_msg "Reloading $DESC configuration" "$NAME"
  test_nginx_config
  start-stop-daemon --stop --signal HUP --quiet --pidfile $PID \
   --oknodo --exec $DAEMON
  log_end_msg $?
  ;;

Seems like all you'd need to do is call service nginx reload instead of restart since it calls test_nginx_config.

Remove portion of a string after a certain character

Why...

This is likely overkill for most people's needs, but, it addresses a number of things that each individual answer above does not. Of the items it addresses, three of them were needed for my needs. With tight bracketing and dropping the comments, this could still remain readable at only 13 lines of code.

This addresses the following:

  • Performance impact of using REGEX vs strrpos/strstr/strripos/stristr.
  • Using strripos/strrpos when character/string not found in string.
  • Removing from left or right side of string (first or last occurrence) .
  • CaSe Sensitivity.
  • Wanting the ability to return back the original string unaltered if search char/string not found.

Usage:

Send original string, search char/string, "R"/"L" for start on right or left side, true/false for case sensitivity. For example, search for "here" case insensitive, in string, start right side.

echo TruncStringAfterString("Now Here Are Some Words Here Now","here","R",false);

Output would be "Now Here Are Some Words ". Changing the "R" to an "L" would output: "Now ".

Here's the function:

function TruncStringAfterString($origString,$truncChar,$startSide,$caseSensitive)
{
    if ($caseSensitive==true && strstr($origString,$truncChar)!==false)
    {
        // IF START RIGHT SIDE:
        if (strtoupper($startSide)=="R" || $startSide==false)
        {   // Found, strip off all chars from truncChar to end
            return substr($origString,0,strrpos($origString,$truncChar));
        }

        // IF START LEFT SIDE: 
        elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
        {   // Found, strip off all chars from truncChar to end
            return strstr($origString,$truncChar,true);
        }           
    }
    elseif ($caseSensitive==false && stristr($origString,$truncChar)!==false)
    {           
        // IF START RIGHT SIDE: 
        if (strtoupper($startSide)=="R" || $startSide==false)
        {   // Found, strip off all chars from truncChar to end
            return substr($origString,0,strripos($origString,$truncChar));
        }

        // IF START LEFT SIDE: 
        elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
        {   // Found, strip off all chars from truncChar to end
            return stristr($origString,$truncChar,true);
        }
    }       
    else
    {   // NOT found - return origString untouched
        return $origString;     // Nothing to do here
    }           

}

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

I have used in my many projects and never got any single issue :)

for your reference, Code are in snippet

_x000D_
_x000D_
* {_x000D_
 margin: 0;_x000D_
}_x000D_
html, body {_x000D_
 height: 100%;_x000D_
}_x000D_
.wrapper {_x000D_
 min-height: 100%;_x000D_
 height: auto !important; /* This line and the next line are not necessary unless you need IE6 support */_x000D_
 height: 100%;_x000D_
 margin: 0 auto -50px; /* the bottom margin is the negative value of the footer's height */_x000D_
  background:green;_x000D_
}_x000D_
.footer, .push {_x000D_
 height: 50px; /* .push must be the same height as .footer */_x000D_
}_x000D_
_x000D_
.footer{_x000D_
  background:gold;_x000D_
  }
_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="wrapper">_x000D_
    Content Area_x000D_
    </div>_x000D_
  _x000D_
  <div class="push">_x000D_
    </div>_x000D_
  _x000D_
  <div class="footer">_x000D_
    Footer Area_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to convert datetime to integer in python

It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetime module (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp()).

If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:

2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)

def to_integer(dt_time):
    return 10000*dt_time.year + 100*dt_time.month + dt_time.day

E.g.

In [1]: import datetime

In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def to_integer(dt_time):
:    return 10000*dt_time.year + 100*dt_time.month + dt_time.day
:    # Or take the appropriate chars from a string date representation.
:--

In [3]: to_integer(datetime.date(2012, 6, 13))
Out[3]: 20120613

If you also want minutes and seconds, then just include further orders of magnitude as needed to display the digits.

I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.

It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.

Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.

It's generally much better to leave the value in a date context, like datetime.date, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.

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

Eduardo Molteni had a great answer:

Using Windows Scheduled Tasks:

In the batch file

"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S 
(local)\SQLExpress -i D:\dbbackups\SQLExpressBackups.sql

In SQLExpressBackups.sql

BACKUP DATABASE MyDataBase1 TO  DISK = N'D:\DBbackups\MyDataBase1.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase1 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

BACKUP DATABASE MyDataBase2 TO  DISK = N'D:\DBbackups\MyDataBase2.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase2 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

GO

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

Get type of all variables

R/Rscript doesn't have concrete datatypes.

R interpreter has a duck-typing memory allocation system. There is no builtin method to tell you the datatype of your pointer to memory. Duck typing is done for speed, but turned out to be a bad idea because now statements such as: print(is.integer(5)) returns FALSE and is.integer(as.integer(5)) returns TRUE. Go figure.

The R-manual on basic types: https://cran.r-project.org/doc/manuals/R-lang.html#Basic-types

The best you can hope for is to write your own function to probe your pointer to memory, then use process of elimination to decide if it is suitable for your needs.

If your variable is a global or an object:

Your object() needs to be penetrated with get(...) before you can see inside. Example:

a <- 10
myGlobals <- objects()
for(i in myGlobals){
  typeof(i)         #prints character
  typeof(get(i))    #prints integer
}

typeof(...) probes your variable pointer to memory:

The R function typeof has a bias to give you the type at maximum depth, for example.

library(tibble)

#expression              notes                                  type
#----------------------- -------------------------------------- ----------
typeof(TRUE)             #a single boolean:                     logical
typeof(1L)               #a single numeric with L postfixed:    integer
typeof("foobar")         #A single string in double quotes:     character
typeof(1)                #a single numeric:                     double
typeof(list(5,6,7))      #a list of numeric:                    list
typeof(2i)               #an imaginary number                   complex

typeof(5 + 5L)           #double + integer is coerced:          double
typeof(c())              #an empty vector has no type:          NULL
typeof(!5)               #a bang before a double:               logical
typeof(Inf)              #infinity has a type:                  double
typeof(c(5,6,7))         #a vector containing only doubles:     double
typeof(c(c(TRUE)))       #a vector of vector of logicals:       logical
typeof(matrix(1:10))     #a matrix of doubles has a type:       list

typeof(substr("abc",2,2))#a string at index 2 which is 'b' is:  character
typeof(c(5L,6L,7L))      #a vector containing only integers:    integer
typeof(c(NA,NA,NA))      #a vector containing only NA:          logical
typeof(data.frame())     #a data.frame with nothing in it:      list
typeof(data.frame(c(3))) #a data.frame with a double in it:     list
typeof(c("foobar"))      #a vector containing only strings:     character
typeof(pi)               #builtin expression for pi:            double

typeof(1.66)             #a single numeric with mantissa:       double
typeof(1.66L)            #a double with L postfixed             double
typeof(c("foobar"))      #a vector containing only strings:     character
typeof(c(5L, 6L))        #a vector containing only integers:    integer
typeof(c(1.5, 2.5))      #a vector containing only doubles:     double
typeof(c(1.5, 2.5))      #a vector containing only doubles:     double
typeof(c(TRUE, FALSE))   #a vector containing only logicals:    logical

typeof(factor())         #an empty factor has default type:     integer
typeof(factor(3.14))     #a factor containing doubles:          integer
typeof(factor(T, F))     #a factor containing logicals:         integer
typeof(Sys.Date())       #builtin R dates:                      double
typeof(hms::hms(3600))   #hour minute second timestamp          double
typeof(c(T, F))          #T and F are builtins:                 logical
typeof(1:10)             #a builtin sequence of numerics:       integer
typeof(NA)               #The builtin value not available:      logical

typeof(c(list(T)))       #a vector of lists of logical:         list
typeof(list(c(T)))       #a list of vectors of logical:         list
typeof(c(T, 3.14))       #a vector of logicals and doubles:     double
typeof(c(3.14, "foo"))   #a vector of doubles and characters:   character
typeof(c("foo",list(T))) #a vector of strings and lists:        list
typeof(list("foo",c(T))) #a list of strings and vectors:        list
typeof(TRUE + 5L)        #a logical plus an integer:            integer
typeof(c(TRUE, 5L)[1])   #The true is coerced to 1              integer
typeof(c(c(2i), TRUE)[1])#logical coerced to complex:           complex
typeof(c(NaN, 'batman')) #NaN's in a vector don't dominate:     character
typeof(5 && 4)           #doubles are coerced by order of &&    logical
typeof(8 < 'foobar')     #string and double is coerced          logical
typeof(list(4, T)[[1]])  #a list retains type at every index:   double
typeof(list(4, T)[[2]])  #a list retains type at every index:   logical
typeof(2 ** 5)           #result of exponentiation              double
typeof(0E0)              #exponential lol notation              double
typeof(0x3fade)          #hexidecimal                           double
typeof(paste(3, '3'))    #paste promotes types to string        character
typeof(3 + ?)           #R pukes on unicode                    error
typeof(iconv("a", "latin1", "UTF-8")) #UTF-8 characters         character
typeof(5 == 5)           #result of a comparison:               logical

class(...) probes your variable pointer to memory:

The R function class has a bias to give you the type of container or structure encapsulating your types, for example.

library(tibble)

#expression            notes                                    class
#--------------------- ---------------------------------------- ---------
class(matrix(1:10))     #a matrix of doubles has a class:       matrix
class(factor("hi"))     #factor of items is:                    factor
class(TRUE)             #a single boolean:                      logical
class(1L)               #a single numeric with L postfixed:     integer
class("foobar")         #A single string in double quotes:      character
class(1)                #a single numeric:                      numeric
class(list(5,6,7))      #a list of numeric:                     list
class(2i)               #an imaginary                           complex
class(data.frame())     #a data.frame with nothing in it:       data.frame
class(Sys.Date())       #builtin R dates:                       Date
class(sapply)           #a function is                          function
class(charToRaw("hi"))  #convert string to raw:                 raw
class(array("hi"))      #array of items is:                     array

class(5 + 5L)           #double + integer is coerced:          numeric
class(c())              #an empty vector has no class:         NULL
class(!5)               #a bang before a double:               logical
class(Inf)              #infinity has a class:                 numeric
class(c(5,6,7))         #a vector containing only doubles:     numeric
class(c(c(TRUE)))       #a vector of vector of logicals:       logical

class(substr("abc",2,2))#a string at index 2 which is 'b' is:  character
class(c(5L,6L,7L))      #a vector containing only integers:    integer
class(c(NA,NA,NA))      #a vector containing only NA:          logical
class(data.frame(c(3))) #a data.frame with a double in it:     data.frame
class(c("foobar"))      #a vector containing only strings:     character
class(pi)               #builtin expression for pi:            numeric

class(1.66)             #a single numeric with mantissa:       numeric
class(1.66L)            #a double with L postfixed             numeric
class(c("foobar"))      #a vector containing only strings:     character
class(c(5L, 6L))        #a vector containing only integers:    integer
class(c(1.5, 2.5))      #a vector containing only doubles:     numeric
class(c(TRUE, FALSE))   #a vector containing only logicals:    logical

class(factor())       #an empty factor has default class:      factor
class(factor(3.14))   #a factor containing doubles:            factor
class(factor(T, F))   #a factor containing logicals:           factor
class(hms::hms(3600)) #hour minute second timestamp            hms difftime
class(c(T, F))        #T and F are builtins:                   logical
class(1:10)           #a builtin sequence of numerics:         integer
class(NA)             #The builtin value not available:        logical

class(c(list(T)))       #a vector of lists of logical:         list
class(list(c(T)))       #a list of vectors of logical:         list
class(c(T, 3.14))       #a vector of logicals and doubles:     numeric
class(c(3.14, "foo"))   #a vector of doubles and characters:   character
class(c("foo",list(T))) #a vector of strings and lists:        list
class(list("foo",c(T))) #a list of strings and vectors:        list
class(TRUE + 5L)        #a logical plus an integer:            integer
class(c(TRUE, 5L)[1])   #The true is coerced to 1              integer
class(c(c(2i), TRUE)[1])#logical coerced to complex:           complex
class(c(NaN, 'batman')) #NaN's in a vector don't dominate:     character
class(5 && 4)           #doubles are coerced by order of &&    logical
class(8 < 'foobar')     #string and double is coerced          logical
class(list(4, T)[[1]])  #a list retains class at every index:  numeric
class(list(4, T)[[2]])  #a list retains class at every index:  logical
class(2 ** 5)           #result of exponentiation              numeric
class(0E0)              #exponential lol notation              numeric
class(0x3fade)          #hexidecimal                           numeric
class(paste(3, '3'))     #paste promotes class to string       character
class(3 + ?)           #R pukes on unicode                   error
class(iconv("a", "latin1", "UTF-8")) #UTF-8 characters         character
class(5 == 5)           #result of a comparison:               logical

Get the data storage.mode of your variable:

When an R variable is written to disk, the data layout changes again, and is called the data's storage.mode. The function storage.mode(...) reveals this low level information: see Mode, Class, and Type of R objects. You shouldn't need to worry about R's storage.mode unless you are trying to understand delays caused by round trip casts/coercions that occur when assigning and reading data to and from disk.

Demo: R/Rscript gettype(your_variable):

Run this R code then adapt it for your purposes, it'll make a pretty good guess as to what type it is.

get_type <- function(variable){ 
  sz <- as.integer(length(variable)) #length of your variable 
  tof <- typeof(variable)            #typeof your variable 
  cls <- class(variable)             #class of your variable 
  isc <- is.character(variable)      #what is.character() has to say about it.  
  d <- dim(variable)                 #dimensions of your variable 
  isv <- is.vector(variable) 
  if (is.matrix(variable)){  
    d <- dim(t(variable))             #dimensions of your matrix
  }    
  #observations ----> datatype 
  if (sz>=1 && tof == "logical" && cls == "logical" && isv == TRUE){ return("vector of logical") } 
  if (sz>=1 && tof == "integer" && cls == "integer" ){ return("vector of integer") } 
  if (sz==1 && tof == "double"  && cls == "Date" ){ return("Date") } 
  if (sz>=1 && tof == "raw"     && cls == "raw" ){ return("vector of raw") } 
  if (sz>=1 && tof == "double"  && cls == "numeric" ){ return("vector of double") } 
  if (sz>=1 && tof == "double"  && cls == "array" ){ return("vector of array of double") } 
  if (sz>=1 && tof == "character"  && cls == "array" ){ return("vector of array of character") } 
  if (sz>=0 && tof == "list"       && cls == "data.frame" ){ return("data.frame") } 
  if (sz>=1 && isc == TRUE         && isv == TRUE){ return("vector of character") } 
  if (sz>=1 && tof == "complex"    && cls == "complex" ){ return("vector of complex") } 
  if (sz==0 && tof == "NULL"       && cls == "NULL" ){ return("NULL") } 
  if (sz>=0 && tof == "integer"    && cls == "factor" ){ return("factor") } 
  if (sz>=1 && tof == "double"     && cls == "numeric" && isv == TRUE){ return("vector of double") } 
  if (sz>=1 && tof == "double"     && cls == "matrix"){ return("matrix of double") } 
  if (sz>=1 && tof == "character"  && cls == "matrix"){ return("matrix of character") } 
  if (sz>=1 && tof == "list"       && cls == "list" && isv == TRUE){ return("vector of list") } 
  if (sz>=1 && tof == "closure"    && cls == "function" && isv == FALSE){ return("closure/function") } 
  return("it's pointer to memory, bruh") 
} 
assert <- function(a, b){ 
  if (a == b){ 
    cat("P") 
  } 
  else{ 
    cat("\nFAIL!!!  Sniff test:\n") 
    sz <- as.integer(length(variable))   #length of your variable 
    tof <- typeof(variable)              #typeof your variable 
    cls <- class(variable)               #class of your variable 
    isc <- is.character(variable)        #what is.character() has to say about it. 
    d <- dim(variable)                   #dimensions of your variable 
    isv <- is.vector(variable) 
    if (is.matrix(variable)){  
      d <- dim(t(variable))                   #dimensions of your variable 
    } 
    if (!is.function(variable)){ 
      print(paste("value: '", variable, "'")) 
    } 
    print(paste("get_type said: '", a, "'")) 
    print(paste("supposed to be: '", b, "'")) 
 
    cat("\nYour pointer to memory has properties:\n")  
    print(paste("sz: '", sz, "'")) 
    print(paste("tof: '", tof, "'")) 
    print(paste("cls: '", cls, "'")) 
    print(paste("d: '", d, "'")) 
    print(paste("isc: '", isc, "'")) 
    print(paste("isv: '", isv, "'")) 
    quit() 
  } 
}
#these asserts give a sample for exercising the code. 
assert(get_type(TRUE),      "vector of logical")  #everything is a vector in R by default. 
assert(get_type(c(TRUE)),   "vector of logical")  #c() just casts to vector 
assert(get_type(c(c(TRUE))),"vector of logical")  #casting vector multiple times does nothing 
assert(get_type(!5),        "vector of logical")  #bang inflicts 'not truth-like' 
assert(get_type(1L),              "vector of integer")   #naked integers are still vectors of 1 
assert(get_type(c(1L, 2L)),       "vector of integer")   #Longs are not doubles 
assert(get_type(c(1L, c(2L, 3L))),"vector of integer")   #nested vectors of integers 
assert(get_type(c(1L, c(TRUE))),  "vector of integer")   #logicals coerced to integer 
assert(get_type(c(FALSE, c(1L))), "vector of integer")   #logicals coerced to integer 
assert(get_type("foobar"),        "vector of character")    #character here means 'string' 
assert(get_type(c(1L, "foobar")), "vector of character")    #integers are coerced to string 
assert(get_type(5),           "vector of double") 
assert(get_type(5 + 5L),      "vector of double") 
assert(get_type(Inf),         "vector of double") 
assert(get_type(c(5,6,7)),    "vector of double") 
assert(get_type(NaN),           "vector of double") 
assert(get_type(list(5)),       "vector of list")    #your list is in a vector. 
assert(get_type(list(5,6,7)),   "vector of list") 
assert(get_type(c(list(5,6,7))),"vector of list") 
assert(get_type(list(c(5,6),T)),"vector of list")    #vector of list of vector and logical 
assert(get_type(list(5,6,7)),   "vector of list") 
assert(get_type(2i),            "vector of complex") 
assert(get_type(c(2i, 3i, 4i)), "vector of complex") 
assert(get_type(c()),            "NULL") 
assert(get_type(data.frame()),   "data.frame") 
assert(get_type(data.frame(4,5)),"data.frame") 
assert(get_type(Sys.Date()),     "Date") 
assert(get_type(sapply),         "closure/function") 
assert(get_type(charToRaw("hi")),"vector of raw") 
assert(get_type(c(charToRaw("a"), charToRaw("b"))), "vector of raw") 
assert(get_type(array(4)),       "vector of array of double") 
assert(get_type(array(4,5)),     "vector of array of double") 
assert(get_type(array("hi")),    "vector of array of character") 
assert(get_type(factor()),       "factor") 
assert(get_type(factor(3.14)),   "factor") 
assert(get_type(factor(TRUE)),   "factor") 
assert(get_type(matrix(3,4,5)),  "matrix of double") 
assert(get_type(as.matrix(5)),   "matrix of double") 
assert(get_type(matrix("yatta")),"matrix of character") 

I put in a C++/Java/Python ideology here that gives me the scoop of what the memory most looks like. R triad typing system is like trying to nail spaghetti to the wall, <- and <<- will package your matrix to a list when you least suspect. As the old duck-typing saying goes: If it waddles like a duck and if it quacks like a duck and if it has feathers, then it's a duck.

How to Free Inode Usage?

If you use docker, remove all images. They used many space....

Stop all containers

docker stop $(docker ps -a -q)

Delete all containers

docker rm $(docker ps -a -q)

Delete all images

docker rmi $(docker images -q)

Works to me

Selenium using Python - Geckodriver executable needs to be in PATH

Selenium answers this question in their DESCRIPTION.rst file:

Drivers
=======

Selenium requires a driver to interface with the chosen browser. Firefox, for example, requires geckodriver <https://github.com/mozilla/geckodriver/releases>_, which needs to be installed before the below examples can be run. Make sure it's in your PATH, e. g., place it in /usr/bin or /usr/local/bin.

Failure to observe this step will give you an error `selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

Basically just download the geckodriver, unpack it and move the executable to your /usr/bin folder.

Use VBA to Clear Immediate Window?

Much harder to do that I'd envisaged. I found an version here by keepitcool that avoids the dreaded Sendkeys

Run this from a regular module.

Updated as initial post missed the Private Function Declarations - poor copy and paste job by yours truly

Private Declare Function GetWindow _
Lib "user32" ( _
ByVal hWnd As Long, _
ByVal wCmd As Long) As Long
Private Declare Function FindWindow _
Lib "user32" Alias "FindWindowA" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
Private Declare Function FindWindowEx _
Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, _
ByVal lpsz1 As String, _
ByVal lpsz2 As String) As Long
Private Declare Function GetKeyboardState _
Lib "user32" (pbKeyState As Byte) As Long
Private Declare Function SetKeyboardState _
Lib "user32" (lppbKeyState As Byte) As Long
Private Declare Function PostMessage _
Lib "user32" Alias "PostMessageA" ( _
ByVal hWnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, ByVal lParam As Long _
) As Long


Private Const WM_KEYDOWN As Long = &H100
Private Const KEYSTATE_KEYDOWN As Long = &H80


Private savState(0 To 255) As Byte


Sub ClearImmediateWindow()
'Adapted  by   keepITcool
'Original from Jamie Collins fka "OneDayWhen"
'http://www.dicks-blog.com/excel/2004/06/clear_the_immed.html


Dim hPane As Long
Dim tmpState(0 To 255) As Byte


hPane = GetImmHandle
If hPane = 0 Then MsgBox "Immediate Window not found."
If hPane < 1 Then Exit Sub


'Save the keyboardstate
GetKeyboardState savState(0)


'Sink the CTRL (note we work with the empty tmpState)
tmpState(vbKeyControl) = KEYSTATE_KEYDOWN
SetKeyboardState tmpState(0)
'Send CTRL+End
PostMessage hPane, WM_KEYDOWN, vbKeyEnd, 0&
'Sink the SHIFT
tmpState(vbKeyShift) = KEYSTATE_KEYDOWN
SetKeyboardState tmpState(0)
'Send CTRLSHIFT+Home and CTRLSHIFT+BackSpace
PostMessage hPane, WM_KEYDOWN, vbKeyHome, 0&
PostMessage hPane, WM_KEYDOWN, vbKeyBack, 0&


'Schedule cleanup code to run
Application.OnTime Now + TimeSerial(0, 0, 0), "DoCleanUp"


End Sub


Sub DoCleanUp()
' Restore keyboard state
SetKeyboardState savState(0)
End Sub


Function GetImmHandle() As Long
'This function finds the Immediate Pane and returns a handle.
'Docked or MDI, Desked or Floating, Visible or Hidden


Dim oWnd As Object, bDock As Boolean, bShow As Boolean
Dim sMain$, sDock$, sPane$
Dim lMain&, lDock&, lPane&


On Error Resume Next
sMain = Application.VBE.MainWindow.Caption
If Err <> 0 Then
MsgBox "No Access to Visual Basic Project"
GetImmHandle = -1
Exit Function
' Excel2003: Registry Editor (Regedit.exe)
'    HKLM\SOFTWARE\Microsoft\Office\11.0\Excel\Security
'    Change or add a DWORD called 'AccessVBOM', set to 1
' Excel2002: Tools/Macro/Security
'    Tab 'Trusted Sources', Check 'Trust access..'
End If


For Each oWnd In Application.VBE.Windows
If oWnd.Type = 5 Then
bShow = oWnd.Visible
sPane = oWnd.Caption
If Not oWnd.LinkedWindowFrame Is Nothing Then
bDock = True
sDock = oWnd.LinkedWindowFrame.Caption
End If
Exit For
End If
Next
lMain = FindWindow("wndclass_desked_gsk", sMain)
If bDock Then
'Docked within the VBE
lPane = FindWindowEx(lMain, 0&, "VbaWindow", sPane)
If lPane = 0 Then
'Floating Pane.. which MAY have it's own frame
lDock = FindWindow("VbFloatingPalette", vbNullString)
lPane = FindWindowEx(lDock, 0&, "VbaWindow", sPane)
While lDock > 0 And lPane = 0
lDock = GetWindow(lDock, 2) 'GW_HWNDNEXT = 2
lPane = FindWindowEx(lDock, 0&, "VbaWindow", sPane)
Wend
End If
ElseIf bShow Then
lDock = FindWindowEx(lMain, 0&, "MDIClient", _
vbNullString)
lDock = FindWindowEx(lDock, 0&, "DockingView", _
vbNullString)
lPane = FindWindowEx(lDock, 0&, "VbaWindow", sPane)
Else
lPane = FindWindowEx(lMain, 0&, "VbaWindow", sPane)
End If


GetImmHandle = lPane


End Function

How to close form

for example, if you want to close a windows form when an action is performed there are two methods to do it

1.To close it directly

Form1 f=new Form1();
f.close(); //u can use below comment also
//this.close();

2.We can also hide form without closing it

 private void button1_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        Form2 f2 = new Form2();
        int flag = 0;
        string u, p;
        u = textBox1.Text;
        p = textBox2.Text;
        if(u=="username" && p=="pasword")
        {
            flag = 1;
        }
        else
        {
          MessageBox.Show("enter correct details");
        }
        if(flag==1)
        {
            f2.Show();
            this.Hide();
        }

    }

How do I remove the file suffix and path portion from a path string in Bash?

If you can't use basename as suggested in other posts, you can always use sed. Here is an (ugly) example. It isn't the greatest, but it works by extracting the wanted string and replacing the input with the wanted string.

echo '/foo/fizzbuzz.bar' | sed 's|.*\/\([^\.]*\)\(\..*\)$|\1|g'

Which will get you the output

fizzbuzz

How to make a owl carousel with arrows instead of next previous

This is how you do it in your $(document).ready() function with FontAwesome Icons:

 $( ".owl-prev").html('<i class="fa fa-chevron-left"></i>');
 $( ".owl-next").html('<i class="fa fa-chevron-right"></i>');

How to remove an element from a list by index

One can either use del or pop, but I prefer del, since you can specify index and slices, giving the user more control over the data.

For example, starting with the list shown, one can remove its last element with del as a slice, and then one can remove the last element from the result using pop.

>>> l = [1,2,3,4,5]
>>> del l[-1:]
>>> l
[1, 2, 3, 4]
>>> l.pop(-1)
4
>>> l
[1, 2, 3]

Convert pandas dataframe to NumPy array

Further to meteore's answer, I found the code

df.index = df.index.astype('i8')

doesn't work for me. So I put my code here for the convenience of others stuck with this issue.

city_cluster_df = pd.read_csv(text_filepath, encoding='utf-8')
# the field 'city_en' is a string, when converted to Numpy array, it will be an object
city_cluster_arr = city_cluster_df[['city_en','lat','lon','cluster','cluster_filtered']].to_records()
descr=city_cluster_arr.dtype.descr
# change the field 'city_en' to string type (the index for 'city_en' here is 1 because before the field is the row index of dataframe)
descr[1]=(descr[1][0], "S20")
newArr=city_cluster_arr.astype(np.dtype(descr))

What to return if Spring MVC controller method doesn't return value?

You can simply return a ResponseEntity with the appropriate header:

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public ResponseEntity updateDataThatDoesntRequireClientToBeNotified(...){
....
return new ResponseEntity(HttpStatus.OK)
}

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

how to run a winform from console application?

You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.

Change the Textbox height?

Try the following :)

        textBox1.Multiline = true;
        textBox1.Height = 100;
        textBox1.Width = 173;

How to call getResources() from a class which has no context?

It can easily be done if u had declared a class that extends from Application

This class will be like a singleton, so when u need a context u can get it just like this:

I think this is the better answer and the cleaner

Here is my code from Utilities package:

 public static String getAppNAme(){
     return MyOwnApplication.getInstance().getString(R.string.app_name);
 }

Resizing an iframe based on content

The solution on http://www.phinesolutions.com/use-jquery-to-adjust-the-iframe-height.html works great (uses jQuery):

<script type=”text/javascript”>
  $(document).ready(function() {
    var theFrame = $(”#iFrameToAdjust”, parent.document.body);
    theFrame.height($(document.body).height() + 30);
  });
</script>

I don't know that you need to add 30 to the length... 1 worked for me.

FYI: If you already have a "height" attribute on your iFrame, this just adds style="height: xxx". This might not be what you want.

Why do you create a View in a database?

I am creating xxx that maps all the relationships between a main table (like Products table) and reference tables (like ProductType or ProductDescriptionByLanguage). This will create a view that will allow me retrieve a product and all it's details translated from its foreign keys to its description. Then I can use an ORM to create objects to easily build grids, combo boxes, etc.

reading HttpwebResponse json response, C#

If you're getting source in Content Use the following method

try
{
    var response = restClient.Execute<List<EmpModel>>(restRequest);

    var jsonContent = response.Content;

    var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);

    foreach (EmpModel item in data)
    {
        listPassingData?.Add(item);
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Data get mathod problem {ex} ");
}

Setting java locale settings

I believe java gleans this from the environment variables in which it was launched, so you'll need to make sure your LANG and LC_* environment variables are set appropriately.

The locale manpage has full info on said environment variables.

Laravel blade check empty foreach

This is my best solution if I understood the question well:

Use of $object->first() method to run the code inside if statement once, that is when on the first loop. The same concept is true with $object->last().

    @if($object->first())
        <div class="panel user-list">
          <table id="myCustomTable" class="table table-hover">
              <thead>
                  <tr>
                     <th class="col-email">Email</th>
                  </tr>
              </thead>
              <tbody>
    @endif

    @foreach ($object as $data)
        <tr class="gradeX">
           <td class="col-name"><strong>{{ $data->email }}</strong></td>
        </tr>
    @endforeach

    @if($object->last())
                </tbody>
            </table>
        </div>
    @endif

import error: 'No module named' *does* exist

I met the same problem, and I try the pdb.set_trace() before the error line.

My problem is the package name duplicate with the module name, like:

test
+-- __init__.py
+-- a
¦   +-- __init__.py
¦   +-- test.py
+-- b
    +-- __init__.py

and at file a/__init__.py, using from test.b import xxx will cause ImportError: No module named b.

How do I diff the same file between two different commits on the same branch?

You can also compare two different files in two different revisions, like this:

git diff <revision_1>:<file_1> <revision_2>:<file_2>

How to have an auto incrementing version number (Visual Studio)?

This is my implementation of the T4 suggestion... This will increment the build number every time you build the project regardless of the selected configuration (i.e. Debug|Release), and it will increment the revision number every time you do a Release build. You can continue to update the major and minor version numbers through Application ➤ Assembly Information...

To explain in more detail, this will read the existing AssemblyInfo.cs file, and use regex to find the AssemblyVersion information and then increment the revision and build numbers based on input from TextTransform.exe.

  1. Delete your existing AssemblyInfo.cs file.
  2. Create a AssemblyInfo.tt file in its place. Visual Studio should create AssemblyInfo.cs and group it with the T4 file after you save the T4 file.

    <#@ template debug="true" hostspecific="true" language="C#" #>
    <#@ output extension=".cs" #>
    <#@ import namespace="System.IO" #>
    <#@ import namespace="System.Text.RegularExpressions" #>
    <#
        string output = File.ReadAllText(this.Host.ResolvePath("AssemblyInfo.cs"));
        Regex pattern = new Regex("AssemblyVersion\\(\"(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<revision>\\d+)\\.(?<build>\\d+)\"\\)");
        MatchCollection matches = pattern.Matches(output);
        if( matches.Count == 1 )
        {
            major = Convert.ToInt32(matches[0].Groups["major"].Value);
            minor = Convert.ToInt32(matches[0].Groups["minor"].Value);
            build = Convert.ToInt32(matches[0].Groups["build"].Value) + 1;
            revision = Convert.ToInt32(matches[0].Groups["revision"].Value);
            if( this.Host.ResolveParameterValue("-","-","BuildConfiguration") == "Release" )
                revision++;
        }
    #>
    
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Resources;
    
    // General Information
    [assembly: AssemblyTitle("Insert title here")]
    [assembly: AssemblyDescription("Insert description here")]
    [assembly: AssemblyConfiguration("")]
    [assembly: AssemblyCompany("Insert company here")]
    [assembly: AssemblyProduct("Insert product here")]
    [assembly: AssemblyCopyright("Insert copyright here")]
    [assembly: AssemblyTrademark("Insert trademark here")]
    [assembly: AssemblyCulture("")]
    
    // Version informationr(
    [assembly: AssemblyVersion("<#= this.major #>.<#= this.minor #>.<#= this.revision #>.<#= this.build #>")]
    [assembly: AssemblyFileVersion("<#= this.major #>.<#= this.minor #>.<#= this.revision #>.<#= this.build #>")]
    [assembly: NeutralResourcesLanguageAttribute( "en-US" )]
    
    <#+
        int major = 1;
        int minor = 0;
        int revision = 0;
        int build = 0;
    #>
    
  3. Add this to your pre-build event:

    "%CommonProgramFiles(x86)%\microsoft shared\TextTemplating\$(VisualStudioVersion)\TextTransform.exe" -a !!BuildConfiguration!$(Configuration) "$(ProjectDir)Properties\AssemblyInfo.tt"
    

Where is the WPF Numeric UpDown control?

This is example of my own UserControl with Up and Down key catching.

Xaml code:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="13" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="13" />
        <RowDefinition Height="13" />
    </Grid.RowDefinitions>
    <TextBox Name="NUDTextBox"  Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" TextAlignment="Right" PreviewKeyDown="NUDTextBox_PreviewKeyDown" PreviewKeyUp="NUDTextBox_PreviewKeyUp" TextChanged="NUDTextBox_TextChanged"/>
    <RepeatButton Name="NUDButtonUP"  Grid.Column="1" Grid.Row="0" FontSize="8" FontFamily="Marlett" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Click="NUDButtonUP_Click">5</RepeatButton>
    <RepeatButton Name="NUDButtonDown"  Grid.Column="1" Grid.Row="1" FontSize="8"  FontFamily="Marlett" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Height="13" VerticalAlignment="Bottom" Click="NUDButtonDown_Click">6</RepeatButton>
</Grid>

And the code:

public partial class NumericUpDown : UserControl
{
    int minvalue = 0, 
        maxvalue = 100,
        startvalue = 10;
    public NumericUpDown()
    {
        InitializeComponent();
        NUDTextBox.Text = startvalue.ToString();
    }

    private void NUDButtonUP_Click(object sender, RoutedEventArgs e)
    {
        int number;
        if (NUDTextBox.Text != "") number = Convert.ToInt32(NUDTextBox.Text);
        else number = 0;
        if (number < maxvalue)
            NUDTextBox.Text = Convert.ToString(number + 1); 
    }

    private void NUDButtonDown_Click(object sender, RoutedEventArgs e)
    {
        int number;
        if (NUDTextBox.Text != "") number = Convert.ToInt32(NUDTextBox.Text);
        else number = 0;
        if (number > minvalue)
            NUDTextBox.Text = Convert.ToString(number - 1); 
    }

    private void NUDTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {

        if (e.Key == Key.Up)
        {
            NUDButtonUP.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonUP, new object[] { true }); 
        }


        if (e.Key == Key.Down)
        {
            NUDButtonDown.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonDown, new object[] { true }); 
        }
    }

    private void NUDTextBox_PreviewKeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Up)
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonUP, new object[] { false });

        if (e.Key == Key.Down)
            typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonDown, new object[] { false });
    }

    private void NUDTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        int number = 0;
        if (NUDTextBox.Text!="")
            if (!int.TryParse(NUDTextBox.Text, out number)) NUDTextBox.Text = startvalue.ToString();
        if (number > maxvalue)  NUDTextBox.Text = maxvalue.ToString();
        if (number < minvalue) NUDTextBox.Text = minvalue.ToString();
        NUDTextBox.SelectionStart = NUDTextBox.Text.Length;

    }

}

Center image using text-align center?

If you want to set the image as the background, I've got a solution:

.image {
    background-image: url(yourimage.jpg);
    background-position: center;
}

How to remove duplicates from Python list and keep order?

A list can be sorted and deduplicated using built-in functions:

myList = sorted(set(myList))
  • set is a built-in function for Python >= 2.3
  • sorted is a built-in function for Python >= 2.4

Convert varchar to uniqueidentifier in SQL Server

It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.

create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
    -- just in case it came in with 0x prefix or dashes...
    set @s = replace(replace(@s,'0x',''),'-','')
    -- inject dashes in the right places
    set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
    return cast(@s as uniqueidentifier)
end

How can I maintain fragment state when added to the back stack?

first: just use add method instead of replace method of FragmentTransaction class then you have to add secondFragment to stack by addToBackStack method

second :on back click you have to call popBackStackImmediate()

Fragment sourceFragment = new SourceFragment ();
final Fragment secondFragment = new SecondFragment();
final FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.add(R.id.child_fragment_container, secondFragment );
ft.hide(sourceFragment );
ft.addToBackStack(NewsShow.class.getName());
ft.commit();
                                
((SecondFragment)secondFragment).backFragmentInstanceClick = new SecondFragment.backFragmentNewsResult()
{
        @Override
        public void backFragmentNewsResult()
        {                                    
            getChildFragmentManager().popBackStackImmediate();                                
        }
};

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

Data binding for TextBox

I Recommend you implement INotifyPropertyChanged and change your databinding code to this:

this.textBox.DataBindings.Add("Text",
                                this.Food,
                                "Name",
                                false,
                                DataSourceUpdateMode.OnPropertyChanged);

That'll fix it.

Note that the default DataSourceUpdateMode is OnValidation, so if you don't specify OnPropertyChanged, the model object won't be updated until after your validations have occurred.

Equivalent of Oracle's RowID in SQL Server

if you just want basic row numbering for a small dataset, how about someting like this?

SELECT row_number() OVER (order by getdate()) as ROWID, * FROM Employees

How to pause for specific amount of time? (Excel/VBA)

Function Delay(ByVal T As Integer)
    'Function can be used to introduce a delay of up to 99 seconds
    'Call Function ex:  Delay 2 {introduces a 2 second delay before execution of code resumes}
        strT = Mid((100 + T), 2, 2)
            strSecsDelay = "00:00:" & strT
    Application.Wait (Now + TimeValue(strSecsDelay))
End Function

How should I log while using multiprocessing in Python?

just publish somewhere your instance of the logger. that way, the other modules and clients can use your API to get the logger without having to import multiprocessing.

Configure Flask dev server to be visible across the network

I had the same problem, I use PyCharm as an editor and when I created the project, PyCharm created a Flask Server. What I did was create a server with Python in the following way;

Config Python Server PyCharm basically what I did was create a new server but flask if not python

I hope it helps you

Why shouldn't I use mysql_* functions in PHP?

There are many reasons, but perhaps the most important one is that those functions encourage insecure programming practices because they do not support prepared statements. Prepared statements help prevent SQL injection attacks.

When using mysql_* functions, you have to remember to run user-supplied parameters through mysql_real_escape_string(). If you forget in just one place or if you happen to escape only part of the input, your database may be subject to attack.

Using prepared statements in PDO or mysqli will make it so that these sorts of programming errors are more difficult to make.

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Vertically aligning text next to a radio button

Used to this

    input[type="radio"]{
    vertical-align:top;
    }
p{
    font-size:10px;line-height: 18px;
}

Demo

Difference between Constructor and ngOnInit

In the Angular life-cycles

1) Angular injector detect constructor parameter('s) and instantiate class.

2) Next angular call life-cycle

Angular Lifecycle Hooks

ngOnChanges --> Call in directive parameters binding.

ngOnInit --> Start angular rendering...

Call other method with state of angular life-cycle.

How to configure socket connect timeout

I had the Same problem when connecting to a Socket and I came up with the below solution ,It works Fine for me. `

private bool CheckConnectivityForProxyHost(string hostName, int port)
       {
           if (string.IsNullOrEmpty(hostName))
               return false;

           bool isUp = false;
           Socket testSocket = null;

           try
           {

               testSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
               IPAddress ip = null;
               if (testSocket != null && NetworkingCollaboratorBase.GetResolvedConnecionIPAddress(hostName, out ip))//Use a method to resolve your IP
               {
                   IPEndPoint ipEndPoint = new IPEndPoint(ip, port);

                   isUp = false;
//time out 5 Sec
                  CallWithTimeout(ConnectToProxyServers, 5000, testSocket, ipEndPoint);

                       if (testSocket != null && testSocket.Connected)
                       {
                           isUp = true;
                       }
                   }

               }
           }
           catch (Exception ex)
           {
               isUp = false;
           }
           finally
           {
               try
               {
                   if (testSocket != null)
                   {
                       testSocket.Shutdown(SocketShutdown.Both);
                   }
               }
               catch (Exception ex)
               {

               }
               finally
               {
                   if (testSocket != null)
                       testSocket.Close();
               }

           }

           return isUp;
       }


 private void CallWithTimeout(Action<Socket, IPEndPoint> action, int timeoutMilliseconds, Socket socket, IPEndPoint ipendPoint)
       {
           try
           {
               Action wrappedAction = () =>
               {
                   action(socket, ipendPoint);
               };

               IAsyncResult result = wrappedAction.BeginInvoke(null, null);

               if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
               {
                   wrappedAction.EndInvoke(result);
               }

           }
           catch (Exception ex)
           {

           }
       }

  private void ConnectToProxyServers(Socket testSocket, IPEndPoint ipEndPoint)
       {
           try
           {
               if (testSocket == null || ipEndPoint == null)
                   return;

                   testSocket.Connect(ipEndPoint);

           }
           catch (Exception ex)
           {

           }
       } 

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You should only need to unbind the service in onDestroy(). Then, The warning will go.

See here.

As the Activity doc tries to explain, there are three main bind/unbind groupings you will use: onCreate() and onDestroy(), onStart() and onStop(), and onResume() and onPause().

How to destroy Fragment?

If you are in the fragment itself, you need to call this. Your fragment needs to be the fragment that is being called. Enter code:

getFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();

or if you are using supportLib, then you need to call:

getSupportFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();

How to convert text column to datetime in SQL

In SQL Server , cast text as datetime

select cast('5/21/2013 9:45:48' as datetime)

Encrypt Password in Configuration Files?

A simple way of doing this is to use Password Based Encryption in Java. This allows you to encrypt and decrypt a text by using a password.

This basically means initializing a javax.crypto.Cipher with algorithm "AES/CBC/PKCS5Padding" and getting a key from javax.crypto.SecretKeyFactory with the "PBKDF2WithHmacSHA512" algorithm.

Here is a code example (updated to replace the less secure MD5-based variant):

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class ProtectedConfigFile {

    public static void main(String[] args) throws Exception {
        String password = System.getProperty("password");
        if (password == null) {
            throw new IllegalArgumentException("Run with -Dpassword=<password>");
        }

        // The salt (probably) can be stored along with the encrypted data
        byte[] salt = new String("12345678").getBytes();

        // Decreasing this speeds down startup time and can be useful during testing, but it also makes it easier for brute force attackers
        int iterationCount = 40000;
        // Other values give me java.security.InvalidKeyException: Illegal key size or default parameters
        int keyLength = 128;
        SecretKeySpec key = createSecretKey(password.toCharArray(),
                salt, iterationCount, keyLength);

        String originalPassword = "secret";
        System.out.println("Original password: " + originalPassword);
        String encryptedPassword = encrypt(originalPassword, key);
        System.out.println("Encrypted password: " + encryptedPassword);
        String decryptedPassword = decrypt(encryptedPassword, key);
        System.out.println("Decrypted password: " + decryptedPassword);
    }

    private static SecretKeySpec createSecretKey(char[] password, byte[] salt, int iterationCount, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount, keyLength);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        return new SecretKeySpec(keyTmp.getEncoded(), "AES");
    }

    private static String encrypt(String property, SecretKeySpec key) throws GeneralSecurityException, UnsupportedEncodingException {
        Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters parameters = pbeCipher.getParameters();
        IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);
        byte[] cryptoText = pbeCipher.doFinal(property.getBytes("UTF-8"));
        byte[] iv = ivParameterSpec.getIV();
        return base64Encode(iv) + ":" + base64Encode(cryptoText);
    }

    private static String base64Encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    private static String decrypt(String string, SecretKeySpec key) throws GeneralSecurityException, IOException {
        String iv = string.split(":")[0];
        String property = string.split(":")[1];
        Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(base64Decode(iv)));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    }

    private static byte[] base64Decode(String property) throws IOException {
        return Base64.getDecoder().decode(property);
    }
}

One problem remains: Where should you store the password that you use to encrypt the passwords? You can store it in the source file and obfuscate it, but it's not too hard to find it again. Alternatively, you can give it as a system property when you start the Java process (-DpropertyProtectionPassword=...).

The same issue remains if you use the KeyStore, which also is protected by a password. Basically, you will need to have one master password somewhere, and it's pretty hard to protect.

Java heap terminology: young, old and permanent generations?

This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.

Here is a good post on permanent generation.

I like the descriptions given for each space in Oracle's guide on JConsole:

For the HotSpot Java VM, the memory pools for serial garbage collection are the following.

  • Eden Space (heap): The pool from which memory is initially allocated for most objects.
  • Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
  • Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
  • Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
  • Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

Short ES6 code

const convertFrom12To24Format = (time12) => {
  const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
  const PM = period === 'PM';
  const hours = (+sHours % 12) + (PM ? 12 : 0);

  return `${('0' + hours).slice(-2)}:${minutes}`;
}
const convertFrom24To12Format = (time24) => {
  const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
  const period = +sHours < 12 ? 'AM' : 'PM';
  const hours = +sHours % 12 || 12;

  return `${hours}:${minutes} ${period}`;
}

How do I remove the title bar from my app?

The easiest way: Just double click on this button and choose "NoTitleBar" ;)

Click here to see where it is :)

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

I have faced the same issue. Here is how I have fixed it.

Step 1: Remove mysql using command:

brew uninstall --force mysql

Step 2: Run command brew doctor which will give you some hint related to your brew packages.

Step 3: Cleanup brew packages using command:

brew cleanup

Step 4: Move/delete previously installed mysql data using command:

mv /usr/local/var/mysql/ /usr/local/var/old_mysql

Step 5: Finally install mysql again using command:

brew install mysql

What are POD types in C++?

Very informally:

A POD is a type (including classes) where the C++ compiler guarantees that there will be no "magic" going on in the structure: for example hidden pointers to vtables, offsets that get applied to the address when it is cast to other types (at least if the target's POD too), constructors, or destructors. Roughly speaking, a type is a POD when the only things in it are built-in types and combinations of them. The result is something that "acts like" a C type.

Less informally:

  • int, char, wchar_t, bool, float, double are PODs, as are long/short and signed/unsigned versions of them.
  • pointers (including pointer-to-function and pointer-to-member) are PODs,
  • enums are PODs
  • a const or volatile POD is a POD.
  • a class, struct or union of PODs is a POD provided that all non-static data members are public, and it has no base class and no constructors, destructors, or virtual methods. Static members don't stop something being a POD under this rule. This rule has changed in C++11 and certain private members are allowed: Can a class with all private members be a POD class?
  • Wikipedia is wrong to say that a POD cannot have members of type pointer-to-member. Or rather, it's correct for the C++98 wording, but TC1 made explicit that pointers-to-member are POD.

Formally (C++03 Standard):

3.9(10): "Arithmetic types (3.9.1), enumeration types, pointer types, and pointer to member types (3.9.2) and cv-qualified versions of these types (3.9.3) are collectively caller scalar types. Scalar types, POD-struct types, POD-union types (clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called POD types"

9(4): "A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor. Similarly a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor.

8.5.1(1): "An aggregate is an array or class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10) and no virtual functions (10.3)."

How to determine if object is in array

You can just use the equality operator: ==. Objects are checked by reference by default, so you don't even need to use the === operator.

try this, just make sure you're using the correct variable reference in the place of car1:

var i, car, l = cars.length;

for (i = 0; i < l; i++)
{
  if ((car = cars[i]) == car1)
  {
    break;
  }
  else car = null;
}

Edit to add:

An array extension was mentioned, so here's the code for it:

Array.prototype.contains = Array.prototype.contains || function(obj)
{
  var i, l = this.length;
  for (i = 0; i < l; i++)
  {
    if (this[i] == obj) return true;
  }
  return false;
};

Note that I'm caching the length value, as the Array's length property is actually an accessor, which is marginally slower than an internal variable.

Setting focus to iframe contents

This is something that worked for me, although it smells a bit wrong:

var iframe = ...
var doc = iframe.contentDocument;

var i = doc.createElement('input');
i.style.display = 'none'; 
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);

hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.