Programs & Examples On #Virtualenv

virtualenv is a tool that creates sandboxed Python environments.

Cron and virtualenv

Since a cron executes in its own minimal sh environment, here's what I do to run Python scripts in a virtual environment:

* * * * * . ~/.bash_profile; . ~/path/to/venv/bin/activate; python ~/path/to/script.py

(Note: if . ~/.bash_profile doesn't work for you, then try . ~/.bashrc or . ~/.profile depending on how your server is set up.)

This loads your bash shell environment, then activates your Python virtual environment, essentially leaving you with the same setup you tested your scripts in.

No need to define environment variables in crontab and no need to modify your existing scripts.

What is the official "preferred" way to install pip and virtualenv systemwide?

Starting from distro packages, you can either use:

sudo apt-get install python-virtualenv

which lets you create virtualenvs, or

sudo apt-get install python{,3}-pip

which lets you install arbitrary packages to your home directory.

If you're used to virtualenv, the first command gives you everything you need (remember, pip is bundled and will be installed in any virtualenv you create).

If you just want to install packages, the second command gives you what you need. Use pip like this:

pip install --user something

and put something like

PATH=~/.local/bin:$PATH

in your ~/.bashrc.


If your distro is ancient and you don't want to use its packages at all (except for Python itself, probably), you can download virtualenv, either as a tarball or as a standalone script:

wget -O ~/bin/virtualenv https://raw.github.com/pypa/virtualenv/master/virtualenv.py
chmod +x ~/bin/virtualenv

If your distro is more of the bleeding edge kind, Python3.3 has built-in virtualenv-like abilities:

python3 -m venv ./venv

This runs way faster, but setuptools and pip aren't included.

How do you set your pythonpath in an already-created virtualenv?

It's already answered here -> Is my virtual environment (python) causing my PYTHONPATH to break?

UNIX/LINUX

Add "export PYTHONPATH=/usr/local/lib/python2.0" this to ~/.bashrc file and source it by typing "source ~/.bashrc" OR ". ~/.bashrc".

WINDOWS XP

1) Go to the Control panel 2) Double click System 3) Go to the Advanced tab 4) Click on Environment Variables

In the System Variables window, check if you have a variable named PYTHONPATH. If you have one already, check that it points to the right directories. If you don't have one already, click the New button and create it.

PYTHON CODE

Alternatively, you can also do below your code:-

import sys
sys.path.append("/home/me/mypy") 

Pip install Matplotlib error with virtualenv

sudo apt-get install libpng-dev libjpeg8-dev libfreetype6-dev

worked for me on Ubuntu 14.04

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

Steps for Window10:

  • Go to https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
  • Download the right version according to python version and hardware specs: for my case, mysqlclient-1.4.2-cp37-cp37m-win32.whl works for python3.7 and Intel CPU.
  • While your env is still activated, go to the download folder and run pip install mysqlclient-1.4.2-cp37-cp37m-win32.whl

How do I update pip itself from inside my virtual environment?

pip is just a PyPI package like any other; you could use it to upgrade itself the same way you would upgrade any package:

pip install --upgrade pip

On Windows the recommended command is:

python -m pip install --upgrade pip

What's the proper way to install pip, virtualenv, and distribute for Python?

I think Glyph means do something like this:

  1. Create a directory ~/.local, if it doesn't already exist.
  2. In your ~/.bashrc, ensure that ~/.local/bin is on PATH and that ~/.local is on PYTHONPATH.
  3. Create a file ~/.pydistutils.cfg which contains

    [install]
    prefix=~/.local
    

    It's a standard ConfigParser-format file.

  4. Download distribute_setup.py and run python distribute_setup.py (no sudo). If it complains about a non-existing site-packages directory, create it manually:

    mkdir -p ~/.local/lib/python2.7/site-packages/

  5. Run which easy_install to verify that it's coming from ~/.local/bin

  6. Run pip install virtualenv
  7. Run pip install virtualenvwrapper
  8. Create a virtual env containing folder, say ~/.virtualenvs
  9. In ~/.bashrc add

    export WORKON_HOME
    source ~/.local/bin/virtualenvwrapper.sh
    

That's it, no use of sudo at all and your Python environment is in ~/.local, completely separate from the OS's Python. Disclaimer: Not sure how compatible virtualenvwrapper is in this scenario - I couldn't test it on my system :-)

Python: No acceptable C compiler found in $PATH when installing python

If you are using alphine with docker, do this:

apk --update add gcc make g++ zlib-dev

How to install a package inside virtualenv?

Avoiding Headaches and Best Practices:

  • Virtual Environments are not part of your git project (they don't need to be versioned) !

  • They can reside on the project folder (locally), but, ignored on your .gitignore.

  • After activating the virtual environment of your project, never "sudo pip install package".
  • After finishing your work, always "deactivate" your environment.
  • Avoid renaming your project folder.


For a better representation, here's a simulation:

creating a folder for your projects/environments

$ mkdir venv

creating environment

$ cd venv/ 

$ virtualenv google_drive
New python executable in google_drive/bin/python
Installing setuptools, pip...done.

activating environment

$ source google_drive/bin/activate

installing packages

(google_drive) $ pip install PyDrive
Downloading/unpacking PyDrive
Downloading PyDrive-1.3.1-py2-none-any.whl
...
...
...    
Successfully installed PyDrive PyYAML google-api-python-client oauth2client six uritemplate httplib2 pyasn1 rsa pyasn1-modules
Cleaning up...

package available inside the environment

(google_drive) $ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import pydrive.auth
>>>  
>>> gdrive = pydrive.auth.GoogleAuth()
>>>

deactivate environment

(google_drive) $ deactivate 

$ 

package NOT AVAILABLE outside the environment

$ python
Python 2.7.6 (default, Oct 26 2016, 20:32:10) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import pydrive.auth
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pydrive.auth
>>> 

Notes:

Why not sudo?

Virtualenv creates a whole new environment for you, defining $PATH and some other variables and settings. When you use sudo pip install package, you are running Virtualenv as root, escaping the whole environment which was created, and then, installing the package on global site-packages, and not inside the project folder where you have a Virtual Environment, although you have activated the environment.

If you rename the folder of your project...

...you'll have to adjust some variables from some files inside the bin directory of your project.

For example:

bin/pip, line 1 (She Bang)

bin/activate, line 42 (VIRTUAL_ENV)

Is it bad to have my virtualenv directory inside my git repository?

If you just setting up development env, then use pip freeze file, caz that makes the git repo clean.

Then if doing production deployment, then checkin the whole venv folder. That will make your deployment more reproducible, not need those libxxx-dev packages, and avoid the internet issues.

So there are two repos. One for your main source code, which includes a requirements.txt. And a env repo, which contains the whole venv folder.

How to install psycopg2 with "pip" on Python?

Make sure Postgres is installed and PATH is updated before running pip install psycopg2

export PATH="$PATH:/Applications/Postgres.app/Contents/Versions/12/bin"

no module named zlib

My objective was to create a new Django project from the command line in Ubuntu, like so:

django-admin.py startproject mysite

I have python2.7.5 installed. I got this error:

ImportError: No module named zlib

For hours I could not find a solution, until now!

Here is a link to the solution -

http://doc.biblissima-condorcet.fr/loris-setup-guide-ubuntu-debian

I followed and executed instruction in Section 1.1 and it is working perfectly! It is an easy solution.

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

Use different Python version with virtualenv

This worked for my usage in Windows 10, where I have Python 3.7 and want to downgrade for a project in Python 3.6.6:

I used "venv" to create a new environment called "venv", I downloaded from https://www.python.org/downloads/windows/ ; install "Download Windows x86-64 executable installer-" ; then I used the following command line in the directory where I want to create my environment

>C:\Users\...\Python\Python36\python.exe -m venv venv

Finally, I activated the environnent using the command line:

>venv\Scripts\activate.bat

And check the python version by calling:

>python --version Python 3.6.6

Activate a virtualenv with a Python script

It turns out that, yes, the problem is not simple, but the solution is.

First I had to create a shell script to wrap the "source" command. That said I used the "." instead, because I've read that it's better to use it than source for Bash scripts.

#!/bin/bash
. /path/to/env/bin/activate

Then from my Python script I can simply do this:

import os
os.system('/bin/bash --rcfile /path/to/myscript.sh')

The whole trick lies within the --rcfile argument.

When the Python interpreter exits it leaves the current shell in the activated environment.

Win!

pip installing in global site-packages instead of virtualenv

Came across the same issue today. I simply reinstalled pip globally with sudo easy_install pip (OSX/ Max), then created my virtualenv again with sudo virtualenv nameOfVEnv. Then after activating the new virtualenv the pip command worked as expected.

I don't think I used sudo on the first virtualenv creation and that may have been the reason for not having access to pip from within the virtualenv, I was able to get access to pip2 before this fix though which was odd.

How to run Spyder in virtual environment?

I follow one of the advice above and indeed it works. In summary while you download Anaconda on Ubuntu using the advice given above can help you to 'create' environments. The default when you download Spyder in my case is: (base) smith@ubuntu ~$. After you create the environment, i.e. fenics and activate it with $ conda activate fenics the prompt change to (fenics) smith@ubuntu ~$. Then you launch Spyder from this prompt, i.e $ spyder and your system open the Spyder IDE, and you can write fenics code on it. Remember every time you open a terminal your system open the default prompt. You have to activate your environment where your package is and the prompt change to it i.e. (fenics).

What is the purpose of "pip install --user ..."?

pip defaults to installing Python packages to a system directory (such as /usr/local/lib/python3.4). This requires root access.

--user makes pip install packages in your home directory instead, which doesn't require any special privileges.

Make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

My understanding is you don't need to install Anaconda again to start using a different version of python. Instead, conda has the ability to separately manage python 2 and 3 environments.

Getting a 'source: not found' error when using source in a bash script

If you're writing a bash script, call it by name:

#!/bin/bash

/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).

The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.

ImportError: No module named 'encodings'

I had a similar issue. I had both anaconda and python installed on my computer and my python dependencies were from the Anaconda directory. When I uninstalled Anaconda, this error started popping. I added PYTHONPATH but it still didn't go. I checked with python -version and go to know that it was still taking the anaconda path. I had to manually delete Anaconda3 directory and after that python started taking dependencies from PYTHONPATH.
Issue Solved!

How to uninstall a package installed with pip install --user

The answer is Not possible yet. You have to remove it manually.

Conda version pip install -r requirements.txt --target ./lib

A quick search on the conda official docs will help you to find what each flag does.

So far:

  • -y: Do not ask for confirmation.
  • -f: I think it should be --file, so it read package versions from the given file.
  • -q: Do not display progress bar.
  • -c: Additional channel to search for packages. These are URLs searched in the order

Python virtualenv questions

in my project wsgi.py file i have this code (it works with virtualenv,django,apache2 in windows and python 3.4)

import os
import sys
DJANGO_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')
sys.path.append(DJANGO_PATH)
sys.path.append('c:/myproject/env/Scripts')
sys.path.append('c:/myproject/env/Lib/site-packages')
activate_this = 'c:/myproject/env/scripts/activate_this.py'
exec(open(activate_this).read())
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
application = get_wsgi_application()

in virtualhost file conf i have

<VirtualHost *:80>
    ServerName mysite
    WSGIScriptAlias / c:/myproject/myproject/myproject/wsgi.py
    DocumentRoot c:/myproject/myproject/
    <Directory  "c:/myproject/myproject/myproject/">
       Options +Indexes +FollowSymLinks +MultiViews
       AllowOverride All
      Require local
   </Directory>
</VirtualHost>

ImportError: No module named Crypto.Cipher

I'm with 3.7. The issue remains after I try to install crypto. And pycrypto just fails in my case. So in the end my build passed via package below: pip install pycryptodome

How can I install packages using pip according to the requirements.txt file from a local directory?

For virtualenv to install all files in the requirements.txt file.

  1. cd to the directory where requirements.txt is located
  2. activate your virtualenv
  3. run: pip install -r requirements.txt in your shell

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

PyPI packages not in the standard library:

  • virtualenv is a very popular tool that creates isolated Python environments for Python libraries. If you're not familiar with this tool, I highly recommend learning it, as it is a very useful tool, and I'll be making comparisons to it for the rest of this answer.

    It works by installing a bunch of files in a directory (eg: env/), and then modifying the PATH environment variable to prefix it with a custom bin directory (eg: env/bin/). An exact copy of the python or python3 binary is placed in this directory, but Python is programmed to look for libraries relative to its path first, in the environment directory. It's not part of Python's standard library, but is officially blessed by the PyPA (Python Packaging Authority). Once activated, you can install packages in the virtual environment using pip.

  • pyenv is used to isolate Python versions. For example, you may want to test your code against Python 2.7, 3.6, 3.7 and 3.8, so you'll need a way to switch between them. Once activated, it prefixes the PATH environment variable with ~/.pyenv/shims, where there are special files matching the Python commands (python, pip). These are not copies of the Python-shipped commands; they are special scripts that decide on the fly which version of Python to run based on the PYENV_VERSION environment variable, or the .python-version file, or the ~/.pyenv/version file. pyenv also makes the process of downloading and installing multiple Python versions easier, using the command pyenv install.

  • pyenv-virtualenv is a plugin for pyenv by the same author as pyenv, to allow you to use pyenv and virtualenv at the same time conveniently. However, if you're using Python 3.3 or later, pyenv-virtualenv will try to run python -m venv if it is available, instead of virtualenv. You can use virtualenv and pyenv together without pyenv-virtualenv, if you don't want the convenience features.

  • virtualenvwrapper is a set of extensions to virtualenv (see docs). It gives you commands like mkvirtualenv, lssitepackages, and especially workon for switching between different virtualenv directories. This tool is especially useful if you want multiple virtualenv directories.

  • pyenv-virtualenvwrapper is a plugin for pyenv by the same author as pyenv, to conveniently integrate virtualenvwrapper into pyenv.

  • pipenv aims to combine Pipfile, pip and virtualenv into one command on the command-line. The virtualenv directory typically gets placed in ~/.local/share/virtualenvs/XXX, with XXX being a hash of the path of the project directory. This is different from virtualenv, where the directory is typically in the current working directory. pipenv is meant to be used when developing Python applications (as opposed to libraries). There are alternatives to pipenv, such as poetry, which I won't list here since this question is only about the packages that are similarly named.

Standard library:

  • pyvenv is a script shipped with Python 3 but deprecated in Python 3.6 as it had problems (not to mention the confusing name). In Python 3.6+, the exact equivalent is python3 -m venv.

  • venv is a package shipped with Python 3, which you can run using python3 -m venv (although for some reason some distros separate it out into a separate distro package, such as python3-venv on Ubuntu/Debian). It serves the same purpose as virtualenv, but only has a subset of its features (see a comparison here). virtualenv continues to be more popular than venv, especially since the former supports both Python 2 and 3.

