Sunday, 5 March 2017

COMMON SHELL COMMANDS

cat [filename]


Display file’s contents to the standard output device
(usually your monitor).
cd /directorypathChange to directory.
chmod [options] mode filenameChange a file’s permissions.
chown [options] filenameChange who owns a file.
clearClear a command line screen/window for a fresh start.
cp [options] source destinationCopy files and directories.
date [options]Display or set the system date and time.
df [options]Display used and available disk space.
du [options]Show how much space each file takes up.
file [options] filenameDetermine what type of data is within a file.
find [pathname] [expression]Search for files matching a provided pattern.
grep [options] pattern [filesname]Search files or output for a particular pattern.
kill [options] pidStop a process. If the process refuses to stop, use kill -9 pid.
less [options] [filename]View the contents of a file one page at a time.
ln [options] source [destination]Create a shortcut.
locate filenameSearch a copy of your filesystem for the specified
filename.
lpr [options]Send a print job.
ls [options]List directory contents.
man [command]Display the help information for the specified command.
mkdir [options] directoryCreate a new directory.
mv [options] source destinationRename or move file(s) or directories.
passwd [name [password]]Change the password or allow (for the system administrator) to
change any password.
ps [options]Display a snapshot of the currently running processes.
pwdDisplay the pathname for the current directory.
rm [options] directoryRemove (delete) file(s) and/or directories.
rmdir [options] directoryDelete empty directories.
ssh [options] user@machineRemotely log in to another Linux machine, over the network.
Leave an ssh session by typing exit.
su [options] [user [arguments]]Switch to another user account.
tail [options] [filename]Display the last n lines of a file (the default is
10).
tar [options] filenameStore and extract files from a tarfile (.tar) or tarball (.tar.gz or .tgz).
topDisplays the resources being used on your system. Press q to
exit.
touch filenameCreate an empty file with the specified name.
who [options]Display who is logged on.


http://www.caffeinecodes.com

Monday, 27 February 2017

Nginx Settings

server {
  listen 80;
  server_name test.com;
  location = /favicon.ico { access_log off; log_not_found off; }
  location /static/ {
      alias /Users/Afxal/workspace/test_project/static/;
  }
  location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;
      proxy_pass http://127.0.0.1:8000;
  }
}


Python Tricks and Tips

