code:
""" invdisttree.py: inverse-distance-weighted interpolation using KDTree
    fast, solid, local
"""
from __future__ import division
import numpy as np
from scipy.spatial import cKDTree as KDTree
    # http://docs.scipy.org/doc/scipy/reference/spatial.html

__date__ = "2010-11-09 Nov"  # weights, doc

#...............................................................................
class Invdisttree:
    """ inverse-distance-weighted interpolation using KDTree:
invdisttree = Invdisttree( X, z )  -- data points, values
interpol = invdisttree( q, nnear=3, eps=0, p=1, weights=None, stat=0 )
    interpolates z from the 3 points nearest each query point q;
    For example, interpol[ a query point q ]
    finds the 3 data points nearest q, at distances d1 d2 d3
    and returns the IDW average of the values z1 z2 z3
        (z1/d1 + z2/d2 + z3/d3)
        / (1/d1 + 1/d2 + 1/d3)
        = .55 z1 + .27 z2 + .18 z3  for distances 1 2 3

    q may be one point, or a batch of points.
    eps: approximate nearest, dist <= (1 + eps) * true nearest
    p: use 1 / distance**p
    weights: optional multipliers for 1 / distance**p, of the same shape as q
    stat: accumulate wsum, wn for average weights

How many nearest neighbors should one take ?
a) start with 8 11 14 .. 28 in 2d 3d 4d .. 10d; see Wendel's formula
b) make 3 runs with nnear= e.g. 6 8 10, and look at the results --
    |interpol 6 - interpol 8| etc., or |f - interpol*| if you have f(q).
    I find that runtimes don't increase much at all with nnear -- ymmv.

p=1, p=2 ?
    p=2 weights nearer points more, farther points less.
    In 2d, the circles around query points have areas ~ distance**2,
    so p=2 is inverse-area weighting. For example,
        (z1/area1 + z2/area2 + z3/area3)
        / (1/area1 + 1/area2 + 1/area3)
        = .74 z1 + .18 z2 + .08 z3  for distances 1 2 3
    Similarly, in 3d, p=3 is inverse-volume weighting.

Scaling:
    if different X coordinates measure different things, Euclidean distance
    can be way off.  For example, if X0 is in the range 0 to 1
    but X1 0 to 1000, the X1 distances will swamp X0;
    rescale the data, i.e. make X0.std() ~= X1.std() .

A nice property of IDW is that it's scale-free around query points:
if I have values z1 z2 z3 from 3 points at distances d1 d2 d3,
the IDW average
    (z1/d1 + z2/d2 + z3/d3)
    / (1/d1 + 1/d2 + 1/d3)
is the same for distances 1 2 3, or 10 20 30 -- only the ratios matter.
In contrast, the commonly-used Gaussian kernel exp( - (distance/h)**2 )
is exceedingly sensitive to distance and to h.

    """
# anykernel( dj / av dj ) is also scale-free
# error analysis, |f(x) - idw(x)| ? todo: regular grid, nnear ndim+1, 2*ndim

    def __init__( self, X, z, leafsize=10, stat=0 ):
        assert len(X) == len(z), "len(X) %d != len(z) %d" % (len(X), len(z))
        self.tree = KDTree( X, leafsize=leafsize )  # build the tree
        self.z = z
        self.stat = stat
        self.wn = 0
        self.wsum = None;

    def __call__( self, q, nnear=6, eps=0, p=1, weights=None ):
            # nnear nearest neighbours of each query point --
        q = np.asarray(q)
        qdim = q.ndim
        if qdim == 1:
            q = np.array([q])
        if self.wsum is None:
            self.wsum = np.zeros(nnear)

        self.distances, self.ix = self.tree.query( q, k=nnear, eps=eps )
        interpol = np.zeros( (len(self.distances),) + np.shape(self.z[0]) )
        jinterpol = 0
        for dist, ix in zip( self.distances, self.ix ):
            if nnear == 1:
                wz = self.z[ix]
            elif dist[0] < 1e-10:
                wz = self.z[ix[0]]
            else:  # weight z s by 1/dist --
                w = 1 / dist**p
                if weights is not None:
                    w *= weights[ix]  # >= 0
                w /= np.sum(w)
                wz = np.dot( w, self.z[ix] )
                if self.stat:
                    self.wn += 1
                    self.wsum += w
            interpol[jinterpol] = wz
            jinterpol += 1
        return interpol if qdim > 1  else interpol[0]

#...............................................................................
if __name__ == "__main__":
    import sys

    N = 10000
    Ndim = 2
    Nask = N  # N Nask 1e5: 24 sec 2d, 27 sec 3d on mac g4 ppc
    Nnear = 8  # 8 2d, 11 3d => 5 % chance one-sided -- Wendel, mathoverflow.com
    leafsize = 10
    eps = .1  # approximate nearest, dist <= (1 + eps) * true nearest
    p = 1  # weights ~ 1 / distance**p
    cycle = .25
    seed = 1

    exec "\n".join( sys.argv[1:] )  # python this.py N= ...
    np.random.seed(seed )
    np.set_printoptions( 3, threshold=100, suppress=True )  # .3f

    print "\nInvdisttree:  N %d  Ndim %d  Nask %d  Nnear %d  leafsize %d  eps %.2g  p %.2g" % (
        N, Ndim, Nask, Nnear, leafsize, eps, p)

    def terrain(x):
        """ ~ rolling hills """
        return np.sin( (2*np.pi / cycle) * np.mean( x, axis=-1 ))

    known = np.random.uniform( size=(N,Ndim) ) ** .5  # 1/(p+1): density x^p
    z = terrain( known )
    ask = np.random.uniform( size=(Nask,Ndim) )

#...............................................................................
    invdisttree = Invdisttree( known, z, leafsize=leafsize, stat=1 )
    interpol = invdisttree( ask, nnear=Nnear, eps=eps, p=p )

    print "average distances to nearest points: %s" % \
        np.mean( invdisttree.distances, axis=0 )
    print "average weights: %s" % (invdisttree.wsum / invdisttree.wn)
        # see Wikipedia Zipf's law
    err = np.abs( terrain(ask) - interpol )
    print "average |terrain() - interpolated|: %.2g" % np.mean(err)

    # print "interpolate a single point: %.2g" % \
    #     invdisttree( known[0], nnear=Nnear, eps=eps )

rawDescription: Inverse Distance Weighted (IDW) Interpolation with Python


code:
def group(lst, limit):

    lim = 0
    grp = []

    for x in lst:
        if x + lim > limit:
            yield grp
            grp = []
            lim = 0

        grp.append(x)
        lim += x

    yield grp

print list(group([1, 1, 1, 1, 2, 2, 1, 3, 1, 1, 2], 3))

rawDescription: Group list by sum of items

description: Group list by sum of items


code:
with open("textfile.txt") as openfile:
    for line in openfile:
        for part in line.split():
            if "color=" in part:
                print part

rawDescription: How to search for word in text file and print part of line with Python?

description: Search for word in text file and print part of line with Python


code:
with open('input.txt') as input_file:
    result = input_file.read().split('===\n')
print result

rawDescription: Python - extract lines between multiple instances of the same delimiter


code:
import urllib
import lxml.html

fd = urllib.urlopen('http://epaper.derstandarddigital.at/')
doc = lxml.html.parse(fd)
matches = doc.xpath('//img[@id="imgPage2]')
if matches:
  print matches[0].get('src')

rawDescription: get image from website

description: Get image from website


code:
for idx, val in enumerate(df.count):
    print val

    # Get the index of this row
    d = df.iloc[idx].name

rawDescription: Plotting multiindex pandas DataFrame with matplotlib


code:
import datetime, time, threading, os

def clock():
    now = datetime.datetime.now()
    print now.strftime('%H:%M')

def set_alarm():
    alarm_time = raw_input('Set Alarm (XX:XX) : ')
    alarm_hour = alarm_time[:alarm_time.find(':')]
    alarm_minute = alarm_time[alarm_time.find(':')+1:]
    alarm_thread = threading.Thread(target=alert_thread, args=(alarm_time, alarm_hour, alarm_minute))
    alarm_thread.start()

def alert_thread(alarm_time, alarm_hour, alarm_minute):
    print "Ringing at {}:{}".format(alarm_hour, alarm_minute)
    while True:
        now = datetime.datetime.now()
        if str(now.hour) == str(alarm_hour) and str(now.minute) == str(alarm_minute):
            print ("Ring.. Ring..")
            break

#program start here
while True:
    now = datetime.datetime.now()
    print '1) Clock'
    print '2) Alarm'
    print '3) Quit'
    choice = input('Choose (1-6) : ')

    if(choice==1):
        clock()
    elif(choice==2):
        set_alarm()
    elif(choice==3):
        break

rawDescription: Command line multithreading

description: Command line multithreading


code:
import sys

if "matplotlib" in sys.modules:
   # Do something
   print
   print "This seems to be working"

rawDescription: How do I load and run specific packages when I launch 'matplotlib'?

description: Load and run specific packages when I launch 'matplotlib'


code:
import fileinput

headers = 'a b c d e'.split()
for line in fileinput.input(['thefile.blah'], inplace=True):
    if fileinput.isfirstline():
        print '\t'.join(headers)
    print line,

rawDescription: Add headers to a file

description: Add headers to a file


code:
tpl = """

Hello {name}

"""
print tpl.format(name="World")

rawDescription: python best way to output larges amount of formatted text

description: Python best way to output larges amount of formatted text


code: for x in my_list: print x.name, x.id

rawDescription: Python Parse List

description: Python Parse List


code:
from multiprocessing import Process

def f(name):
    print 'hello', name

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    #p.join()

rawDescription: fabric run fork

description: Fabric run fork


code:
import sys
import unittest
from cStringIO import StringIO

import nose
from nose.result import _TextTestResult

class TestRunner(unittest.TextTestRunner):
    def _makeResult(self):
        self.result = _TextTestResult(
            self.stream, self.descriptions, self.verbosity)
        return self.result

def count_unit_tests(module_name):
    stream = StringIO()
    runner = TestRunner(stream=stream)

    result = nose.run(
        testRunner=runner,
        argv=[sys.argv[0],
              module_name,
              '-s',
              '-v',
              '--collect-only'
        ]
    )

    return runner.result.testsRun

if __name__ == '__main__':
    print count_unit_tests('.')

rawDescription: Count and return number of nosetests

description: Count and return number of nosetests


code:
ss=['01010100','10010101010','010101110101010101'] #encoded message

from bitstring import BitArray,BitStream
print 'write it to file'
with open('binary.bin','wb') as f:
    s=''.join(ss);
    b=BitArray(bin=s)
    f.write(b.tobytes())# thanks to Scott, tobytes() method is very useful