Recommendation for beginners:

This is my personal recommendation for beginners: start by learning virtualenv and pip, tools which work with both Python 2 and 3 and in a variety of situations, and pick up other tools once you start needing them.

How to repeat last command in python interpreter shell?

Ipython isn't allways the way... I like it pretty much, but if you try run Django shell with ipython. Something like>>>

ipython manage.py shell

it does'n work correctly if you use virtualenv. Django needs some special includes which aren't there if you start ipython, because it starts default system python, but not that virtual.

Upgrade python in a virtualenv

For everyone with the problem

Error: Command '['/Users/me/Sites/site/venv3/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1.

You have to install python3.6-venv

 sudo apt-get install python3.6-venv

How do I tell a Python script to use a particular version

You can add a shebang line the to the top of the script:

#!/usr/bin/env python2.7

But that will only work when executing as ./my_program.py.

If you execute as python my_program.py, then the whatever Python version that which python returns will be used.

In re: to virtualenv use: virtualenv -p /usr/bin/python3.2 or whatever to set it up to use that Python executable.

bash: mkvirtualenv: command not found

On Windows 10, to create the virtual environment, I replace "pip mkvirtualenv myproject" by "mkvirtualenv myproject" and that works well.

No module named pkg_resources

Apparently you're missing setuptools. Some virtualenv versions use distribute instead of setuptools by default. Use the --setuptools option when creating the virtualenv or set the VIRTUALENV_SETUPTOOLS=1 in your environment.

PyLint "Unable to import" error - how to set PYTHONPATH?

If you want to walk up from the current module/file that was handed to pylint looking for the root of the module, this will do it.

[MASTER]
init-hook=sys.path += [os.path.abspath(os.path.join(os.path.sep, *sys.argv[-1].split(os.sep)[:i])) for i, _ in enumerate(sys.argv[-1].split(os.sep)) if os.path.isdir(os.path.abspath(os.path.join(os.path.sep, *sys.argv[-1].split(os.sep)[:i], '.git')))][::-1]

If you have a python module ~/code/mymodule/, with a top-level directory layout like this

~/code/mymodule/
+-- .pylintrc
+-- mymodule/
¦   +-- src.py
+-- tests/
    +-- test_src.py

Then this will add ~/code/mymodule/ to your python path and allow for pylint to run in your IDE, even if you're importing mymodule.src in tests/test_src.py.

You could swap out a check for a .pylintrc instead but a git directory is usually what you want when it comes to the root of a python module.

Before you ask

The answers using import sys, os; sys.path.append(...) are missing something that justifies the format of my answer. I don't normally write code that way, but in this case you're stuck dealing with the limitations of the pylintrc config parser and evaluator. It literally runs exec in the context of the init_hook callback so any attempt to import pathlib, use multi-line statements, store something into variables, etc., won't work.

A less disgusting form of my code might look like this:

import os
import sys

def look_for_git_dirs(filename):
    has_git_dir = []
    filename_parts = filename.split(os.sep)
    for i, _ in enumerate(filename_parts):
        filename_part = os.path.abspath(os.path.join(os.path.sep, *filename_parts[:i]))
        if os.path.isdir(os.path.join(filename_part, '.git')):
            has_git_dir.append(filename_part)
    return has_git_dir[::-1]

# don't use .append() in case there's < 1 or > 1 matches found
sys.path += look_for_git_dirs(sys.argv[-1])

I wish I could have used pathlib.Path(filename).parents it would have made things much easier.

Determine if Python is running inside virtualenv

The most reliable way to check for this is to check whether sys.prefix == sys.base_prefix. If they are equal, you are not in a virtual environment; if they are unequal, you are. Inside a virtual environment, sys.prefix points to the virtual environment, and sys.base_prefix is the prefix of the system Python the virtualenv was created from.

The above always works for Python 3 stdlib venv and for recent virtualenv (since version 20). Older versions of virtualenv used sys.real_prefix instead of sys.base_prefix (and sys.real_prefix did not exist outside a virtual environment), and in Python 3.3 and earlier sys.base_prefix did not ever exist. So a fully robust check that handles all of these cases could look like this:

import sys

def get_base_prefix_compat():
    """Get base/real prefix, or sys.prefix if there is none."""
    return getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix

def in_virtualenv():
    return get_base_prefix_compat() != sys.prefix

If you only care about supported Python versions and latest virtualenv, you can replace get_base_prefix_compat() with simply sys.base_prefix.

Using the VIRTUAL_ENV environment variable is not reliable. It is set by the virtualenv activate shell script, but a virtualenv can be used without activation by directly running an executable from the virtualenv's bin/ (or Scripts) directory, in which case $VIRTUAL_ENV will not be set. Or a non-virtualenv Python binary can be executed directly while a virtualenv is activated in the shell, in which case $VIRTUAL_ENV may be set in a Python process that is not actually running in that virtualenv.

How to setup virtual environment for Python in VS Code?

The question is how to create a new virtual environment in VSCode, that is why telling the following Anaconda solution might not the needed answer to the question. It is just relevant for Anaconda users.

Just create a venv using conda, see here. Afterwards open VSCode and left-click on the VSCode interpreter shown in VSCode at the bottom left:

vscode interpreter info

Choose a virtual environment that pops up in a dropdown of the settings window, and you are done. Mind the answer of @RamiMa.

how to specify new environment location for conda create

like Paul said, use

conda create --prefix=/users/.../yourEnvName python=x.x

if you are located in the folder in which you want to create your virtual environment, just omit the path and use

conda create --prefix=yourEnvName python=x.x

conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with

source activate yourEnvName

How to use MySQLdb with Python and Django in OSX 10.6?

mysql_config must be on the path. On Mac, do

export PATH=$PATH:/usr/local/mysql/bin/
pip install MySQL-python

How to leave/exit/deactivate a Python virtualenv

I had the same problem while working on an installer script. I took a look at what the bin/activate_this.py did and reversed it.

Example:

#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys

# Path to virtualenv
venv_path = os.path.join('/home', 'sixdays', '.virtualenvs', 'test32')

# Save old values
old_os_path = os.environ['PATH']
old_sys_path = list(sys.path)
old_sys_prefix = sys.prefix


def deactivate():
    # Change back by setting values to starting values
    os.environ['PATH'] = old_os_path
    sys.prefix = old_sys_prefix
    sys.path[:0] = old_sys_path


