Tuesday, July 16, 2013

localhost/phpmyadmin error fixed


 Many starters face this problem on linux atleat people on ubutntu.

 Should you get a 404 "Not Found" error when you point your browser to the location of phpMyAdmin (such as: http://localhost/phpmyadmin) this is likely caused by not checking the 'Apache 2' selection during installation. To redo the installation run the following:


Code:
 sudo dpkg-reconfigure -plow phpmyadmin
Then select Apache 2 for the webserver you wish to configure.

If this does not work, then you can do the following to include the phpMyadmin-shipped Apache configuration into Apache:

Code:
sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf
sudo /etc/init.d/apache2 reload
Source: http://www.linuxquestions.org/questions/linux-software-2/how-to-fix-the-requested-url-phpmyadmin-was-not-found-on-this-server-796610/

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

PyManga--A python based gui to download manga

I often used to see people sitting infront of the big screens and clicking the mouse to check their favourate manga.I got plenty of time so decided to make the script.
This is the dumbest program ...with lots of bugs in it.What do you expect in one day ??
How to run this program
1.Download this program from sourceforge
2.Extract ==> one shortcut and one zip file
extract the zip file and run the file manga.exe
3.you'll see a popup and follow the instructions









usage:
Ex:1   naruto 100   
Ex2: bleach 245
  **** Spell properly else program will not run  
Ex:<anime name> number



Enter and click ok...wait for some time to download(as soon as black window aka command prompt disappears download is complete) check the manga downloader folder you'll find a new directory/folder check the images for more info..
or you can got to mangareader.net and copy the link at the top and paste it.Make sure you're on the first page(first image should be there on that page)3,4 images.
If you have python then install easygui and beautifulsoup4 modules using pip.Then copy this script and run...



import os
import urllib2
import urllib
from urlparse import urlparse
from bs4 import BeautifulSoup
import easygui as eg


eg.msgbox("Search/Enter proper url"+'\n'+"Ex:naruto 100 or bleach 400"+'\n'+" www.mangareader.net/naruto/100",title="Manga Downloader", ok_button="ok")
q=eg.enterbox(msg='Search or Enter the Link.',title='Manga Downloader')
print q

def user_input(q):
    if 'www' in q:
        site1(q)
    else:
        search(q)

def search(query):
    """Name episod
    Ex: 1.Bleach 544
         2.Naruto 100"""

    s=query.lower().strip(' ').split(' ')
        
    link='http://www.mangareader.net/'+s[0]+'/'+s[1]
    if len(s) > 2:
        link='http://www.mangareader.net/'+'-'.join(s[0:-1])+'/'+s[-1]

    site1(link)


def site1(link):
    link=link.strip('http://')
    link=link.strip('.html')
    if (link.count('/')>2):
        print 'link.count:',link.count('/')

        two=link.find('/',20)
        three=link.find('/',two+1)
        #link=http://www.mangareader.net/440-45521-1/watashi-ni-xx-shinasai/chapter-8.html
        link='http://www.mangareader.net/'+link[two+1:three]+'/'+link[three+9:]
        print link

    if 'http://' not in link:
        
        link1="http://"+link
    else:
        link1=link
    
    try:
        html=urllib2.urlopen(link1).read()

    except urllib2.HTTPError:
        print('Enter proper url')
    
    soup = BeautifulSoup(html)
    link_image=soup.img['src']
    link_next=soup.img.parent['href']
    """ Creates folder at specified location"""
    link_properties = urlparse(link)
    start=link_properties.path.find('/')
    end=link_properties.path.find('/',start+1)
    folder_name=link_properties.path[start+1:end]+'_'+link_properties.path[end+1:]
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)
    """Completed creating Directory"""
        
    
    
    if 'www.' in link_next:
        pass
    link_next='http://www.mangareader.net'+link_next
    i=0
    while ('/'+link_properties.path[end+1:]+'/')in link_image:
        
            f = open(folder_name+'/'+str(i+1)+'.jpg','wb')
            f.write(urllib.urlopen(link_image).read())
            f.close()
            html=urllib2.urlopen(link_next).read()
            soup = BeautifulSoup(html)
            link_image=soup.img['src']
            link_next=soup.img.parent['href']
            link_next='http://www.mangareader.net'+link_next
            print link_next,link_image
            i=i+1

#search("one piece 100")
user_input(q)



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Wednesday, July 10, 2013

What is bash??what the heck is shell??[Learn ubuntu/Linux with me -Day 3]

People often confuse with these terms.Some say Bash Commands,some say shell commands.It's really confusing.The below text is from this website.

What is Bash?

Bash is the shell, or command language interpreter, for the GNU operating system. The name is an acronym for the ‘Bourne-Again SHell’, a pun on Stephen Bourne, the author of the direct ancestor of the current Unix shell sh, which appeared in the Seventh Edition Bell Labs Research version of Unix.
Bash is largely compatible with sh and incorporates useful features from the Korn shell ksh and the C shell csh. It is intended to be a conformant implementation of the IEEE POSIX Shell and Tools portion of the IEEE POSIX specification (IEEE Standard 1003.1). It offers functional improvements over sh for both interactive and programming use.
While the GNU operating system provides other shells, including a version of csh, Bash is the default shell. Like other GNU software, Bash is quite portable. It currently runs on nearly every version of Unix and a few other operating systems - independently-supported ports exist for MS-DOS, OS/2, and Windows platforms.

What is a shell?