print 'read it to file'
b=BitArray(filename='binary.bin')
print b.bin

rawDescription: convert huffman code string to binary

description: Convert huffman code string to binary


code:
g = d.hit.groupby([d.experiment, d.treatment, d.replicate]).value_counts().unstack().reset_index()
print g
print g.fillna(0).groupby(['experiment', 'treatment']).mean()

rawDescription: Calculating means in replicates using groupby


code:
from subprocess import Popen, PIPE

# Run "cat", which is a simple Linux program that prints it's input.
process = Popen(['/bin/cat'], stdin=PIPE, stdout=PIPE)
process.stdin.write('Hello\n')
print repr(process.stdout.readline()) # Should print 'Hello\n'
process.stdin.write('World\n')
print repr(process.stdout.readline()) # Should print 'World\n'

# "cat" will exit when you close stdin.  (Not all programs do this!)
process.stdin.close()
print 'Waiting for cat to exit'
process.wait()
print 'cat finished with return code %d' % process.returncode

rawDescription: Keep a subprocess alive and keep giving it commands? Python


code:
import ipaddr
from elasticsearch import Elasticsearch
es = Elasticsearch(['http://localhost:9200'])
pm = es.indices.put_mapping

es.indices.delete(index='ips', ignore=[400, 404])
es.indices.create(index='ips', ignore=400)

pm(index='ips', doc_type='ip',
   body={
         "ip":{
               "properties":{
                             "ipv4":{"type":"nested",
                                     "properties":{
                                                   "first":{"type":"integer" },
                                                   "last":{"type":"integer" }
                                                   }
                                    },
                             "ipv6":{"type":"nested",
                                     "properties":{
                                                   "lofirst":{"type":"long" },
                                                   "lolast":{"type":"long" },
                                                   "hifirst":{"type":"long" },
                                                   "hilast":{"type":"long" }
                                                   }
                                    }
                           }
            }
     }
)

def cidrtoes(ip):
    '''
    Convert IP address or network to ES-stored format

    :param ip: IPv4 or IPv6 address or network in CIDR notation
    :returns: dictionary which can be added to ES document
    '''
    ipnet = ipaddr.IPNetwork(ip)
    if ipnet.version == 4:
        s = {'first':int(ipnet) - 2 ** 31,
             'last':int(ipnet[-1]) - 2 ** 31}
    elif ipnet.version == 6:
        s = {'lofirst':(int(ipnet) & 2 ** 64 - 1) - 2 ** 63,
             'lolast':(int(ipnet[-1]) & 2 ** 64 - 1) - 2 ** 63,
             'hifirst':(int(ipnet) >> 64) - 2 ** 63,
             'hilast':(int(ipnet[-1]) >> 64) - 2 ** 63}
    return s

def ip4toes(address):
    '''
    Convert IPv4 address to ES-stored format

    :param address: IPv4 address
    :returns: IPv4 converted to signed integer
    '''
    ip = ipaddr.IPAddress(address)
    return int(ip) - 2 ** 31

def ip6toes(address):
    '''
    Convert IPv6 address to ES-stored format

    :param address: IPv6 address
    :returns: IPv6 address converted to low and high 64 bit signed integers
    '''
    ip = ipaddr.IPAddress(address)
    return [(int(ip) & 2 ** 64 - 1) - 2 ** 63, (int(ip) >> 64) - 2 ** 63 ]

doc = {'ipv4':[cidrtoes('0.0.0.0/24'), cidrtoes('0.0.1.0/24'), cidrtoes('255.255.255.255')],
       'ipv6':[cidrtoes('::/64'), cidrtoes('1::/64'), cidrtoes('2::3')],
       }

es.index(index="ips", doc_type="ip", body=doc)
es.indices.flush(index="ips")

# IPv4 query
ip = '0.0.1.0'
searchip = ip4toes(ip)

s = es.search(index='ips', doc_type='ip', body=
{"query":{
          "filtered":{
                      "filter":{'nested':{
                                          'path':'ipv4',
                                          'filter':{
                                                    'and':[
                                                           {"range": {"first": {'lte':searchip}}},
                                                           {"range": {"last": {'gte':searchip}}},
                                                           ]
                                                    }
                                          }
                                }
                      }
          }
          }
              )

print "IPv4 result", s

# IPv6 query
ip = '2::3'
lo = ip6toes(ip)[0]
hi = ip6toes(ip)[1]

s = es.search(index='ips', doc_type='ip', body=
{"query":{
          "filtered":{
                      "filter":{'nested':{
                                          'path':'ipv6',
                                          'filter':{
                                                    'and':[
                                                           {"range": {"lofirst": {'lte':lo}}},
                                                           {"range": {"lolast": {'gte':lo}}},
                                                           {"range": {"hifirst": {'lte':hi}}},
                                                           {"range": {"hilast": {'gte':hi}}},
                                                           ]
                                                    }
                                          }
                                }
                      }
          }
          }
              )

print "IPv6 result", s

rawDescription: How can I store and search multiple IPv4 and IPv6 subnets in elasticsearch?

description: Store and search multiple IPv4 and IPv6 subnets in elasticsearch


code:
counts = {}
for row in table:
    # use the `get` method of a dict with the optional `d` argument
    # set to 0 (see ">>> help(dict.get)" if get is new for you)
    counts[row[2]] = counts.get(row[2],0) + 1

for row in table:
    print formatter(row,counts[row[2]])

rawDescription: I want to print the occurance count of column3 in front of it as shown below


code:
from geopy import geocoders
g = geocoders.Google(GOOGLE_MAPS_API_KEY)
(place, point) = g.geocode('Eiffel Tower, Paris')
print point

rawDescription: Get physical map location of object based off user input


code:
import wx