# Activate the virtualenvironment
activate_this = os.path.join(venv_path, 'bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))


# Print list of pip packages for virtualenv for example purpose
import pip
print str(pip.get_installed_distributions())

# Unload pip module
del pip

# Deactivate/switch back to initial interpreter
deactivate()

# Print list of initial environment pip packages for example purpose
import pip
print str(pip.get_installed_distributions())

I am not 100% sure if it works as intended. I may have missed something completely.

Virtualenv Command Not Found

sudo apt-get install python-virtualenv

Broken references in Virtualenvs

After trying a few things, this worked for me:

go to your virtualenv directory (but don't run workon):

cd ~/.virtualenv/name_of_broken_venv

Now delete these files:

rm -rf .Python bin/python* lib/python2.7/* include/python2.7

Then to rebuild your venv, run:

virtualenv .
workon name_of_broken_venv
pip freeze

You should now see a list of your installed packages again.

Is it possible to install another version of Python to Virtualenv?

This procedure installs Python2.7 anywhere and eliminates any absolute path references within your env folder (managed by virtualenv). Even virtualenv isn't installed absolutely.

Thus, theoretically, you can drop the top level directory into a tarball, distribute, and run anything configured within the tarball on a machine that doesn't have Python (or any dependencies) installed.

Contact me with any questions. This is just part of an ongoing, larger project I am engineering. Now, for the drop...

  1. Set up environment folders.

    $ mkdir env
    $ mkdir pyenv
    $ mkdir dep
    
  2. Get Python-2.7.3, and virtualenv without any form of root OS installation.

    $ cd dep
    $ wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz
    $ wget https://raw.github.com/pypa/virtualenv/master/virtualenv.py
    
  3. Extract and install Python-2.7.3 into the pyenv dir. make clean is optional if you are doing this a 2nd, 3rd, Nth time...

    $ tar -xzvf Python-2.7.3.tgz
    $ cd Python-2.7.3
    $ make clean
    $ ./configure --prefix=/path/to/pyenv
    $ make && make install
    $ cd ../../
    $ ls
    dep    env    pyenv
    
  4. Create your virtualenv

    $ dep/virtualenv.py --python=/path/to/pyenv/bin/python --verbose env
    
  5. Fix the symlink to python2.7 within env/include/

    $ ls -l env/include/
    $ cd !$
    $ rm python2.7
    $ ln -s ../../pyenv/include/python2.7 python2.7
    $ cd ../../
    
  6. Fix the remaining python symlinks in env. You'll have to delete the symbolically linked directories and recreate them, as above. Also, here's the syntax to force in-place symbolic link creation.

    $ ls -l env/lib/python2.7/
    $ cd !$
    $ ln -sf ../../../pyenv/lib/python2.7/UserDict.py UserDict.py
    [...repeat until all symbolic links are relative...]
    $ cd ../../../
    
  7. Test

    $ python --version
    Python 2.7.1
    $ source env/bin/activate
    (env)
    $ python --version
    Python 2.7.3
    

Aloha.

How can I upgrade specific packages using pip and a requirements file?

This solved the issue for me:

pip install -I --upgrade psutil --force

Afterwards just uninstall psutil with the new version and hop you can suddenly install the older version (:

List all virtualenv

How do I find the Django virtual environment name if I forgot?. It is very Simple, you can find from the following location, if you forgot Django Virtual Environment name on Windows 10 Operating System.

c:\Users<name>\Envs<Virtual Environments>

enter image description here

Where does pip install its packages?

One can import the package then consult its help

import statsmodels
help(sm)

At the very bottom of the help there is a section FILE that indicates where this package was installed.

This solution was tested with at least matplotlib (3.1.2) and statsmodels (0.11.1) (python 3.8.2).

Issue with virtualenv - cannot activate

If you see the 5 folders (Include,Lib,Scripts,tcl,pip-selfcheck) after using the virtualenv yourenvname command, change directory to Scripts folder in the cmd itself and simply use "activate" command.

Where is virtualenvwrapper.sh after pip install?

/usr/share/virtualenvwrapper/virtualenvwrapper.sh

I've installed it on Ubuntu 16.04 and it resulted in this location.

setting an environment variable in virtualenv

You could try:

export ENVVAR=value

in virtualenv_root/bin/activate. Basically the activate script is what is executed when you start using the virtualenv so you can put all your customization in there.

Using Python 3 in virtualenv

In python3.6 I tried python3 -m venv myenv, as per the documentation, but it was taking so long. So the very simple and quick command is python -m venv yourenv It worked for me on python3.6.

Using (Ana)conda within PyCharm

I know it's late, but I thought it would be nice to clarify things: PyCharm and Conda and pip work well together.

The short answer

Just manage Conda from the command line. PyCharm will automatically notice changes once they happen, just like it does with pip.

The long answer

Create a new Conda environment:

conda create --name foo pandas bokeh

This environment lives under conda_root/envs/foo. Your python interpreter is conda_root/envs/foo/bin/pythonX.X and your all your site-packages are in conda_root/envs/foo/lib/pythonX.X/site-packages. This is same directory structure as in a pip virtual environement. PyCharm sees no difference.

Now to activate your new environment from PyCharm go to file > settings > project > interpreter, select Add local in the project interpreter field (the little gear wheel) and hunt down your python interpreter. Congratulations! You now have a Conda environment with pandas and bokeh!

Now install more packages:

conda install scikit-learn

OK... go back to your interpreter in settings. Magically, PyCharm now sees scikit-learn!

And the reverse is also true, i.e. when you pip install another package in PyCharm, Conda will automatically notice. Say you've installed requests. Now list the Conda packages in your current environment:

conda list

The list now includes requests and Conda has correctly detected (3rd column) that it was installed with pip.

Conclusion

This is definitely good news for people like myself who are trying to get away from the pip/virtualenv installation problems when packages are not pure python.

NB: I run PyCharm pro edition 4.5.3 on Linux. For Windows users, replace in command line with in the GUI (and forward slashes with backslashes). There's no reason it shouldn't work for you too.

EDIT: PyCharm5 is out with Conda support! In the community edition too.

How to activate an Anaconda environment

Note that the command for activating an environment has changed in Conda version 4.4. The recommended way of activating an environment is now conda activate myenv instead of source activate myenv. To enable the new syntax, you should modify your .bashrc file. The line that currently reads something like

export PATH="<path_to_your_conda_install>/bin:$PATH"

Should be changed to

. <path_to_your_conda_install>/etc/profile.d/conda.sh

This only adds the conda command to the path, but does not yet activate the base environment (which was previously called root). To do also that, add another line

conda activate base

after the first command. See all the details in Anaconda's blog post from December 2017. (I think that this page is currently missing a newline between the two lines, it says .../conda.shconda activate base).

(This answer is valid for Linux, but it might be relevant for Windows and Mac as well)

How do I activate a virtualenv inside PyCharm's terminal?

Thanks Chris, your script worked for some projects but not all on my machine. Here is a script that I wrote and I hope anyone finds it useful.

#Stored in ~/.pycharmrc 

ACTIVATERC=$(python -c 'import re
import os
from glob import glob

try:
  #sets Current Working Directory to _the_projects .idea folder
  os.chdir(os.getcwd()+"/.idea") 

  #gets every file in the cwd and sets _the_projects iml file
  for file in glob("*"): 
    if re.match("(.*).iml", file):
      project_iml_file = file

  #gets _the_virtual_env for _the_project
  for line in open(project_iml_file):
    env_name = re.findall("~/(.*)\" jdkType", line.strip())
    # created or changed a virtual_env after project creation? this will be true
    if env_name:
      print env_name[0] + "/bin/activate"
      break

    inherited = re.findall("type=\"inheritedJdk\"", line.strip())
    # set a virtual_env during project creation? this will be true
    if inherited:
      break

  # find _the_virtual_env in misc.xml
  if inherited:
    for line in open("misc.xml").readlines():
      env_at_project_creation = re.findall("\~/(.*)\" project-jdk", line.strip())
      if env_at_project_creation:
        print env_at_project_creation[0] + "/bin/activate"
        break
finally:
  pass
')

if [ "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; fi

Use virtualenv with Python with Visual Studio Code in Ubuntu

As of September 2016 (according to the GitHub repository documentation of the extension) you can just execute a command from within Visual Studio Code that will let you select the interpreter from an automatically generated list of known interpreters (including the one in your project's virtual environment).

How can I use this feature?

  • Select the command Python: Select Workspace Interpreter(*) from the command palette (F1).
  • Upon selecting the above command a list of discovered interpreters will be displayed in a quick pick list.
  • Selecting an interpreter from this list will update the settings.json file automatically.

(*) This command has been updated to Python: Select Interpreter in the latest release of Visual Studio Code (thanks @nngeek).

Also, notice that your selected interpreter will be shown at the left side of the statusbar, e.g., Python 3.6 64-bit. This is a button you can click to trigger the Select Interpreter feature.

How to source virtualenv activate in a Bash script

When you source, you're loading the activate script into your active shell.

When you do it in a script, you load it into that shell which exits when your script finishes and you're back to your original, unactivated shell.

Your best option would be to do it in a function

activate () {
  . ../.env/bin/activate
}

or an alias

alias activate=". ../.env/bin/activate"

Hope this helps.

How to avoid "Permission denied" when using pip with virtualenv

virtualenv permission problems might occur when you create the virtualenv as sudo and then operate without sudo in the virtualenv.

As found out in your question's comment, the solution here is to create the virtualenv without sudo to be able to work (esp. write) in it without sudo.

How to activate virtualenv?

Create your own Python virtual environment called <Your Env _name >:. I have given it VE.

git clone https://github.com/pypa/virtualenv.git
python virtualenv.py VE

To activate your new virtual environment, run (notice it's not ./ here):

. VE/bin/activate

Sample output (note prompt changed):

(VE)c34299@a200dblr$

Once your virtual environment is set, you can remove the Virtualenv repo.

How can I make a list of installed packages in a certain virtualenv?

In Python3

pip list

Empty venv is

Package    Version
---------- ------- 
pip        19.2.3 
setuptools 41.2.0

To start a new environment

python3 -m venv your_foldername_here

Activate

cd your_foldername_here
source bin/activate

Deactivate

deactivate

You can also stand in the folder and give the virtual environment a name/folder (python3 -m venv name_of_venv).

Venv is a subset of virtualenv that is shipped with Python after 3.3.

Unable to install boto3

I have faced the same issue and also not using virtual environment. easy_install is working for me.

easy_install boto3

if...else within JSP or JSTL

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<c:set var="isiPad" value="value"/>
<c:choose>
   <!-- if condition -->
   <c:when test="${...}">Html Code</c:when> 
   <!-- else condition -->
   <c:otherwise>Html code</c:otherwise>   
</c:choose>

Convert columns to string in Pandas

Here's the other one, particularly useful to convert the multiple columns to string instead of just single column:

In [76]: import numpy as np
In [77]: import pandas as pd
In [78]: df = pd.DataFrame({
    ...:     'A': [20, 30.0, np.nan],
    ...:     'B': ["a45a", "a3", "b1"],
    ...:     'C': [10, 5, np.nan]})
    ...: 

In [79]: df.dtypes ## Current datatype
Out[79]: 
A    float64
B     object
C    float64
dtype: object

## Multiple columns string conversion
In [80]: df[["A", "C"]] = df[["A", "C"]].astype(str) 

In [81]: df.dtypes ## Updated datatype after string conversion
Out[81]: 
A    object
B    object
C    object
dtype: object

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Simply difference between Forward(ServletRequest request, ServletResponse response) and sendRedirect(String url) is

forward():

  1. The forward() method is executed in the server side.
  2. The request is transfer to other resource within same server.
  3. It does not depend on the client’s request protocol since the forward () method is provided by the servlet container.
  4. The request is shared by the target resource.
  5. Only one call is consumed in this method.
  6. It can be used within server.
  7. We cannot see forwarded message, it is transparent.
  8. The forward() method is faster than sendRedirect() method.
  9. It is declared in RequestDispatcher interface.

sendRedirect():

  1. The sendRedirect() method is executed in the client side.
  2. The request is transfer to other resource to different server.
  3. The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.
  4. New request is created for the destination resource.
  5. Two request and response calls are consumed.
  6. It can be used within and outside the server.
  7. We can see redirected address, it is not transparent.
  8. The sendRedirect() method is slower because when new request is created old request object is lost.
  9. It is declared in HttpServletResponse.

Is there a difference between "throw" and "throw ex"?

It's better to use throw instead of throw ex.

throw ex reset the original stack trace and can't be found the previous stack trace.

If we use throw, we will get a full stack trace.

Disabling submit button until all fields have values

This works well since all the inputs have to meet the condition of not null.

$(function () {
    $('#submits').attr('disabled', true);
    $('#input_5').change(function () {
        if ($('#input_1').val() != '' && $('#input_2').val() != '' && $('#input_3').val() != '' && $('#input_4').val() != '' && $('#input_5').val() != '') {
            $('#submit').attr('disabled', false);
        } else {
            $('#submit').attr('disabled', true);
        }
     });
 });

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

C# importing class into another class doesn't work

MyClass is a class not a namespace. So this code is wrong:

using MyClass //THIS CODE IS NOT CORRECT

You should check the namespace of the MyClass (e.g: MyNamespace). Then call it in a proper way:

MyNamespace.MyClass myClass =new MyNamespace.MyClass();

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

In Linux Mint 18 Cinnamon be sure to check /etc/profile.d/jdk_home.sh I renamed this file to jdk_home.sh.old and now my path does not keep getting overridden and I can call java -version and see Java 9 as expected. Even though I correctly selected Java 9 in update-aternatives --config java this jdk_home.sh file kept overriding the $PATH on boot-up.

How to know which is running in Jupyter notebook?

import sys
print(sys.executable)
print(sys.version)
print(sys.version_info)

Seen below :- output when i run JupyterNotebook outside a CONDA venv

/home/dhankar/anaconda2/bin/python
2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jul  2 2016, 17:42:40) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)
 

Seen below when i run same JupyterNoteBook within a CONDA Venv created with command --

conda create -n py35 python=3.5 ## Here - py35 , is name of my VENV

in my Jupyter Notebook it prints :-

/home/dhankar/anaconda2/envs/py35/bin/python
3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:53:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)

also if you already have various VENV's created with different versions of Python you switch to the desired Kernel by choosing KERNEL >> CHANGE KERNEL from within the JupyterNotebook menu... JupyterNotebookScreencapture

Also to install ipykernel within an existing CONDA Virtual Environment -

http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernels-for-different-environments

Source --- https://github.com/jupyter/notebook/issues/1524

 $ /path/to/python -m  ipykernel install --help
 usage: ipython-kernel-install [-h] [--user] [--name NAME]
                          [--display-name DISPLAY_NAME]
                          [--profile PROFILE] [--prefix PREFIX]
                          [--sys-prefix]

Install the IPython kernel spec.

optional arguments: -h, --help show this help message and exit --user Install for the current user instead of system-wide --name NAME Specify a name for the kernelspec. This is needed to have multiple IPython kernels at the same time. --display-name DISPLAY_NAME Specify the display name for the kernelspec. This is helpful when you have multiple IPython kernels. --profile PROFILE Specify an IPython profile to load. This can be used to create custom versions of the kernel. --prefix PREFIX Specify an install prefix for the kernelspec. This is needed to install into a non-default location, such as a conda/virtual-env. --sys-prefix Install to Python's sys.prefix. Shorthand for --prefix='/Users/bussonniermatthias/anaconda'. For use in conda/virtual-envs.

How do I enable index downloads in Eclipse for Maven dependency search?

Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories, and it should work.

The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

Insert a string at a specific index

Using slice

You can use slice(0,index) + str + slice(index). Or you can create a method for it.

_x000D_
_x000D_
String.prototype.insertAt = function(index,str){_x000D_
  return this.slice(0,index) + str + this.slice(index)_x000D_
}_x000D_
console.log("foo bar".insertAt(4,'baz ')) //foo baz bar
_x000D_
_x000D_
_x000D_

Splice method for Strings

You can split() the main string and add then use normal splice()

_x000D_
_x000D_
String.prototype.splice = function(index,del,...newStrs){_x000D_
  let str = this.split('');_x000D_
  str.splice(index,del,newStrs.join('') || '');_x000D_
  return str.join('');_x000D_
}_x000D_
_x000D_
_x000D_
 var txt1 = "foo baz"_x000D_
_x000D_
//inserting single string._x000D_
console.log(txt1.splice(4,0,"bar ")); //foo bar baz_x000D_
_x000D_
_x000D_
//inserting multiple strings_x000D_
console.log(txt1.splice(4,0,"bar ","bar2 ")); //foo bar bar2 baz_x000D_
_x000D_
_x000D_
//removing letters_x000D_
console.log(txt1.splice(1,2)) //f baz_x000D_
_x000D_
_x000D_
//remving and inseting atm_x000D_
console.log(txt1.splice(1,2," bar")) //f bar baz
_x000D_
_x000D_
_x000D_

Applying splice() at multiple indexes

The method takes an array of arrays each element of array representing a single splice().

_x000D_
_x000D_
String.prototype.splice = function(index,del,...newStrs){_x000D_
  let str = this.split('');_x000D_
  str.splice(index,del,newStrs.join('') || '');_x000D_
  return str.join('');_x000D_
}_x000D_
_x000D_
_x000D_
String.prototype.mulSplice = function(arr){_x000D_
  str = this_x000D_
  let dif = 0;_x000D_
  _x000D_
  arr.forEach(x => {_x000D_
    x[2] === x[2] || [];_x000D_
    x[1] === x[1] || 0;_x000D_
    str = str.splice(x[0] + dif,x[1],...x[2]);_x000D_
    dif += x[2].join('').length - x[1];_x000D_
  })_x000D_
  return str;_x000D_
}_x000D_
_x000D_
let txt = "foo bar baz"_x000D_
_x000D_
//Replacing the 'foo' and 'bar' with 'something1' ,'another'_x000D_
console.log(txt.splice(0,3,'something'))_x000D_
console.log(txt.mulSplice(_x000D_
[_x000D_
[0,3,["something1"]],_x000D_
[4,3,["another"]]_x000D_
]_x000D_
_x000D_
))
_x000D_
_x000D_
_x000D_

Use of document.getElementById in JavaScript

Consider

 var x = document.getElementById("age");

Here x is the element with id="age".

Now look at the following line

var age = document.getElementById("age").value;

this means you are getting the value of the element which has id="age"

Not class selector in jQuery

You need the :not() selector:

$('div[class^="first-"]:not(.first-bar)')

or, alternatively, the .not() method:

$('div[class^="first-"]').not('.first-bar');

How to redirect from one URL to another URL?

If you want to redirect, just use window.location. Like so:

window.location = "http://www.redirectedsite.com"

How to merge lists into a list of tuples?

In Python 2:

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a, list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]

In Python 3:

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> list(zip(list_a, list_b))
[(1, 5), (2, 6), (3, 7), (4, 8)]

SQL alias for SELECT statement

You could store this into a temporary table.

So instead of doing the CTE/sub query you would use a temp table.

Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/

Implementing IDisposable correctly

You have no need to do your User class being IDisposable since the class doesn't acquire any non-managed resources (file, database connection, etc.). Usually, we mark classes as IDisposable if they have at least one IDisposable field or/and property. When implementing IDisposable, better put it according Microsoft typical scheme:

public class User: IDisposable {
  ...
  protected virtual void Dispose(Boolean disposing) {
    if (disposing) {
      // There's no need to set zero empty values to fields 
      // id = 0;
      // name = String.Empty;
      // pass = String.Empty;

      //TODO: free your true resources here (usually IDisposable fields)
    }
  }

  public void Dispose() {
    Dispose(true);

    GC.SuppressFinalize(this);
  } 
}

Image.open() cannot identify image file - Python?

If you are using Anaconda on windows then you can open Anaconda Navigator app and go to Environment section and search for pillow in installed libraries and mark it for upgrade to latest version by right clicking on the checkbox.

Screenshot for reference:enter image description here

This has fixed the following error:

PermissionError: [WinError 5] Access is denied: 'e:\\work\\anaconda\\lib\\site-packages\\pil\\_imaging.cp36-win_amd64.pyd'

How to make a website secured with https

Try making a boot directory in PHP, as in

<?PHP
$ip = $_SERVER['REMOTE_ADDR'];
$privacy = ['BOOTSTRAP_CONFIG'];
$shell   = ['BOOTSTRAP_OUTPUT'];
enter code here
if $ip == $privacy {
function $privacy int $ip = "https://";
} endif {
echo $shell
}
?>

Thats mainly it!

When do I need to use a semicolon vs a slash in Oracle SQL?

I know this is an old thread, but I just stumbled upon it and I feel this has not been explained completely.

There is a huge difference in SQL*Plus between the meaning of a / and a ; because they work differently.

The ; ends a SQL statement, whereas the / executes whatever is in the current "buffer". So when you use a ; and a / the statement is actually executed twice.

You can easily see that using a / after running a statement:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:37:20 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> drop table foo;

Table dropped.

SQL> /
drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

In this case one actually notices the error.


But assuming there is a SQL script like this:

drop table foo;
/

And this is run from within SQL*Plus then this will be very confusing:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:38:05 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> @drop

Table dropped.

drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

The / is mainly required in order to run statements that have embedded ; like a CREATE PROCEDURE statement.

Why maven settings.xml file is not there?

Installation of Maven doesn't create the settings.xml file. You have to create it on your own. Just put it in your .m2 directory where you expected it, see http://maven.apache.org/settings.html for reference. The m2eclipse plugin will use the same settings file as the command line.

Logging levels - Logback - rule-of-thumb to assign log levels

Not different for other answers, my framework have almost the same levels:

  1. Error: critical logical errors on application, like a database connection timeout. Things that call for a bug-fix in near future
  2. Warn: not-breaking issues, but stuff to pay attention for. Like a requested page not found
  3. Info: used in functions/methods first line, to show a procedure that has been called or a step gone ok, like a insert query done
  4. log: logic information, like a result of an if statement
  5. debug: variable contents relevant to be watched permanently

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Instead of Windows PowerShell, find the item in the Start Menu called SharePoint 2013 Management Shell:

enter image description here

Installing PG gem on OS X - failure to build native extension

I spent a day on this and here's how I got it fixed:

I found that global value of build.pg was set to: /opt/local/lib/postgresql91/bin/pg_config and that was not where postgres was installed.

I fixed it with replacing the value of build.pg to: bundle config build.pg --with-pg-config=/usr/local/Cellar/postgresql/9.4.4/bin/pg_config which is where my postgresql installation is.

Laravel - Pass more than one variable to view

Use compact

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();
    return View::make('users', compact('ms','persons'));
}

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

Great answers, but you could just open the command prompt and type in

 SET PATH=C:\Program Files\Nodejs;%PATH%

How to have the cp command create any necessary folders for copying a file to a destination

rsync is work!

#file:
rsync -aqz _vimrc ~/.vimrc

#directory:
rsync -aqz _vim/ ~/.vim

Converting an array to a function arguments list

@bryc - yes, you could do it like this:

Element.prototype.setAttribute.apply(document.body,["foo","bar"])

But that seems like a lot of work and obfuscation compared to:

document.body.setAttribute("foo","bar")

"use database_name" command in PostgreSQL

You must specify the database to use on connect; if you want to use psql for your script, you can use "\c name_database"

user_name=# CREATE DATABASE testdatabase; 
user_name=# \c testdatabase 

At this point you might see the following output

You are now connected to database "testdatabase" as user "user_name".
testdatabase=#

Notice how the prompt changes. Cheers, have just been hustling looking for this too, too little information on postgreSQL compared to MySQL and the rest in my view.

"Could not find acceptable representation" using spring-boot-starter-web

My return object didn't have @XmlRootElement annotation on the class. Adding the annotation solved my issue.

@XmlRootElement(name = "ReturnObjectClass")
public class ReturnObjectClass {

    @XmlElement(name = "Status", required = true)
    protected StatusType status;
    //...
}

How to add an event after close the modal window?

If you're using version 3.x of Bootstrap, the correct way to do this now is:

$('#myModal').on('hidden.bs.modal', function (e) {
  // do something...
})

Scroll down to the events section to learn more.

http://getbootstrap.com/javascript/#modals-usage

This appears to remain unchanged for whenever version 4 releases (http://v4-alpha.getbootstrap.com/components/modal/#events), but if it does I'll be sure to update this post with the relevant information.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

If at all anyone is looking to convert data in 1 variable that lies in 2 or 3 different lines like below

'Data1

Data2'

And you want to display data as 'Data1 Data2' then use below

select TRANSLATE ('Data1

Data2', ''||CHR(10), ' ') from dual;

it took me hrs to get the right output. Thanks to me I just saved you 1 or 2 hrs :)

Prepare for Segue in Swift

Swift 4, Swift 3

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "MySegueId" {
        if let nextViewController = segue.destination as? NextViewController {
                nextViewController.valueOfxyz = "XYZ" //Or pass any values
                nextViewController.valueOf123 = 123
        }
    }
}

How do you easily create empty matrices javascript?

This is an exact fix to your problem, but I would advise against initializing the matrix with a default value that represents '0' or 'undefined', as Arrays in javascript are just regular objects, so you wind up wasting effort. If you want to default the cells to some meaningful value, then this snippet will work well, but if you want an uninitialized matrix, don't use this version:

/**
* Generates a matrix (ie: 2-D Array) with: 
* 'm' columns, 
* 'n' rows, 
* every cell defaulting to 'd';
*/
function Matrix(m, n, d){
    var mat = Array.apply(null, new Array(m)).map(
        Array.prototype.valueOf,
        Array.apply(null, new Array(n)).map(
            function() {
               return d;
            }
        )
    );
    return mat;
}

Usage:

< Matrix(3,2,'dobon');
> Array [ Array['dobon', 'dobon'], Array['dobon', 'dobon'], Array['dobon', 'dobon'] ]

If you would rather just create an uninitialized 2-D Array, then this will be more efficient than unnecessarily initializing every entry:

/**
* Generates a matrix (ie: 2-D Array) with: 
* 'm' columns, 
* 'n' rows, 
* every cell remains 'undefined';
*/
function Matrix(m, n){
    var mat = Array.apply(null, new Array(m)).map(
        Array.prototype.valueOf,
        new Array(n)
    );
    return mat;
}

Usage:

< Matrix(3,2);
> Array [ Array[2], Array[2], Array[2] ]

In Maven how to exclude resources from the generated jar?

This calls exactly for the using the Maven JAR Plugin

For example, if you want to exclude everything under src/test/resources/ from the final jar, put this:

<build>

        <plugins>
            <!-- configure JAR build -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.1</version>
                <configuration>
                    <excludes>
                        <exclude>src/test/resources/**</exclude>
                    </excludes>
                </configuration>
            </plugin>

...

Files under src/test/resources/ will still be available on class-path, they just won't be in resulting JAR.

'do...while' vs. 'while'

One of the applications I have seen it is in Oracle when we look at result sets.

Once you a have a result set, you first fetch from it (do) and from that point on.. check if the fetch returns an element or not (while element found..) .. The same might be applicable for any other "fetch-like" implementations.

Loop through all nested dictionary values?

Iterative solution as an alternative:

def traverse_nested_dict(d):
    iters = [d.iteritems()]

    while iters:
        it = iters.pop()
        try:
            k, v = it.next()
        except StopIteration:
            continue

        iters.append(it)

        if isinstance(v, dict):
            iters.append(v.iteritems())
        else:
            yield k, v


d = {"a": 1, "b": 2, "c": {"d": 3, "e": {"f": 4}}}
for k, v in traverse_nested_dict(d):
    print k, v

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Python update a key in dict if it doesn't exist

With the following you can insert multiple values and also have default values but you're creating a new dictionary.

d = {**{ key: value }, **default_values}

I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .

Speed test comparing a for loop based method with a dict comprehension with unpack operator Speed test comparing a for loop based method with a dict comprehension with unpack operator method.

if no copy (d = default_vals.copy()) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5 and greater. Memory footprint of both methods are the same.

jQuery: Return data after ajax call success

The only way to return the data from the function would be to make a synchronous call instead of an asynchronous call, but that would freeze up the browser while it's waiting for the response.

You can pass in a callback function that handles the result:

function testAjax(handleData) {
  $.ajax({
    url:"getvalue.php",  
    success:function(data) {
      handleData(data); 
    }
  });
}

Call it like this:

testAjax(function(output){
  // here you use the output
});
// Note: the call won't wait for the result,
// so it will continue with the code here while waiting.

C - Convert an uppercase letter to lowercase

#include <stdio.h>
#include <string.h>

int main()
{
    char string[] = "Strlwr in C";

    printf("%s\n",strlwr(string));

    return  0;
}

use strlwr for lowering the case

Directory.GetFiles of certain extension

I would have done using just single line like

List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
      .Where(file => new string[] { ".jpg", ".gif", ".png" }
      .Contains(Path.GetExtension(file)))
      .ToList();

Go to next item in ForEach-Object

You may want to use the Continue statement to continue with the innermost loop.

Excerpt from PowerShell help file:

In a script, the continue statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements:

  • for
  • foreach
  • while

Android change SDK version in Eclipse? Unable to resolve target android-x

In Build: v22.6.2-1085508 ADT you need to add(select Android 4.4.2)

Goto project --> properties --> Android(This is second in listed item order leftPanel) and in the RightPanel Project Build Target, select Android 4.4.2 as Target name and apply changes It will rebuild the workspace.

In my case unable to resolve target 'android-17' eclipse was being shown as compile error and in code: import java.util.HashMap was not being referenced.

Bootstrap 3 - Responsive mp4-video

Tip for MULTIPLE VIDEOS on a page: I recently solved an issue with no mp4 playback in Chrome or Firefox (played fine in IE) in a page with 16 videos in modals (bootstrap 3) after discovering the frame rates of all the videos must be identical. I had 6 videos at 25fps and 12 at 29.97fps... after rendering all to 25fps versions, everything runs smooth across all browsers.

CSS3 transition events

If you simply want to detect only a single transition end, without using any JS framework here's a little convenient utility function:

function once = function(object,event,callback){
    var handle={};

    var eventNames=event.split(" ");

    var cbWrapper=function(){
        eventNames.forEach(function(e){
            object.removeEventListener(e,cbWrapper, false );
        });
        callback.apply(this,arguments);
    };

    eventNames.forEach(function(e){
        object.addEventListener(e,cbWrapper,false);
    });

    handle.cancel=function(){
        eventNames.forEach(function(e){
            object.removeEventListener(e,cbWrapper, false );
        });
    };

    return handle;
};

Usage:

var handler = once(document.querySelector('#myElement'), 'transitionend', function(){
   //do something
});

then if you wish to cancel at some point you can still do it with

handler.cancel();

It's good for other event usages as well :)

How to build and run Maven projects after importing into Eclipse IDE

When you add dependency in pom.xml , do a maven clean , and then maven build , it will add the jars into you project.

You can search dependency artifacts at http://mvnrepository.com/

And if it doesn't add jars it should give you errors which will mean that it is not able to fetch the jar, that could be due to broken repository or connection problems.

Well sometimes if it is one or two jars, better download them and add to build path , but with a lot of dependencies use maven.

Connection string with relative path to the database file

In your config file give the relative path

ConnectionString = "Data Source=|DataDirectory|\Database.sdf";

Change the DataDirectory to your executable path

string path = AppDomain.CurrentDomain.BaseDirectory;
AppDomain.CurrentDomain.SetData("DataDirectory", path);

If you are using EntityFramework, then you can set the DataDirectory path in your Context class

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

MySQL SELECT WHERE datetime matches day (and not necessarily time)

NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24' - it is a performance killer:

  • it will calculate DATE() for all rows, including those, that don't match
  • it will make it impossible to use an index for the query

It is much faster to use

SELECT * FROM tablename 
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'

as this will allow index use without calculation.

EDIT

As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read

SELECT * FROM tablename 
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'

The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.

Logical XOR operator in C++?

The != operator serves this purpose for bool values.

ORA-00907: missing right parenthesis

I would recommend separating out all of the foreign-key constraints from your CREATE TABLE statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.

You can add an FK constraint to a table using SQL like the following:

ALTER TABLE orders ADD CONSTRAINT orders_FK
  FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);

In particular, your formats and library tables both have foreign-key constraints on one another. The two CREATE TABLE statements to create these two tables can never run successfully, as each will only work when the other table has already been created.

Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

Along the same lines as SCFrench's answer, but with a more C# style spin..

I would (and often do) make a class containing multiple static methods. For example:

classdef Statistics

    methods(Static)
        function val = MyMean(data)
            val = mean(data);
        end

        function val = MyStd(data)
            val = std(data);
        end
    end

end

As the methods are static you don't need to instansiate the class. You call the functions as follows:

data = 1:10;

mean = Statistics.MyMean(data);
std = Statistics.MyStd(data);     

Each for object?

_x000D_
_x000D_
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
  console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

//output
a: 1
b: 2

How to get year and month from a date - PHP

Probably not the most efficient code, but here it goes:

$dateElements = explode('-', $dateValue);
$year = $dateElements[0];

echo $year;    //2012

switch ($dateElements[1]) {

   case '01'    :  $mo = "January";
                   break;

   case '02'    :  $mo = "February";
                   break;

   case '03'    :  $mo = "March";
                   break;

     .
     .
     .

   case '12'    :  $mo = "December";
                   break;


}

echo $mo;      //January

ITextSharp HTML to PDF?

The above code will certainly help in converting HTML to PDF but will fail if the the HTML code has IMG tags with relative paths. iTextSharp library does not automatically convert relative paths to absolute ones.

I tried the above code and added code to take care of IMG tags too.

You can find the code here for your reference: http://www.am22tech.com/html-to-pdf/

rails bundle clean

If you are using Bundler 1.1 or later you can use bundle clean, just as you imagined you could. This is redundant if you're using bundle install --path (Bundler manages the location you specified with --path, so takes responsibility for removing outdated gems), but if you've used Bundler to install the gems as system gems then bundle clean --force will delete any system gems not required by your Gemfile. Blindingly obvious caveat: don't do this if you have other apps that rely on system gems that aren't in your Gemfile!

Pat Shaughnessy has a good description of bundle clean and other new additions in bundler 1.1.

ant build.xml file doesn't exist

There may be two situations.

  1. No build.xml is present in the current directory
  2. Your ant configuration file has diffrent name.

Please see and confim the same. In the case one you have to find where your build file is located and in the case 2, You will have to run command ant -f <your build file name>.

How to build minified and uncompressed bundle with webpack?

You can define two entry points in your webpack configuration, one for your normal js and the other one for minified js. Then you should output your bundle with its name, and configure UglifyJS plugin to include min.js files. See the example webpack configuration for more details:

module.exports = {
 entry: {
   'bundle': './src/index.js',
   'bundle.min': './src/index.js',
 },

 output: {
   path: path.resolve(__dirname, 'dist'),
   filename: "[name].js"
 },

 plugins: [
   new webpack.optimize.UglifyJsPlugin({
      include: /\.min\.js$/,
      minimize: true
   })
 ]
};

After running webpack, you will get bundle.js and bundle.min.js in your dist folder, no need for extra plugin.

Select2() is not a function

you might be referring two jquery scripts which is giving the above error.

Get random item from array

Use PHP Rand function

<?php
  $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
  $rand_keys = array_rand($input, 2);
  echo $input[$rand_keys[0]] . "\n";
  echo $input[$rand_keys[1]] . "\n";
?>

More Help

how to display a javascript var in html body

_x000D_
_x000D_
<script type="text/javascript">_x000D_
        function get_param(param) {_x000D_
   var search = window.location.search.substring(1);_x000D_
   var compareKeyValuePair = function(pair) {_x000D_
      var key_value = pair.split('=');_x000D_
      var decodedKey = decodeURIComponent(key_value[0]);_x000D_
      var decodedValue = decodeURIComponent(key_value[1]);_x000D_
      if(decodedKey == param) return decodedValue;_x000D_
      return null;_x000D_
   };_x000D_
_x000D_
   var comparisonResult = null;_x000D_
_x000D_
   if(search.indexOf('&') > -1) {_x000D_
      var params = search.split('&');_x000D_
      for(var i = 0; i < params.length; i++) {_x000D_
         comparisonResult = compareKeyValuePair(params[i]); _x000D_
         if(comparisonResult !== null) {_x000D_
            break;_x000D_
         }_x000D_
      }_x000D_
   } else {_x000D_
      comparisonResult = compareKeyValuePair(search);_x000D_
   }_x000D_
_x000D_
   return comparisonResult;_x000D_
}_x000D_
_x000D_
var parcelNumber = get_param('parcelNumber'); //abc_x000D_
var registryId  = get_param('registryId'); //abc_x000D_
var registrySectionId = get_param('registrySectionId'); //abc_x000D_
var apartmentNumber = get_param('apartmentNumber'); //abc_x000D_
_x000D_
        _x000D_
    </script>
_x000D_
_x000D_
_x000D_

then in the page i call the values like so:

_x000D_
_x000D_
 <td class="tinfodd"> <script  type="text/javascript">_x000D_
                                                    document.write(registrySectionId)_x000D_
                                                    </script></td>
_x000D_
_x000D_
_x000D_

Does Python SciPy need BLAS?

Following the instructions given by 'cfi' works for me, although there are a few pieces they left out that you might need:

1) Your lapack directory, after unzipping, may be called lapack-X-Y (some version number), so you can just rename that to LAPACK.

cd ~/src
mv lapack-[tab] LAPACK

2) In that directory, you may need to do:

cd ~/src/LAPACK 
cp lapack_LINUX.a libflapack.a

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Using "-Filter" with a variable

Try this:

$NameRegex = "chalmw-dm"  
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}

MySQL - select data from database between two dates

SELECT users.* FROM users WHERE created_at BETWEEN '2011-12-01' AND '2011-12-07';

How to convert char* to wchar_t*?

I did something like this. The first 2 zeros are because I don't know what kind of ascii type things this command wants from me. The general feeling I had was to create a temp char array. pass in the wide char array. boom. it works. The +1 ensures that the null terminating character is in the right place.

char tempFilePath[MAX_PATH] = "I want to convert this to wide chars";

int len = strlen(tempFilePath);

// Converts the path to wide characters
    int needed = MultiByteToWideChar(0, 0, tempFilePath, len + 1, strDestPath, len + 1);

What is the C# equivalent of NaN or IsNumeric?

I was using Chris Lively's snippet (selected answer) encapsulated in a bool function like Gishu's suggestion for a year or two. I used it to make sure certain query strings were only numeric before proceeding with further processing. I started getting some errant querystrings that the marked answer was not handling, specifically, whenever a comma was passed after a number like "3645," (returned true). This is the resulting mod:

   static public bool IsNumeric(string s)
   {
      double myNum = 0;
      if (Double.TryParse(s, out myNum))
      {
         if (s.Contains(",")) return false;
         return true;
      }
      else
      {
         return false;
      }
   }

Push Notifications in Android Platform

or....

3) Keep a connection to the server, send keep-alives every few minutes, and the server can push messages instantly. This is how Gmail, Google Talk, etc. works.

How do I close an open port from the terminal on the Mac?

To find the process try:

sudo lsof -i :portNumber

Kill the process which is currently using the port using its PID

kill PID

and then check to see if the port closed. If not, try:

kill -9 PID

I would only do the following if the previous didnt work

sudo kill -9 PID

Just to be safe. Again depending on how you opened the port, this may not matter.

Can Json.NET serialize / deserialize to / from a stream?

The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:

public static object DeserializeFromStream(Stream stream)
{
    var serializer = new JsonSerializer();

    using (var sr = new StreamReader(stream))
    using (var jsonTextReader = new JsonTextReader(sr))
    {
        return serializer.Deserialize(jsonTextReader);
    }
}

Documentation: Deserialize JSON from a file stream

What does the "More Columns than Column Names" error mean?

This error can get thrown if your data frame has sf geometry columns.

What is 0x10 in decimal?

0x means the number is hexadecimal, or base 16.

0x10 is 16.

Entity framework linq query Include() multiple children entities

EF 4.1 to EF 6

There is a strongly typed .Include which allows the required depth of eager loading to be specified by providing Select expressions to the appropriate depth:

using System.Data.Entity; // NB!

var company = context.Companies
                     .Include(co => co.Employees.Select(emp => emp.Employee_Car))
                     .Include(co => co.Employees.Select(emp => emp.Employee_Country))
                     .FirstOrDefault(co => co.companyID == companyID);

The Sql generated is by no means intuitive, but seems performant enough. I've put a small example on GitHub here

EF Core

EF Core has a new extension method, .ThenInclude(), although the syntax is slightly different:

var company = context.Companies
                     .Include(co => co.Employees)
                           .ThenInclude(emp => emp.Employee_Car)
                     .Include(co => co.Employees)
                           .ThenInclude(emp => emp.Employee_Country)

With some notes

  • As per above (Employees.Employee_Car and Employees.Employee_Country), if you need to include 2 or more child properties of an intermediate child collection, you'll need to repeat the .Include navigation for the collection for each child of the collection.
  • As per the docs, I would keep the extra 'indent' in the .ThenInclude to preserve your sanity.

How does the keyword "use" work in PHP and can I import classes with it?

use doesn't include anything. It just imports the specified namespace (or class) to the current scope

If you want the classes to be autoloaded - read about autoloading

Jquery, set value of td in a table?

use .html() along with selector to get/set HTML:

 $('#detailInfo').html('changed value');

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

I had the same problem and I solved it installing both crystal Report Runtime 32 and 64 bit both version

Base64 encoding and decoding in client-side Javascript

Here is a tightened up version of Sniper's post. It presumes well formed base64 string with no carriage returns. This version eliminates a couple of loops, adds the &0xff fix from Yaroslav, eliminates trailing nulls, plus a bit of code golf.

decodeBase64 = function(s) {
    var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
    var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for(i=0;i<64;i++){e[A.charAt(i)]=i;}
    for(x=0;x<L;x++){
        c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
        while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
    }
    return r;
};

react button onClick redirect page

update:

React Router v5 with hooks:

import React from 'react';
import { useHistory } from "react-router-dom";
function LoginLayout() {

  const history = useHistory();

  const routeChange = () =>{ 
    let path = `newPath`; 
    history.push(path);
  }

  return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
          <Row>
            <Col xs="6">                      
              <Button color="primary" className="px-4"
                onClick={routeChange}
                  >
                  Login
                </Button>
            </Col>
            <Col xs="6" className="text-right">
              <Button color="link" className="px-0">Forgot password?</Button>
            </Col>
          </Row>
          ...
        </Container>
      </div>
  );
}
export default LoginLayout;

with React Router v5:

import { useHistory } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink  } from 'reactstrap';

class LoginLayout extends Component {

  routeChange=()=> {
    let path = `newPath`;
    let history = useHistory();
    history.push(path);
  }

  render() {
    return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
          <Row>
            <Col xs="6">                      
              <Button color="primary" className="px-4"
                onClick={this.routeChange}
                  >
                  Login
                </Button>
            </Col>
            <Col xs="6" className="text-right">
              <Button color="link" className="px-0">Forgot password?</Button>
            </Col>
          </Row>
          ...
        </Container>
      </div>
    );
  }
}

export default LoginLayout;

with React Router v4:

import { withRouter } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink  } from 'reactstrap';

class LoginLayout extends Component {
  constuctor() {
    this.routeChange = this.routeChange.bind(this);
  }

  routeChange() {
    let path = `newPath`;
    this.props.history.push(path);
  }

  render() {
    return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
          <Row>
            <Col xs="6">                      
              <Button color="primary" className="px-4"
                onClick={this.routeChange}
                  >
                  Login
                </Button>
            </Col>
            <Col xs="6" className="text-right">
              <Button color="link" className="px-0">Forgot password?</Button>
            </Col>
          </Row>
          ...
        </Container>
      </div>
    );
  }
}

export default withRouter(LoginLayout);

Returning JSON from PHP to JavaScript?

There's a JSON section in the PHP's documentation. You'll need PHP 5.2.0 though.

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

If you don't, here's the PECL library you can install.

<?php
    $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

    echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>

figure of imshow() is too small

That's strange, it definitely works for me:

from matplotlib import pyplot as plt

plt.figure(figsize = (20,2))
plt.imshow(random.rand(8, 90), interpolation='nearest')

I am using the "MacOSX" backend, btw.

How can I use console logging in Internet Explorer?

You can access IE8 script console by launching the "Developer Tools" (F12). Click the "Script" tab, then click "Console" on the right.

From within your JavaScript code, you can do any of the following:

<script type="text/javascript">
    console.log('some msg');
    console.info('information');
    console.warn('some warning');
    console.error('some error');
    console.assert(false, 'YOU FAIL');
</script>

Also, you can clear the Console by calling console.clear().

NOTE: It appears you must launch the Developer Tools first then refresh your page for this to work.

How to change the text color of first select option

I really wanted this (placeholders should look the same for text boxes as select boxes!) and straight CSS wasn't working in Chrome. Here is what I did:

First make sure your select tag has a .has-prompt class.

Then initialize this class somewhere in document.ready.

# Adds a class to select boxes that have prompt currently selected.
# Allows for placeholder-like styling.
# Looks for has-prompt class on select tag.
Mess.Views.SelectPromptStyler = Backbone.View.extend
  el: 'body'

  initialize: ->
    @$('select.has-prompt').trigger('change')

  events:
    'change select.has-prompt': 'changed'

  changed: (e) ->
    select = @$(e.currentTarget)
    if select.find('option').first().is(':selected')
      select.addClass('prompt-selected')
    else
      select.removeClass('prompt-selected')

Then in CSS:

select.prompt-selected {
  color: $placeholder-color;
}

'profile name is not valid' error when executing the sp_send_dbmail command

I got the same problem also. Here's what I did:

If you're already done granting the user/group the rights to use the profile name.

  1. Go to the configuration Wizard of Database Mail
  2. Tick Manage profile security
  3. On public profiles tab, check your profile name
  4. On private profiles tab, select NT AUTHORITY\NETWORK SERVICE for user name and check your profile name
  5. Do #4 this time for NT AUTHORITY\SYSTEM user name
  6. Click Next until Finish.

Add image in pdf using jspdf

For result in base64, before convert to canvas:

var getBase64ImageUrl = function(url, callback, mine) {

                    var img = new Image();

                    url = url.replace("http://","//");

                    img.setAttribute('crossOrigin', 'anonymous');

                    img.onload = function () {
                        var canvas = document.createElement("canvas");
                        canvas.width =this.width;
                        canvas.height =this.height;

                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(this, 0, 0);

                        var dataURL = canvas.toDataURL(mine || "image/jpeg");

                        callback(dataURL);
                    };
                    img.src = url;

                    img.onerror = function(){

                        console.log('on error')
                        callback('');

                    }

            }

   getBase64ImageUrl('Koala.jpeg', function(img){
         //img is a base64encode result
         //return img;
          console.log(img);

          var doc = new jsPDF();
              doc.setFontSize(40);
              doc.text(30, 20, 'Hello world!');
              doc.output('datauri');
              doc.addImage(img, 'JPEG', 15, 40, 180, 160);
    });

Using sendmail from bash script for multiple recipients

Use option -t for sendmail.

in your case - echo -e $mail | /usr/sbin/sendmail -t and add yout Recepient list to message itself like To: [email protected] [email protected] right after the line From:.....

-t option means - Read message for recipients. To:, Cc:, and Bcc: lines will be scanned for recipient addresses. The Bcc: line will be deleted before transmission.

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

ORA-00932: inconsistent datatypes: expected - got CLOB

I just ran over this one and I found by accident that CLOBs can be used in a like query:

   UPDATE IMS_TEST 
   SET TEST_Category  = 'just testing'  
 WHERE TEST_SCRIPT    LIKE '%something%'
   AND ID             = '10000239' 

This worked also for CLOBs greater than 4K

The Performance won't be great but that was no problem in my case.

Video file formats supported in iPhone

Quoting the iPhone OS Technology Overview:

iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:

  • H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • Numerous audio formats, including the ones listed in “Audio Technologies”

For information about the classes of the Media Player framework, see Media Player Framework Reference.

LINQ-to-SQL vs stored procedures?

I'm assuming you mean Linq To Sql

For any CRUD command it's easy to profile the performance of a stored procedure vs. any technology. In this case any difference between the two will be negligible. Try profiling for a 5 (simple types) field object over 100,000 select queries to find out if there's a real difference.

On the other hand the real deal-breaker will be the question on whether you feel comfortable putting your business logic on your database or not, which is an argument against stored procedures.

How to insert date values into table

You can also use the "timestamp" data type where it just needs "dd-mm-yyyy"

Like:

insert into emp values('12-12-2012');

considering there is just one column in the table... You can adjust the insertion values according to your table.

Getting the text that follows after the regex match

You just need to put "group(1)" instead of "group()" in the following line and the return will be the one you expected:

System.out.println("I found the text: " + matcher.group(**1**).toString());

Swift - Remove " character from string

If you want to remove more characters for example "a", "A", "b", "B", "c", "C" from string you can do it this way:

someString = someString.replacingOccurrences(of: "[abc]", with: "", options: [.regularExpression, .caseInsensitive])

How to make HTML table cell editable?

This is the essential point although you don't need to make the code this messy. Instead you could just iterate through all the <td> and add the <input> with the attributes and finally put in the values.

_x000D_
_x000D_
function edit(el) {_x000D_
  el.childNodes[0].removeAttribute("disabled");_x000D_
  el.childNodes[0].focus();_x000D_
  window.getSelection().removeAllRanges();_x000D_
}_x000D_
function disable(el) {_x000D_
  el.setAttribute("disabled","");_x000D_
}
_x000D_
<table border>_x000D_
<tr>_x000D_
<td ondblclick="edit(this)"><input value="cell1" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="cell2" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="cell3" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="so forth..." disabled onblur="disable(this)">_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Select unique values with 'select' function in 'dplyr' library

In dplyr 0.3 this can be easily achieved using the distinct() method.

Here is an example:

distinct_df = df %>% distinct(field1)

You can get a vector of the distinct values with:

distinct_vector = distinct_df$field1

You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

Tomcat in Intellij Idea Community Edition

Tomcat (Headless) can be integrated with IntelliJ Idea - Community edition.

Step-by-step instructions are as below:

  1. Add tomcatX-maven-plugin to pom.xml

    <build>
        <plugins>
            <plugin>
                 <groupId>org.apache.tomcat.maven</groupId>
                 <artifactId>tomcat7-maven-plugin</artifactId>
                 <version>2.2</version>
                 <configuration>
                     <path>SampleProject</path>
                 </configuration>
            </plugin>
        </plugins>
    </build>
    
  2. Add new run configuration as below:

    Run >> Edit Configurations >> + >> Maven
    
    Parameters tab ...
    Name :: Tomcat
    Working Directory :: Project Root Directory
    Command Line :: tomcat7:run
    
    Runner tab ...
    VM Options :: <user needed options>
    JRE :: <project needed>
    
  3. Invoke Tomcat in Run/Debug mode directly from IntelliJ Run >> Run/Debug menu

NOTE: Though this is considered a hacking of using using Tomcat integration features of IntelliJ - Enterprise version features, but I would consider this a programmatic way integrating tomcat to the IntelliJ Idea - community edition.

How can I get the list of files in a directory using C or C++?

Shreevardhan answer works great. But if you want to use it in c++14 just make a change namespace fs = experimental::filesystem;

i.e.,

#include <string>
#include <iostream>
#include <filesystem>

using namespace std;
namespace fs = experimental::filesystem;

int main()
{
    string path = "C:\\splits\\";
    for (auto & p : fs::directory_iterator(path))
        cout << p << endl;
    int n;
    cin >> n;
}

Return index of highest value in an array

Other answers may have shorter code but this one should be the most efficient and is easy to understand.

/**
 * Get key of the max value
 *
 * @var array $array
 * @return mixed
*/
function array_key_max_value($array)
{
    $max = null;
    $result = null;
    foreach ($array as $key => $value) {
        if ($max === null || $value > $max) {
            $result = $key;
            $max = $value;
        }
    }

    return $result;
}

Datatables on-the-fly resizing

$(document).ready(function() {
    $('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
        // var target = $(e.target).attr("href"); // activated tab
        // alert (target);
        $($.fn.dataTable.tables( true ) ).css('width', '100%');
        $($.fn.dataTable.tables( true ) ).DataTable().columns.adjust().draw();
    } ); 
});

It works for me, with "autoWidth": false,

HTTP Error 404.3-Not Found in IIS 7.5

In windows server 2012, even after installing asp.net you might run into this issue.

Check for "Http activation" feature. This feature is present under Web services as well.

Make sure you add the above and everything should be awesome for you !!!

Javascript: How to loop through ALL DOM elements on a page?

Andy E. gave a good answer.

I would add, if you feel to select all the childs in some special selector (this need happened to me recently), you can apply the method "getElementsByTagName()" on any DOM object you want.

For an example, I needed to just parse "visual" part of the web page, so I just made this

var visualDomElts = document.body.getElementsByTagName('*');

This will never take in consideration the head part.

Calculate the display width of a string in Java

It doesn't always need to be toolkit-dependent or one doesn't always need use the FontMetrics approach since it requires one to first obtain a graphics object which is absent in a web container or in a headless enviroment.

I have tested this in a web servlet and it does calculate the text width.

import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

...

String text = "Hello World";
AffineTransform affinetransform = new AffineTransform();     
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);     
Font font = new Font("Tahoma", Font.PLAIN, 12);
int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
int textheight = (int)(font.getStringBounds(text, frc).getHeight());

