Tuesday, 25 November 2014

jQuery Location Autocomplete with Google Maps Places

This is a simple jQuery plugin that enables you to pick a place/address/location from a dropdown suggestion box and display the place on the Google Maps, based on Google Maps API's places library.

HTML+Javascript Code


  
    

    placepicker

    

    
    
    
    

    

    

    

    

  

  

    

jquery-placepicker

A simple placepicker component for the google-maps api.

Basic usage

Set value by location coordinates

Use hidden inputs for submitting location coordinates

Integrating a map view

Advanced usage

Custom map CSS class and JavaScript callback

If you want this plugin. Download from here.
Download


OR

Another Google map Api code is there. you can use it also.

HTML+Javascript Code

  
    Place Autocomplete
    
    
    
    

    
  
  
    
    

Wednesday, 5 November 2014

What is difference between MYISAM and InnoDB?

I am writing this article to understand the difference between MYISAM and INNODB.

MYISAM:
1. MYISAM supports Table-level Locking
2. MyISAM designed for need of speed
3. MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
4. MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
5. MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.

INNODB:
1. InnoDB supports Row-level Locking
2. InnoDB designed for maximum performance when processing high volume of data
3. InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
4. InnoDB stores its tables and indexes in a tablespace
5. InnoDB supports transaction. You can commit and rollback with InnoDB

Saturday, 18 October 2014

What is MongoDB and how to install MongoDB?

"MongoDB is an open-source document database that provides high performance, high availability, and easy scalability. Documents (objects) map nicely to programming language data types. Embedded documents and arrays reduce need for joins."

Other words:

"A MongoDB deployment hosts a number of databases. database holds a set of collections. collection holds a set of documents.document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data."

Document Database

A record in MongoDB is a document, which is a data structure composed of field (Key) and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.A MongoDB document.

{
  "name":"Rossum",
  "age":54,
  "status":true,
  "groups":["news","sports"],
}

The advantages of using documents are:

  • Documents (i.e. objects) correspond to native data types in many programming languages.
  • Embedded documents and arrays reduce need for expensive joins.
  • Dynamic schema supports fluent polymorphism.
  • It is in document (Json) format, so there is no problem with join tables that’s why it’s speed is very fast rather then other database like Msql, Sqlserver and others.

Key Features

·         High Performance
·         High Availability
·         Automatic Scaling
·         Flexibility
·         Ease of use
·         Power

Installation of  MongoDB

First download mongoDB for different OS then go through below steps

Install on Windows

MongoDBDownload- 64-bit zip | msi
MongoDB Download- 32-bit zip | msi
MongoDB Download- 64-bit legacy zip | msi

Install on Linux

Install on Mac

Install on Solarisis


If you want previous release then click on below link

Steps:

  • Now download it and extract it in any directory for linux, mac, solorisis and install msi for windows.
  • Open terminal and go through same directory where mongoDB extract by cd command
  • Type this command  Python setup.py install

Now MongoDB is installed successfully . If you want to see mongodb UI interface then download below download and install the  it will show UI interface on your system for MongoDB.

Robomongo-this is for MongoDB UI interface. There are number of UI interface but according to me it’s good.


Monday, 13 October 2014

How to change root password for mysql and phpmyadmin

It depends on your configuration. Follow the instruction below to reconfigure phpmyadmin, and reset MySQL password.

  1. Ctrl + Alt + T to launch terminal
  2. sudo dpkg-reconfigure phpmyadmin
  3. Connection method for MySQL database for phpmyadmin: unix socket
  4. Name of the database's administrative user: root
  5. Password of the database's administrative user: mysqlsamplepassword
  6. MySQL username for phpmyadmin: root
  7. MySQL database name for phpmyadmin: phpmyadmin
  8. Web server to reconfigure automatically: apache2
  9. ERROR 1045
  10. ignore
  11. sudo dpkg-reconfigure mysql-server-5.5
  12. New password for the MySQL "root" user: mysqlsamplepassword
  13. Repeat password for the MySQL "root" user: mysqlsamplepassword
  14. After all this run following command on terminal to secure your mysql server. sudo mysql_secure_installation
  15. Enter current password for root (enter for none): mysqlsamplepassword
  16. Change the root password? [Y/n] n
  17. Remove anonymous users? [Y/n] y
  18. Disallow root login remotely? [Y/n] y
  19. Remove test database and access to it? [Y/n] y
  20. Reload privilege tables now? [Y/n] y
Wish it helps!

Thanks

Thursday, 2 October 2014

Read any system's drive data in network using python

By wmi module it's not possible to read all files of network system but we can read by two ways.

1) Mount remote system drive in to your local system.
2) set netuse virtual connection and access to read files.