class Myframe(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        pan = wx.Panel(self)
        self.cbx = wx.ComboBox(pan, -1, pos=(10,30),
                                choices=["SEARCH", "SELECT",
                                         "PASS", "LOG", "DATABASE"],
                                style=wx.CB_DROPDOWN )
        self.cbx_2 = wx.ComboBox(pan, -1, pos=(10,60),
                            choices=["LOOK", "GO", "FILL"],
                            style=wx.CB_DROPDOWN )

        self.cbx.Bind(wx.EVT_MOUSEWHEEL, self.do_nothing)
        self.cbx.Bind(wx.EVT_COMBOBOX, self.on_selection)
        self.cbx_2.Bind(wx.EVT_MOUSEWHEEL, self.do_nothing)
        self.cbx_2.Bind(wx.EVT_COMBOBOX, self.on_selection_2)

    def on_selection(self, evt):
        """I do not want this to be executed inadvertently when
         moving mousewheel"""
        print self.cbx.GetStringSelection()

    def on_selection_2(self, evt):
        """this is another combobox. dont mind if mouse move it or not"""
        print self.cbx.GetStringSelection()

    def do_nothing(self, evt):
        print 'on events pit'

if __name__ == "__main__":
    App = wx.PySimpleApp()
    Myframe().Show()
    App.MainLoop()

rawDescription: Disable mousewheel events on wx.ComboBox widget


code:
def liste_kontrol(liste):
    name=raw_input("Name pls:")
    if name in liste:
        print "now u seeng on list", name, liste[name]
    else:
        print "cant found."
liste= {"john":"002050505","jack":"0551282"}
liste_kontrol(liste)

rawDescription: Python dictionary in if else

description: Python dictionary in if else


code:
def print_tree_store(store):
    rootiter = store.get_iter_first()
    print_rows(store, rootiter, "")

def print_rows(store, treeiter, indent):
    while treeiter != None:
        print indent + str(store[treeiter][:])
        if store.iter_has_child(treeiter):
            childiter = store.iter_children(treeiter)
            print_rows(store, childiter, indent + "\t")
        treeiter = store.iter_next(treeiter)

rawDescription: How to read all gtk.TreeModelRow (in Python)

description: Read all gtk.TreeModelRow (in Python)


code:
emailAddress = linkedInApp.get('people/~/email-address')
print emailAddress.data

rawDescription: How to get email address from LinkedIn using Flask-oauthlib?

description: Get email address from LinkedIn using Flask-oauthlib


code:
import urlparse
path = urlparse.urlsplit(uri).path
print path.split('/')[n]

rawDescription: How to get a Url segment in django

description: Get a Url segment in django


code:
import csv

csvname = raw_input("Enter csv name: ")

sbuxfile = csv.reader(open(csvname), delimiter=',', quotechar='|')
# List of Data
row5, row8, row3, row7, avgequity, roe1, roe2 = ([] for i in range(7))

count = 0
# Grab data and numerical values from CSV.
for row in sbuxfile:
  count += 1
  if count == 8:
     row8 = row
  elif count == 5:
     row5 = row
  elif count == 3:
     row3 = row
  elif count == 7:
     row7 = row

a = 1

# Perform calculations for average equity and ROE.
while a < 8 :
   if a == 1:
     avgequity.append(round(float(row8[a]),2))
     roe1.append(float(row5[a]) / float(row8[a]))
     roe2.append((float(row5[a]) / float(row3[a])) * (float(row3[a]) / float(row7[a])) * (float(row7[a]) / float(row8[a])))
     a+=1   #added this line
   else:
     avgequity.append(round(float(row8[a]),2) + float(row8[a-1])/2) #rewrote this line as it had an error
     roe1.append(float(row5[a]) / float(row8[a]))
     roe2.append((float(row5[a]) / float(row3[a])) * (float(row3[a]) / float(row7[a])) * (float(row7[a]) / ((float(row8[a]) + float(row8[a-1]))/2)))
     a+=1

print "\nAverage equity is " + str(avgequity) + "\n"
print "ROE method 1 is " + str(roe1) + "\n"
print "ROE method 2 is " + str(roe2)

rawDescription: Why Does This Program Run on Linux Python Shell But Not on Windows?


code:
bag_sword = []

def equip(x):
    global bag_sword
    if x == "iron sword":
        if "iron sword" in bag_sword:
            print "You can't have 2 weapons equipped!"
        else:
            bag_sword.append("iron sword")

print bag_sword # Prints "[]".
equip("iron sword") # Prints nothing. Puts the string "iron sword" in bag_sword.
print bag_sword # Prints "['iron sword']".
equip("iron sword") # Prints "You can't have 2 weapons equipped!". bag_sword is unchanged.

rawDescription: Python function not returning anything

description: Python function not returning anything


code:
import sys, urllib, re, urlparse
from BeautifulSoup import BeautifulSoup

if not len(sys.argv) == 2:
    print >> sys.stderr, "Usage: %s <URL>" % (sys.argv[0],)
    sys.exit(1)

url = sys.argv[1]

f = urllib.urlopen(url)
soup = BeautifulSoup(f)
for i in soup.findAll('img', attrs={'src': re.compile('(?i)(jpg|png)$')}):
    full_url = urlparse.urljoin(url, i['src'])
    print "image URL: ", full_url

rawDescription: Python download all files from internet address?


code:
import re
bad_words = ["stupid", "idiot"]
regex = re.compile("|".join(re.escape(word) for word in bad_words), re.IGNORECASE)
print regex.search('youareanidiot').group()

# prints "idiot"

rawDescription: Regex Question: How can I check if any of values in list are matched?


code:
from Tkinter import *
from PIL import ImageGrab
import cStringIO, base64, time, threading

Picturelabel = Label(BalanceFrame)
Picturelabel.grid(row=3, column=2, columnspan=3)

class PictureThread(threading.Thread):

    def run(self):
        print "test"
        box = (0,0,500,500) #x,x,width,height
        fp = cStringIO.StringIO()
    while(1):
            MyImage = ImageGrab.grab(box)
            MyImage.save(fp, 'GIF')
            self.image = PhotoImage(data=base64.encodestring(fp.getvalue()))
            Picturelabel.image = self.image
            fp.reset() # reset the fp position to the start
            fp.truncate() # and truncate the file so we don't get garbage
            time.sleep(5)

PictureThread().start()
window.mainloop()

rawDescription: Displaying and refreshing my picture every 5 seconds


code:
from django.db import models
from django.db import transaction

class MyModel(models.Model):
    # model definition

    @transaction.commit_on_success()
    def save(self, *args, **kwargs):
        try:
            super(MyModel, self).save(*args, **kwargs)
            do_other_things()
            obj2 = MySecondModel(mymodel = self, foo = "bar")
            obj2.save()
        except:
            print 'exception'
            raise
        else:
            print 'job done'

class MySecondModel(models.Model):
    myModelId = models.ForeignKey(MyModel)
    # other fields defining this model

rawDescription: Django transactions: managing two different transactions atomically inside the overriding of save() method


code:
import Image
import math
from numpy import matrix
from numpy import linalg

def rot_x(angle,ptx,pty):
    return math.cos(angle)*ptx + math.sin(angle)*pty

def rot_y(angle,ptx,pty):
    return -math.sin(angle)*ptx + math.cos(angle)*pty

angle = math.radians(45)
im = Image.open('test.jpg')
(x,y) = im.size
xextremes = [rot_x(angle,0,0),rot_x(angle,0,y-1),rot_x(angle,x-1,0),rot_x(angle,x-1,y-1)]
yextremes = [rot_y(angle,0,0),rot_y(angle,0,y-1),rot_y(angle,x-1,0),rot_y(angle,x-1,y-1)]
mnx = min(xextremes)
mxx = max(xextremes)
mny = min(yextremes)
mxy = max(yextremes)
print mnx,mny
T = matrix([[math.cos(angle),math.sin(angle),-mnx],[-math.sin(angle),math.cos(angle),-mny],[0,0,1]])
Tinv = linalg.inv(T);
print Tinv
Tinvtuple = (Tinv[0,0],Tinv[0,1], Tinv[0,2], Tinv[1,0],Tinv[1,1],Tinv[1,2])
print Tinvtuple
im = im.transform((int(round(mxx-mnx)),int(round((mxy-mny)))),Image.AFFINE,Tinvtuple,resample=Image.BILINEAR)
im.save('outputpython2.jpg')

rawDescription: Python/PIL affine transformation

description: Python/PIL affine transformation


code:
print ('\n')
country = ''
province = ''
gstTax = 0.05
hrmTax = 0.13
otherTax = gstTax + 0.06
car = 30000.42
shoes = 333.24
laptop = 1000.98
itemsInBasket = []
itemsInBasket.append('Car added to the basket, price: {0:.2f} $'.format(car))
itemsInBasket.append('Shoes added to the basket, price: {0:.2f} $'.format(shoes))
itemsInBasket.append('Laptop added to the basket, price: {0:.2f} $'.format(laptop))

orderTotal = 0
for item in itemsInBasket:
    print item
    if 'Car' in item:
        orderTotal += car
    elif 'Shoes' in item:
        orderTotal += shoes
    elif 'Laptop' in item:
        orderTotal += laptop

country = str(raw_input('Country residence? ')).capitalize()
if country == 'Canada':
    province = str(raw_input('Which province? ')).capitalize()
    if province == 'Alberta':
        print 'Your final payment: ', (orderTotal + gstTax), '$'
    elif province == 'Ontario' or province == 'New Brunswick' \
        or province == 'Nova Scotia':
        print 'Your final payment: ', (orderTotal + hrmTax), '$'
    else:
        print 'Your final payment: ', (orderTotal + otherTax), '$'
else:
    print 'Your final payment: ', (orderTotal), '$'
print 'Transaction ended, thank you for your purchase'

rawDescription: python - select from a list of things

description: Python - select from a list of things


code:
def externalCode(two, first=1, second=2):
    print two, first, second

params = {'two': 9, 'first': 8, 'second': 7}
externalCode(**params)

rawDescription: Send dictionary to function that does not accept **kwargs?


code:
text_file = open("myfile.txt","r")
lines = text_file.readlines()
print len(lines)
target = open ("filename.txt", 'a') ## a will append, w will over-write
hello1Found = False
hello2Found = False

for line in lines :
    if hello1Found == True :
        if line[0:5] == "hello":
            hello2Found = True
            hello1Found = False
            break ## When second hello is found looping/saving to file is stopped
              ##(though using break is not a good practice here it suffice your simple requirement
        else:
            print line #write the line to new file
            target.write(line)
    if hello1Found == False:
        if line[0:5] == "hello": ##find first occurrence of hello
            hello1Found = True
            print line
            target.write(line)      ##if hello is found for the first time write the
                                ##line/subsequent lines to new file till the occurrence of second hello

rawDescription: Split large text file using keyword delimiter


code:
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt

N = 10

np.random.seed(10)
a=np.random.randint(-1, N, size=(5, 5))
print a

fig, ax = plt.subplots()

colors = [(0.0,0.0,0.0),(1.0,1.0,1.0)]
colors.extend(mpl.cm.jet(np.linspace(0, 1, N-1)))
cmap = mpl.colors.ListedColormap(colors)
mat=ax.matshow(a, cmap=cmap, vmin=-1, vmax=N-1)
cax = plt.colorbar(mat, ticks=np.linspace(-0.5, N-1-0.5, N+1))
cax.set_ticklabels(range(-1, N))
plt.show()

rawDescription: Add separate colors for two (or more) specific values in color plot and color bar


code:
import subprocess, re

# Use subprocess.check_output to get the output from the terminal command
lines = subprocess.check_output("s3cmd ls s3://voylladb-backups/db/".split(" ")).split("\n")

# the format is a bit weird so we want to isolate just the s3:// paths
# we'll use a regex search to find the s3:// pattern and any subsequent characters
file_re = re.compile("s3://.+")
files = []

# next we iterate over each line of output from s3cmd ls looking for the s3 paths
for line in lines:
    result = file_re.search(line)
    if result:
        # and add them to our list
        files.append(result.group(0))

# finally, reverse the list so the newest file is first, and grab the first item
files.sort(reverse=True)
print files[0] # production_dump_2013-09-12_21-00.sql.gz

rawDescription: How to parse a file, name of which is not known

description: Parse a file, name of which is not known


code:
d = { 'a': 100, 'b': 100, 'c': 10 }

tmp = {}
for key, value in d.items():
  if value in tmp:
    tmp[value].append(key)
  else:
    tmp[value] = [ key ]
print tmp # {10: ['c'], 100: ['a','b']}

e = {}
for value, keys in tmp.items():
  e[';'.join(keys)] = value

print e # {'a;b': 100, 'c': 10}

rawDescription: Two key with same value to one key in python


code:
import xml.etree.ElementTree as ET

sample = '''
<doc xmlns:text="http://example.com/">
    <text:p>Text of the paragraph, <text:span>wrapped text</text:span>
    continuing <text:soft-page-break />and more of the text.</text:p>
</doc>
'''

class MyTreeBuilder(ET.TreeBuilder):

    def start(self, tag, attrib):
        if not tag.endswith('soft-page-break'):
            return super(MyTreeBuilder, self).start(tag, attrib)

    def end(self, tag):
        if not tag.endswith('soft-page-break'):
            return super(MyTreeBuilder, self).end(tag)

def my_fromstring(data):
    parser = ET.XMLParser(target=MyTreeBuilder())
    parser.feed(data)
    return parser.close()

print ET.tostring(my_fromstring(sample))

rawDescription: How to remove the <text:soft-page-break /> element from the ElementTree?

description: Remove the <text:soft-page-break /> element from the ElementTree


code:
import os
from timeit import timeit

def remove():
    os.remove('test.txt')
    external_command()

def empty():
    open('test.txt', 'wb').close()  # same as your with statement, but shorter
    external_command()

def external_command():
    ''' not actually an external command, but pretend... '''
    with open('test.txt', 'a') as f:
        f.write('mooo')

print 'removal took', timeit(remove, number=1000), 'seconds'
#O: removal took 0.132004915145 seconds

print 'emptying took', timeit(empty, number=1000), 'seconds'
#O: emptying took 0.106063604726 seconds

rawDescription: More Efficient: with open(file, "wb"): pass or os.remove(file)


code:
from pywinauto import application

app = application.Application()
app.connect_(title='Calculator')
window = app.Calculator
print window.Children[5].Text

rawDescription: Python: Exploring data of GUI program

description: Python: Exploring data of GUI program


code:
import SocketServer
import BaseHTTPServer

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_GET(self):
        # The URL the client requested
        print self.path

        # analyze self.path, map the local file location...

        # open the file, load the data
        with open('test.py') as f: data = f.read()

        # send the headers
        self.send_response(200)
        self.send_header('Content-type', 'application/octet-stream') # you may change the content type
        self.end_headers()
        # If the file is not found, send error code 404 instead of 200 and display a message accordingly, as you wish.

        # wfile is a file-like object. writing data to it will send it to the client
        self.wfile.write(data)

        # XXX: Obviously, you might want to send the file in segments instead of loading it as a whole

if __name__ == '__main__':

    PORT = 8080 # XXX

    try:
        server = SocketServer.ThreadingTCPServer(('', 8080), RequestHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

rawDescription: File Sharing Site in Python

description: File Sharing Site in Python


code:
if epg_time_3.tm_min == 30:
    print "you are here, now let do something..."

rawDescription: Check minutes from time.struct_time object


code:
import requests
url = "https://encrypted-tbn1.gstatic.com/images?q=tbn%3AANd9GcTwC6cNpAen5dgGgTmmH2SG75xhvTN-oRliaOgG-3meNQVm-GdpUu7SQX5wpA"
h = requests.head(url)
print h.headers.get('content-type')

rawDescription: how to differentiate between normal url and image url programmactically

description: Differentiate between normal url and image url programmactically


rawDescription: Pandas dataframe to json without index

description: Pandas dataframe to json without index


code:
import tornado.ioloop
import tornado.web
import tornado.gen

class PingHandler(tornado.web.RequestHandler):

    connection_closed = False

    def on_connection_close(self):
        print "closed"
        self.connection_closed = True

    @tornado.gen.coroutine  # <= async handler
    def get(self):

        for i in range(600):

            if self.connection_closed:
                # `on_connection_close()` has been called,
                # break out of the loop
                break

            self.write("pong %s\n" % i)
            self.flush()

            # Add a timeout. Similar to time.sleep(1), but non-blocking:
            yield tornado.gen.Task(
                tornado.ioloop.IOLoop.instance().add_timeout,
                tornado.ioloop.IOLoop.instance().time() + 1,
            )

        self.finish()
        print "finished"

if __name__ == "__main__":
    application = tornado.web.Application([("/ping", PingHandler), ])
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: How to catch write aborts in python-tornado?

description: Catch write aborts in python-tornado


code:
def printStuff(labels,dG):
    for index, node in enumerate(dG.nodes()):
        print '%s:%d\n' % (labels[index],dG.node[node]['count'])

dG = nx.DiGraph()

for i, word in enumerate(str1):

    try:
        next_word = str1[i + 1]
        if not dG.has_node(word):
            dG.add_node(word)
            dG.node[word]['count'] = 1
        else:
            dG.node[word]['count'] += 1
        if not dG.has_node(next_word):
            dG.add_node(next_word)
            dG.node[next_word]['count'] = 0

        if not dG.has_edge(word, next_word):
            dG.add_edge(word, next_word, weight=maxint - 1)
        else:
            dG.edge[word][next_word]['weight'] -= 1
    except IndexError:
        if not dG.has_node(word):
            dG.add_node(word)
            dG.node[word]['count'] = 1
        else:
            dG.node[word]['count'] += 1
    except:
        raise

    printStuff(h[i], dG)

rawDescription: increasing i in a loop in python

description: Increasing i in a loop in python


code:
import httplib
conn = httplib.HTTPConnection("mydomain.com")
conn.request("HEAD", "/thevideofile.mp4")
res = conn.getresponse()
print res.getheaders()

rawDescription: How do I get a content-type of a file in Python? (with url..)

description: Get a content-type of a file in Python? (with url..)


code:
import sys
print sys.prefix

rawDescription: How to install external packages into Canopy?

description: Install external packages into Canopy


code:
from ctypes import CDLL, c_int, c_uint8, c_uint16, c_uint32, c_char, c_char_p, Structure, POINTER
from ctypes.util import find_library

import os

class c_dir(Structure):
    pass

class c_dirent(Structure):
    _fields_ = [
        ("d_fileno", c_uint32),
        ("d_reclen", c_uint16),
        ("d_type", c_uint8),
        ("d_namlen", c_uint8),
        ("d_name", c_char * 4096),
        # proper way of getting platform MAX filename size?
        # ("d_name", c_char * (os.pathconf('.', 'PC_NAME_MAX')+1) )
    ]

c_dirent_p = POINTER(c_dirent)
c_dir_p = POINTER(c_dir)

c_lib = CDLL(find_library("c"))
opendir = c_lib.opendir
opendir.argtypes = [c_char_p]
opendir.restype = c_dir_p

# FIXME Should probably use readdir_r here
readdir = c_lib.readdir
readdir.argtypes = [c_dir_p]
readdir.restype = c_dirent_p

closedir = c_lib.closedir
closedir.argtypes = [c_dir_p]
closedir.restype = c_int

def listdir(path):
    """
    A generator to return the names of files in the directory passed in
    """
    dir_p = opendir(".")
    try:
        while True:
            p = readdir(dir_p)
            if not p:
                break
            name = p.contents.d_name
            if name not in (".", ".."):
                yield name
    finally:
        closedir(dir_p)

if __name__ == "__main__":
    for name in listdir("."):
        print name

rawDescription: Iterating through a directory

description: Iterating through a directory


code:
class Node(object):
    def __init__(self, number):
        self.number=number
        self.right=None
        self.lef=None

    def add_node(self,number):
        if number < self.number:
            self.left = self.left.add_node(number)
        if number > self.number:
            self.right = self.right.add_node(number)

    def __str__(self):
        return str(self.number)

print Node(6)

rawDescription: printing a binary tree

description: Printing a binary tree


code: print hashes[8][:-1]

rawDescription: \n appending at the end of each line

description: \n appending at the end of each line


code:
for link in soup.findAll('a'):
    currenturl =  link.get('href')
    if not currenturl.startswith("http"):
        currenturl = "http://test.url/" + currenturl
    print currenturl

rawDescription: Add http://xxx.xx/ to a string using python


code:
data = [[1,2,3],
        [1,2,3]]

column = 1
print sum(row[column] for row in data)

rawDescription: How can I sum a column of a python list?

description: Sum a column of a python list


code:
with tf.Session() as sess:
    val1, val2 = sess.run([var1, var2], {x:myInputs, y:myOutputs})
    print "var1 =", val1
    print "var2 =", val2

rawDescription: Does Tensorflow rerun for each eval() call?


code:
import jsonpickle as jp

json = '''
{
    "attr1": true,
    "attr2": "fooA",
    "attr3": 7,
    "attr4": [
        {
        "someattr1": "fooB",
        "someattr2": "barC"
        },
        {
        "someattr1": "fooD",
        "someattr2": "barE"
        }
        ],
    "attr6": false
} '''

print jp.decode(json)['attr4'][1]['someattr1']  #index == 1 → 2nd in the series!!

rawDescription: Using jsonpickle in python to parse multiple child attributes


code:
import csv

with open('data.csv', 'rb') as csv_file:
    data = list(csv.DictReader(csv_file))

keys = ['Name', 'Location']
new_data = [dict((k, d[k]) for k in keys) for d in data]

print new_data

rawDescription: Extract multiple key:value pairs from one dict to a new dict


code:
import urllib2

url = 'http://server-A.com/form.php'
res = urllib2.urlopen(url)
print res.read()

rawDescription: How can I implement my PHP curl request to Python

description: Implement my PHP curl request to Python


code:
with tempfile.NamedTemporaryFile() as temp:
    print temp.name

rawDescription: can linux command line programs see python temporary files?

description: Can linux command line programs see python temporary files


code:
def foo():
  print "foo"
def bar():
  print "bar"

if sunny:
  del foo
else:
  del bar

rawDescription: Stop evaluation within a module

description: Stop evaluation within a module


code:
import itertools

for num in itertools.count(1): # count up from 1 infinitely
    phone = superhero_dict.get('phone_number_' + str(num))
    if phone is None:
        break
    print phone

rawDescription: How can I print a variables stored in a dictionary to screen using a for loop?

description: Print a variables stored in a dictionary to screen using a for loop


code:
a = pd.DataFrame({'from': changed_from, 'L': changed_to})
print a
#   L from
#0  d    b

out = pd.merge(a, df2, on=['L'])
out.rename(columns={'L':'to'}, inplace=True)
out = out[['U','T','from', 'to']]
print out
#   U        T from to
#0  2  string2    b  d

rawDescription: pandas - check changes in dataframe

description: Pandas - check changes in dataframe


rawDescription: Find the index of minimum values in given array in Python


code:
class CustomList(list):

  def __init__(self, parent_instance, *args, **kwargs):
    super(CustomList, self).__init__(*args, **kwargs)
    self.parent_instance = parent_instance

  def append(self, item):
      self.parent_instance.added = True
      super(CustomList, self).append(item)

class MyClass(object):
    added = False

    def __init__(self):
        self.list = CustomList(self, [1,2,3])

c = MyClass()
print c.added  # False
c.list.append(4)
print c.added  # True

rawDescription: Add a decorator to existing builtin class method in python


code:
os.chdir("/tmp/")
files = [DOC(file=f) for f in glob.glob("*.xml")]
the_doc = ROOT(*files)
print lxml.etree.tostring(the_doc, pretty_print=True)

rawDescription: Creating xml file in Python that lists all files in a given directory


code:
from itertools import product
import hashlib

digits = '0123456789'

for combo in product(digits, repeat=16):
    coords = '{}.{} {}.{}'.format(
        ''.join(combo[:2]), ''.join(combo[2:8]),
        ''.join(combo[8:10]), ''.join(combo[10:]))
    hash = hashlib.sha256(coords).hexdigest()
    if hash == '3f1c756daec9ebced7ff403acb10430659c13b328c676c4510773dc315784e4e':
        print coords
        break

rawDescription: Is it possible to crack SHA256, when you know the answer is a coordinate?


code:
import os
import posixpath
import socket
import urllib
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

class MyFileHandler(SimpleHTTPRequestHandler):
    def translate_path(self, path):
        """Translate a /-separated PATH to the local filename syntax.

        Components that mean special things to the local file system
        (e.g. drive or directory names) are ignored.  (XXX They should
        probably be diagnosed.)

        """
        # abandon query parameters
        path = path.split('?',1)[0]
        path = path.split('#',1)[0]
        path = posixpath.normpath(urllib.unquote(path))
        words = path.split('/')
        words = filter(None, words)
        path = '/' # yourpath
        for word in words:
            drive, word = os.path.splitdrive(word)
            head, word = os.path.split(word)
            if word in (os.curdir, os.pardir): continue
            path = os.path.join(path, word)
        return path

def run():
    try:
        httpd = HTTPServer(('', 7214), MyFileHandler)
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    except socket.error as e:
        print e
    else:
        httpd.server_close()

rawDescription: Send Values to BaseHTTPRequestHandler

description: Send Values to BaseHTTPRequestHandler


code:
i=0

while i < len(text):
    print text[i]
    i += 1

rawDescription: Printing one character at a time from a string, using the while loop


code:
mod = __import__("mod")
for klass in vars(mod):
    o =  getattr(mod, klass)
    if type(o) == type:
        print o

rawDescription: python automatic (or dynamic) import classes in packages

description: Python automatic (or dynamic) import classes in packages


code:
def follow(thefile):
    thefile.seek(0,2)
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line

def beginread():
    loglines = follow(logfile)
    for line in loglines:
        print line

rawDescription: How to auto-refresh a log.txt file

description: Auto-refresh a log.txt file


code:
import time

# receive one packet
t0 = time.time()
# then receive the other packet
t1 = time.time()

print 'Time between packets (seconds):', t1 - t0

rawDescription: Python script to calculate the time between 2 successive packets received over the serial port


code:
def binary_search(func, min_x, max_x, target_y):
    while max_x - min_x > 1:
        midpoint = (min_x + max_x) / 2
        if func(midpoint) > target_y:
            max_x = midpoint
        else:
            min_x = midpoint
    return min_x

print binary_search(lambda n: n**2, 0, 600, 300**2)

rawDescription: How do I find the optimal function input integer (X) to get closest to a target output (Y)?

description: Find the optimal function input integer (X) to get closest to a target output (Y)


code:
def upload_and_get_data(username, password, image_filename):
    print image_filename, type(image_filename)
    browser = mechanize.Browser()
    browser.open("http://itmages.ru/user/login")
    form = browser.form = browser.forms().next()
    form["LoginForm[username]"] = username
    form["LoginForm[password]"] = password
    login_response = browser.submit()

    # file uploading
    form = browser.form = browser.forms().next()
    form.add_file(open(image_filename, "r"),
                  filename=os.path.basename(image_filename))
    send_response = browser.submit()

    table_regex = re.compile('<table class="stat".*?<input.*?
')
    table_data_text = table_regex.findall(
        send_response.get_data().replace("\n", " "))[0]
    table_data_regex = re.compile(
        '
 *<td.*?([^<]*)	 *(.*?)	 *
')
    table_data = dict(table_data_regex.findall(table_data_text))
    return table_data

rawDescription: Use python to connect to a php page and upload image


code:
foo = 'qwqwqw'
bar = 'wq'

idx = 0
counter = 0

while True:
    try:
        # find the next instance of bar, starting at idx
        found_at = foo.index(bar, idx)

        # move idx to the next possible position (after the instance of bar)
        idx = found_at + len(bar)

        # increase the counter
        counter += 1
    except ValueError:
        # foo.index(bar) will raise ValueError if bar cannot be found.  that
        # means we are done
        break

print counter

rawDescription: Python haystack and needle

description: Python haystack and needle


code:
import re

successful_msg="file has been uploaded"
def log_check(fileName):
     search_fileName = fileName
     print search_fileName
     with open("/tmp/test.log") as line:
         # New variable to determine if fileName is matched or not
         matched = 0
         for match in line:
                 m = re.search(r"%s" %search_fileName, match)

                 # If fileName found, update above variable
                 if m:
                      matched = 1

                 n=re.search(r"%s" %successful_msg,match)

                 # On any line, if both phrases are present on the same line:
                 if n and m:
                      print match
                      break

         # If for loop exited without break...
         else:
              # If we found the filename...
              if matched == 1:
                  print "File not updated"
              # If even the filename was not found...
              else:
                  print "File is not processed"

for inputName in glob.glob('./files/*'):
    log_check(inputName)

rawDescription: Multiple string matching in Python

description: Multiple string matching in Python


code:
data = """

Title1

Text1

Text1

Title2

Text2

Text2

Title3

Text3

Text3

Title2-1

Text2-1

Text2-1

Title3-1

Text3-1

Text3-1

"""
from bs4 import BeautifulSoup

soup = BeautifulSoup(data)

sections = soup.find_all('section')

for each in sections: #iterate over loop [above sections]
    if each.find('section'):
        continue
    else:
        print each.prettify()

rawDescription: Beautiful Soup iterate over html tag

description: Beautiful Soup iterate over html tag


code:
#!/usr/bin/python

import sys

# Test that script was run directly
if __name__=='__main__':
    for line in sys.stdin:
       hour = re.search(r'\b([0-9]{2}):', line).group(1)
else:
    print 'Imported local time.py instead of global time module!'
    sys.exit(1)

rawDescription: Why does importing subprocess change my output?


code:
from itertools import islice
def chunkwise(n, iterable):
    it = iter(iterable)
    while True:
        chunk = list(islice(it, n))
        if not chunk:
            break
        yield chunk

print list(chunkwise(3, range(10)))
# [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

rawDescription: python equivalent to clojure's partition-all?

description: Python equivalent to clojure's partition-all


code:
def accept_input():
    import sys
    while True:
        print "Type Y to continue, ctrl-c to exit"
        ch = sys.stdin.read(1)
        sys.stdin.flush()   #<===========
        if ch != "Y":
            pass
        else:
            return ch

rawDescription: Python sys.stdin.read() accept input condition print prompt twice


rawDescription: Join all except last x in list

description: Join all except last x in list


code:
words = {"woof":A,"arf bark":B}
input = "woof,arf bark"
inputList = input.split(',')
for word in inputList:
    print words[word]

rawDescription: How do you create a translator in Python?

description: Create a translator in Python


code:
def test(the_list):
    for i in range(len(the_list)):
        the_list[i] = the_list[i].lower()

the_list=["Python", "Programming"]
test(the_list)
print the_list

rawDescription: Modify list elements by passing it to a function


code:
class UrlBuilder:
    def __init__(self,domain,path="blah",params="foo=bar"):
        self.domain = domain
        self.path = path
        self.params = params

    def withPath(self,path):
        self.path = path
        return self

    def withParams(self,params):
        self.params = params
        return self

    def __str__(self):
        return 'http://' + self.domain + '/' + self.path + '?' + self.params
        # or return urlparse.urlunparse( ( "http", self.domain, self.path, self.params, "", "" )

    def build(self):
        return self.__str__()

if __name__ == '__main__':
    u = UrlBuilder('www.example.com')
    print u.withPath('bobloblaw')
    print u.withParams('lawyer=yes')
    print u.withPath('elvis').withParams('theking=true')

rawDescription: url builder for python

description: Url builder for python


code:
for i in range(len(some_list)):
    print lst[i], lst2[i], lst3[i], lst4[i], lst5[i]

rawDescription: Python: Write Individual lists as columns in csv


code:
philips_trousers = []

for _ in range(5):
    philips_trousers.append(list("TROUSERS"))

print philips_trousers

rawDescription: Appending to a multi-dimensional array in Python


code:
for item in XML_Document.getElementsByTagName('item'):
    tag1 = item.getElementsByTagName('tag1')[0].toxml(encoding="utf-8")
    tag2 = item.getElementsByTagName('tag2')[0].toxml(encoding="utf-8")
    tag3 = item.getElementsByTagName('tag3')[0].toxml(encoding="utf-8")
    print tag1, tag2, tag3

rawDescription: Parsing XML Using minidom

description: Parsing XML Using minidom


code:
import json
print json.dumps({u'words': [u'every', u'single', u'word']})

rawDescription: u'Too' u'much' u'unicode' u'returned'

description: U'Too' u'much' u'unicode' u'returned'


rawDescription: Convert rows of hexadecimal values to binary, vertically by column


code:
for table in db.execute("SELECT name FROM my_db.sqlite_master WHERE type='table'").fetchall():
    print db.execute("SELECT * FROM %s WHERE lat > 15  and lon < 30"%table).fetchall()

rawDescription: How can I search an entire database in Python's sqlite3?

description: Search an entire database in Python's sqlite3


code:
nav = soup.find( 'nav' )
child_li = nav.ul.find_all("li", recursive=False)
for c in child_li:
    print c.text

rawDescription: Beautiful Soup first child in thia html web scrape


code:
from ctypes import *
buf = create_unicode_buffer(500)
WinPath = windll.kernel32.GetLongPathNameW
WinPath(unicode(tempDir), buf, 500)
print buf.value

rawDescription: How to get long file system path from python on Windows

description: Get long file system path from python on Windows


code:
from nanpy import Arduino
from nanpy import serial_manager
from time import sleep

serial_manager.connect('/dev/ttyUSB0')

POT = 0
LED1 = 13
LED2 = 12
LED3 = 11
LED4 = 10
LED5 = 9
LED6 = 8
LED7 = 7
LED8 = 6

Arduino.pinMode(POT, Arduino.INPUT)
Arduino.pinMode(13, Arduino.OUTPUT)
Arduino.pinMode(12, Arduino.OUTPUT)
Arduino.pinMode(11, Arduino.OUTPUT)
Arduino.pinMode(10, Arduino.OUTPUT)
Arduino.pinMode(9, Arduino.OUTPUT)
Arduino.pinMode(8, Arduino.OUTPUT)
Arduino.pinMode(7, Arduino.OUTPUT)
Arduino.pinMode(6, Arduino.OUTPUT)

print "starting"
while True:
    pot = Arduino.analogRead(POT)
    if pot < 450:
        Arduino.digitalWrite(LED1, Arduino.HIGH)
        Arduino.digitalWrite(LED2, Arduino.HIGH)
        Arduino.digitalWrite(LED3, Arduino.HIGH)
        Arduino.digitalWrite(LED4, Arduino.HIGH)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.01)
    elif pot > 650:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.HIGH)
        Arduino.digitalWrite(LED6, Arduino.HIGH)
        Arduino.digitalWrite(LED7, Arduino.HIGH)
        Arduino.digitalWrite(LED8, Arduino.HIGH)
        sleep(.01)
    else:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.01)
    print pot

rawDescription: Led issue with arduino controled by raspberry pi/python


code:
from multiprocessing import Pool, cpu_count
import Queue

from urllib3 import HTTPConnectionPool
import threading

def ReqOsrm(url_input):
    # Create threadsafe connection pool
    conn_pool = HTTPConnectionPool(host='127.0.0.1', port=5005, maxsize=1000)

    # Create consumer thread class
    class Consumer(threading.Thread):
        def __init__(self, queue):
            threading.Thread.__init__(self)
            self._queue = queue

        def run(self):
          while True:
              msg = self._queue.get()
              try:
                response = conn_pool.request('GET', url)
                print response
              except Exception as err:
                print err
              self._queue.task_done()

    # Create work queue and a pool of workers
    queue = Queue.Queue()
    num_threads = 20
    workers = []
    for _ in xrange(num_threads):
        worker = Consumer(queue)
        worker.start()
        workers.append(worker)

    for url in url_input:
        queue.put(url)

    queue.join()

url_routes = [
    ["/proc1-0", "/proc1-1"],
    ["/proc2-0", "/proc2-1"],
    ["/proc3-0", "/proc3-1"],
    ["/proc4-0", "/proc4-1"],
    ["/proc5-0", "/proc5-1"],
    ["/proc6-0", "/proc6-1"],
    ["/proc7-0", "/proc7-1"],
    ["/proc8-0", "/proc8-1"],
    ["/proc9-0", "/proc9-1"],
]

pool = Pool(int(cpu_count()))
calc_routes = pool.map(ReqOsrm, url_routes)
pool.close()
pool.join()

rawDescription: Python Requests - ephemeral port exhaustion


code:
#!/usr/bin/env python
from gevent import monkey, sleep
monkey.patch_all()
import threading

class ExampleThread(threading.Thread):
    def run(self):
        for i in xrange(10):
            print 'working'
            sleep()

if __name__ == '__main__':
    worker = ExampleThread()
    worker.start()
    print 'this will be printed after the first call to sleep'

rawDescription: Using gevent monkey patching with threading makes thread work serially


code:
for event in pygame.event.get():
    print event
    if event.type == QUIT:
        exit()
    if event.type == USEREVENT+1:
        timerFunc()

rawDescription: detecting user events in pygame

description: Detecting user events in pygame


code:
values = [76, 76, 74, 2, 9, 30, 30, 29, 66, 93]
sum_odd = sum(x for x in values if x%2)
sum_even = sum(values) - sum_odd
print sum_odd,sum_even

rawDescription: Why wont the even and odd numbers print true answers?


code:
import random
total = 0
for x in range(1,10):
    int1 = random.randint(1,2)
    int2 = random.randint(1,2)
    total = total + int1 + int2
    print str(int1) + (' int1')
    print str(int2) + (' int2')
    print str(total) + (' total')

rawDescription: Can't keep a total of numbers in python

description: Can't keep a total of numbers in python


code:
from distutils.version import StrictVersion
fromVersion="5.5.0"
toVersion="7.0.0"
if ( StrictVersion(fromVersion) < StrictVersion(toVersion) ):
  print "From is less than to version"

rawDescription: Python converts "5.4" but but not "5.4.4" to a float, whats going on here?


code:
sentence = input('Sentence: ') # You should use raw_input if it is python 2.7
if not sentence[0].isupper() and sentence[-1] != '.': # You can check the last character using sentence[-1]
    # both the conditions are not satisfied
    print 'Your sentence does not start with a capital letter and has no full stop at the end.'
elif not sentence[0].isupper():
    # sentence does not start with a capital letter
    print 'Your sentence does not start with a capital letter.'
elif sentence[-1] != '.':
    # sentence does not end with a full stop
    print 'Your sentence does not end with a full stop.'
else:
    # sentence is perfect
    print 'Your sentence is perfect.'

rawDescription: Program that checks for capitalisation and full stop


code:
import pyaudio
import wave
import sys

chunk = 1024

def convert(data, sampleSize = 4, channel = 0):
    for i in range(0, len(data), 2*sampleSize):
        for j in range(0, sampleSize):
           data[i + j + sampleSize * channel] = data[i + j + sampleSize * (1 - channel)]

if len(sys.argv) < 2:
    print "Plays a wave file.\n\n" +\
          "Usage: %s filename.wav" % sys.argv[0]
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

p = pyaudio.PyAudio()

# open stream
stream = p.open(format =
                p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate = wf.getframerate(),
                output = True)

# read data
data = wf.readframes(chunk)
convert(data)

# play stream
while data != '':
    stream.write(data)
    data = wf.readframes(chunk)
    convert(data)

stream.close()
p.terminate()

rawDescription: Playing a single channel of audio using PyAudio or similar


code:
import pickle
class PicklableFile(object):
    def __init__(self, fileobj):
        self.fileobj = fileobj

    def __getattr__(self, key):
        return getattr(self.fileobj, key)

    def __getstate__(self):
        ret = self.__dict__.copy()
        ret['_file_name'] = self.fileobj.name
        ret['_file_mode'] = self.fileobj.mode
        ret['_file_pos'] = self.fileobj.tell()
        del ret['fileobj']
        return ret

    def __setstate__(self, dict):
        self.fileobj = open(dict['_file_name'], dict['_file_mode'])
        self.fileobj.seek(dict['_file_pos'])
        del dict['_file_name']
        del dict['_file_mode']
        del dict['_file_pos']
        self.__dict__.update(dict)

f = PicklableFile(open("/tmp/blah"))
print f.readline()
data = pickle.dumps(f)
f2 = pickle.loads(data)
print f2.read()

rawDescription: Design of a python pickleable object that describes a file


code:
for row in data['rows']:
    if row['visits'] >= 10:
       print row['customVariable1']

rawDescription: Python List index out of range when traversing list/json Object


code:
# incoming connection
def setup(self):
    print "connection established", self.client_address

def handle(self):
    while 1:
        try:
            self.data = self.request.recv(1024).strip()

            # incoming message
            self.headers = self.headsToDict(self.data.split("\r\n"))

            # its a handshake
            if "Upgrade" in self.headers and self.headers["Upgrade"] == "websocket":
                key = self.headers["Sec-WebSocket-Key"]
                accept = b64encode(sha1(key + MAGIC).hexdigest().decode('hex'))
                response = "HTTP/1.1 101 Switching Protocols\r\n"
                response += "Upgrade: websocket\r\n"
                response += "Connection: Upgrade\r\n"
                response += "Sec-WebSocket-Accept: "+accept+"\r\n\r\n"
                print response
                self.request.send(response)
            # its a normal message, echo it back
            else:
                print self.data
                self.request.send(self.data)
        except:
            print "except"
            break

rawDescription: Keeping the WebSocket connection alive

description: Keeping the WebSocket connection alive


code:
class ListMutator(object):

    def __init__(self, seq):
        self.data = seq

    def foo1(self, arg1, arg2):
        self.data = [x + arg1 for x in self.data]
        # This allows chaining:
        return self

    def foo2(self, arg1, arg2):
        self.data = [x*arg1 for x in self.data]
        return self

if __name__ == "__main__":
    lm = ListMutator([1,2,3,4])
    lm.foo1(2, 0).foo2(10, 0)
    print lm.data

    # Or, if you really must:
    print ListMutator([1,2,3,4]).foo1(2, 0).foo2(10, 0).data

rawDescription: Python: jQuery-like function chaining?

description: Python: jQuery-like function chaining


code:
csvwriter.writerow(header2+header1[2:4])

csv2copy=[]
for row2 in csv2reader: csv2copy.append(row2)

for row1 in csv1reader:
    for row2 in csv2copy:
        print row1,row2,counter
        if row1[0]==row2[0]:
            counter=counter+1
            csvwriter.writerow(row2+row1[2:4])

rawDescription: Compare two CSV files in Python

description: Compare two CSV files in Python


code:
with open("filename") as myfile:
    firstNtoMlines = myfile.readlines()[N:N+M] # the interval you want to read
    print firstNtoMlines

rawDescription: Python: reading N number from file, M at time


code:
print 'iWantAVariableWithThisName' in locals()
junkVar = 'iWantAVariableWithThisName'
exec(junkVar + " = 1")
print 'iWantAVariableWithThisName' in locals()

rawDescription: Is it possible to "dynamically" create local variables in Python?


code:
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class ExampleHandler(FileSystemEventHandler):
    def on_created(self, event): # when file is created
        # do something, eg. call your function to process the image
        print "Got event for file %s" % event.src_path

observer = Observer()
event_handler = ExampleHandler() # create event handler
# set observer to use created handler in directory
observer.schedule(event_handler, path='/folder/to/watch')
observer.start()

# sleep until keyboard interrupt, then stop + rejoin the observer
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()

rawDescription: Running a python script when a new file is created


code:
lst = ["http://www.a3.bs.com",
       "http://www.a1.bw.com",
       "http://www.a2.be.com",
       "http://www.a3.br.com"]

for i in re.findall("http://www\.a[0-9a-zA-Z]\.b[0-9a-zA-Z]\.com", " ".join(lst)):
    print re.subn('a', 'z', i)[0]

rawDescription: Replace unknown alphanumeric character in string in Python


code:
def searchBegin (searchChar):
    regex = searchChar
    regex += '.{2,7}'
    pattern = re.compile(regex)
    for (offset, line) in enumerate(lines):
        if re.match(pattern, line):
            return line
            break
        else:
            print "no match"
    return 'none'

rawDescription: Why is my code skipping straight to else?


code:
def searchNode(tree, node, path):
    if tree == None:
        return
    else:
        #print tree.value
        path.append(tree.value) #add to path because we visited
        searchNode(tree.left,node, path)
        searchNode(tree.right,node, path)
        if tree.value == node:
            print "Node " + str(node) + " found!"
            print path
        else:
            path.pop()  #remove from path because we are going back

rawDescription: Keeping track of tree node's parent in Python


code:
OPS = [operator.add, operator.sub, operator.add]
nums = [1, 2, 3, 4]
print reduce(lambda x, y: y[0](x, y[1]), zip(OPS, nums[1:]), nums[0])

rawDescription: Idiom for "reducing" a list with another list of methods


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from scrapy import Selector
from selenium.webdriver.support.ui import Select, WebDriverWait
import csv
import time
import requests
from scrapy import Selector as s

driver = webdriver.Firefox()
Links = ['','','','','']
for each in links:
    driver.get(each)
    time.sleep(02)
    driver.find_element_by_id("showAll").click()
    time.sleep(04)
    source = driver.page_source
    sel = s(text=source,type="html")
    apartment_listing = sel.xpath('//section[@class="placardHeader"]//a[@class="placardTitle"]//@href').extract()
    with open("C:\Users\ssamant\Desktop\Client\Anida\Phase_II\Apartments\\apartment_listing.csv","ab")as export:
        for each1 in apartment_listing:
            export.write('{}\n'.format(each1))
    #New_link = driver.current_url
    i = 0
    while (i)<21:
        driver.find_element_by_class_name('next').click()
        time.sleep(02)
        source1 = driver.page_source
        sel1 = s(text=source1,type="html")
        apartment_listing1 = sel.xpath('//section[@class="placardHeader"]//a[@class="placardTitle"]//@href').extract()
        with open("C:\Users\ssamant\Desktop\Client\Anida\Phase_II\Apartments\\apartment_listing.csv","ab")as export:
            for each2 in apartment_listing1:
                export.write('{}\n'.format(each2))
        i = i+1

rawDescription: Web scrape aspx website using python

description: Web scrape aspx website using python


code:
#!/usr/bin/env python

import grp, pwd

user = "myname"
groups = [g.gr_name for g in grp.getgrall() if user in g.gr_mem]
gid = pwd.getpwnam(user).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
print groups

rawDescription: Python: How to get group ids of one username (like id -Gn )


code:
import matplotlib.pyplot as P
import numpy as N

x_value = N.arange(0,10,1)
y_value = N.random.rand(10)
bandwidth = N.random.rand(10)*10
print bandwidth
P.fill_between(x_value, y_value+bandwidth/2, y_value-bandwidth/2, alpha=.5)
P.plot(x_value,y_value)
P.show()

rawDescription: Fat band using matplotlib in python

description: Fat band using matplotlib in python


code:
def valid_entry():
    # Here we define a number of attempts (which is what I think
    # you were doing with invalid_input). If the person enters 10
    # invalid attempts, the return value is None. We then check to
    # see if the value we get back from our function is None, and if
    # not, proceed as expected.
    num_attempts = 0
    while num_attempts < 10:
        # Here we do the input piece. Note that if we hit a ValueError,
        # the 'continue' statement skips the rest of the code and goes
        # back to the beginning of the while loop, which will prompt
        # again for the price.
        try:
            price = int(raw_input("Enter your price : "))
        except ValueError:
            print 'Please enter a number.'
            num_attempts += 1
            continue

        # Now check the price, and if it isn't in our range, increment
        # our attempts and go back to the beginning of the loop.
        if price < 0 or price > 100:
            print "This is an invalid entry"
            print "Please enter a number between 0 and 100"
            num_attempts += 1
        else:
            # If we get here, we know that the price is both a number
            # and within our target range. Therefore we can safely return
            # this number.
            return price

    # If we get here, we have exhausted our number of attempts and we will
    # therefore return 'None' (and alert the user this is happening).
    print 'Too many invalid attempts. Moving to the next item.'
    return None

def prices():
    # Here we go from 1-8 (since the upper bound is not included when
    # using range).
    x = range(1,9)

    # Here we use a variable (total) to store our running total, which will
    # then be presented at the end.
    total = 0

    # Now we iterate through our range.
    for item in x:
        print "\n\t\titem",item

        # Here is the important part - we call our valid_entry function and
        # store the result in the 'price' variable. If the price is not
        # None (which as we saw is the return value if the number of attempts
        # is > 10), we proceed as usual.
        price = valid_entry()
        if price is not None:
            if price <10:
                # Note this should probably be += 1
                total += 1
                print "This is ok"

            elif price >= 10 and price < 45:
                total += 5
                print "This is great"

            elif price >= 45 and price < 70:
                total += 15
                print "This is really great"

            # We know that price >= 70 here
            else:
                total += 40
                print "This is more than i expected"

    # Now print out the total amount spent
    print "\nYou now have spent a total of ", total

prices()

rawDescription: inserting a while loops into a for loop

description: Inserting a while loops into a for loop


code:
someString = 'Hello\nthere\npeople\nof\nEarth'
someList = someString.splitlines()
aNewString = someList[1]
print aNewString

rawDescription: Read line x of string?

description: Read line x of string


code:
import string
import re

s = u"Dobre uczynki są jak dobre poematy. Można łatwo uchwycić, ku czemu zmierzają, lecz nie zawsze da się je racjonalnie wytłumaczyć."
regex = re.compile(r'[%s\s]+' % re.escape(string.punctuation))
print regex.split(s)

rawDescription: What's the fast way to split a unicode string into a list, using white spaces OR punctuation as a separator?


rawDescription: Compose a python array of all but every 17th element


code:
#!/usr/bin/python
import lxml.etree as ET
import urllib2

response = urllib2.urlopen('some/url/to.xml')
xml = response.read()

root = ET.fromstring(xml)

for item in root.findall('.//item'):
    title = item.find('title').text
    print title

rawDescription: Parse XML in Python with lxml.etree

description: Parse XML in Python with lxml.etree


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
import random

Base= declarative_base()

class Customer(Base):
    __tablename__ = 'customer'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode)
    orders = relationship("Order", backref="customer")