Add the necessary values to these dimensions to create any required margin.

SQL query to check if a name begins and ends with a vowel

Try this below code,

SELECT DISTINCT CITY
FROM   STATIOn
WHERE  city RLIKE '^[aeiouAEIOU].*.[aeiouAEIOU]$'

Get TimeZone offset value from TimeZone without TimeZone name

I know this is old, but I figured I'd give my input. I had to do this for a project at work and this was my solution.

I have a Building object that includes the Timezone using the TimeZone class and wanted to create zoneId and offset fields in a new class.

So what I did was create:

private String timeZoneId;
private String timeZoneOffset;

Then in the constructor I passed in the Building object and set these fields like so:

this.timeZoneId = building.getTimeZone().getID();
this.timeZoneOffset = building.getTimeZone().toZoneId().getId();

So timeZoneId might equal something like "EST" And timeZoneOffset might equal something like "-05:00"

I would like to not that you might not

Is there a shortcut to make a block comment in Xcode?

Seems like already a lot of people answers this question.

in Swift 3.0, single line comment is to put double forward slashes upfront : "//" ; multiline is put "/* .... */".

Hope this helps.

How to solve PHP error 'Notice: Array to string conversion in...'

Array to string conversion in latest versions of php 7.x is error, rather than notice, and prevents further code execution.