At its base, a shell is simply a macro processor that executes commands. The term macro processor means functionality where text and symbols are expanded to create larger expressions.
A Unix shell is both a command interpreter and a programming language. As a command interpreter, the shell provides the user interface to the rich set of GNU utilities. The programming language features allow these utilities to be combined. Files containing commands can be created, and become commands themselves. These new commands have the same status as system commands in directories such as /bin, allowing users or groups to establish custom environments to automate their common tasks.
Shells may be used interactively or non-interactively. In interactive mode, they accept input typed from the keyboard. When executing non-interactively, shells execute commands read from a file.
A shell allows execution of GNU commands, both synchronously and asynchronously. The shell waits for synchronous commands to complete before accepting more input; asynchronous commands continue to execute in parallel with the shell while it reads and executes additional commands. The redirection constructs permit fine-grained control of the input and output of those commands. Moreover, the shell allows control over the contents of commands’ environments.
Shells also provide a small set of built-in commands (builtins) implementing functionality impossible or inconvenient to obtain via separate utilities. For example, cd, break, continue, and exec) cannot be implemented outside of the shell because they directly manipulate the shell itself. The history, getopts, kill, or pwd builtins, among others, could be implemented in separate utilities, but they are more convenient to use as builtin commands. All of the shell builtins are described in subsequent sections.
While executing commands is essential, most of the power (and complexity) of shells is due to their embedded programming languages. Like any high-level language, the shell provides variables, flow control constructs, quoting, and functions.
Shells offer features geared specifically for interactive use rather than to augment the programming language. These interactive features include job control, command line editing, command history and aliases. Each of these features is described in this manual.


Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Useful Commands [Learn ubuntu/Linux with me -Day 3]

Boring Thoery:

What is a command?
A command can be given in any of these ways
  1. An executable program [files located in usr/bin directory] .
  2. Any C,C++,Python Program.
  3. Any builtin command [Ex:exit,cd]
    wait a sec how do i know if a command is builtin or not??
    There's a command which can do that for you.type <command>
    Ex: type cd  ,type exit (try these in your terminal)

    cam@hac3er:~$ type cd
    cd is a shell builtin
    cam@hac3er:~$ type exit
    exit is a shell builtin
    Interested to know more about builtins check these links
    Bash Manual 
  4. A Shell Function
  5. An alias

Interesting Part:


type – Display A Command's Type:

The type command is a shell builtin that displays the kind of command the shell will
execute, given a particular command name. It works like this:
Useage:type <command>
where “command” is the name of the command you want to examine. Here are some.Try these in your terminal
examples:

cam@hac3er:~$ type cd
cd is a shell builtin
cam@hac3er:~$ type exit
exit is a shell builtin
cam@hac3er:~$ type ls
ls is aliased to `ls --color=auto'
cam@hac3er:~$ type cp
cp is /bin/cp
cam@hac3er:~$ type mv
mv is /bin/mv

You can see different outputs which are self explanatory.cp is a command which is at a given location you can find cp at that location.

which – Display An Executable's Location: 

Usage:which <Executable>
 Just try these you'll understand

cam@hac3er:/$ which ls
/bin/ls
cam@hac3er:/$ which cd
cam@hac3er:/$ which cp
/bin/cp
cam@hac3er:/$ which mv
/bin/mv
cam@hac3er:/$ which exit
cam@hac3er:/$



Remember which works for only executables i mean the scripts written in a programming language.If you try to invoke it on builtins then it may throw an error or displays nothing.

help – Get Help For Shell Builtins:

You can get help from terminal by typing this command.you'll not understand a bit if you are a starter.
Usage:  help <comand>
bash has a built-in help facility available for each of the shell builtins. To use it, type “help” followed by the name of the shell builtin. For example:
cd is a builtin


cam@hac3er:/$ help cd
cd: cd [-L|[-P [-e]]] [dir]
    Change the shell working directory.
  
    Change the current directory to DIR.  The default DIR is the value of the
    HOME shell variable.
    .........................

    .........................(you'll get half a page of text)


Hey what if i need to get help for non builtins like cp or mkdir??
That would be a good question
Usage: Executable --help
Executable means like cp,mv,mkdir =>these are scripts remember??


cam@hac3er:/$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx - umask
  -p, --parents     no error if existing, make parent directories as needed
  -v, --verbose     print a message for each created directory
  -Z, --context=CTX  set the SELinux security context of each created
                      directory to CTX
      --help     display this help and exit
      --version  output version information and exit

Report mkdir bugs to bug-coreutils@gnu.org
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'mkdir invocation'


cam@hac3er:/$ cp --help


Usage: cp [OPTION]... [-T] SOURCE DEST
  or:  cp [OPTION]... SOURCE... DIRECTORY
  or:  cp [OPTION]... -t DIRECTORY SOURCE...
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

Mandatory arguments to long options are mandatory for short options too.
  -a, --archive                same as -dR --preserve=all
      --attributes-only        don't copy the file data, just the attributes
      --backup[=CONTROL]       make a backup of each existing destination file
  -b                           like --backup but does not accept an argument
      --copy-contents          copy contents of special files when recursive
.............................trimmed I got a huge help text..................



man – Display A Program's Manual Page:

Most executable programs intended for command line use provide a formal piece of documentation called a manual or man page. A special paging program called man is used to view them.
Usage: 1)man <command>    Ex: man ls
            2)man section search_term    Ex: man 5 passwd



I didn't get the second syntax.
Then go through this boring theory but it's worth it
man uses less to display[remember ??less is used to view files,we discussed that in our previous posts]
man is divided into several sections so that is why you need to provide a section number for that
  Section       Contents
   1                 User commands
   2                 Programming interfaces kernel system calls
   3                 Programming interfaces to the C library
   4                 Special files such as device nodes and drivers
   5                 File formats
   6                 Games and amusements such as screen savers
   7                 Miscellaneous
   8                 System administration commands
Sometimes we need to look in a specific section of the manual to find what we are looking for.


apropos – Display Appropriate Commands:

Usage: apropros search_term
A simple search utility of command line.

cam@hac3er:/$ apropos floppy
fdformat (8)         - low-level format a floppy disk
mbadblocks (1)       - tests a floppy disk, and marks the bad blocks in the FAT
mformat (1)          - add an MSDOS filesystem to a low-level formatted floppy disk
mxtar (1)            - Wrapper for using GNU tar directly from a floppy disk

 

whatis – Display A Very Brief Description Of A Command:
The whatis program displays the name and a one line description of a man page
matching a specified keyword:
Usage: whatis cd

cam@hac3er:/$ whatis cd
cd: nothing appropriate.
cam@hac3er:/$ whatis ls
ls (1)               - list directory contents
cam@hac3er:/$ whatis mkdir
mkdir (1)            - make directories
mkdir (2)            - create a directory
cam@hac3er:/$ whatis cp
cp (1)               - copy files and directories
cam@hac3er:/$ whatis mv
mv (1)               - move (rename) files
cam@hac3er:/$



Creating Your Own Commands With alias:
Hey one thing that's irritating is that there is no command on my name :(
Let's create one.
One common thing i do is i often change my directory to desktop.. and give a command ls...this is a regular task i do.what if i combine both of them i.e changing directory and displaying it's contents.wow that's cool
Usage:alias yourname(somename)= <'command1;command2'>


You need to type properly and note that commands will be in between singlequotes
right click on a directory if you're not sure about the path of any directory.

cam@hac3er:/$ alias ajay='cd /home/cam/Desktop;ls;'
 

cam@hac3er:/$ ajay
1.html  2.py  comp_game.py   fb_pp.py  fb.py~  got.py~        Sublime Text 2
1.py    ajay  comp_game.py~  fb.py     got.py  ioredirection  test.py


cam@hac3er:~/Desktop$ type ajay
ajay is aliased to `cd /home/cam/Desktop;ls;'
 