class Order(Base):
    __tablename__ = "order"

    id = Column(Integer, primary_key=True)
    customer_id= Column(Integer, ForeignKey('customer.id'))
    amount = Column(Integer)

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

session = Session(e)

session.add_all([
    Customer(name="c%d" % i, orders=[
        Order(amount=random.randint(10, 100))
        for j in xrange(random.randint(0, 5))
    ])
    for i in xrange(100)
])

amount_sum = func.sum(Order.amount).label('totalamount')
amount = session.query(Order.customer_id, amount_sum).\
            group_by(Order.customer_id).\
            order_by(amount_sum.desc()).\
            limit(10).\
            subquery()

for a, b in session.query(Customer, amount.c.totalamount).\
    join(amount, amount.c.customer_id==Customer.id):
    print a.name, b

rawDescription: Grouping totals in SQLAlchemy

description: Grouping totals in SQLAlchemy


code:
#!/usr/bin/env python

# parse initial string
import json

def keyCleaner(d):
    if type(d) is dict:
        for key, value in d.iteritems():
            d[key] = keyCleaner(value)
            if '.' in key:
                d[key.replace('.', '_')] = value
                del(d[key])
        return d
    if type(d) is list:
        return map(keyCleaner, d)
    if type(d) is tuple:
        return tuple(map(keyCleaner, d))
    return d