For mounting remote system drive in your local system, use below code
import win32api
import win32net
import win32netcon,win32wnet

username='user'
password='psw'

try:
    win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, 'Z:','\\\\192.168.1.18\\D$', None, username,password, 0)
    print "connection established successfully"
except:
    print  "connection not established"

 

After connection you can read all files data
 

for root, dirnames, filenames in os.walk('\\\\192.168.1.18\D$'):
        for filename in filenames:
            match=os.path.join(root, filename)
            datafile = file(match)
            for line in datafile:
               print line


2) for set virtual connection use below code
 

import win32api
import win32net

ip = '192.168.1.18'
username = 'ram'
password = 'ram@123'

try:
    use_dict={}
    use_dict['remote']=unicode('\\\\192.168.1.18\C$')
    use_dict['password']=unicode(password)
    use_dict['username']=unicode(username)
    win32net.NetUseAdd(None, 2, use_dict)
except:
    print  "connection not established"


Hi Guys if these all post are helpful for you then please follow my blog through google plus or Facebook, I will share other useful post for you . If you have any feedback for me please share it.

Thanks guys for your support.

Python urllib2 post request

We can post a request through urllib with parameter. we can also encode a dict using urllib like this:

See below code :
import urllib
import urllib2

url = 'http://example.com/...'
values = { 'productslug': 'bar','qty': 'bar' }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()
print result


You can encode value through urlencode and send it securely by requested url.  you can also send data without encryption. It will execute url request and return response.


Hi Guys if these all post are helpful for you then please follow my blog through google plus or facebook, I will share other useful post for you . If you have any suggestion for me please share to me.

Thanks guys for your support.

Wednesday, 1 October 2014

Upload or send file to ftp server in python

you can send or upload any file to ftp server very easy using python. In below code i have used ftplib module for sending files.

use below code and run it.


import ftplib
def send_File(file, user, pwd):
    ftp = ftplib.FTP("ftp.example.com")
    ftp.login(user, pwd)
    ftp.storlines("STOR " + file, open(file))
send_File("users.txt","username","password")

Thank you guys for your support.

Using the urllib Module to Fetch a Remote Resource

If you want to read html content of any site or any js, css, other files also then use below code it will show all files content. Only you have to provide the url and some time if you want to read any js, css file which is present any root path then give "domain_name.com/path_of_any_file/", it will show that file content.

import urllib
import sys
f = urllib.urlopen("http://www.google.com")
while 1:
    buf = f.read(2048)
    if not len(buf):
        break
    sys.stdout.write(buf)


Thank you guys for your support.

How to read website html, css, js files using python

If you want to read html content of any site or any js, css, other files also then use below code it will show all files content. Only you have to provide the url and some time if you want to read any js, css file which is present any root path then give "domain_name.com/path_of_any_file/", it will show that file content.

import urllib
import sys
f = urllib.urlopen("http://www.google.com")
while 1:
    buf = f.read(2048)
    if not len(buf):
        break
    sys.stdout.write(buf)


Thank you guys for your support.

How to Read POP3 E-mail messages from accounts using python

Use below code for reading POP3 emails from any account.


import poplib
import getpass
serveur = poplib.POP3('mail.example.com')
#User Authentication
serveur.user(getpass.getuser())
serveur.pass_(getpass.getpass())
# Get message count
nbr_message = len(serveur.list()[1])
# print message subjects
for elem in range(nbr_message) :
    for msg in serveur.retr(elem+1)[1]:
        if msg.startswith('Subject'):
            print msg
            break
serveur.quit()

Thank you guys for your support.

How to Extract list of URLs in a web page using python

I think this post is very useful for finding the url for downloading and extracting url using python code.
Here I am using "sgmllib" python built in module for finding urls.

Use below code and run it with any urls


__author__ = "Ashish jain (example@gmail.com)"
__version__ = "$Revision: 1.0 $"
__date__ = "$Date: 2014/10/01 21:57:19 $"
__license__ = "Python"
from sgmllib import SGMLParser
class URLLister(SGMLParser):
  def reset(self):
    SGMLParser.reset(self)
    self.urls = []
  def start_a(self, attrs):
    href = [v for k, v in attrs if k=='href']
    if href:
      self.urls.extend(href)
if __name__ == "__main__":
  import urllib
  usock = urllib.urlopen("http://diveintopython.net/")
  parser = URLLister()
  parser.feed(usock.read())
  parser.close()
  usock.close()
  for url in parser.urls:
   print url

Thank you guys for your support.

How to read email message from .msg file

For reading the .msg file, I am using python built in library "email". you can read .msg file by below code.