Using print, echo on array is not an option anymore.

Suppressing errors and notices is not a good practice, especially when in development environment and still debugging code.

Use var_dump,print_r, iterate through input value using foreach or for to output input data for names that are declared as input arrays ('name[]')

Most common practice to catch errors is using try/catch blocks, that helps us prevent interruption of code execution that might cause possible errors wrapped within try block.

  try{  //wrap around possible cause of error or notice
    
    if(!empty($_POST['C'])){
        echo $_POST['C'];
    }

  }catch(Exception $e){

    //handle the error message $e->getMessage();
  }

Round up to Second Decimal Place in Python

Updated answer:
The problem with my original answer, as pointed out in the comments by @jpm, is the behavior at the boundaries. Python 3 makes this even more difficult since it uses "bankers" rounding instead of "old school" rounding. However, in looking into this issue I discovered an even better solution using the decimal library.

import decimal

def round_up(x, place=0):
    context = decimal.getcontext()
    # get the original setting so we can put it back when we're done
    original_rounding = context.rounding
    # change context to act like ceil()
    context.rounding = decimal.ROUND_CEILING

    rounded = round(decimal.Decimal(str(x)), place)
    context.rounding = original_rounding
    return float(rounded)

Or if you really just want a one-liner:

import decimal
decimal.getcontext().rounding = decimal.ROUND_CEILING