print keyCleaner(json.loads('{"uuid":"94e31-02f59","project":{"name":"oasis","job.no":215493452,"subset":"beta"},"time":1412371841024}'))

rawDescription: Iterating Through Keys for String Replacement in Python


code:
L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
indices = (2, 5, 7)

start = 0
sections = []
for end in indices:
    sections.append(L1[start:end])
    start = end
sections.append(L1[start:])

for part in sections:
    print part
# [1, 2]
# [3, 4, 5]
# [6, 7]
# [8, 9]

rawDescription: How to perform multiple list slices at the same time in python

description: Perform multiple list slices at the same time in python


code:
try:
    x = int(x)
except ValueError:
    print "{} is not an integer".format(x)

rawDescription: How to determine whether string is a number when the number is negative

description: Determine whether string is a number when the number is negative


code:
def _recurse_tree(parent, depth, source):
    last_line = source.readline().rstrip()
    while last_line:
        tabs = last_line.count('\t')
        if tabs < depth:
            break
        node = last_line.strip()
        if tabs >= depth:
            if parent is not None:
                print "%s: %s" %(parent, node)
            last_line = _recurse_tree(node, tabs+1, source)
    return last_line

inFile = open("test.txt")
_recurse_tree(None, 0, inFile)

rawDescription: Python file parsing: Build tree from text file