cam@hac3er:~/Desktop$ unalias ajay
 

cam@hac3er:~/Desktop$ type ajay
bash: type: ajay: not found

 


To see all the aliases defined in the environment, use the alias command without
arguments.To remove that alias use:unalias name_of_the_alias


we'll it's too much for a post.Chek these links and keep typing in your terminal.
Bash Reference >>>Bash FAQ   >>>GNU Documentation >>Wikipedia

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Saturday, July 6, 2013

How to send messages to billions of users on facebook with one simple script

 Although title looks good,but due to facebook's spam preventing algorithm this message will be sent to other folder[rarely people will see them],but if the user is a friend of your's then you can send message directly



#usr/bin/env/python
"""
This script can get the user data from facebook graph api.
This is written for better understanding of python 
Modules required:BeautifulSoup
Author:Ajay Kumar Medepalli
Blog:http://pythonnotesbyajay.blogspot.in/
"""
import smtplib
import email
from email.MIMEMultipart import MIMEMultipart
from email.parser import Parser
from email.MIMEText import MIMEText
import urllib2
#from BeautifulSoup import BeautifulSoup
"""There are two versions of BeautifulSoup.This script is updated with the latest one"""
from bs4 import Beautifulsoup
import time
import random


"""
Algorithm Explaination:
Aim: To send messages to fb users 
To send messages we need to have their usernames. (FB has introduced this messaging system like if i've my username i can receive message from 
    email clients and fb email id would be username@facebook.com)

FB Graphi API provides us to acess usernames if users have created one.
get_fb_username ==> This function will get you all usernames 
send_mail ==> This functions will send messages to users (Note :  The message will be sent to other folder if you are not a friend )

"""
 
user_name_array=[]  #List or array to store usernames of facebook
def get_fb_username(id):
    try:
        """
        In fb graph api every url doesn't point to a user or json object from which username can be extracted
        There are some urls which we don't need,since we are using range function there will be errors.To avoid errors we are using
        try 
        """
        url=urllib2.urlopen('https://graph.facebook.com/'+str(id)).read()
        """
        id ==> it's the number.So i'm converting it into string.
        Our urls look like
        https://graph.facebook.com/1
        open your browser or install RESTFUL api addon and check the url
        https://graph.facebook.com/4 
        The above url leads you to the Mark Zuckerberg's page which has his details in json 

        {
   "id": "101",
   "first_name": "xx",
   "gender": "male",
   "last_name": "yyy",
   "link": "https://www.facebook.com/zz",
   "locale": "en_US",
   "name": "Xxx YYy",
   "username": "cam"
}
    
        """

        soup = BeautifulSoup(url)
        all_attr=soup.prettify()
        print all_attr
        gend=all_attr.find("gender")
        if(all_attr[gend+9] == 'm'): # just a check to see if user is a male 
            gender='male'
        elif (all_attr[gend+9] == 'f'): #checking if the user is a female
            gender = 'female'
        else:
            gender="The user didn't specify any gender"
        if all_attr.find('username') != -1: #if there is a username then proceed
            start_quote=all_attr.find('username')+10 #find the first occurence of username
            end_quote=all_attr.find('"',start_quote+1) 
#find the '"' after the username
 
            user_name=all_attr[start_quote:end_quote+1].strip('"')+'@facebook.com' 
#generated username and adding @facebook.com to the username
 
            user_name_array.append(str(user_name)) # adding username to list or array
            print "username ==>"+'\t'+user_name +'\t'+ "gender ==>"+"\t"+gender
            print "\n"
         
    except urllib2.HTTPError:
        pass
 
 
     
 """
The range function in python is so useful . We can generate 1000s of username .I've called the function inside range function.
 """
for i in range(124896015,124896016,1):
#for i in range(startvalue,stopvalue,stepvalue):
    get_fb_username(i+1)
print user_name_array
 