1. Emulating "?:"
Python doesn't know the trinary operator "?:" from C. However, it's pretty easy to emulate:
x ? y : z    -->    [z, y][bool(x)]
(If you're sure that x is already a boolean type (or an integer of value 0 or 1), you can omit the bool() function, of course.)
How does the trick work? We simply create a small list constant, containing the two values to choose from, and use the boolean as an index into the list. "False" is equivalent to 0 and will select the first element, while "True" is equivalent to 1 and will select the second one.
Note that always all three operands will be evaluated, unlike the "?:" operator in C. If you need shortcut evaluation, use an if-else statement.
Actually, there's another way to do it with shortcut evaluation, but it only works if ydoes not contain a boolean False equivalent:
x ? y : z    -->    bool(x) and y or z
2. Checking the Python version
You will often find yourself using features that are not available in older versions of Python. If someone happens to run your program with a too old version, an ugly exception traceback will be printed which is usually not very helpful to the user. Better use a snippet like this:
import sys
if not hasattr(sys, "hexversion") or sys.hexversion < 0x020300f0:
    sys.stderr.write("Sorry, your Python is too old.\n")
    sys.stderr.write("Please upgrade at least to 2.3.\n")
    sys.exit(1)
Those lines should be at the very top of your program, even before any other import statements. The variable hexversion is only available since Python 1.5.2, so we first check if it is there, just in case someone has an even older version. The format of the variable is 0x<maj><min><rev><rel> (major, minor and revision number, and an indication of the release status, which is f0 for official final releases). Each of the four parts is two hexadecimal digits.
3. Debugging CGIs
The "cgitb" module (available since Python 2.2) is extremely helpful when debugging CGI programs. Whenever a run-time error (i.e. exception) occurs, a nicely formatted HTML fragment will be produced, containing the backtrace with source context, line numbers and even contents of the variables involved. To use this module, put this line somewhere at the top of your CGI program:
import cgitb; cgitb.enable()
4. Parallel sorting of lists
Sometimes you want to sort a list, and there's a second list (of the same length) which should be sorted along with it. Of course, you could have used a single list of 2-tuples in the first place, but sometimes a program requires a different structure. Anyway, it's easy. The following snippet works with two or more lists (the example shows only two).
data = zip(list1, list2)
data.sort()
list1, list2 = map(lambda t: list(t), zip(*data))
Note that zip() returns a list of tuples, so you have to convert the result of the last zip() back to lists. That's what the map() command along with the lambda function does. If you don't actually need lists, the last line could be simplified like this:
tuple1, tuple2 = zip(*data)
5. Normalizing a MAC address
I found myself having to convert MAC addresses (sometimes called ethernet address) to a canonical format, i.e. each of the six parts with two digits, and having all lowercase hexadecimal digits. It's quite likely that there is an easier way, but this is what I came up with:
mac = ":".join([i.zfill(2) for i in mac.split(":")]).lower()
(The zfill method of string objects is available since Python 2.2.2.)
6. Sorting IP addresses
How to sort a list of strings that represent IP addresses? Of course, you could supply an appropriate comparison function to the sort() method of the list object, but that's very inefficient (read: slow).
It is better to first pre-process the list so it can be sorted with the efficient built-in comparison function (which simply compares strings character-by-character), and afterwards post-process the sorted list back to the normal format. That trick is applicable to a lot of sorting situations, not just IP addresses.
In the case of IP addresses, we re-format them so that each of the four octets is aligned inside a three-character field (preceded by spaces if necessary). Then all strings will be the same length and can be sorted using the fast built-in comparison function. Afterwards, we simply remove all spaces.
for i in range(len(ips)):
    ips[i] = "%3s.%3s.%3s.%3s" % tuple(ips[i].split("."))
ips.sort()
for i in range(len(ips)):
    ips[i] = ips[i].replace(" ", "")
7. Parsing command line options
This is a code snippet for parsing command line options (using the getopt module) in a sophisticated way. In this example, the program accepts three options (both as one-letter options and as long options) and requires at least two arguments.
import sys, getopt, os.path
me = os.path.basename(sys.argv[0])

debug   = False
really  = True
verbose = False

my_options = (
    ("d", "debug",     "debug   = True",  "Enable debug mode."),
    ("n", "notreally", "really  = False", "No action, display only."),
    ("v", "verbose",   "verbose = True",  "Increase verbosity.")
)

short_opts = reduce(lambda a, b: a + b[0], my_options, "")
long_opts  = map(lambda x: x[1], my_options)

def usage ():
    args = "[-%s] <dir1> <dir2> [...]" % short_opts
    print >> sys.stderr, "Usage: ", me, args, "\nOptions:"
    for opt in my_options:
        print >> sys.stderr, "-" + opt[0], opt[3]
    sys.exit(1)

try:
    opts, args = getopt.getopt(sys.argv[1:], short_opts, long_opts)
except getopt.GetoptError:
    usage()

for o, p in opts:
    for shrt, lng, action in my_options:
        if o[1:] in shrt or o[2:] == lng:
            exec action
            break
    else:
        usage()

if len(args) < 2:
    usage()
8. Mixing Python and shell scripts
Sometimes it might be useful to write a script that can be used as a shell script or as a Python script at the same time. This is possible. The trick is that a sequence of four quote characters means an empty string to the shell, but in Python it starts a triple-quoted string that begins with a quote character. So you can embed shell commands within that triple-quoted string. Note that the first string in a module or script is simply stored as the doc string for that module, but other than that it is simply ignored by the Python interpreter.
The following example demonstrates that trick. It is started as a shell script (because of the #!/bin/sh line). The embedded shell commands check if Python is installed. If not, a useful error message is displayed and the script exits. Otherwise, if Python is found, the script is re-executed with it. Python ignores the triple-quoted doc string and executes the rest like a normal Python program.
If you want to have a a real doc string for your program, you will have to assign it afterwards. The script below shows how to do this, too.
#!/bin/sh

"""":
if which python >/dev/null; then
    exec python "$0" "$@"
else
    echo "${0##*/}: Python not found. Please install Python." >&2
    exit 1
fi
"""

__doc__ = """
Demonstrate how to mix Python + shell script.
"""

import sys
print "Hello World!"
print "This is Python", sys.version
print "This is my argument vector:", sys.argv
print "This is my doc string:", __doc__
sys.exit (0)
9. Converting signal numbers to names
Unfortunately there is no existing function in the "signal" module that converts a signal number to a signal name, although that would be a useful thing to have. The following function fills that gap.
import signal

def signal_numtoname (num):
    name = []
    for key in signal.__dict__.keys():
        if key.startswith("SIG") and getattr(signal, key) == num:
            name.append (key)
    if len(name) == 1:
        return name[0]
    else:
        return str(num)

How To Install Ruby on Rails on Ubuntu 14.04 using RVM

 How To Install Ruby on Rails on Ubuntu 14.04 using RVM

Introduction

Ruby on Rails is one of the most popular application stacks for developers wishing to create sites and web apps. The Ruby programming language, coupled with the Rails development framework, makes app development simple.
Since Ruby on Rails doesn't come in a neatly packaged format, getting the framework installed used to be one of the more difficult parts of getting started. Luckily, tools like rvm, the Ruby Version Manager, have made installation simple.
In this guide, we'll show how to install rvm on an Ubuntu 14.04 VPS, and use it to install a stable version of Ruby and Rails. Although you can go through these procedures as the root user, we'll assume you're operating using an unprivileged user as shown in steps 1-4 in this guide.

The Quick Way

The quickest way of installing Ruby on Rails with rvm is to run the following commands as a regular user:
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
\curl -sSL https://get.rvm.io | bash -s stable --rails
You will be prompted for your regular user's password as part of the installation procedure.
Let's go over exactly what's happening here.
The gpg command contacts a public key server and requests a key associated with the given ID. In this case we are requesting the RVM project's key which is used to sign each RVM release. Having the RVM project's public key allows us to verify the legitimacy of the RVM release we will be downloading, which is signed with the matching private key.
The \curl portion uses the curl web grabbing utility to grab a script file from the rvm website. The backslash that leads the command ensures that we are using the regular curl command and not any altered, aliased version.
The -s flag indicates that the utility should operate in silent mode, the -S flag overrides some of this to allow curl to output errors if it fails. The -L flag tells the utility to follow redirects.
The script is then piped directly to bash for processing. The -s flag indicates that the input is coming from standard in. We then specify that we want the latest stable version of rvm, and that we also want to install the latest stable Rails version, which will pull in the associated Ruby.
Following a long installation procedure, all you need to do is source the rvm scripts by typing:
source ~/.rvm/scripts/rvm
You should now have a full Ruby on Rails environment configured.

Installing Specific Ruby and Rails Versions

If you need to install specific versions of Ruby for your application, you can do so with rvm like this:
rvm install ruby_version
After the installation, we can list the available Ruby versions we have installed by typing:
rvm list
We can switch between the Ruby versions by typing:
rvm use ruby_version
We can use various Rails versions with each Ruby by creating gemsets and then installing Rails within those using the normal gem commands:
rvm gemset create gemset_name    # create a gemset
rvm ruby_version@gemset_name  # specify Ruby version and our new gemset
gem install rails -v rails_version   # install specific Rails version
The gemsets allow us to have self-contained environments for gems and allow us to have multiple environments for each version of Ruby that we install.

Wednesday, 11 May 2016

18 Funny Facts About Engineers


1. For engineers every course apart from engineering is easy.
2. An engineer has the power of getting up at 9.25 am and reaching the class at 9.30 am.
3. T-shirt and jeans are engineer's national dress and Maggi is the national food.
4. A normal person will fix the broken things but an engineer will first break a thing and then he would fix it.
5. An engineer can build a car, spaceship and they even can make time machine. However, he just can’t build a relationship with a girl.
6. An engineer doesn't care for the rise in price of petrol or gold but he gets mad when cigarette costs Rs.5.50 instead of 5.20.
7. An engineer loves to solve a problem. If there is no problem, then he will create one and would start solving it.
8. An engineer can derive any relation just give them the final expression.
9. Are you made of copper(CU) and tellurium(TE), because you’re CUTE. This is how engineers flirt.
10. An engineers’s worst nightmare is teacher taking the class but not taking the attendance.
11. An engineer can finish his syllabus in one night.
12. An Engineer knows nothing, but only an Engineer knows this.
13. An Engineer will never sleep in night and will never wake up in morning.
14. An Engineer is the most innocent person in front of his parents.
15. Never argue with an engineer because arguing with Engineers is like killing the mosquito on your cheek, you might or might not kill it, but you’ll end up slapping yourself.
16. The most common dialogue on the opening day of an engineering college is, “Bhai, iss saal bhi koi khaas ladkiya nahi hain!”
17. No one can speak better English than an engineer who is having a bottle of beer in his hand.
18. There is always a hidden folder in engineer's laptop.

More

Install MySQL on Ubuntu 14.04


During the installation process, you will be prompted to set a password for the MySQL root user as shown below. Choose a strong password and keep it in a safe place for future reference.
Setting the MySQL root password in Ubuntu 14.04 LTS (Trusty Tahr).
MySQL will bind to localhost (127.0.0.1) by default.

How To Install the Django Web Framework on Ubuntu 14.04

May 11 2016  Django, Python Frameworks, Python Ubuntu

Introduction

Django is a full-featured Python web framework for developing dynamic websites and applications. Using Django, you can quickly create Python web applications and rely on the framework to do a good deal of the heavy lifting.
In this guide, we will show you how to get Django up and running on an Ubuntu 14.04 server. After installation, we'll show you how to start a new project to use as the basis for your site.

Different Methods

There are a number of different ways in which you can install Django depending upon your needs and how you want to configure your development environment. These have different advantages and one method may lend itself better to your specific situation than others.
Some of the different methods are below:
  • Global Install from Packages: The official Ubuntu repositories contain Django packages that can be installed easily with the conventional apt package manager. This is very simple, but not as flexible as some other methods. Also, the version contained in the repositories may lag behind the official versions available from the project.
  • Global Install through pip: The pip tool is a package manager for Python packages. If you installpip, you can easily install Django on the system level for use by any user. This should always contain the latest stable release. Even so, global installations are inherently less flexible.
  • Install through pip in a Virtualenv: The Python virtualenv package allows you to create self-contained environments for various projects. Using this technology, you can install Django in a project directory without affecting the greater system. This allows you to provide per-project customizations and packages easily. Virtual environments add some slight mental and process overhead in comparison to globally accessible installation, but provide the most flexibility.
  • Development Version Install through git: If you wish to install the latest development version instead of the stable release, you will have to acquire the code from the git repo. This is necessary to get the latest features/fixes and can be done globally or locally. Development versions do not have the same stability guarantees, however.
With the above caveats and qualities in mind, select the installation method that best suites your needs out of the below instructions.

Global Install from Packages

If you wish to install Django using the Ubuntu repositories, the process is very straight forward.
First, update your local package index with apt, and then install the python-django package:
sudo apt-get update
sudo apt-get install python-django
You can test that the installation was successful by typing:
django-admin --version
1.6.1
This means that the software was successfully installed. You may also notice that the Django version is not the latest stable. To learn a bit about how to use the software, skip ahead to learn how to create sample project.

Global Install through pip

If you wish to install the latest version of Django globally, a better option is to use pip, the Python package manager. First, we need to install the pip package manager. Refresh your apt package index:
sudo apt-get update
Now you can install pip. If you plan on using Python version 2, install using the following commands:
sudo apt-get install python-pip
If, instead, you plan on using Python 3, use this command:
sudo apt-get install python3-pip
Now that you have pip, we can easily install Django. If you are using Python 2, you can type:
sudo pip install django
If you are using Python 3, use the pip3 command instead:
sudo pip3 install django
You can verify that the installation was successful by typing:
django-admin --version
1.7.5
As you can see, the version available through pip is more up-to-date than the one from the Ubuntu repositories (yours will likely be different from the above).

Install through pip in a Virtualenv

Perhaps the most flexible way to install Django on your system is with the virtualenv tool. This tool allows you to create virtual Python environments where you can install any Python packages you want without affecting the rest of the system. This allows you to select Python packages on a per-project basis regardless of conflicts with other project's requirements.
We will begin by installing pip from the Ubuntu repositories. Refresh your local package index before starting:
sudo apt-get update
If you plan on using version 2 of Python, you can install pip by typing:
sudo apt-get install python-pip
If, instead, you plan on using version 3 of Python, you can install pip by typing:
sudo apt-get install python3-pip
Once pip is installed, you can use it to install the virtualenv package. If you installed the Python 2pip, you can type:
sudo pip install virtualenv
If you installed the Python 3 version of pip, you should type this instead:
sudo pip3 install virtualenv
Now, whenever you start a new project, you can create a virtual environment for it. Start by creating and moving into a new project directory:
mkdir ~/newproject
cd ~/newproject
Now, create a virtual environment within the project directory by typing:
virtualenv newenv
This will install a standalone version of Python, as well as pip, into an isolated directory structure within your project directory. We chose to call our virtual environment newenv, but you should name it something descriptive. A directory will be created with the name you select, which will hold the file hierarchy where your packages will be installed.
To install packages into the isolated environment, you must activate it by typing:
source newenv/bin/activate
Your prompt should change to reflect that you are now in your virtual environment. It will look something like (newenv)username@hostname:~/newproject$.
In your new environment, you can use pip to install Django. Regardless of whether you are using version 2 or 3 of Python, it should be called just pip when you are in your virtual environment. Also note that youdo not need to use sudo since you are installing locally:
pip install django
You can verify the installation by typing:
django-admin --version
1.7.5
To leave your virtual environment, you need to issue the deactivate command from anywhere on the system:
deactivate
Your prompt should revert to the conventional display. When you wish to work on your project again, you should re-activate your virtual environment by moving back into your project directory and activating:
cd ~/newproject
source newenv/bin/activate

Development Version Install through git

If you need a development version of Django, you will have to download and install Django from its gitrepository.
To do so, you will need to install git on your system with apt. Refresh your local package index by typing:
sudo apt-get update
Now, we can install git. We will also install the pip Python package manager. We will use this to handle the installation of Django after it has been downloaded. If you are using Python 2, you can type:
sudo apt-get install git python-pip
If you are using Python 3 instead, you should type this:
sudo apt-get install git python3-pip
Once you have git, you can clone the Django repository. Between releases, this repository will have more up-to-date features and bug fixes at the possible expense of stability. You can clone the repository to a directory called django-dev within your home directory by typing:
git clone git://github.com/django/django ~/django-dev
Once the repository is cloned, you can install it using pip. We will use the -e option to install in "editable" mode, which is needed when installing from version control. If you are using version 2 of Python, type:
sudo pip install -e ~/django-dev
If you are using Python 3, type:
sudo pip3 install -e ~/django-dev
You can verify that the installation was successful by typing:
django-admin --version
1.9.dev20150305171756
Note that you can also combine this strategy with the use of virtualenv above if you wish to install a development version of Django in a single environment.

Creating a Sample Project

Now that you have Django installed, we can show you briefly how to get started on a project.
You can use the django-admin command to create a project:
django-admin startproject projectname
cd projectname
This will create a directory called projectname within your current directory. Within this, a management script will be created and another directory called projectname will be created with the actual code.
Note: If you were already in a project directory that you created for use with the virtualenv command, you can tell Django to place the management script and inner directory into the current directory without the extra layer by typing this (notice the ending dot):
django-admin startproject projectname .
To bootstrap the database (this uses SQLite by default) on more recent versions of Django, you can type:
python manage.py migrate
If the migrate command doesn't work, you likely are using an older version of Django. Instead, you can type:
python manage.py syncdb
You will be asked to create an administrative user as part of this process. Select a username, email address, and password for the user.
If you used the migrate command above, you'll need to create the administrative user manually. You can create an administrative user by typing:
python manage.py createsuperuser
You will be prompted for a username, an email address, and a password for the user.
Once you have a user, you can start up the Django development server to see what a fresh Django project looks like. You should only use this for development purposes. Run:
python manage.py runserver 0.0.0.0:8000
Visit your server's IP address followed by :8000 in your web browser
server_ip_address:8000
You should see something that looks like this:
Django public page
Now, append /admin to the end of your URL to get to the admin login page:
server_ip_address:8000/admin
Django admin login
If you enter the admin username and password that you just created, you should be taken to the admin section of the site:
Django admin page
When you are finished looking through the default site, you can stop the development server by typingCTRL-C in your terminal.
The Django project you've created provides the structural basis for designing a more complete site. Check out the Django documentation for more information about how to build your applications and customize your site.

Conclusion

You should now have Django installed on your Ubuntu 14.04 server, providing the main tools you need to create powerful web applications. You should also know how to start a new project and launch the developer server. Leveraging a complete web framework like Django can help make development faster, allowing you to concentrate only on the unique aspects of your applications.