code:
class TimeoutException(Exception):   # Custom exception class
  pass

def TimeoutHandler(signum, frame):   # Custom signal handler
  raise TimeoutException

# Change the behavior of SIGALRM
OriginalHandler = signal.signal(signal.SIGALRM,TimeoutHandler)

# Start the timer. Once 30 seconds are over, a SIGALRM signal is sent.
signal.alarm(30)

# This try/except loop ensures that you'll catch TimeoutException when it's sent.
try:
  ssh_foo(bar)   # Whatever your SSH command is that hangs.
except TimeoutException:
  print "SSH command timed out."

# Reset the alarm stuff.
signal.alarm(0)
signal.signal(signal.SIGALRM,OriginalHandler)

rawDescription: Option for SSH to timeout after a short time? ClientAlive & ConnectTimeout don't seem to do what I need them to do


code:
for line in lines:
    print line
    line = line.strip()
    ping = subprocess.Popen(
                ["ping", "-c", "1", "-s", "1", "-l", "1",line],
                stdout = subprocess.PIPE,
                stderr = subprocess.PIPE
          )
    out, error = ping.communicate()
    print out

rawDescription: Python: Troubleshooting ping script

description: Python: Troubleshooting ping script


code:
from pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo
#...
data = 'beforeafter'

tableOpen, tableClose = makeHTMLTags("table")
tableBody = tableOpen + SkipTo(tableClose) + tableClose
thetable = (tableBody).searchString(data)[0][2]