def send_mail():
    random_text=["hi","hello","Nice to meet you","How are you","wassup","hi!!!",'just wanted to say hi']
    server = smtplib.SMTP()
    server.connect('smtp.gmail.com', 587) # for eg. host = 'smtp.gmail.com', port = 587
    server.ehlo()
    server.starttls()
    server.login('username@gmail.com', 'password')
    #replace this with u r gmail id
    #password ==> ur gmail password
    fromaddr ='username@gmail.com'
 
    for i in range(len(user_name_array)-1):
 
        msg = email.MIMEMultipart.MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = user_name_array[i]
        msg['Subject'] = 'hi'
         
        msg.attach(MIMEText(random_text[random.randint(0,len(random_text)-1)]))
        #msg.attach(MIMEText('put some custom message.', 'plain')) 
        server.sendmail(fromaddr,user_name_array[i],msg.as_string())
    server.quit()  
send_mail()

But you need to make few changes
1.change the numbers in the range function,if you've a fast computer then you can start all the way from 4 to 5000000 (Mark zuckerberg has id =4)
2.change the user@gmail.com,password with your details
3.Edit the message you want to send aswell
How to use this??
pip install BeautifulSoup ==>Download this module
a.copy and paste this script somewhere on u rcomputer
b.cd somewhere
c.python scriptname.py



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Friday, July 5, 2013

How to get bulk email ids and send them messages separetly rather CC?


 Recently i've been doing ubuntu tutorials.This is the odd one.
I've got a forwarded mail which has lot of emails.I thought of promoting my blog.It's tedious to type all those emails or removing extra characters.
 With this you can forward emails faster and people will really read it.



import smtplib
import email
from email.MIMEMultipart import MIMEMultipart
from email.parser import Parser
from email.MIMEText import MIMEText

import mimetypes
s='"xxx@yyy.com"<xxx@yyy.com>,"xxx@yyy.com"<xxx@yyy.com>'
# ==> s='Insert the copied email ids between ' single quotes''
email_id_array=[]
old_lts=0
old_gts=0
#lts,gts==> less than sign, greater than sign
while old_lts!=-1:
    lts=s.find('<',old_lts+1)
    gts=s.find('>',old_gts+1)
    
    
    email_id=s[lts+1:gts]
    print email_id
    email_id_array.append(email_id)
    old_lts=lts
    old_gts=gts
email_id_array.pop()
print email_id_array



with open('C:\Documents and Settings\Ajay\Desktop\emails.txt','w') as f:
#C:\Documents and Settings\Ajay\Desktop\emails.txt ==> change this to appropriate location
    for i in range(len(email_id_array)):
        f.write(email_id_array[i]+','+"\n")
"""Some part of this was taken from 
http://jayrambhia.com/blog/send-emails-using-python/
this blog.
you can add atatchments aswell 
"""
server = smtplib.SMTP()
server.connect('smtp.gmail.com', 587) # for eg. host = 'smtp.gmail.com', port = 587
server.ehlo()
server.starttls()
server.login('your gmail id', 'your secret password')
#username@gmail.com
#Enter your password.
fromaddr ='your gmail id'

for i in range(len(email_id_array)-1):

    msg = email.MIMEMultipart.MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = email_id_array[i]
    msg['Subject'] = 'Testing...'
    msg.attach(MIMEText('Very Important..'))
    msg.attach(MIMEText('WEFORCHRIST has crossed 1900+ fans on facebook.Join us @ www.facebook.com/weforchrist.Hope you like our page.', 'plain')) # just a way to say.. Ha! I use Python.
    server.sendmail(fromaddr,email_id_array[i],msg.as_string())
    server.quit()  

your gmail id and password should be given, rest the same...
Copy the above script and give it a name.Start python interpreter and run this module.If your from Linux i need not explain anything.
If you don't have python download from Python official website
1.Download and install python
2.Get the email ids from any forwarded message.
3.save the above python script and run the module

                                   
4. Success...Your message is sent.

 Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Copy/Make/Move/Remove/Create Links-2 in Ubuntu/Linux[Learn ubuntu/Linux with me -Day 2



This is the continuation of my previous post

Click on the images for a better enlarged view.

How to remove files and directories from Terminal?


rm <file_name>
 
The above command deletes the file.

rm -r <dir_name>

The above command removes the directory.

I said i'll be telling you about links...remember hard & Symbolic links

first let's see the syntax for creating Links.


Before running down to the theory which i copied from a pdf i suggest you to go to these links,because you can get short and sweet answers.

>>Stackoverflow

>>askubuntu

>>wiki

Hard Links:


Hard links are the original Unix way of creating links, compared to symbolic links, which
are more modern. By default, every file has a single hard link that gives the file its name.
When we create a hard link, we create an additional directory entry for a file. Hard links
have two important limitations:
1. A hard link cannot reference a file outside its own file system. This means a link
may not reference a file that is not on the same disk partition as the link itself.
2. A hard link may not reference a directory.
A hard link is indistinguishable from the file itself. Unlike a symbolic link, when you list
a directory containing a hard link you will see no special indication of the link. When a
hard link is deleted, the link is removed but the contents of the file itself continue to exist
(that is, its space is not deallocated) until all links to the file are deleted.
It is important to be aware of hard links because you might encounter them from time to
time, but modern practice prefers symbolic links, which we will cover next.

Symbolic Links:

Symbolic links were created to overcome the limitations of hard links. Symbolic links
work by creating a special type of file that contains a text pointer to the referenced file or
directory. In this regard, they operate in much the same way as a Windows shortcut
though of course, they predate the Windows feature by many years ;-)
A file pointed to by a symbolic link, and the symbolic link itself are largely
indistinguishable from one another. For example, if you write some something to the
symbolic link, the referenced file is also written to. However when you delete a symbolic
link, only the link is deleted, not the file itself. If the file is deleted before the symbolic
link, the link will continue to exist, but will point to nothing. In this case, the link is said
to be broken. In many implementations, the ls command will display broken links in a
distinguishing color, such as red, to reveal their presence.
The concept of links can seem very confusing, but hang in there. We're going to try all
this stuff and it will, hopefully, become clear.