# here's the one-liner
float(round(decimal.Decimal(str(0.1111)), ndigits=2))
>> 0.12

# Note: this only affects the rounding of `Decimal`
round(0.1111, ndigits=2)
>> 0.11

Here are some examples:

round_up(0.022499999999999999, 2)
>> 0.03
round_up(0.1111111111111000, 2)
>> 0.12
round_up(0.1111111111111000, 3)
>> 0.112

round_up(3.4)
>> 4.0

# @jpm - boundaries do what we want
round_up(0.1, 2)
>> 0.1
round_up(1.1, 2)
>> 1.1

# Note: this still rounds toward `inf`, not "away from zero"
round_up(2.049, 2)
>> 2.05
round_up(-2.0449, 2)
>> -2.04

We can use it to round to the left of the decimal as well:

round_up(11, -1)
>> 20

We don't multiply by 10, thereby avoiding the overflow mentioned in this answer.

round_up(1.01e308, -307)
>> 1.1e+308

Original Answer (Not recommended):
This depends on the behavior you want when considering positive and negative numbers, but if you want something that always rounds to a larger value (e.g. 2.0449 -> 2.05, -2.0449 -> -2.04) then you can do:

round(x + 0.005, 2)

or a little fancier:

def round_up(x, place):
    return round(x + 5 * 10**(-1 * (place + 1)), place)

This also seems to work as follows:

round(144, -1)
# 140
round_up(144, -1)
# 150
round_up(1e308, -307)
# 1.1e308

Android: How can I print a variable on eclipse console?

System.out.println and Log.d both go to LogCat, not the Console.

Check if an image is loaded (no errors) with jQuery

var isImgLoaded = function(imgSelector){
  return $(imgSelector).prop("complete") && $(imgSelector).prop("naturalWidth") !== 0;
}

// Or As a Plugin

    $.fn.extend({
      isLoaded: function(){
        return this.prop("complete") && this.prop("naturalWidth") !== 0;
      }
    })

// $(".myImage").isLoaded() 

How do I set a variable to the output of a command in Bash?

When setting a variable make sure you have no spaces before and/or after the = sign. I literally spent an hour trying to figure this out, trying all kinds of solutions! This is not cool.

Correct:

WTFF=`echo "stuff"`
echo "Example: $WTFF"

Will Fail with error "stuff: not found" or similar

WTFF= `echo "stuff"`
echo "Example: $WTFF"

How do I set response headers in Flask?

Use make_response of Flask something like

@app.route("/")
def home():
    resp = make_response("hello") #here you could use make_response(render_template(...)) too
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

From flask docs,

flask.make_response(*args)

Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.

Add vertical scroll bar to panel

Assuming you're using winforms, default panel components does not offer you a way to disable the horizontal scrolling components. A workaround of this is to disable the auto scrolling and add a scrollbar yourself:

ScrollBar vScrollBar1 = new VScrollBar();
vScrollBar1.Dock = DockStyle.Right;
vScrollBar1.Scroll += (sender, e) => { panel1.VerticalScroll.Value = vScrollBar1.Value; };
panel1.Controls.Add(vScrollBar1);

Detailed discussion here.

HashMap to return default value for non-found keys?

In Java 8, use Map.getOrDefault. It takes the key, and the value to return if no matching key is found.

Delete first character of a string in Javascript

var s = "0test";
if(s.substr(0,1) == "0") {
    s = s.substr(1);
}

For all 0s: http://jsfiddle.net/An4MY/