removeText = replaceWith(thetable)
scriptOpen, scriptClose = makeHTMLTags("script")
scriptBody = scriptOpen + SkipTo(scriptClose) + scriptClose
scriptBody.setParseAction(removeText)
data = (scriptBody).transformString(data)

print data

rawDescription: Strip text except from the contents of a tag


code:
import re

input = """
TOPIC:topic_0 2056
 ab  2.0
 cd  5.0
 ef  3.0
 gh  10.0

 TOPIC:topic_1 1000
 aa  3.0
 bd  5.0
 gh  2.0
"""

result = {}
for line in input.splitlines():
    line = line.strip()
    if not line:
        continue

    columns = re.split(r"\s+", line)
    value = columns[0]
    if value[:6] == 'TOPIC:':
        result[value] = []
        points = result[value]
        continue

    points.append(float(columns[1]))

for k, v in result.items():
    print k, sum(v)

rawDescription: Summing columns in a text file

description: Summing columns in a text file


code:
for key in my_dict.keys():
    my_dict[key] = mydict[key].replace('\\n', '')
    my_dict[key] = re.sub('[^A-Za-z0-9 ]+', '', my_dict[key])
print my_dict

rawDescription: Removing \n \\n and other unwanted characters from a json unicode dictionary with python


code:
a = 10
def test():
  global a
  a = a + 2

print a
test()
print a

rawDescription: Python: How to make variables consistent throughout different functions?


rawDescription: Paging python lists in slices of 4 items


code:
for i in xrange(15):
    first = '(%s) %s' % (i, lst[i])
    padding = ' ' * (30 - len(first))
    second = '(%s) %s' % (i + 15, lst[i + 15])
    print '%s%s%s' % (first, padding, second)

rawDescription: print an enumerated list in multiple columns

description: Print an enumerated list in multiple columns


code:
text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland"
x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = new_text
    print line,
x.close()

rawDescription: Search the word, and replace the whole line containing the word in a file in Python using fileinput


code:
samples=2048; #Number of samples (frequency values)
min_freq=0.; #Frequency range
max_freq=3.141592653589793/4; #Frequency range
freq_scale="linear" #Chooses whether plot is "linear"
mag_scale="dB" #Chooses whether magnitude plot scale.
fscale = freq_scale.lower()
mscale = mag_scale.lower()
mscale = "dB"

fig = plt.figure()
Hz = 3.141592653589793 / 12.

# Sample the frequency range linearly (data scale) and get the data
freqs = list(line(samples, min_freq, max_freq, finish=True))
freqs_label = list(line(samples, min_freq / Hz, max_freq / Hz, finish=True))
data = filt.freq_response(freqs)
mag = { "dB": dB20 }[mscale]
print mag(data);

rawDescription: Extract numerical values from zfilter object in python in AudioLazy library


code:
if eval(statement):
    print row

rawDescription: Evaluating if statement in python from a string


code:
import re
from collections import Counter
trainfiles = 'hello hello, world my world!'

wordlist = re.findall(r'\b\w+\b', trainfiles)
wordlist = Counter(wordlist)
for word, count in wordlist.items():
    if count == 1:
        trainfiles = re.sub(r'\b{}\b'.format(word), '<unk>', trainfiles)