Example for Hard Links:



When thinking about hard links, it is helpful to imagine that files are made up of two
parts: the data part containing the file's contents and the name part which holds the file's
name. When we create hard links, we are actually creating additional name parts that all
refer to the same data part. The system assigns a chain of disk blocks to what is called an
inode, which is then associated with the name part. Each hard link therefore refers to a
specific inode containing the file's contents

On my desktop I've got a directory named ajay in which there are two directories named dir1 ,dir2 and a passwd file.View the above image in full screen.I've created hard links.
ls -l will give the number 4 to both passwd and passwd-hard file but to check wether they are different files or links we can use ls -li which gives us inode number.This number is same as you can see in the output.

Example for Symbolic Link:


The first example is pretty straightforward, we simply add the “-s” option to create a
symbolic link rather than a hard link. But what about the next two? Remember, when we
create a symbolic link, we are creating a text description of where the target file is
relative to the symbolic link. It's easier to see if we look at the ls output:
The listing for passwd-sym in dir1 shows that is it a symbolic link by the leading “l” in
the first field and that it points to “../passwd”, which is correct. Relative to the location of passwd-sym, passwd is in the directory above it. Notice too, that the length of the symbolic
link file is 9, the number of characters in the string “../passwd” rather than the length of the file to which it is pointing.
When creating symbolic links, you can either use absolute pathnames or relative path names.

In addition to regular files, symbolic links can also reference directories.



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Copy/Make/Move/Remove/Create Links-1 in Ubuntu/Linux[Learn ubuntu/Linux with me -Day 2]



Click on the images for a better enlarged view.


Looking at the title of post one may say ...Hey Ajay you are an idiot...Copy/paste this is the first task any user can do with a mouse click or simple drag and drop can do that. well I'll say by th end you'll understand.The commands which you are going to learn in this post will be used widely so just fire up terminal create dummy folders on your Desktop with some text files in them.

Command Description
mkdir directory... Why the heck did you put three dots?
Because you can repeat that..
What??
Here's the example
mkdir dir1 dir2 dir3 dir4
This will create the four directories.
cp item1 item2 item1 and item2 can be a file/directory
cp item1 item2 item3 directory
This will copy all items to the directory.
mv item1 item2 Moving and Renaming is done using this.
rm item Remove files
ln file link
ln -s item link
creates hard link
Creates symbolic link


 This is a bit complicated tutorial you need to do a lot of typing
mkdir:
The syntax is simple and self explanatory

cp:

copies files and directories

cp <somedir/somefile> .

did u see a dot at the end..?? copy a file from the given location to the current working directory.Check the image
dot/period is equivalent to current directory

you can do much more with copy


mv:

Renaming files and Moving the directories.

mv somefile somefile1

The above command does this ==> somefile is renamed to somefile1

mv somefile1 somedir1

this will move somefile1 to somedir1

Example :

1.cd Desktop ==>this will take you to Desktop
2.mkdir facebook ==>This will create facebook directory on your Desktop
3.cd facebook ==>This will take you inside facebook directory
4.mkdir profile friends job education relationship ==>will create 5 directories inside facebook directory
5.mv education friends job relationship profile ==>education friends job relationship directories are moved to profile directory
6.ls -l ==>Displays files/dirs in longer format[-l for longer].Now you can see only one directory inside facebook that's profile
7.cd profile ==>change your directory to profile.
8.ls -l displays files and dirs
9.cp -v /etc/passwd .
what the heck is this??
general syntax for copy ==> cp <from location of file> <to location>
cp is for copy ...v for verbose...
there is a password file @  /etc/passwd ==>from location
to location: . (period/dot stands for current location),So what's current location?it's facebook directory.
10.ls -l gives  profile dir and passwd file

The rest you can play around..
cp -i
i??i means interactive like if the to location has already that file cp -i will ask for your permisssion should it overwrite or not?if you type y it will overwrote else if you type n it will not overwrite the file.
cp -v will not tell you anything if a duplicate file exists,it just overwrites the file.


click the image for a better view and try these commands.


 This is too much for one post I'll post the rest in next post.Links are bit tough to understand...Play around with these.More you type more you learn.

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Thursday, July 4, 2013

ls command explained [Learn ubuntu/Linux with me -Day 2]



Click on the images for a better enlarged view.

Just Enter these commands in your Terminal.Description gives you an idea but I'll explain in detail.

Command Equivalent Long Command Description
ls -a ls --all Lists all Files including hidden files
ls -d ls --directory Ex: ls -ld /etc Try the above command and search on google.
ls -r ls --reverse Displays results in reverse order.
ls -S no long command Sort results by file size
ls -t no long command Sort by Modification time.
ls -l no long command. Displays results in long format

I'm in my home directory,check out those images.


How to hide files in ubuntu?
Some times you need to hide some files.In windows it's simple.How do you do it in ubuntu?
Rename the file /directory to .ajay or <dot>dirname[dot followed by a name].
it's as simple as that.File is gone.

How to view Hidden files in ubuntu?
Two ways
1.ctrl+h
2.Go to terminal ==>ls -a ==> displays hidden files.

Sort the files based on size and time of Modification

ls -S ==>Sort files based on Size[Capital or big S]

ls -t ===>Sort files based on time of Modification.


ls-l Explained:

ls -l ==> To show long listing information about the file/directory.
You get many things in the output.Each term is explained.You'll find similarity but not the exact thing.
1.drwxr-xr-x or -rw-rw-r-- 
d will be there for directories.
rwxr ==> these are permissions [read /write] .You don't need much but just remember.I'll cover this in detail.
2.Next you see a number ==>Number of hard links.

What the heck is hard link??Is there something called soft links?
Yes,yes there are hard links and soft links.I'll explain in detail in my next post.

3.cam ==> The user name of the file's owner. ***this will be your username.
4.cam ==> The name of the group which owns the file. *** this will be mostly username else it will be root.
5.4096 ==> Size of the file in bytes.
6.Jul 5 09:58 ==> Date and time of the file's last modification.
7.Desktop ==> Name of the file/directory.

*** Everthing will be different for you but the pattern remains mostly same.If you've any doubts let me know.

ls --help:

Last but not least ls --help ,there are many commands you can find them along with description .

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Learn ubuntu/Linux with me -Day 1

I've been working on ubuntu since 4 years or so,It's time to write a blog with some screen shots.There's a wonderful book which is free,if you've time then go ahead and read for yourself.
Let's dive in.
Problem that you'll face: 
Typing... you need to type a lot of commands don't use mouse it's not for hackers it's for  dummies,the solution for this is given at the end,but for now for very first time you need to type every command.

Click on the images for a better enlarged view



Type this to fire up your Terminal
ctrl+alt+t

or you can search Terminal from the dashboard.


Commands that we'll discuss today.Just enter this in your terminal.
Just enter these commands in terminal.I tried to explain with examples,check the screenshots for a better understanding
Just do these
Command What it does
date displays current date
cal displays current month calender
pwd Displays Present working Directory
cd <dirname> changes to the dirname directory
ls Lists all files and directories
file <filename> Displays the type of file
less <file_name> shows the content of file
***** <file name> ===> name of the file without '<' or '>' symbols,but the file should exist.
If your a noob then create a directory on your desktop.Inside it create a text file.
now use this command
cd Desktop/directoryname
now type ls in your terminal
ls will display the name of  the text file
**** file names/ dirnames shouldn't contain spaces..if they have space then you need to use double quotes. cd "ajay kumar" or ls "ajay kumar"


Frequently used:
pwd ==>present working Directory
cd ==> Change directory
ls ==> Lists all directories and files
Less Frequently used:
file <file name> ==> Determine File type
less <file name> ==> View Contents. 

In the screen shot below you'll see cam@hac3er:~$ This may vary for you,you may have some thing like this==> 'username@computer-name:~$'




cd Desktop ==> will take you to the Desktop directory.[ cd<space>dirname ]
dirname here is the directory name.The directory name is case sensitive.Desktop is different from desktop.

How the heck I know the directory name? Use the command ls It lists all the directories and files.
cd .. ==> takes you back to previous directory;
cd-- ==> will take you to home directory. 


Create a text file[ajay]/download an image file from internet
cd Desktop
file ajay
It will give you the type of file.
less ajay
The above command will display the content of that file.
To come out of less input q from keyboard

Don't name a file with space trust me on this.If you've a space in your directory or a file you need to use double quotes.

 

Solution for the Problem:
Use up and down arrows to move around the previous commands,Terminal Emulators can save upto 500 command history.
Once you move those arrows you can edit a part of command by pressing backspace.
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Tuesday, March 19, 2013

Sets in python


A set is an unordered collection of zero or more immutable Python data objects. Sets do not allow duplicates and are written as comma-delimited values enclosed in curly braces. The empty set is represented by set(). Sets are heterogeneous, and the collection can be assigned to a variable as below.
1
2
3
4
5
6
>>> {3,6,"cat",4.5,False}
{False, 4.5, 3, 6, 'cat'}
>>> mySet = {3,6,"cat",4.5,False}
>>> mySet
{False, 4.5, 3, 6, 'cat'}
>>>
Even though sets are not considered to be sequential, they do support a few of the familiar operations presented earlier. Table  reviews these operations and the following session gives examples of their use.
Operation Name Operator Explanation
membership in Set membership
length len Returns the cardinality of the set
| aset | otherset Returns a new set with all elements from both sets
& aset & otherset Returns a new set with only those elements common to both sets
- aset - otherset Returns a new set with all items from the first set not in second
<= aset <= otherset Asks whether all elements of the first set are in the second
Operations on a Set in Python
1
2
3
4
5
6
7
8
9
>>> mySet
{False, 4.5, 3, 6, 'cat'}
>>> len(mySet)
5
>>> False in mySet
True
>>> "dog" in mySet
False
>>>
Sets support a number of methods that should be familiar to those who have worked with them in a mathematics setting. Table  provides a summary. Examples of their use follow. Note that union, intersection, issubset, and difference all have operators that can be used as well.
Method Name Use Explanation
union aset.union(otherset) Returns a new set with all elements from both sets
intersection aset.intersection(otherset) Returns a new set with only those elements common to both sets
difference aset.difference(otherset) Returns a new set with all items from first set not in second
issubset aset.issubset(otherset) Asks whether all elements of one set are in the other
add aset.add(item) Adds item to the set
remove aset.remove(item) Removes item from the set
pop aset.pop() Removes an arbitrary element from the set
clear aset.clear() Removes all elements from the set