String.prototype.ltrim0 = function() {
 return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();

Android : How to read file in bytes?

If you want to use a the openFileInput method from a Context for this, you can use the following code.

This will create a BufferArrayOutputStream and append each byte as it's read from the file to it.

/**
 * <p>
 *     Creates a InputStream for a file using the specified Context
 *     and returns the Bytes read from the file.
 * </p>
 *
 * @param context The context to use.
 * @param file The file to read from.
 * @return The array of bytes read from the file, or null if no file was found.
 */
public static byte[] read(Context context, String file) throws IOException {
    byte[] ret = null;

    if (context != null) {
        try {
            InputStream inputStream = context.openFileInput(file);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            int nextByte = inputStream.read();
            while (nextByte != -1) {
                outputStream.write(nextByte);
                nextByte = inputStream.read();
            }

            ret = outputStream.toByteArray();

        } catch (FileNotFoundException ignored) { }
    }

    return ret;
}

How do I skip an iteration of a `foreach` loop?

Another approach is to filter using LINQ before the loop executes:

foreach ( int number in numbers.Where(n => n >= 0) )
{
    // process number
}

Button background as transparent

Try new way to set background transparent

    android:background="?android:attr/selectableItemBackground"

How to enable C# 6.0 feature in Visual Studio 2013?

Information for obsoleted prerelease software:

According to this it's just a install and go for Visual Studio 2013:

In fact, installing the C# 6.0 compiler from this release involves little more than installing a Visual Studio 2013 extension, which in turn updates the MSBuild target files.

So just get the files from https://github.com/dotnet/roslyn and you are ready to go.

You do have to know it is an outdated version of the specs implemented there, since they no longer update the package for Visual Studio 2013:

You can also try April's End User Preview, which installs on top of Visual Studio 2013. (note: this VS 2013 preview is quite out of date, and is no longer updated)

So if you do want to use the latest version, you have to download the Visual Studio 2015.

How to visualize an XML schema?

We offer a tool called DocFlex/XML XSDDoc that allows you to enjoy both things at once:

  • To have diagram represetation of your XML schema
  • To have all those diagrams embedded (and hyperlinked) in a highly sophisticated XML schema documentation

The diagrams in fact are generated not by us, but by Altova XMLSpy. We implemented an Integration with XMLSpy (with the full support of all diagram hyperlinks):

XML schema documentation with diagrams generated by XMLSpy

Here you can see the full this doc: http://www.filigris.com/docflex-xml/xsddoc/examples/html/XMLSchema/index.html

The whole thing provides a functionality not offered by any single vendor right now on the market!

Some our customers were so impressed that they purchased an extra license for XMLSpy only because of our tool. (That's no joke!)


Currently, we've also implemented similar integrations with other XML editors:

With <oXygen/> XML Editor:

XSDDoc with diagrams generated by <oXygen/> XML Editor

See: http://www.filigris.com/docflex-xml/OxygenXML/demo/html/xslt20/index.html

With Liquid XML Studio:

XSDDoc with diagrams generated by Liquid XML

See: http://www.filigris.com/docflex-xml/LiquidXML/demo/html/XMLSchema/index.html


Concerning what all those diagrams depict... Essentially, they are all about content model of XSD elements (as well as other XSD components that lead to elements: complexTypes, element/attribute groups). It seems, there are two approaches here:

  1. To show what a result content model (represented by the given component) would look. That's the approach of XMLSpy.
  2. To show how a particular content model (of the given component) was derived from other components. That's the approach of <oXygen/> XML and Liquid XML.

I personally believe that the diagrams generated by XMLSpy are more useful.

Yet, there were no attempts so far (at least known to me) to depict graphically anything else contained in XML schemas, although one can imagine many...

How to get names of enum entries?

I wrote a helper function to enumerate an enum:

static getEnumValues<T extends number>(enumType: {}): T[] {
  const values: T[] = [];
  const keys = Object.keys(enumType);
  for (const key of keys.slice(0, keys.length / 2)) {
    values.push(<T>+key);
  }
  return values;
}

Usage:

for (const enumValue of getEnumValues<myEnum>(myEnum)) {
  // do the thing
}

The function returns something that can be easily enumerated, and also casts to the enum type.

Maintaining the final state at end of a CSS3 animation

If you are using more animation attributes the shorthand is:

animation: bubble 2s linear 0.5s 1 normal forwards;

This gives:

  • bubble animation name
  • 2s duration
  • linear timing-function
  • 0.5s delay
  • 1 iteration-count (can be 'infinite')
  • normal direction
  • forwards fill-mode (set 'backwards' if you want to have compatibility to use the end position as the final state[this is to support browsers that has animations turned off]{and to answer only the title, and not your specific case})

line breaks in a textarea

Ahh, it is really simple

just add

white-space:pre-wrap;

to your displaying element css

I mean if you are showing result using <p> then your css should be

p{
   white-space:pre-wrap;
}

How to create a fixed sidebar layout with Bootstrap 4?

I'm using the J.S. to fix a sidebar menu. I've tried a lot of solutions with CSS but it's the simplest way to solve it, just add J.S. adding and removing a native BootStrap class: "position-fixed".

The J.S.:

var lateral = false;
function fixar() {

            var element, name, arr;
            element = document.getElementById("minhasidebar");

            if (lateral) {
                element.className = element.className.replace(
                        /\bposition-fixed\b/g, "");
                lateral = false;
            } else {

                name = "position-fixed";
                arr = element.className.split(" ");
                if (arr.indexOf(name) == -1) {
                    element.className += " " + name;
                }
                lateral = true;
            }

        }

The HTML:

Sidebar:

<aside>
        <nav class="sidebar ">
             <div id="minhasidebar">
                 <ul class="nav nav-pills">
                     <li class="nav-item"><a class="nav-link active" 
                     th:href="@{/hoje/inicial}"> <i class="oi oi-clipboard"></i> 
                     <span>Hoje</span>
                     </a></li>
                 </ul>
             </div>
        </nav>            
</aside>

Android getText from EditText field

Try this.

EditText text = (EditText)findViewById(R.id.edittext1);
String  str = text.getText().toString().trim();

Have log4net use application config file for configuration data

Have you tried adding a configsection handler to your app.config? e.g.

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

How to run two jQuery animations simultaneously?

Posting my answer to help someone, the top rated answer didn't solve my qualm.

When I implemented the following [from the top answer], my vertical scroll animation just jittered back and forth:

$(function () {
 $("#first").animate({
   width: '200px'
}, { duration: 200, queue: false });

$("#second").animate({
   width: '600px'
}, { duration: 200, queue: false });
});

I referred to: W3 Schools Set Interval and it solved my issue, namely the 'Syntax' section:

setInterval(function, milliseconds, param1, param2, ...)

Having my parameters of the form { duration: 200, queue: false } forced a duration of zero and it only looked at the parameters for guidance.

The long and short, here's my code, if you want to understand why it works, read the link or analyse the interval expected parameters:

var $scrollDiv = '#mytestdiv';
var $scrollSpeed = 1000;
var $interval = 800;

function configureRepeats() {
   window.setInterval(function () {
       autoScroll($scrollDiv, $scrollSpeed);
   }, $interval, { queue: false });
};

Where 'autoScroll' is:

    $($scrollDiv).animate({
        scrollTop: $($scrollDiv).get(0).scrollHeight
    }, { duration: $scrollSpeed });

    //Scroll to top immediately 
    $($scrollDiv).animate({
        scrollTop: 0
    }, 0);

Happy coding!

How to increase space between dotted border dots

AFAIK there isn't a way to do this. You could use a dashed border or perhaps increase the width of the border a bit, but just getting more spaced out dots is impossible with CSS.

Cmake is not able to find Python-libraries

I was facing this problem while trying to compile OpenCV 3 on a Xubuntu 14.04 Thrusty Tahr system. With all the dev packages of Python installed, the configuration process was always returning the message:

Could NOT found PythonInterp: /usr/bin/python2.7 (found suitable version "2.7.6", minimum required is "2.7")
Could NOT find PythonLibs (missing: PYTHON_INCLUDE_DIRS) (found suitable exact version "2.7.6")
Found PythonInterp: /usr/bin/python3.4 (found suitable version "3.4", minimum required is "3.4")
Could NOT find PythonLibs (missing: PYTHON_LIBRARIES) (Required is exact version "3.4.0")

The CMake version available on Thrusty Tahr repositories is 2.8. Some posts inspired me to upgrade CMake. I've added a PPA CMake repository which installs CMake version 3.2.

After the upgrade everything ran smoothly and the compilation was successful.

How to insert TIMESTAMP into my MySQL table?

Please try CURRENT_TIME() or now() functions

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"

OR

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"

OR you could try with PHP date function here:

$date = date("Y-m-d H:i:s");

Spring Boot REST API - request timeout?

You need to return a Callable<> if you want spring.mvc.async.request-timeout=5000 to work.

@RequestMapping(method = RequestMethod.GET)
public Callable<String> getFoobar() throws InterruptedException {
    return new Callable<String>() {
        @Override
        public String call() throws Exception {
            Thread.sleep(8000); //this will cause a timeout
            return "foobar";
        }
    };
}

SQL: Insert all records from one table to another table without specific the columns

All the answers above, for some reason or another, did not work for me on SQL Server 2012. My situation was I accidently deleted all rows instead of just one row. After our DBA restored the table to dbo.foo_bak, I used the below to restore. NOTE: This only works if the backup table (represented by dbo.foo_bak) and the table that you are writing to (dbo.foo) have the exact same column names.

This is what worked for me using a hybrid of a bunch of different answers:

USE [database_name];
GO
SET IDENTITY_INSERT dbo.foo ON;
GO
INSERT INTO [dbo].[foo]
           ([rown0]
           ,[row1]
           ,[row2]
           ,[row3]
           ,...
           ,[rown])
     SELECT * FROM [dbo].[foo_bak];
GO
SET IDENTITY_INSERT dbo.foo OFF;
GO

This version of my answer is helpful if you have primary and foreign keys.

CURL to pass SSL certifcate and password

I went through this when trying to get a clientcert and private key out of a keystore.

The link above posted by welsh was great, but there was an extra step on my redhat distribution. If curl is built with NSS ( run curl --version to see if you see NSS listed) then you need to import the keys into an NSS keystore. I went through a bunch of convoluted steps, so this may not be the cleanest way, but it got things working

So export the keys into .p12

keytool -importkeystore -srckeystore $jksfile -destkeystore $p12file \
        -srcstoretype JKS -deststoretype PKCS12 \
        -srcstorepass $jkspassword -deststorepass $p12password  
        -srcalias $myalias -destalias $myalias \
        -srckeypass $keypass -destkeypass $keypass -noprompt

And generate the pem file that holds only the key

 echo making ${fileroot}.key.pem
 openssl pkcs12 -in $p12 -out ${fileroot}.key.pem  \
         -passin pass:$p12password  \
         -passout pass:$p12password  -nocerts
  • Make an empty keystore:
mkdir ~/nss
chmod 700 ~/nss
certutil -N -d ~/nss
  • Import the keys into the keystore
pks12util -i <mykeys>.p12 -d ~/nss -W <password for cert >

Now curl should work.

curl --insecure --cert <client cert alias>:<password for cert> \
     --key ${fileroot}.key.pem  <URL>

As I mentioned, there may be other ways to do this, but at least this was repeatable for me. If curl is compiled with NSS support, I was not able to get it to pull the client cert from a file.

What is the difference between ndarray and array in numpy?

numpy.array is a function that returns a numpy.ndarray. There is no object type numpy.array.

Store multiple values in single key in json

Use arrays:

{
    "number": ["1", "2", "3"],
    "alphabet": ["a", "b", "c"]
}

You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'

jQuery UI themes and HTML tables

I've got a one liner to make HTML Tables look BootStrapped:

<table class="table table-striped table-bordered table-hover">

The theme suits other controls and it supports alternate row highlighting.

How do I find out what is hammering my SQL Server?

For a GUI approach I would take a look at Activity Monitor under Management and sort by CPU.

What is a serialVersionUID and why should I use it?

To tell the long story short this field is used to check if serialized data can be deserialized correctly. Serialization and deserialization are often made by different copies of program - for example server converts object to string and client converts received string to object. This field tells that both operates with same idea about what this object is. This field helps when:

  • you have many different copies of your program in different places (like 1 server and 100 clients). If you will change your object, alter your version number and forget to update one this clients, it will know that he is not capable of deserialization

  • you have stored your data in some file and later on you try to open it with updated version of your program with modified object - you will know that this file is not compatible if you keep your version right

When is it important?

Most obvious - if you add some fields to your object, older versions will not be able to use them because they do not have these fields in their object structure.

Less obvious - When you deserialize object, fields that where not present in string will be kept as NULL. If you have removed field from your object, older versions will keep this field as allways-NULL that can lead to misbehavior if older versions rely on data in this field (anyway you have created it for something, not just for fun :-) )

Least obvious - Sometimes you change the idea you put in some field's meaning. For example when you are 12 years old you mean "bicycle" under "bike", but when you are 18 you mean "motorcycle" - if your friends will invite you to "bike ride across city" and you will be the only one who came on bicycle, you will undestand how important it is to keep same meaning across fields :-)

I can't access http://localhost/phpmyadmin/

You should use localhost:portnumber/phpmyadmin Here the Portnumber is the number which you set for your web server or if you have not set it until now it is by Default - 80.

LINQ Using Max() to select a single row

Simply in one line:

var result = table.First(x => x.Status == table.Max(y => y.Status));

Notice that there are two action. the inner action is for finding the max value, the outer action is for get the desired object.

How can I install Visual Studio Code extensions offline?

UPDATE 2017-12-13

You can now download the extension directly from the marketplace.

Enter image description here

As of Visual Studio Code 1.7.1 dragging or opening the extension does not work any more. In order to install it manually you need to:

  • open the extensions sidebar
  • click on the ellipsis in the right upper corner
  • choose Install from VSIX

Install from VSIX...


Old Method

According to the documentation it is possible to download an extension directly:

An extension's direct download URL is in the form:

https://${publisher}.gallery.vsassets.io/_apis/public/gallery/publisher/${publisher}/extension/${extension name}/${version}/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage

This means that in order to download the extension you need to know

  • the publisher name
  • the version
  • the extension name

You can find all this information in the URL.

Example

Here's an example for downloading an installing the C# v1.3.0 extension:

Publisher, Extension and Version

You can find the publisher and the extension names on the extension's homepage inside its URL:

https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp

Here the publisher is ms-vscode and the extension name is csharp.

The version can be found on the right side in the More Info area.

To download it you need to create a link from the template above:

https://ms-vscode.gallery.vsassets.io/_apis/public/gallery/publisher/ms-vscode/extension/csharp/1.3.0/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage

All packages will have the same name Microsoft.VisualStudio.Services.VSIXPackage, so you'll need to rename it after downloading if you want to know what package it was later.

Installation

In order to install the extension

  • Rename the file and give it the *.vsix extension
  • Open Visual Studio Code, go to menu FileOpen File... or Ctrl + O and select the .vsix file
  • If everything went fine, you should see this message at the top of the window:

Extension was successfully installed. Restart to enable it.

How to put a component inside another component in Angular2?

You don't put a component in directives

You register it in @NgModule declarations:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , MyChildComponent ],
  bootstrap: [ App ]
})

and then You just put it in the Parent's Template HTML as : <my-child></my-child>

That's it.

HTML5 Email Validation

Here is the example I use for all of my form email inputs. This example is ASP.NET, but applies to any:

<asp:TextBox runat="server" class="form-control" placeholder="Contact's email" 
    name="contact_email" ID="contact_email" title="Contact's email (format: [email protected])" 
    type="email" TextMode="Email" validate="required:true"
    pattern="[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*" >
</asp:TextBox>

HTML5 still validates using the pattern when not required. Haven't found one yet that was a false positive.

This renders as the following HTML:

<input class="form-control" placeholder="Contact's email" 
    name="contact_email" id="contact_email" type="email" 
    title="Contact's email (format: [email protected])" 
    pattern="[a-zA-Z0-9!#$%&amp;'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*">

How to customize message box

MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form

Is there an "exists" function for jQuery?

You don't have to check if it's greater than 0 like $(selector).length > 0, $(selector).length it's enough and an elegant way to check the existence of elements. I don't think that it is worth to write a function only for this, if you want to do more extra things, then yes.

if($(selector).length){
  // true if length is not 0
} else {
  // false if length is 0
}

Swift Alamofire: How to get the HTTP response status code

For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 5.0

Used request modifier to increase and decrease the timeout interval.

Alamofire's request creation methods offer the most common parameters for customization but sometimes those just aren't enough. The URLRequests created from the passed values can be modified by using a RequestModifier closure when creating requests. For example, to set the URLRequest's timeoutInterval to 120 seconds, modify the request in the closure.

var manager = Session.default
 manager.request(urlString, method: method, parameters: dict, headers: headers, requestModifier: { $0.timeoutInterval = 120 }).validate().responseJSON { response in

OR

RequestModifiers also work with trailing closure syntax.

var manager = Session.default
     manager.request("https://httpbin.org/get") { urlRequest in
    urlRequest.timeoutInterval = 60
    urlRequest.allowsConstrainedNetworkAccess = false
}
.response(...)

Java random numbers using a seed

The easy way is to use:

Random rand = new Random(System.currentTimeMillis());

This is the best way to generate Random numbers.

Why is @font-face throwing a 404 error on woff files?

The answer to this post was very helpful and a big time saver. However, I found that when using FontAwesome 4.50, I had to add an additional configuration for woff2 type of extension also as shown below else requests for woff2 type was giving a 404 error in Chrome's Developer Tools under Console> Errors.

According to the comment by S.Serp, the below configuration should be put within <system.webServer> tag.

<staticContent>
  <remove fileExtension=".woff" />
  <!-- In case IIS already has this mime type -->
  <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
  <remove fileExtension=".woff2" />
  <!-- In case IIS already has this mime type -->
  <mimeMap fileExtension=".woff2" mimeType="application/x-font-woff2" />
</staticContent>

PyCharm shows unresolved references error for valid code

If you are using vagrant the error can be caused by wrong python interpreter. In our vagrant we are using pyenv so I had to change Python Interpreter path path from /usr/bin/python to /home/vagrant/.pyenv/versions/vagrant/bin/python enter image description here

Best way to disable button in Twitter's Bootstrap

The easiest way to do this, is to use the disabled attribute, as you had done in your original question:

<button class="btn btn-disabled" disabled>Content of Button</button>

As of now, Twitter Bootstrap doesn't have a method to disable a button's functionality without using the disabled attribute.

Nonetheless, this would be an excellent feature for them to implement into their javascript library.

How do I post button value to PHP?

Give them all a name that is the same

For example

<input type="button" value="a" name="btn" onclick="a" />
<input type="button" value="b" name="btn" onclick="b" />

Then in your php use:

$val = $_POST['btn']

Edit, as BalusC said; If you're not going to use onclick for doing any javascript (for example, sending the form) then get rid of it and use type="submit"

Add new line in text file with Windows batch file

You can use:

type text1.txt >> combine.txt
echo >> combine.txt
type text2.txt >> combine.txt

or something like this:

echo blah >> combine.txt
echo blah2 >> combine.txt
echo >> combine.txt
echo other >> combine.txt

JavaScript Regular Expression Email Validation

It would be best to use:

var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,20}$/;

This allows domains such as: whatever.info (4 letters at the end)

Also to test, using

pattern.test("[email protected]")

returns true if it works

http://www.w3schools.com/js/js_obj_regexp.asp

Java System.out.print formatting

Since you're using formatters for the rest of it, just use DecimalFormat:

import java.text.DecimalFormat;

DecimalFormat xFormat = new DecimalFormat("000")
System.out.print(xFormat.format(x + 1) + " ");

Alternative you could do whole job in whole line using printf:

System.out.printf("%03d %s  %s    %s    \n",  x + 1, // the payment number
formatter.format(monthlyInterest),  // round our interest rate
formatter.format(principleAmt),
formatter.format(remainderAmt));

How can moment.js be imported with typescript?

Not sure when this changed, but with the latest version of typescript, you just need to use import moment from 'moment'; and everything else should work as normal.

UPDATE:

Looks like moment recent fixed their import. As of at least 2.24.0 you'll want to use import * as moment from 'moment';

Does "git fetch --tags" include "git fetch"?