print trainfiles

rawDescription: How to replace the words that appear once in a sentence in python

description: Replace the words that appear once in a sentence in python


code:
class abstractstatic(staticmethod):
    __slots__ = ()
    def __init__(self, function):
        super(abstractstatic, self).__init__(function)
        function.__isabstractmethod__ = True
    __isabstractmethod__ = True

class A(object):
    __metaclass__ = abc.ABCMeta
    @abstractstatic
    def test():
        print 5

rawDescription: `staticmethod` and `abc.abstractmethod`: Will it blend?


code:
external_dep={}
def handle_gerrit(num, external_dep):
    deps=findexternaldep(num)
    external_dep[num] = deps
    for num in deps:
        handle_gerrit(num, external_dep)

handle_gerrit("253036", external_dep)
print external_dep

rawDescription: recursively looping through each value in deps

description: Recursively looping through each value in deps


code:
print df.Pattern.str.split(',').tolist()
[['a'], ['a', 'b']]

rawDescription: fetch the column values of a pandas data frame to a list

description: Fetch the column values of a pandas data frame to a list


code:
class Team(object): # use object for new style classes
    def __init__(self, x=2):
        self.x = x # use self to refer to the instance

    def p(self):
        print self.x # self.x

a = Team()
a.p()
2

b = Team(4) # give b a different value for x
b.p()
4

rawDescription: Python class namespacing

description: Python class namespacing


code:
import os

def details(dev):

    fulldir = "/media/ravi/"+dev

    disk = os.statvfs(fulldir)

    print("")
    print"Driver name " + Name[x]
    print("")

    totalBytes = float(disk.f_bsize*disk.f_blocks)
    print "total space: %.2f GB" % (totalBytes/1024/1024/1024)

    totalUsedSpace = float(disk.f_bsize*(disk.f_blocks-disk.f_bfree))
    print "used space: %.2f GB" % (totalUsedSpace/1024/1024/1024)

    totalAvailSpace = float(disk.f_bsize*disk.f_bfree)
    print "available space: %.2f GB" % (totalAvailSpace/1024/1024/1024)

    print("------------------------------")

Name = os.listdir("/media/ravi/")
length = len(Name)
print(Name[-1])

for x in range(length):
    details(str(Name[x]))

rawDescription: Python code to check free space of a USB drive connected to the Linux machine


code:
for k,v in z.items():
 print '%s, %s' % (k.n(3, chop=True), v)

rawDescription: presion number and radical output in sympy

description: Presion number and radical output in sympy


code:
import wx
from wx.lib.pubsub import pub

########################################################################
class OtherFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, wx.ID_ANY, "Secondary Frame")
        panel = wx.Panel(self)

        msg = "Enter a Message to send to the main frame"
        instructions = wx.StaticText(panel, label=msg)
        self.msgTxt = wx.TextCtrl(panel, value="")
        closeBtn = wx.Button(panel, label="Send and Close")
        closeBtn.Bind(wx.EVT_BUTTON, self.onSendAndClose)

        sizer = wx.BoxSizer(wx.VERTICAL)
        flags = wx.ALL|wx.CENTER
        sizer.Add(instructions, 0, flags, 5)
        sizer.Add(self.msgTxt, 0, flags, 5)
        sizer.Add(closeBtn, 0, flags, 5)
        panel.SetSizer(sizer)

    #----------------------------------------------------------------------
    def onSendAndClose(self, event):
        """
        Send a message and close frame
        """
        msg = self.msgTxt.GetValue()
        pub.sendMessage("panelListener", message=msg)
        pub.sendMessage("panelListener", message="test2", arg2="2nd argument!")
        self.Close()

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        pub.subscribe(self.myListener, "panelListener")

        btn = wx.Button(self, label="Open Frame")
        btn.Bind(wx.EVT_BUTTON, self.onOpenFrame)

    #----------------------------------------------------------------------
    def myListener(self, message, arg2=None):
        """
        Listener function
        """
        print "Received the following message: " + message
        if arg2:
            print "Received another arguments: " + str(arg2)

    #----------------------------------------------------------------------
    def onOpenFrame(self, event):
        """
        Opens secondary frame
        """
        frame = OtherFrame()
        frame.Show()

########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="New PubSub API Tutorial")
        panel = MyPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

rawDescription: How to capture sub frame close event in main frame?

description: Capture sub frame close event in main frame


code:
import wx

class MyForm(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title="Tutorial")

        self.eventDict = {}
        for name in dir(wx):
            if name.startswith('EVT_'):
                evt = getattr(wx, name)
                if isinstance(evt, wx.PyEventBinder):
                    self.eventDict[evt.typeId] = name

        # Add a panel so it looks the correct on all platforms
        panel = wx.Panel(self, wx.ID_ANY)
        btn = wx.Button(panel, wx.ID_ANY, "Get POS")

        btn.Bind(wx.EVT_BUTTON, self.onEvent)
        panel.Bind(wx.EVT_LEFT_DCLICK, self.onEvent)
        panel.Bind(wx.EVT_RIGHT_DOWN, self.onEvent)

    def onEvent(self, event):
        """
        Print out what event was fired
        """
        evt_id = event.GetEventType()
        print self.eventDict[evt_id]

# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm().Show()
    app.MainLoop()

rawDescription: Getting the event name rather than integer ID in wxPython


code:
from splinter import *
from selenium import *

username1 = '***'
password1 = '***'

browser1 = Browser('phantomjs')
browser1.visit('http://***.nl/admin')
browser1.fill('username', username1)
browser1.fill('password', password1)
browser1.click_link_by_text('Inloggen')

url1 = browser1.url
title1 = browser1.title

titlecheck1 = 'Dashboard'

print "Step 1 (***):"

if title1 == titlecheck1:
    print('Succeeded')

else:
    print('Failed')
    browser1.quit()

print 'The source is:'
print browser1.html

browser1.quit()

rawDescription: How do I login to a website and print the source?

description: Login to a website and print the source


code:
words = set(line.strip() for line in open("words"))
for w in words:
    even, odd = w[::2], w[1::2]
    if even in words and odd in words:
        print even, odd

rawDescription: How to optimize this Python code (from ThinkPython, Exercise 10.10)

description: Optimize this Python code (from ThinkPython, Exercise 10.10)


code:
import csv

pattern="3-5;7;10-16"

off = []
for i in pattern.split(';'):
    if '-' in i:
        off += range(int(i.split('-')[0]),int(i.split('-')[1])+1)
    else:
        off += [int(i)]

with open('test.txt') as f:
    reader = csv.reader(f)
    reader = [','.join(item) for i,item in enumerate(reader) if i+1 not in off]

print reader

with open('input.txt', 'w') as f2:
    for i in reader:
        f2.write(i+'\n')

rawDescription: delete rows on a csv file depending on pattern python

description: Delete rows on a csv file depending on pattern python


code:
a = 'hello'
a = ''.join(sorted(a))
print a

rawDescription: reorder characters in a string in Python

description: Reorder characters in a string in Python


rawDescription: Convert string to nested tuple : Python

description: Convert string to nested tuple : Python


code:
master = Tk.Tk()
master.title('Program Application')
#Folder(10)
print "VSM activated input range first"
################### Declare button and respective method ###################
button = Tk.Button(text='VSM', command=VSM, fg="red")
button.config( height = 8, width = 80 )
button.pack() #pack is needed to display the button
bluebutton = Tk.Button(text="AGM Folder",command= lambda: Folder(0), fg="blue").pack(side = LEFT)
bluebutton = Tk.Button(text="VSM Folder",command= lambda: Folder(1), fg="blue").pack(side = RIGHT)
Label(text='Correct Range for Gradient').pack(side=TOP,padx=10,pady=10)

# ---------------------- change from here -------------------------
frame = Frame(master)
frame.pack(side=LEFT, expand=1)

Label(frame, text='X2').grid(row=0, column=1)
Label(frame, text='X1').grid(row=0, column=3)
Label(frame, text='OP').grid(row=1, column=0)
Label(frame, text='IP').grid(row=2, column=0)

entryX2 = Entry(frame, width=10)
entryX2.grid(row=1, column=1, padx=10, pady=10)
entryX2IP = Entry(frame, width=10)
entryX2IP.grid(row=2, column=1, padx=10, pady=10)
Tk.Button(frame, text='Input Range', command=lambda: Folder(2), fg="red").grid(row=0, column=2, rowspan=3, padx=10, pady=10)
entryX1 = Entry(frame,width=10)
entryX1.grid(row=1, column=3)
entryX1IP = Entry(frame,width=10)
entryX1IP.grid(row=2, column=3)
# ---------------------- to here -------------------------
master.mainloop() # Continue loop till user close tab

rawDescription: Unable to set multiple Labels to the left side, how can I do it?


code:
import numpy as np
#some example data; 128 images of 4x4 pixels
voxeldata = np.random.randint(0,100, (128, 4,4))
#we need to apply the same binning range to each pixel to get sensibble output
globalminmax = voxeldata.min(), voxeldata.max()+1
#number of output bins
bins = 20
bin_boundaries = np.empty(bins+1)
#function to wrap np.histogram, passing on only the first return value
def hist(pixel):
    h, b = np.histogram(pixel, bins=bins, range=globalminmax)
    bin_boundaries[:] = b  #simply overwrite; result should be identical each time
    return h
#apply this for each pixel
histdata = np.apply_along_axis(hist, 0, voxeldata)
print bin_boundaries
print histdata[:,0,0]  #print the histogram of an arbitrary pixel

rawDescription: Numpy Histogram - Python

description: Numpy Histogram - Python


code:
from email.header import make_header, decode_header
header = make_header(decode_header(msg['subject']))
unicode_header = unicode(header)
print repr(unicode_header)  # prints: u'Welcome to AtlasMail'

rawDescription: python how to convert str to unicode ( persion )?

description: Python how to convert str to unicode ( persion )


code:
def func1(): pass
def func2(): pass
def func3(): pass
#     ...
def func62(): pass
def func63(): pass

if 0 < a < 64:
    globals()['func'+str(a)]()
else:
    print 'a is out of range'

rawDescription: better writing style for the following code

description: Better writing style for the following code


code:
b = ['cat', 'dog', 'god', 'star', 'lap', 'act']
array = []
t = 0
for i, value in enumerate(b):
    t = i+1
    while t<len(b):
        if ''.join(sorted(value))==''.join(sorted(b[t])):
            array.extend([value, b[t]])
        t+=1
print array
['cat', 'act', 'dog', 'god']

rawDescription: Filter Anagram in Array in Python

description: Filter Anagram in Array in Python