aset.clear() Removes all elements from the set
Methods Provided by Sets in Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
>>> mySet
{False, 4.5, 3, 6, 'cat'}
>>> yourSet = {99,3,100}
>>> mySet.union(yourSet)
{False, 4.5, 3, 100, 6, 'cat', 99}
>>> mySet | yourSet
{False, 4.5, 3, 100, 6, 'cat', 99}
>>> mySet.intersection(yourSet)
{3}
>>> mySet & yourSet
{3}
>>> mySet.difference(yourSet)
{False, 4.5, 6, 'cat'}
>>> mySet - yourSet
{False, 4.5, 6, 'cat'}
>>> {3,100}.issubset(yourSet)
True
>>> {3,100}<=yourSet
True
>>> mySet.add("house")
>>> mySet
{False, 4.5, 3, 6, 'house', 'cat'}
>>> mySet.remove(4.5)
>>> mySet
{False, 3, 6, 'house', 'cat'}
>>> mySet.pop()
False
>>> mySet
{3, 6, 'house', 'cat'}
>>> mySet.clear()
>>> mySet
set()
>>>
 From:http://interactivepython.org/courselib/static/pythonds/Introduction/introduction.html

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Monday, March 18, 2013

Strings in Python

Before you read my stuff have a look at official documentation.Get some vague idea and come back here.
Check the pleac project...I love that site,last but not least tutorials point,even then you don't understand you're in right place. :)).

1.Introduction to strings.



#!usr/bin/env/python
###############################################################################
mystr = "\n"        #a new line character.

mystr_raw=r"\n"     #two characters,\ and n.
print mystr_raw 
print "Length of mystr_raw:",len(mystr_raw),'\n'

###############################################################################
mystr_dq="Matthew 'Mark' Luke" #Single quote inside double quote.
print mystr_dq+"\n"            #'+' is used for adding(concatenating the strings.)

mystr_sq='Matthew "Mark" Luke' #dq(double quote) inside sq(single quote).
print mystr_sq+"\n"           

################################################################################
mystr_1_multiplelines="""These examples are
taken from pleac project.Really inspiring"""    #used triple double quotes.
print mystr_1_multiplelines+'\n'

mystr_2_multiplelines='''These examples are     
taken from pleac project.Really inspiring'''    #used triple single quotes.
print mystr_2_multiplelines+'\n'
################################################################################


Output:

\n
Length of mystr_raw: 2
Matthew 'Mark' Luke
Matthew "Mark" Luke
These examples are
taken from pleac project.Really inspiring
These examples are
taken from pleac project.Really inspiring



2.String Slicing.


#!usr/bin/env/python
"""Python strings are immutable once created they cann't be modified"""
mystr="Python is awesome!!!!"#P(0 or -21) y(1 or-20) t(2 or 19)....awesome(10,11,12,13,14,15,16 or -11,-10...-5 )
#     +012345678901234567890  Indexing forwards  (left to right)
#      109876543210987654321- Indexing backwards (right to left)
print'Printing..the full string ===>',mystr +'\n'

print mystr[0] +'\n'  #using forward indexing to print 'P'.
#Output:P
print mystr[-21]+'\n' #using backward indexing to print 'P'
#Output:P
print mystr[-1],mystr[len(mystr)-1]+'\n' #length=21,Since indexing is started at 0 we'll have one less 
#len(mystr)=lenght of the string.
""" 
mystr[a:b]
Case 1:Forward Indexing 
0<=a<b<=(len(mystr)-1)
mystr[a:b]==>Start from a till b-1
mystr[:b]==>assume a=0,start from a till b-1
mystr[a:]==>start from a till end.
Case2:Backward Indexing===>here we are using negative numbers,So do look
at couple of examples.
-len(mystr)<=a<b<=-1
"""
print mystr[0:5]+'\n' #start from 0 to 5-1==>(Pytho)
print mystr[1:]+'\n'  #start from one till end==>(ython is awesome!!!!)
print mystr[:18]+'\n' #start from 0 to 18-1==>(Python is awesome!)
print mystr[-20:-5]+'\n'#start from -20 till -5==>(ython is awesom)
#mystr[-5:-20] will return an empty string.
print mystr[-5:]+'\n' #start from -5(e) till end(!)===>(e!!!!)
print mystr[:-18]     #start from -21 till (-18-1=-19)===>(Pyt)

mystr = mystr[:9] + " easier than C" + mystr[17:]
print mystr
 

Output: 

Printing..the full string ===> Python is awesome!!!!
P
P
! !
Pytho
ython is awesome!!!!
Python is awesome!
ython is awesom
e!!!!
Pyt
Python is easier than C!!!!

3.String Methods.

 
#!usr/bin/env/python
"""String Methods """

mystr="Try 'import this' in your python interpreter"
print mystr.count('in')
#Counts number of occurences of 'in'.
#Output:2 
print mystr.find('i') # index of first occurence of i==&gt;5('i' in import)
print mystr.find('in')#index of first occurence of in==&gt;18(returns position of i in in i.e 18)
print mystr.find('in',19)#start from 19 and find first occurence of in
#There's an 'in' in interpreter.
print "Ajay".find('a')
#Output is 2

print "AJAY".lower()
#Return a copy of AJAY, but with upper case letters converted to lower case.
print "ajay".upper()

print mystr.replace("import this","import string")
#Dude strings do not change in python....but what happened right now?? It just return a copy of mystr.

print mystr
#mystr is same unmodified.

import string  #All string methods can be done like this.Try lower,upper and find in the simlar way.
print string.replace(mystr,"import this","import string")

"""Below are some useful oneline methods.
Replace str with a variable mystr or strings like "Ajay is dumb"."""

# str.capitalize()
print mystr.capitalize()
"""Return a copy of the string with its first character capitalized and the rest lowercased."""

"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""

#str.split()==&gt;Creates a list.

print "Ajay is dumb,idiot,mining engineer".split()
#Split after a whitespace(space)
#Output:['Ajay', 'is', 'dumb,idiot,mining', 'engineer']