import email
def read_MSG(file):
    email_File = open(file)
    messagedic = email.Message(email_File)
    content_type = messagedic["plain/text"]
    FROM = messagedic["From"]
    TO = messagedic.getaddr("To")
    sujet = messagedic["Subject"]
    email_File.close()
    return content_type, FROM, TO, sujet
myMSG= read_MSG("client.msg")
print myMSG

Thank you guys for your support.

Tuesday, 30 September 2014

error: command 'gcc' failed with exit status 1 or status 4

You are getting this error because of gcc library which is not present in your system. If you get above error in ubuntu or windows then follow below step.

For Ubuntu or linux system, Install all library

sudo apt-get install libxml2
sudo apt-get install libxslt1.1
sudo apt-get install libxml2-dev
sudo apt-get install libxslt1-dev
sudo apt-get install python-libxml2
sudo apt-get install python-libxslt1
sudo apt-get install python-dev
sudo apt-get install python-setuptools

easy_install lxml

It has worked for my ubuntu 12.10 100% sure.

If you have windows system then try to download below msi file and install it. It will install gcc library and now you can reosolve this error.

It tries to fix all the problems with compiling Python distutils extensions with GCC (the good ol' MSVCR71.DLL problem, if you know what I am speaking of). See below for details, but it really should Just Works(TM). Using GCC, it is possible to produce extensions (.pyd) which are fully compatible with the official python.org distribution (so, they can be mix'n'matched with extensions compiled with Visual Studio).

Download the package here: Gcc-mingw-4.3.3 exe

It's GPL licensed (do I really need to say that?)

It contains:
    GCC 4.3.3-tdm-1 (http://www.tdragon.net/recentgcc/)
    binutils 2.19.1
    mingw32-make 3.81-2
    mingwrt 3.16
    w32api 3.13

What does the installer do?

    Copies the binary files to run GCC.
    Install the gccmrt script (see below).
    Optionally modify the environment PATH.
    Optionally configures an existing Python installation to use GCC for distutils.

If your Problem is not resolving with above solution then try to install (http://sourceforge.net/projects/mingw/files/Installer/), but i am not sure this solution will work for you or not.

Thanks guys for your support.

How to send SMS/MMS with Twilio using python

Sending an SMS (Short Message Service) message via Twilio is really easy. You will need to look in your Twilio account to get the sid and authentication token as well as your twilio number. Once you have those three pieces of key information, you can send an SMS message.


you’ll need to sign up on Twilio(https://www.twilio.com/try-twilio/) and you’ll also need to install the Python twilio wrapper. To install the latter, just do the following:
 
pip install twilio

 
so you can send message by this site through your python programing code. Now after creating account take SID auth token number and twillio number, fill these in below code and run it.

 

Sending SMS only

from twilio.rest import TwilioRestClient
 
#----------------------------------------------------------------------
def send_sms(msg, to):
    """"""
    sid = "text-random"
    auth_token = "youAreAuthed"
    twilio_number = "123-456-7890"
 
    client = TwilioRestClient(sid, auth_token)
 
    message = client.messages.create(body=msg,
                                     from_=twilio_number,
                                     to=to,
                                     )
if __name__ == "__main__":
    msg = "Hello from Python!"
    to = "111-111-1111"
    send_sms(msg, to)

Sending an MMS Message

import configobj
from twilio.rest import TwilioRestClient

#----------------------------------------------------------------------
def send_mms(msg, to, img):
    """"""
    cfg = configobj.ConfigObj("/path/to/config.ini")
    sid = cfg["twilio"]["sid"]
    auth_token = cfg["twilio"]["auth_token"]
    twilio_number = cfg["twilio"]["twilio_number"]

    client = TwilioRestClient(sid, auth_token)

    message = client.messages.create(body=msg,
                                     from_=twilio_number,
                                     to=to,
                                     MediaUrl=img
                                     )

if __name__ == "__main__":
    msg = "Hello from Python!"
    to = "111-111-1111"
    img = "http://www.website.com/example.jpg"
    send_mms(msg, to=to, img=img)




 

Thanks guys for your support.

Create Shortcuts using python for windows

I’ve been tasked with creating shortcuts to new applications that need to be placed on the user’s desktop or in their Start Menu or both. In this article, I will show you how to accomplish this task.
I also recommend Tim Golden’s winshell module for creating desktop icon, download winshell for windows from here winshell.

Run below script, it will create desktop shortcut icon.

 import os, winshell
 
desktop = winshell.desktop()
path = os.path.join(desktop, "myNeatWebsite.url")
target = "http://www.google.com/"
 
shortcut = file(path, 'w')
shortcut.write('[InternetShortcut]\n')
shortcut.write('URL=%s' % target)
shortcut.close()

Now check on desktop and click on desktop shortcut icon for executing.

Or you can create shortcut icon by Pythoncom module

  import os, sys
 import pythoncom
 win32com.shell import from shell, shellcon

 shortcut = pythoncom. CoCreateInstance (
   shell. CLSID_ShellLink,
   None,
   pythoncom. CLSCTX_INPROC_SERVER,
   shell. IID_IShellLink
 )
 program_location = R'c: \ Program Files \ SomeCoolProgram \ PROG.EXE '
 shortcut. SetPath (program_location)
 shortcut. SetDescription ("My Program Does Something Really Cool!")
 shortcut. SetIconLocation (program_location, 0)

 desktop_path = shell. SHGetFolderPath (0, shellcon. CSIDL_DESKTOP, 0, 0)
 persist_file = shortcut. QueryInterface (pythoncom. IID_IPersistFile)
 persist_file. Save (os. path. join (desktop_path, "My shortcut.lnk"), 0)

The next example, we will use the win32com module from the PyWin32 package to create a shortcut to Media Player Classic, which is a nice open-source media player.

 import os, winshell
from win32com.client import Dispatch

desktop = winshell.desktop()
path = os.path.join(desktop, "Media Player Classic.lnk")
target = r"P:\Media\Media Player Classic\mplayerc.exe"
wDir = r"P:\Media\Media Player Classic"
icon = r"P:\Media\Media Player Classic\mplayerc.exe"

shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = icon
shortcut.save()


 Thanks guys for your support.

Monday, 16 June 2014

Send email with Outlook in Python

We can send email by outlook with filling all details by python code. and we can implement send email functionality in our project easily.

First we have to give details like from, to  subject and attachment then this all details will be filled in outlook with python code. please see the below code.


import win32com.client
from win32com.client import Dispatch, constants
 
const=win32com.client.constants
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "I AM SUBJECT!!"
newMail.Body = "I AM IN THE BODY\nSO AM I!!!"
newMail.To = "abc@abc.com"
attachment1 = r"E:\test\logo.png"

newMail.Attachments.Add(Source=attachment1)
newMail.display()

#newMail.send()

How to send email with attachments in python

Send email functionality is very useful functionality. for this we have to configured server configuration as your web email configuration.

If you have gmail email SMTP configuration then you have to configured as below with Send email functionality.


                
                import smtplib, os
                from email.mime.text import MIMEText
                from email.mime.multipart import MIMEMultipart
                from email.mime.base import MIMEBase
                from email import Encoders
 
                gmail_user = "ashish@example.com"
                gmail_name = "Ashish "
                gmail_pwd = "example@123"
                name='Ashish'
                attach='E:/test/test.pdf'
                body ="Dear %s ,\n\nPlease find the attached files.\n\nThanks and Regards:\nAshish" % (name)
                msg = MIMEMultipart()
                msg['From'] = gmail_name
                msg['To'] = "ashish1@example.com"
                msg['Subject'] = "Send email with attachment"
                msg.attach(MIMEText(body))
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(attach))
                msg.attach(part)
                mailServer = smtplib.SMTP("smtp.gmail.com", 25)
                mailServer.ehlo()
                mailServer.starttls()
                mailServer.ehlo()
                mailServer.login(gmail_user, gmail_pwd)
                mailServer.sendmail(gmail_name, "ashish1@example.com", msg.as_string())   # name + e-mail address in the From: field
                mailServer.close()

Sunday, 15 June 2014

Read zip files in python


We can read all the files without extracting zip file easily. and we can read line by line in zip files.

Script
try:
   root = zipfile.ZipFile("C:\Python27\Project\Rokar.zip", "r")
except:
   root = "." 
data=[]
for name in root.namelist()

       for line in root.read(name):
           data.append(line)
print ''.join(data)


or
try:
   root = zipfile.ZipFile("C:\Python27\Project\Rokar.zip", "r")
except:
   root = "."  

with root as z:

   with z.open('manage.py') as f:

       for line in f:

           print line

Saturday, 14 June 2014

Find MAC address of system in python



Simple we can find mac addresses by socket connection and netifaces library. first you have to download this library from given below link according to python version and OS .

https://pypi.python.org/pypi/netifaces#downloads



from socket import *
import netifaces as nif
def mac_for_ip(ip):
    'Returns a list of MACs for interfaces that have given IP, returns
None if not found'
    for i in nif.interfaces():
        addrs = nif.ifaddresses(i)
        try:
            if_mac = addrs[nif.AF_LINK][0]['addr']
            if_ip = addrs[nif.AF_INET][0]['addr']
        except IndexError, KeyError: #ignore ifaces that dont have MAC or IP
            if_mac = if_ip = None
        if if_ip == ip:
            return if_mac
    return None

print mac_for_ip(gethostbyname_ex(gethostname())[2][0])

 
Output : 1e:23:3j:49:8b