The general problem here is that git fetch will fetch +refs/heads/*:refs/remotes/$remote/*. If any of these commits have tags, those tags will also be fetched. However if there are tags not reachable by any branch on the remote, they will not be fetched.

The --tags option switches the refspec to +refs/tags/*:refs/tags/*. You could ask git fetch to grab both. I'm pretty sure to just do a git fetch && git fetch -t you'd use the following command:

git fetch origin "+refs/heads/*:refs/remotes/origin/*" "+refs/tags/*:refs/tags/*"

And if you wanted to make this the default for this repo, you can add a second refspec to the default fetch:

git config --local --add remote.origin.fetch "+refs/tags/*:refs/tags/*"

This will add a second fetch = line in the .git/config for this remote.


I spent a while looking for the way to handle this for a project. This is what I came up with.

git fetch -fup origin "+refs/*:refs/*"

In my case I wanted these features

  • Grab all heads and tags from the remote so use refspec refs/*:refs/*
  • Overwrite local branches and tags with non-fast-forward + before the refspec
  • Overwrite currently checked out branch if needed -u
  • Delete branches and tags not present in remote -p
  • And force to be sure -f

ASP.NET MVC3 Razor - Html.ActionLink style

Reviving an old question because it seems to appear at the top of search results.

I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.

  1. I wrapped the action link with a div that would contain the parent style:
<div class="parent-style-one">
      @Html.ActionLink("Homepage", "Home", "Home")
</div>
  1. Next I create the CSS for the div, this will be the parent css and will be inherited by the child elements such as the action link.
  .parent-style-one {
     /* your styles here */
  }
  1. Because all an action link is, is an element when broken down as html so you just need to target that element in your css selection:
  .parent-style-one a {
     text-decoration: none;
  }
  1. For transition effects I did this:
  .parent-style-one a:hover {
        text-decoration: underline;
        -webkit-transition-duration: 1.1s; /* Safari */
        transition-duration: 1.1s;         
  }

This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.

Ignore Duplicates and Create New List of Unique Values in Excel

In my case the excel was frozen when using the formula of

B2=INDEX($A$2:$A$20, MATCH(0, COUNTIF($B$1:B1, $A$2:$A$20), 0))

because there was many rows (10000). So I did in another way which I show below.

I have copied my original list to a second column and then with the function of Excel "remove duplicates" I could find the list of unique values.

Copied from Microsoft Office Website:

Select all the rows, including the column headers, in the list 

you want to filter.

Click the top left cell of the range, and then drag to the bottom right cell.

On the Data menu, point to Filter, and then click Advanced Filter.
In the Advanced Filter dialog box, click Filter the list, in place.
Select the Unique records only check box, and then click OK.

The filtered list is displayed and the duplicate rows are hidden.

On the Edit menu, click Office Clipboard.

The Clipboard task pane is displayed.

Make sure the filtered list is still selected, and then click Copy Copy button.

The filtered list is highlighted with bounding outlines and the selection appears as an > > item at the top of the Clipboard.

On the Data menu, point to Filter, and then click Show All.

The original list is re-displayed.

Press the DELETE key.

The original list is deleted.

In the Clipboard, click on the filtered list item.

The filtered list appears in the same location as the original list.

Source: Microsoft Office Website (link removed, cause dead)

Assign one struct to another in C

This is a simple copy, just like you would do with memcpy() (indeed, some compilers actually produce a call to memcpy() for that code). There is no "string" in C, only pointers to a bunch a chars. If your source structure contains such a pointer, then the pointer gets copied, not the chars themselves.

Permission denied (publickey,keyboard-interactive)

You need to change the sshd_config file in the remote server (probably in /etc/ssh/sshd_config).

Change

PasswordAuthentication no

to

PasswordAuthentication yes

And then restart the sshd daemon.

Using Python 3 in virtualenv

This is all you need, in order to run a virtual environment in python / python3

First if virtualenv not installed, run

pip3 install virtualenv 

Now Run:

virtualenv -p python3 <env name> 

Sometime the cmd virtualenv fails, if so use this:

python3 -m virtualenv <env_name>  # you can specify full path instead <env_name> to install the file in a different location other than the current location

Now activate the virtual env:

source <env_name>/bin/activate

Or:

source `pwd`/<env_name>/bin/activate

Now run

which python

You should see the full path to your dir and <env_name>/bin/python suffix

To exit the virtualenv, run:

deactivate 

How to move text up using CSS when nothing is working

try a negative margin.

margin-top: -10px; /* as an example */

Opposite of append in jquery

Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.

jQuery remove all list items from an unordered list

An example using .remove():

<p>Remove LI's from list</p>
<ul>
    <li>Test</li>
    <li>Test</li>
    <li>Test</li>
    <li>Test</li>
    <li>Test</li>
</ul>
<p>END</p>

setTimeout(function(){$('ul li').remove();},1000);

http://jsfiddle.net/userdude/ZAd2Y/

Also, .empty() should have worked.

Tomcat 8 Maven Plugin for Java 8

Since November 2017, one can use tomcat8-maven-plugin:

<!-- https://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat8-maven-plugin -->
<dependency>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat8-maven-plugin</artifactId>
    <version>2.2</version>
</dependency>

Note that this plugin resides in ICM repo (not in Maven Central), hence you should add the repo to your pluginsRepositories in your pom.xml:

<pluginRepositories>
    <pluginRepository>
        <id>icm</id>
        <name>Spring Framework Milestone Repository</name>
        <url>http://maven.icm.edu.pl/artifactory/repo</url>
    </pluginRepository>
</pluginRepositories>

What does ||= (or-equals) mean in Ruby?

a ||= b

is equivalent to

a || a = b

and not

a = a || b

because of the situation where you define a hash with a default (the hash will return the default for any undefined keys)

a = Hash.new(true) #Which is: {}

if you use:

a[10] ||= 10 #same as a[10] || a[10] = 10

a is still:

{}

but when you write it like so:

a[10] = a[10] || 10

a becomes:

{10 => true}

because you've assigned the value of itself at key 10, which defaults to true, so now the hash is defined for the key 10, rather than never performing the assignment in the first place.

Spring Boot Java Config Set Session Timeout

You should be able to set the server.session.timeout in your application.properties file.

ref: http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

inject bean reference into a Quartz job in Spring?

Jdbc jobstore

If you are using jdbc jobstore Quartz uses a different classloader. That prevents all the workarounds for autowiring, since objects from spring will not be compatible at quartz side, because they originited from a different class loader.

To fix that, the default classloader has to be set in the quartz properties file like this:

org.quartz.scheduler.classLoadHelper.class=org.quartz.simpl.ThreadContextClassLoadHelper

As reference: https://github.com/quartz-scheduler/quartz/issues/221

Differences between git pull origin master & git pull origin/master

git pull = git fetch + git merge origin/branch

git pull and git pull origin branch only differ in that the latter will only "update" origin/branch and not all origin/* as git pull does.

git pull origin/branch will just not work because it's trying to do a git fetch origin/branch which is invalid.

Question related: git fetch + git merge origin/master vs git pull origin/master

How can I ping a server port with PHP?

Try this :

echo exec('ping -n 1 -w 1 72.10.169.28');

What are the aspect ratios for all Android phone and tablet devices?

I researched the same thing several months ago looking at dozens of the most popular Android devices. I found that every Android device had one of the following aspect ratios (from most square to most rectangular):

  • 4:3
  • 3:2
  • 8:5
  • 5:3
  • 16:9

And if you consider portrait devices separate from landscape devices you'll also find the inverse of those ratios (3:4, 2:3, 5:8, 3:5, and 9:16)


More complete answer here: stackoverflow community spreadsheet of Android device resolutions and DPIs

Check empty string in Swift?

Check check for only spaces and newlines characters in text

extension String
{
    var  isBlank:Bool {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
    }
}

using

if text.isBlank
{
  //text is blank do smth
}

C# MessageBox dialog result

You can also do it in one row:

if (MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)

And if you want to show a messagebox on top:

if (MessageBox.Show(new Form() { TopMost = true }, "Text", "Text", MessageBoxButtons.YesNo) == DialogResult.Yes)

Disable a textbox using CSS

**just copy paste this code and run you can see the textbox disabled **

<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title> 

<style>.container{float:left;width:200px;height:25px;position:relative;}
       .container input{float:left;width:200px;height:25px;}
       .overlay{display:block;width:208px;position:absolute;top:0px;left:0px;height:32px;} 
</style>
 </head>
<body>
      <div class="container">
       <input type="text" value="[email protected]" />
       <div class="overlay">
        </div>
       </div> 
</body>
</html>

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

Drop multiple columns in pandas

Try this

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

Mongoose, Select a specific field with find

The _id field is always present unless you explicitly exclude it. Do so using the - syntax:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select('name -_id');

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

Or explicitly via an object:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

SVN Commit failed, access forbidden

If the problem lies client side, this could be one of the causes of the error.

On clients TortoiseSVN saves client credentials under

Tortoise settings / saved data / authentication data.

I got the same error trying to commit my files, but my credentials were changed. Clearing this cache here will give you a popup on next commit attempt for re-entering your correct credentials.

How to undo a git merge with conflicts

Sourcetree

If you not commit your merge, then just double click on another branch (=checkout) and when sourcetree ask you about discarding all changes then agree

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you are using Windows command line to print the data, you should use

chcp 65001

This worked for me!

How to check if a Java 8 Stream is empty?

I would simply use:

stream.count()>0

DataGridView changing cell background color

try the following (in RowDataBound method of GridView):

protected void GridViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // this will only change the rows backgound not the column header 

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[0].BackColor = System.Drawing.Color.LightCyan; //first col
        e.Row.Cells[1].BackColor = System.Drawing.Color.Black; // second col
    }
}

connect to host localhost port 22: Connection refused

  1. Before installing/reinstalling anything check the status of sshd . . .
sudo systemctl status sshd
  1. You should see something like . . .
? sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; disabled; vendor prese>
   Active: inactive (dead)
     Docs: man:sshd(8)
           man:sshd_config(5)
  1. Just enable and start sshd
sudo systemctl enable sshd
sudo systemctl start sshd

Programmatically set image to UIImageView with Xcode 6.1/Swift

This code is in the wrong place:

var image : UIImage = UIImage(named:"afternoon")!
bgImage = UIImageView(image: image)
bgImage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(bgImage)

You must place it inside a function. I recommend moving it inside the viewDidLoad function.

In general, the only code you can add within the class that's not inside of a function are variable declarations like:

@IBOutlet weak var bgImage: UIImageView!

Convert character to ASCII code in JavaScript

str.charCodeAt(index)

Using charCodeAt() The following example returns 65, the Unicode value for A.

'ABC'.charCodeAt(0) // returns 65

JQuery DatePicker ReadOnly

All of the listed solutions give a mediocre user experience or cause issues if you want to re-enable the datepicker with it's settings in-tact. I used a method similar to making a select read-only, which is to disable it but add a hidden field with the same name. Check it:

Usage:

$("#datepicker").readonlyDatepicker(true); //makes the datepicker readonly
$("#datepicker").readonlyDatepicker(false); //makes the datepicker editable again

jQuery function:

$.fn.readonlyDatepicker = function (makeReadonly) {
    $(this).each(function(){

        //find corresponding hidden field
        var name = $(this).attr('name');
        var $hidden = $('input[name="' + name + '"][type="hidden"]');

        //if it doesn't exist, create it
        if ($hidden.length === 0){
            $hidden = $('<input type="hidden" name="' + name + '"/>');
            $hidden.insertAfter($(this));
        }

        if (makeReadonly){
            $hidden.val($(this).val());
            $(this).unbind('change.readonly');
            $(this).attr('disabled', true);
        }
        else{
            $(this).bind('change.readonly', function(){
                $hidden.val($(this).val());
            });
            $(this).attr('disabled', false);
        }
    });
};

Declaring variables inside or outside of a loop

As many people have pointed out,

String str;
while(condition){
    str = calculateStr();
    .....
}

is NOT better than this:

while(condition){
    String str = calculateStr();
    .....
}

So don't declare variables outside their scopes if you are not reusing it...

How to iterate over rows in a DataFrame in Pandas

Sometimes a useful pattern is:

# Borrowing @KutalmisB df example
df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]}, index=['a', 'b'])
# The to_dict call results in a list of dicts
# where each row_dict is a dictionary with k:v pairs of columns:value for that row
for row_dict in df.to_dict(orient='records'):
    print(row_dict)

Which results in:

{'col1':1.0, 'col2':0.1}
{'col1':2.0, 'col2':0.2}

Console.log not working at all

Now in modern browsers, console.log() can be used by pressing F12 key. The picture will be helpful to understand the concept clearly. Console.log() and document.write()

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

 IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

cmdGetPaymentStatement.Parameters.AddWithValue("@pStartDate", DateTime.Parse("22/12/2017", culture, System.Globalization.DateTimeStyles.AssumeLocal)).IsNullable = true;

Remove characters after specific character in string, then remove substring?

To remove everything before a specific char, use below.

string1 = string1.Substring(string1.IndexOf('$') + 1);

What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!

But for a URL, I would use the built in .NET class to take of that.

Explaining Python's '__enter__' and '__exit__'

Python calls __enter__ when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls __exit__ to free up the resource

Let's consider Context Managers and the “with” Statement in Python. Context Manager is a simple “protocol” (or interface) that your object needs to follow so it can be used with the with statement. Basically all you need to do is add enter and exit methods to an object if you want it to function as a context manager. Python will call these two methods at the appropriate times in the resource management cycle.

Let’s take a look at what this would look like in practical terms. Here’s how a simple implementation of the open() context manager might look like:

class ManagedFile:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        self.file = open(self.name, 'w')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

Our ManagedFile class follows the context manager protocol and now supports the with statement.

>>> with ManagedFile('hello.txt') as f:
...    f.write('hello, world!')
...    f.write('bye now')`enter code here`

Python calls enter when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls exit to free up the resource.

Writing a class-based context manager isn’t the only way to support the with statement in Python. The contextlib utility module in the standard library provides a few more abstractions built on top of the basic context manager protocol. This can make your life a little easier if your use cases matches what’s offered by contextlib.

Form content type for a json HTTP POST?

multipart/form-data

is used when you want to upload files to the server. Please check this article for details.

Stop fixed position at footer

$(window).scroll(() => {
    const footerToTop = $('.your-footer').position().top;
    const scrollTop = $(document).scrollTop() + $(window).height();
    const difference = scrollTop - footerToTop;
    const bottomValue = scrollTop > footerToTop ? difference : 0;
    $('.your-fixed-element').css('bottom', bottomValue);
});

Detecting TCP Client Disconnect

If you're using overlapped (i.e. asynchronous) I/O with completion routines or completion ports, you will be notified immediately (assuming you have an outstanding read) when the client side closes the connection.

Woocommerce, get current product id

If the query hasn't been modified by a plugin for some reason, you should be able to get a single product page's "id" via

global $post;
$id = $post->ID

OR

global $product;
$id = $product->id;

EDIT: As of WooCommerce 3.0 this needs to be

global $product;
$id = $product->get_id();