print "Ajay is dumb,idiot,mining engineer".split(',')
#splits after a coma ',' and forms a list of words.
#Output:['Ajay is dumb', 'idiot', 'mining engineer']

print "Ajay is dumb,idiot,mining engineer".split(None,1)
#None is nothing but your telling to split after whitespace.but number of splits should be one.
#In place of None you can use ',' or anything.In place of 1 you can use any number
"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""
#str.strip()
#Return a copy of the string with the leading and trailing characters removed.
print "    Ajay loves space(white space)   ".strip()
#Output:Ajay loves space(white space)
print 'www.example.com'.strip('cmowz.')
#Output:example
#??? What happened let's try some more examples.
print 'www.example.com'.strip('cmoz.')
#Output:www.example
#'cmoz.'==&gt;'.comz'===&gt;'.com' can be removed because it's in a sequence.z is ignored.
print 'www.example.com'.strip('cmz.')
#Output:www.example.co
#'.cmz'==&gt;'m'==&gt;So m is removed.
"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""
#str.join
seq = ['1','2','3','4','5']   #'1','2'....are strings.
print '+'.join(seq)
#Output:1+2+3+4+5

print '*_*'.join("Ajay's blog is the dumbest".split())
#Output:Ajay's*_*blog*_*is*_*the*_*dumbest
#Just combined the split and join.To understand this first we did a split on the string.
# 1)"Ajay's blog is the dumbest".split() 
#2)later i joined the list elements using str.join

"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""
#str.partition
print("Python programmers are awesome :) ".partition('are'))
#Output:('Python programmers ', 'are', ' awesome :) ')
#It's gives a tuple of 3 elements.
#1)Everything before the partition element==&gt;here it's "Python programmers"
#2)Partition element itself.===&gt;'are'
#3)Everything after Partition element.==&gt;'awesome'

#Check out the original documentation for more examples and methods. 

Output:
2
5
18
33
2
ajay AJAY
Try 'import string' in your python interpreter
Try 'import this' in your python interpreter
Try 'import string' in your python interpreter
Try 'import this' in your python interpreter
['Ajay', 'is', 'dumb,idiot,mining', 'engineer']
['Ajay is dumb', 'idiot', 'mining engineer']
['Ajay', 'is dumb,idiot,mining engineer']
Ajay loves space(white space)
example
www.example
www.example.co
1+2+3+4+5
Ajay's*_*blog*_*is*_*the*_*dumbest
('Python programmers ', 'are', ' awesome :) ')

Check out the questions from SO,some day you gonna be same place so practice them.One more i missed here is string formatting,translate method which are important.I'll be posting when i'm free :)).

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Saturday, March 16, 2013

imap and map in python.

  •  The imap() function returns an "iterator" that calls a function on the values in the input
    iterators and returns the results.
  • Like map() but stops when the shortest iterable is exhausted instead
of filling in None for shorter iterables.The sentence is bit odd but let's go through it.

>>>from itertools import *
>>> list(imap(pow, xrange(10), count()))
[1, 1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489]


  1. pow is a builtin function which caluclates power of two numbers(pow(2,5==>2**5==>32)
  2. In the above example we passed 3 arguments,1 pow function,xrange(10) ,count.
  3. imap maps the power function over those other two arguments.This is equivalent to pow(xrange(10),count())
  4. xrange(10) will exhaust after 10 values,despite count() being infinite iteration it stops because xrange(10) has exhausted.
  5. we make a list of all the powers by calling list()
  6.  
Input:
#!usr/bin/env/python
from itertools import *
#Using imap from itertools.
print 'Triples:'
for i in imap(lambda x:3*x,xrange(5)):
    print i
print "\nMultiples:"
for i in imap(lambda x,y:(x, y, x*y), xrange(5), xrange(5,10)):
    print '%d * %d = %d' % i
print "\n Zip"
print list(map(pow, xrange(10), count()))
Output:
Triples:
0
3
6
9
12

Multiples:
0 * 5 = 0
1 * 6 = 6
2 * 7 = 14
3 * 8 = 24
4 * 9 = 36

 Zip
Traceback (most recent call last):
  File "/home/ubuntu/Desktop/map_imap.py", line 11, in 
    print list(map(pow, xrange(10), count()))
TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int'
[Finished in 0.2s with exit code 1]
The error is expected because count() is infinite iteration,but xrange() is exhausted so it can't perform operations which have "None" argument.
     











Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Iterables and Generators,yield explained

http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained
This would be the best explanation.

To understand what yield does, you must understand what generators are. And before generators come iterables.

Iterables

When you create a list, you can read its items one by one, and it's called iteration:
>>> mylist = [1, 2, 3]
>>> for i in mylist:
...    print(i)
1
2
3
Mylist is an iterable. When you use a comprehension list, you create a list, and so an iterable:
>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
...    print(i)
0
1
4
Everything you can use "for... in..." on is an iterable: lists, strings, files... These iterables are handy because you can read them as much as you wish, but you store all the values in memory and it's not always what you want when you have a lot of values.

Generators

Generators are iterables, but you can only read them once. It's because they do not store all the values in memory, they generate the values on the fly:
>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
...    print(i)
0
1
4
It just the same except you used () instead of []. BUT, you can not perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1 and ends calculating 4, one by one.

Yield

Yield is a keyword that is used like return, except the function will return a generator.
>>> def createGenerator():
...    mylist = range(3)
...    for i in mylist:
...        yield i*i
...
>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
...     print(i)
0
1
4
Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.
To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is bit tricky :-)
Then, your code will be run each time the for uses the generator.
Now the hard part:
The first time your function will run, it will run from the beginning until it hits yield, then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return.
The generator is considered empty once the function runs but does not hit yield anymore. It can be because the loop had come to ends, or because you do not satisfy a "if/else" anymore.