code:
import subprocess
output = subprocess.check_output("uptime", shell=False)
print output.split()

rawDescription: how to split output of system call in python into list of words?

description: Split output of system call in python into list of words


code:
from itertools import chain

class Meta1(type):
    def __new__(metacls, name, bases, dct):
        print name
        return type.__new__(metacls, name, bases, dct)

class BaseComponableMeta(type):
    def __new__(metacls, *args, **kw):
        return metacls.__superclass.__new__(metacls, *args, **kw)

class ComponentMeta(object):
    def __init__(self, metaclass):
        self.metaclass = metaclass
    def __call__(self, name, bases,dct):
        #retrieves the deepest previous metaclass in the object hierarchy
        bases_list = sorted ((cls for cls in chain(*(base.mro() for base in bases)))
        , key=lambda s: len(type.mro(s.__class__)))
        previous_metaclass = bases_list[-1].__class__
        # Adds the "__superclass" attribute to the metaclass, so that it can call
        # its bases:
        metaclass_dict = dict(self.metaclass.__dict__).copy()
        new_metaclass_name = self.metaclass.__name__
        metaclass_dict["_%s__superclass" % new_metaclass_name] = previous_metaclass
        #dynamicaly generates a new metaclass for this class:
        new_metaclass = type(new_metaclass_name, (previous_metaclass, ), metaclass_dict)
        return new_metaclass(name, bases, dct)

# From here on, example usage:

class ComponableMeta(BaseComponableMeta):
    pass

class NewComponableMeta_1(BaseComponableMeta):
    def __new__(metacls, *args):
        print "Overriding the previous metaclass part 1"
        return metacls.__superclass.__new__(metacls, *args)

class NewComponableMeta_2(BaseComponableMeta):
    def __new__(metacls, *args):
        print "Overriding the previous metaclass part 2"
        return metacls.__superclass.__new__(metacls, *args)

class A(object):
    __metaclass__ = Meta1

class B(A):
    __metaclass__ = ComponentMeta(ComponableMeta)

# trying multiple inheritance, and subclassing the metaclass once:
class C(B, A):
    __metaclass__ = ComponentMeta(NewComponableMeta_1)

# Adding a third metaclass to the chain:
class D(C):
    __metaclass__ = ComponentMeta(NewComponableMeta_2)

# class with a "do nothing" metaclass, which calls its bases metaclasses:
class E(D):
    __metaclass__ = ComponentMeta(ComponableMeta)

rawDescription: Finding __metaclass__ used before redefinition in Python


code:
def f():
    f.count += 1
    print "Call number {0}".format(count)
f.count = 0

rawDescription: Can I assign attribute to a function inside itself?

description: Assign attribute to a function inside itself


code:
class player(object):
    def __init__(self):
        self.d = []

class dealer(object):
    def __init__(self, *decks): #feel free to add more stuff this is just an example :)
        self.decks = [d for d in decks]

    def deal(self):
        for d in self.decks:
            d.append(1) # just an example
            d.append(2)

p1 = player()
p2 = player()
p3 = player()

d = dealer(p1.d,p2.d,p3.d)
d.deal()
print p1.d # was changed by deal

rawDescription: passing multiple instances of the same class through objects

description: Passing multiple instances of the same class through objects


code:
class SubclassAttributes(type):
    def __getattr__(cls, name):  # classmethod of instances
        for subclass in cls.__subclasses__():
            if subclass.__name__ == name:
                return subclass
        else:
            raise TypeError('Class {!r} has no subclass '
                            'named {!r}'.format(cls.__name__, name))

class Base(object):
    __metaclass__ = SubclassAttributes

class Derived1(Base): pass
class Derived2(Base): pass

print Base.Derived1  # <class '__main__.Derived1'>
print Base.Derived2  # <class '__main__.Derived2'>
print Base.Derived3  # TypeError: Class 'Base' has no subclass named 'Derived3'

rawDescription: python access the subclasses of a class as properties

description: Python access the subclasses of a class as properties


code:
from PIL import Image
img = Image.open("test1.jpg") #jpg, png, etc.
pix = img.load()
print img.size #Get the width and height of the image for iterating over
print pix[15,15] #Get the RGBA Value of the a pixel of an image
pix[15, 15] = value # Set the RGBA Value of the image (tuple)
img.save("out.jpg") # Saves the modified pixels to image

rawDescription: Create, Modify, and Save an image in python 3.x


code:
#!/usr/bin/python
a = []
b = []
nums = raw_input("Enter input- ")
#append all to a list
for n in nums.split():
    n = int(n)
    if n < 0:
        break
    a.append(n)

#get the maximums
b = list(a)
first_max = max(b)
b.remove(first_max)
second_max = max(b)
b.remove(second_max)
third_max = max(b)

#get the minimums
b = list(a)
first_min = min(b)
b.remove(first_min)
second_min = min(b)
b.remove(second_min)
third_min = min(b)

## now swap
xMax, yMax, zMax = a.index(first_max), a.index(second_max), a.index(third_max)
xMin, yMin, zMin = a.index(first_min), a.index(second_min), a.index(third_min)
a[xMax], a[xMin] = a[xMin], a[xMax]
a[yMax], a[yMin] = a[yMin], a[yMax]
a[zMax], a[zMin] = a[zMin], a[zMax]

print a

rawDescription: How to swap maximums with the minimums? (python)

description: Swap maximums with the minimums? (python)


code:
def get_page(url):
    """ loads a webpage into a string """
    src = ''

    req = urllib2.Request(url)

    try:
        response = urllib2.urlopen(req)
        chunk = True
        while chunk:
            chunk = response.read(1024)
            src += chunk
        response.close()
    except IOError:
        print 'can\'t open',url
        return src

    return src

rawDescription: python,not getting full response

description: Python,not getting full response


code:
bol = False
while bol == False:
    pin=str(raw_input("What is your 4-digit pin number? "))
    for digit in pin:
        if int(digit) in [1,2,3,4]:
            bol = True
        else:
            print "invalid pin"
            bol = False
            break

rawDescription: Trying to make this python program work

description: Trying to make this python program work


code:
with open('path/to/input') as infile:
  for line in infile:
    left, comma, right = line.partition(',')
    print "%s%s%s" %(left.replace(' ', "+"), comma, right)

rawDescription: Replace all occurrences of space until the first comma regex?


rawDescription: Parsing a string into a list of dicts

description: Parsing a string into a list of dicts


code:
from multiprocessing import Process, Manager

def myf(myd):
    myd[1] = "HELLO WORLD!"

def proc(d):
    myf(d)

m=Manager()
locdict=m.dict()
locdict[2] = "HI BUDDY!"

p = Process(target=proc, args=(locdict,))

p.start()
p.join()
print locdict

rawDescription: share dict between processes

description: Share dict between processes


code:
import gtk
icon_theme = gtk.icon_theme_get_default()
icon_info = icon_theme.lookup_icon("my-icon-name", 48, 0)
print icon_info.get_filename()

rawDescription: How can I get the full file path of an icon name?

description: Get the full file path of an icon name


code:
x= time.time(); urllib2.urlopen("http://www.google.com").read(); print time.time()-x
0.166881084442

x= time.time(); urllib2.urlopen("http://www.google.com").geturl(); print time.time()-x
0.0772399902344

rawDescription: Will this urllib2 python code download the page of the file?


code:
p = re.match(r'.for[^=]*=\s*(.*)',dict['comment'])
if p:
    print '%s' %p.group(1)

rawDescription: python pattern match want string after the match

description: Python pattern match want string after the match


code:
import sys
import cv2
import math
import numpy
from scipy.ndimage import label

pi_4 = 4*math.pi

def segment_on_dt(img):
    border = img - cv2.erode(img, None)

    dt = cv2.distanceTransform(255 - img, 2, 3)
    dt = ((dt - dt.min()) / (dt.max() - dt.min()) * 255).astype(numpy.uint8)
    _, dt = cv2.threshold(dt, 100, 255, cv2.THRESH_BINARY)

    lbl, ncc = label(dt)
    lbl[border == 255] = ncc + 1

    lbl = lbl.astype(numpy.int32)
    cv2.watershed(cv2.cvtColor(img, cv2.COLOR_GRAY2RGB), lbl)
    lbl[lbl < 1] = 0
    lbl[lbl > ncc] = 0

    lbl = lbl.astype(numpy.uint8)
    lbl = cv2.erode(lbl, None)
    lbl[lbl != 0] = 255
    return lbl

def find_circles(frame):
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
    frame_gray = cv2.GaussianBlur(frame_gray, (5, 5), 2)

    edges = frame_gray - cv2.erode(frame_gray, None)
    _, bin_edge = cv2.threshold(edges, 0, 255, cv2.THRESH_OTSU)
    height, width = bin_edge.shape
    mask = numpy.zeros((height+2, width+2), dtype=numpy.uint8)
    cv2.floodFill(bin_edge, mask, (0, 0), 255)

    components = segment_on_dt(bin_edge)

    circles, obj_center = [], []
    contours, _ = cv2.findContours(components,
            cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    for c in contours:
        c = c.astype(numpy.int64) # XXX OpenCV bug.
        area = cv2.contourArea(c)
        if 100 < area < 3000:
            arclen = cv2.arcLength(c, True)
            circularity = (pi_4 * area) / (arclen * arclen)
            if circularity > 0.5: # XXX Yes, pretty low threshold.
                circles.append(c)
                box = cv2.boundingRect(c)
                obj_center.append((box[0] + (box[2] / 2), box[1] + (box[3] / 2)))

    return circles, obj_center

def track_center(objcenter, newdata):
    for i in xrange(len(objcenter)):
        ostr, oc = objcenter[i]
        best = min((abs(c[0]-oc[0])**2+abs(c[1]-oc[1])**2, j)
                for j, c in enumerate(newdata))
        j = best[1]
        if i == j:
            objcenter[i] = (ostr, new_center[j])
        else:
            print "Swapping %s <-> %s" % ((i, objcenter[i]), (j, objcenter[j]))
            objcenter[i], objcenter[j] = objcenter[j], objcenter[i]

video = cv2.VideoCapture(sys.argv[1])

obj_center = None
while True:
    ret, frame = video.read()
    if not ret:
        break

    circles, new_center = find_circles(frame)
    if obj_center is None:
        obj_center = [(str(i + 1), c) for i, c in enumerate(new_center)]
    else:
        track_center(obj_center, new_center)

    for i in xrange(len(circles)):
        cv2.drawContours(frame, circles, i, (0, 255, 0))
        cstr, ccenter = obj_center[i]
        cv2.putText(frame, cstr, ccenter, cv2.FONT_HERSHEY_COMPLEX, 0.5,
                (255, 255, 255), 1, cv2.CV_AA)

    cv2.imshow("result", frame)
    cv2.waitKey(10)
    if len(circles[0]) < 5:
        print "lost something"

rawDescription: Unreliable results with cv2.HoughCircles


code:
import pygame

pygame.init()

# create a window that will capture the events
pygame.display.set_mode((200, 200))

running = 1
while(running):
   for event in pygame.event.get():
      if event.type == pygame.KEYDOWN:
         if event.key == pygame.K_ESCAPE:
            print "hi"
            running = 0

rawDescription: Why is this tiny pygame program freezing and doing nothing?


code:
vdCacheType = {'AWB' : 'Always WriteBack', 'WB': 'Write Back',
               'NR': 'No Read Ahead', 'Ra': 'Read Ahead Adaptive',
               'WT': 'Write Through',  'R' : 'Read Ahead Always',
               'D': 'Direct IO', 'C': 'Cached' }

import re
rx = re.compile('|'.join(sorted(vdCacheType, key=len, reverse=True)))
print ', '.join([vdCacheType[m] for m in rx.findall('NRWTD')])
# No Read Ahead, Write Through, Direct IO

rawDescription: Finding abbreviations in a string in python


code:
import json

data = {
    "name": "Johnson",
    "json": '{"array":[1,2,3],"boolean":true,"null":null,"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"Hello World"}'
}

data['json'] = json.loads(data['json'])
print data['json']['number']

rawDescription: Accessing json data in flask html page

description: Accessing json data in flask html page


code:
import re
with open('/tmp/spam.txt') as f:
  for steam64id in re.findall(r'STEAM_\d:\d:\d+', f.read()):
    print steam64id

rawDescription: Sanitizing a Piece of Text in Python

description: Sanitizing a Piece of Text in Python


code:
for value in enumerate(data):
   print bin(ord(value))

rawDescription: How to Read-in Binary of a File in Python

description: Read-in Binary of a File in Python


code:
import numpy as np
import random
np.random.seed(123)
A = np.round(np.random.rand(25000,2,2),2)
B = np.round(np.random.rand(25000,2,2),2)

import scipy.spatial
tree = scipy.spatial.cKDTree(A.reshape(25000, 4))
results = tree.query_ball_point(B.reshape(25000, 4), r=1e-04, p=1)

print [r for r in results if r != []]
# [[14252], [1972], [7108], [13369], [23171]]

rawDescription: find 2d elements in a 3d array which are similar to 2d elements in another 3d array

description: Find 2d elements in a 3d array which are similar to 2d elements in another 3d array


code:
class Foo():
   def __init__(self):
      print "Hello"
   def __del__(self):
      print "Goodbye"

Foo()
_
'Hello world!'

rawDescription: Behaviour of __del__ on unassigned python object


code:
import gzip, os

localFile = 'cat.gz'
outFile = os.path.splitext(localFile)[0]

print 'Unzipping {} to {}'.format(localFile, outFile)

with gzip.open(localFile, 'rb') as inF:
    with open( outFile, 'wb') as outF:
        outF.write( inF.read(size=1024) )

rawDescription: unzipping large files using python

description: Unzipping large files using python


code:
class A(object):
    KEYWORD = 'Class A'

class B(A):
    KEYWORD = 'Class B'

class C(object):
    pass

def list_class_keywords():
    for name, obj in globals().items():
        print name, hasattr(obj, 'KEYWORD')

if __name__ == '__main__':
    list_class_keywords()

rawDescription: Python: search global classes in a single module file


code:
def pr(a):
    print 'Namespace'
    seen = set()
    def f(a, indent):
        for k, v in sorted(a.__dict__.items()):
            s = indent * ' '
            if type(v) == argparse.Namespace:
                if id(v) in seen:
                    print '%s%s: Namespace' % (s, k)
                else:
                    seen.add(id(v))
                    print '%s%s:' % (s, k)
                    f(v, indent + 1)
            elif type(v) == bytearray:
                print '%s%s: bytearray(%s)' % (s, k, len(v))
            elif type(v) == list:
                print '%s%s: [%s]' % (s, k, len(v))
            elif type(v) == str:
                print '%s%s: %s' % (s, k, repr(v))
            elif type(v) == tuple:
                print '%s%s: (%s)' % (s, k, len(v))
            elif type(v) in (int, long):
                print '%s%s: %x' % (s, k, v)
            else:
                print '%s%s: %s' % (s, k, v)
    f(a, 1)

rawDescription: Printing cyclic data structures

description: Printing cyclic data structures


code:
import itertools
a = [["a","b"], ["c"]]
print list(itertools.chain.from_iterable(a))

rawDescription: join list of lists in python

description: Join list of lists in python


code:
ind = [i for i, x in enumerate(windowed_freqs) if x >= 240 and x <= 285]

#now take the DB data only at the indicies where x is between the proper range.
value = fftData_inDB[ind]

#print freqs[ind]
maxval=-1000
maxind=0
for j in ind:
    if fftData_inDB[j] > maxval:
        maxval = fftData_inDB[j]
        maxind = j
print 'max power in range is {} dBm'.format(maxval)
print 'corresponding frequency is {} Hz'.format(freqs[maxind])

rawDescription: Need help selecting frequency range for peaks search after FFT operation


code:
def CalcManager(myData,start,end):
    print 'in calc manager'
    print type(myData[0])

    manager = Manager()
    d = manager.list(myData)

    nprocs = 3
    result_q = multiprocessing.Queue()
    procs = []

    interval = (end-start)/nprocs
    new_start = start

    for i in range(nprocs):
        new_end = new_start + interval
        if new_end > end:
            new_end = end
        p = multiprocessing.Process(target=multiProcess,
                                    args=(d, new_start, new_end, result_q, i))
        procs.append(p)
        p.start()
        #Increment our next start to the current end
        new_start = new_end+1
    print 'finished starting'

    for i in range(nprocs):
        result = result_q.get()
        print len(result)

    #Joint the process to wait for all data/process to be finished
    for p in procs:
        p.join()

rawDescription: Multiprocessing passing an array of dicts through shared memory


code:
from datetime import datetime
from dateutil.parser import parse

def extract_date(text):

    date = {}
    date_1 = parse(text, fuzzy=True, default=datetime(2001, 01, 01))
    date_2 = parse(text, fuzzy=True, default=datetime(2002, 02, 02))

    if date_1.day == 1 and date_2.day ==2:
        date["day"] = "XX"
    else:
        date["day"] = date_1.day

    if date_1.month == 1 and date_2.month ==2:
        date["month"] = "XX"
    else:
        date["month"] = date_1.month

    if date_1.year == 2001 and date_2.year ==2002:
        date["year"] = "XXXX"
    else:
        date["year"] = date_1.year

    return(date)

print extract_date("Posted: by dave August 1st")

rawDescription: Parse unformatted dates in Python

description: Parse unformatted dates in Python


code:
from lxml import etree
data = """<assetsMain>
<assetParent type='character' shortName='char'>
<asset>pub</asset>
<asset>car</asset>
</assetParent>
<assetParent type='par' shortName='pr'>
<asset>camera</asset>
<asset>rig</asset>
</assetParent>
</assetsMain>
"""
doc = etree.XML(data)
for aP in doc.xpath('//assetParent'):
  parent = aP.attrib['type']
  for a in aP.xpath('./asset/text()'):
    print parent, a.strip()

rawDescription: getting specific xml nodes attributes

description: Getting specific xml nodes attributes


code:
def read_coords(file_handle):
    try:
        nrecords = int(file_handle.readline())
    except ValueError:
        return False
    return [file_handle.readline() for i in range(nrecords)]

coord_sets = []
with open("some.txt") as f:
   coords = read_coords(f)
   while coords != False:
       coord_sets.append(coords)
       coords = read_coords(f)

print "coord_sets =",coord_sets

rawDescription: How would I read n lines where n is the first line in a file using Python?


code:
mydict = dict(((u'520775', [[u'Kategori:2. divisjon fotball for herrer 2008']]),
(u'754686', [[u'Kategori:Debutalbum', u'Kategori:Musikkalbum fra 1990',
              u'Kategori:Tre Sm\xe5 Kinesere-album']]),
(u'381191', [[u'Kategori:Serierundene i Adeccoligaen 2007']]),
(u'972597', [[u'Kategori:Tippeligaen 2011']]),
(u'263001', [[u'Kategori:Musikkalbum fra 2003']]),
(u'23037', [[u'Kategori:Luftforsvaret']]),
(u'640060', [[u'Kategori:Deltagermedaljen', u'Kategori:F\xf8dsler i 1923',
              u'Kategori:Norske folkemusikere',
              u'Kategori:Norske trekkspillere', u'Kategori:Paul Harris Fellow',
              u'Kategori:Personer fra Vefsn kommune']])))

for key, value in mydict.iteritems():
    print key,
    for elem in value[0]:
        print elem + ',',
    print

rawDescription: Python: Trouble with Encoding

description: Python: Trouble with Encoding


code:
import os
import sys
import zipfile

class ZipTools:
    """
    Zip tools
    """
    def __init__(self, folder_path=None, pkg_zip=None):
        self.path = folder_path
        self.zip_name = pkg_zip
        self.temp_dir = 'c:\\temp'
        self.archive = '{p}\\{z}'.format(p=self.temp_dir, z='a.zip')

    def zip(self):
        parent_folder = os.path.dirname(self.path)
        # Retrieve the paths of the folder contents.
        contents = os.walk(self.path)
        try:
            zip_file = zipfile.ZipFile(self.archive, 'w', zipfile.ZIP_DEFLATED)
            for root, folders, files in contents:
                # Include all subfolders, including empty ones.
                for folder_name in folders:
                    ab_path = os.path.join(root, folder_name)
                    rel_path = ab_path.replace(parent_folder + '\\' + self.zip_name, '')
                    print rel_path
                    zip_file.write(ab_path, rel_path)
                for file_name in files:
                    ab_path = os.path.join(root, file_name)
                    rel_path = ab_path.replace(parent_folder + '\\' + self.zip_name, '')
                    zip_file.write(ab_path, rel_path)
        except zipfile.BadZipfile, message:
            print message
            sys.exit(1)
        finally:
            zip_file.close()

if __name__ == '__main__':
    ab = ZipTools('c:\\temp\\trashtests', 'a.zip')
    ab.zip()

rawDescription: shutil.make_archive creates zip file , but skips empty directories

description: Shutil.make_archive creates zip file , but skips empty directories


code:
for link in soup.find_all('a'):
    if link.find('img'):
        print link

rawDescription: Python, BeautifulSoup - print only links which contains <img> in content


code:
age = [3,14,55]
sum_age = 0
count = 1
count2 = 0
g = 0

while g < len(age):
    sum_age += age[g]
    g += 1
average = sum_age / len(age) #the average calc.
print "The average is:", average

g = 0
while g < len(age):
    if age[g] > average:
        count = count + 1
    g += 1
print "The number above the average is:", count

rawDescription: Python 2.7.5, display count of array average, proper syntax and looping with empty space?


code:
def gather_public_ip():
   ACCESS_KEY = config.get('aws','access_key')
   SECRET_KEY = config.get('aws','secret_key')
   regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
   all_EIP = []
   for region in regions:
      client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
      addresses_dict = client.describe_addresses()
      for eip_dict in addresses_dict['Addresses']:
          print eip_dict['PublicIp']
          all_EIP.append(eip_dict['PublicIp'])
   return all_EIP

rawDescription: How to return the whole list from a python function

description: Return the whole list from a python function


code:
import re, mmap

with open('/var/log/error.log', 'r+') as f:
  data = mmap.mmap(f.fileno(), 0)
  mo = re.search('error: (.*)', data)
  if mo:
    print "found error", mo.group(1)

rawDescription: How do I re.search or re.match on a whole file without reading it all into memory?

description: Re.search or re.match on a whole file without reading it all into memory


code:
import re
s = '1 john 2 james 34 baker 45 discover'
s = re.split(' (?=\d+)',s)
print s

['1 john', '2 james', '34 baker', '45 discover']

rawDescription: Splitting a string in python by what follows the split character


code:
import csv

minimum = [float('inf'), float('inf')]
maximum = [float('-inf'), float('-inf')]

with open(inputfilename, 'r') as infile:
    with open(outputfilename, 'wb') as outfile:
        writer = csv.writer(outfile)
        for line in infile:
            row = map(int, line.split())
            minimum = map(min, zip(minimum, row))
            maximum = map(max, zip(maximum, row))
            writer.writerow(row)

x_extremes, y_extremes = zip(minimum, maximum)
print ' '.join(map(str, x_extremes)), ' '.join(map(str, y_extremes))

rawDescription: Python script: Removing tabs, separating columns with comma, listing max/min


code: print pageObj.extractText()

rawDescription: Can run script line by line in shell, but full script returns nothing


code:
from Quartz import CGWindowListCopyWindowInfo, kCGNullWindowID, kCGWindowListOptionAll
import datetime, time
print datetime.datetime.now()
found = False
count = 0
windowName = "Hello World"
while 1:
    list = CGWindowListCopyWindowInfo(kCGWindowListOptionAll, kCGNullWindowID)
time.sleep(0.2)
for a in list:
    try:
        if a['kCGWindowName'] == windowName:
            print "**** yippee *****"
            print "window found"
            print a
            found = True
            break
    except:
        pass
    if found == True:
        break
    print "NOT FOUND", count
    count+=1

print datetime.datetime.now()

rawDescription: What is an alternative to win32gui in python 2.7 for mac


code:
def calc_v(latitude):
   for t in range(0,360):
       v=(23.5*math.sin(math.pi*(t-80)/180)+90-latitude)/90
       yield v

def decide_v(v):
    if 0<v<1:
       return v**2
    elif v>=1:
       return 1
    else:
       return 0

for v in calc_v(latitude):
    print decide_v(v)

rawDescription: Call function? Python

description: Call function? Python


code:
def main():
    print "Hello"
    testv=5
    if testv==6:
        print "!!!"
        return 0;
    else:
        print "World"
    print "***********"
    return 0;

if __name__ == "__main__":
    main()

rawDescription: How to quit a program in Python in if

description: Quit a program in Python in if


code:
class A(object):
    def foo(self):
        print 'parent'

class B(A):
    def foo(self):
        print 'child'

B.parent = super(B)
B().foo()
B().parent.foo()

rawDescription: When to use super(type) in python?

description: When to use super(type) in python


code:
def pipl(n):
    plt.plot(np.arange(1,n), [pi(i) for i in np.arange(1,n)])
    print plt.show()

pipl(100)

rawDescription: python return array from iteration

description: Python return array from iteration


code:
#!/usr/bin/python

print "Content-Type: text/html;charset=utf-8";
print

import urllib

str = "Hello World?"
str = urllib.quote_plus(str)

print str

rawDescription: How to encode a string for url param in python

description: Encode a string for url param in python


code:
import numpy as np

M = np.random.random_sample((3, 3))

rgb = np.random.random_sample((5, 4, 3))

slow_result = np.zeros_like(rgb)
for i in range(rgb.shape[0]):
    for j in range(rgb.shape[1]):
        slow_result[i, j, :] = np.dot(M, rgb[i, j, :])

# faster method
rgb_reshaped = rgb.reshape((rgb.shape[0] * rgb.shape[1], rgb.shape[2]))
result = np.dot(M, rgb_reshaped.T).T.reshape(rgb.shape)

print np.allclose(slow_result, result)

rawDescription: Apply transformation matrix to pixels in OpenCV image


code:
import argparse as ap

def dothis():
    print "We're doing this."

def dothat():
    print "We're doing that."

if __name__ == "__main__":
    parser = ap.ArgumentParser()
    parser.add_argument('thing', choices=['dothis', 'dothat'])
    args = parser.parse_args()
    f = locals()[args.thing]
    f()

rawDescription: What is the canonical way to send arguments to a Python script?


code:
import sys

import gobject
gobject.threads_init()

import pygst
pygst.require('0.10')
import gst
from gst.extend.discoverer import Discoverer

def on_discovered(discoverer, ismedia, infile):
    print '\non_discovered:', infile
    discoverer.print_info()

if __name__ == '__main__':
    if len(sys.argv) >= 2:
        print 'Audio file: %s ' % sys.argv[0]
        discoverer = Discoverer(sys.argv[1])
        discoverer.connect('discovered', on_discovered, sys.argv[1])

        # The MainLoop
        mainloop = gobject.MainLoop()
        gobject.idle_add(discoverer.discover)
        mainloop.run()

    else:
        print 'Usage: %s <input_file>' % sys.argv[0]

rawDescription: How do I use the Discoverer module with pygi GstPbutils?

description: Use the Discoverer module with pygi GstPbutils


code: print "frozen_f=", dict( (i,f(i)) for i in range(100) )

rawDescription: A simple freeze behavior decorator

description: A simple freeze behavior decorator


code:
final = myClassObject.getPlays()
print final

rawDescription: Using a class-object's function output later in the program [Python 2.7]


code:
for status in tweepy.Cursor(status.user_timeline, id=user, include_entities=True).items(20):
    for url in status.entities['urls']:
         print url['expanded_url']

rawDescription: How do I print out the full url with tweepy?

description: Print out the full url with tweepy


code:
import numpy as np

x = [0,2,3,4]
y = [23,4,34,67]

m, __ = np.polyfit(x, y, 1)
print m

rawDescription: Finding the derivative of a plot given two axis - python


code:
import operator
d = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div }
operation = d.keys()
a = 5
b = 2
for op in operation:
    output = d[op](a, b)
    print output

rawDescription: for in loop arithmetic

description: For in loop arithmetic


code:
import tempfile

print tempfile.gettempdir() # prints the current temporary directory

f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here

rawDescription: Cross-platform way of getting temp directory in Python


code:
import re
StringIn = 'negxxx data1 xxxneg  out of span negxxx data2 xxxneg negzzz data1 zzzneg  out of span negzzz data2 zzzneg'
StringIn = re.sub(r"negxxx(.*?)xxxneg", r"\1" , StringIn)
StringIn = re.sub(r"negzzz(.*?)zzzneg", r"\1" , StringIn)
print StringIn

rawDescription: python regex replace all occurances with the matched string

description: Python regex replace all occurances with the matched string


code:
from BeautifulSoup import BeautifulSoup

xmldoc = open('datafile.xml', 'r').read()
bs = BeautifulSoup(xmldoc)

entryList = bs.findAll('entry')

for entry in entryList:
    print entry.content.find('m:properties').find('d:new_date').contents[0]
    print entry.content.find('m:properties').find('d:bc_10year').contents[0]

rawDescription: Parsing XML in python - stumped how to do this


code:
a = {'Other': '1.05', 'United States': '93.67', 'Liberia': '3.26', '" alt="" />\n
\n
': '', 'Canada': '2.02'}
b = {}

for k, v in a.iteritems():
    if v == ''  or "alt" in k:
        pass
    else:
        b[k] = v
print b

rawDescription: searching Python Dictionary

description: Searching Python Dictionary


code:
def abc():
    letters = ['a','b','c']
    for letter in letters:
        print letter
        yield letter
numbered = enumerate(abc())
for i, word in numbered:
    print i, word

rawDescription: enumerate()-ing a generator in Python

description: Enumerate()-ing a generator in Python


code:
d={'Alyssa':22, 'Char':25, 'Dan':25, 'Jeff':20, 'Kasey':20, 'Kim':20, 'Mogran':25, 'Ryan':25, 'Stef':22}
import collections
print collections.Counter(d.values()).most_common()[-1][0]
22

rawDescription: Find least frequent value in dictionary

description: Find least frequent value in dictionary


code:
dictio = {'Customer 1': {'Vitamin A': 0, 'Calcium': 1, 'Protein': 1, 'B vitamins': 0, 'HPMR': 0}, 'Customer 2': {'Vitamin A': 0, 'Calcium': 0, 'Protein': 1, 'B vitamins': 1, 'HPMR': 0}}
a = []
for key in dictio.keys():
    for key_ in dictio[key].keys():
        a.append((key,key_,dictio[key][key_]))

print a

rawDescription: flatten a dictionary of dictionaries in to a list in python

description: Flatten a dictionary of dictionaries in to a list in python


code:
import random
n = 3
data = zip(fantasies, damages)
total = 0
for i in range(n):
    myChoice = random.choice(data)
    print myChoice[0]
    total += myChoice[1]

rawDescription: Sum up values at corresponding indices from another list


code:
class Person(object):
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def __eq__(self, other):
    return self.age == other.age
  def __hash__(self):
    return hash(self.age)
  def get_detail(self):
    print "I am %s, my age is %d" % (self.name, self.age)

tom = Person('tom', 18)
jack = Person('jack', 20)
mary = Person('mary', 22)
mary2 = Person('mary2', 22)
mary3 = Person('mary3', 22)

person_set = set()
person_set.add(tom)
person_set.add(jack)
person_set.add(mary)
person_set.add(mary2)
person_set.add(mary3)
len(person_set)
for p in person_set:
  p.get_detail()

rawDescription: add object into python's set collection and determine by object's attribute

description: Add object into python's set collection and determine by object's attribute


code:
import heapq
class MyObject(object):
    def __init__(self, val):
        self.val = val
    def __cmp__(self, other):
        return cmp(self.val, other.val)

q = []
heapq.heappush(q, MyObject(50))
heapq.heappush(q, MyObject(40))
heapq.heappush(q, MyObject(30))
heapq.heappush(q, MyObject(20))
heapq.heappush(q, MyObject(200))
obj = heapq.heappop(q)
print obj.val

rawDescription: How to heapify by field from custom objects

description: Heapify by field from custom objects


code:
import sys
if sys.stdout.isatty():
    print "Running from command line"
else:
    print "Running from cron"

rawDescription: How can I tell if my script is being run from a cronjob or from the command line?

description: Tell if my script is being run from a cronjob or from the command line


code:
print "The plural of plural is plural{0}. {1}".format(
    's' if count > 1 else '', "Isnt't it!?")

rawDescription: Python: "inline" block / condition to return a char?


code:
import datetime
class DatedList(list):

    def __init__(self, values, dates):
        list.__init__(self, values)
        self.dates = dates
        self._dt_to_idx = {k:v for v,k in enumerate(dates)}

    def __getitem__(self, arg):
        if isinstance(arg, slice):
            start = self._dt_to_idx[arg.start]
            stop = self._dt_to_idx[arg.stop]
            return list.__getitem__(self, slice(start, stop, arg.step))
        else:
            return list.__getitem__(self, self._dt_to_idx[arg])

dates = [datetime.date(2012,1,x) for x in range(2,6)]
dl = DatedList([1,2,3,4], dates)
print dl[dates[2]]
print dl[dates[1]:dates[3]]

rawDescription: Creating a list using a date as index

description: Creating a list using a date as index


code:
import sys
import select
import tty
import termios

from curses import ascii

def isData():
    return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

old_settings = termios.tcgetattr(sys.stdin)
try:
    tty.setcbreak(sys.stdin.fileno())

    i = 0
    while 1:
        print i
        i += 1

        if isData():
            c = sys.stdin.read(1)
            if c == chr(ascii.ESC):
                break

finally:
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

rawDescription: Capturing user input at arbitrary times in python


code:
#make some soup
soup = BeautifulSoup(urllib2.urlopen(url).read())

#extract byline and date text from their respective tags
try:
    byline=soup.find("p", {'class':'byline'}).text
    date=soup.find("span", {'class':'timestamp'}).text
except:
    print 'byline missing!'

rawDescription: using regex to grab information from an article

description: Using regex to grab information from an article


code:
from email.header import decode_header
bytes, encoding = decode_header('=?utf-8?Q?12_=D7=A1=D7=91=D7=99=D7=97?=')[0]
print bytes.decode(encoding)

rawDescription: How to decode this representation of a unicode string in Python?

description: Decode this representation of a unicode string in Python


code:
for row in list2D:
    print " ".join(map(str,row))

rawDescription: Displaying python 2d list without commas, brackets, etc. and newline after every row


code:
d = [
    {
        'sentence': 'I am currently working',
        'variable1': 1,
        'variable2': 10
    },
    {
        'sentence': 'How are you today?',
        'variable1': 2,
        'variable2': 20
    },
]
"\n".join(x['sentence'] for x in d)
print "\n".join(x['sentence'] for x in d)

rawDescription: How to display in a new window the last item of each dictionary in a list of dictionaries?

description: Display in a new window the last item of each dictionary in a list of dictionaries


code:
for f in fcn:
    for ix in range(len(a)):
      print f(a[ix], b[ix], c[ix])

rawDescription: Python: Mapping arguments to functions in array


code:
chosen_word = random.choice(['cat', 'dog'])
letters_set = set(chosen_word)
while len(letters_set) > 0:
    letter = raw_input() #make controls on this.
    if letter in letters_set:
        letters_set.remove(letter)
        print "Good!"
        print ''.join(map(lambda c: c in letters_set and '_' or c, chosen_word))
    else:
        print "Bad Bad, try again!"

rawDescription: Get a letter out of a word

description: Get a letter out of a word


code:
from __future__ import division
import math

def func(x):
    return x*x*x-x-0.1

def sign(n):
    try:
        return n/abs(n)
    except ZeroDivisionError:
        return 0

def root(f, a, b, eps=1e-6):
    f_a = f(a)
    if abs(f_a) < eps:
        return a
    f_b = f(b)
    if abs(f_b) < eps:
        return b

    half = (b+a)/2
    f_half = f(half)

    if sign(f_half) != sign(f_a):
        return root(f, a, half, eps)
    else:
        return root(f, half, b, eps)

print root(func, -1.5, -0.5, 1e-8)  # -0.945649273694

rawDescription: python fuction finding root( or zero) with minimum distance from real root epsilon

description: Python fuction finding root( or zero) with minimum distance from real root epsilon


code:
for i in xrange(len(Derivative)-1):
    if Derivative[i] > 0 and Derivative[i+1] < 0:
        print "crossing between indexes {} and {}".format(i, i+1)

rawDescription: Finding zero crossings from a list in python


code:
def thread1():
     time.sleep(5)
     return True

def thread2(t1,gui):
    while thread.is_alive():
        pass
    print "Fertig"
    wx.CallAfter(gui.ThreadDone)

class MyFrame(wx.Frame):
   def startThread(self):
      calcThread = threading.Thread(target=thread1)
      checkThread = threading.Thread(target=thread2, args=(calcThread,self))
   def ThreadDone(self):
       print "Both threads done???"
       print "Now modify gui from main thread(here!)"

rawDescription: wxPython: Show Frame while doing something in other thread

description: WxPython: Show Frame while doing something in other thread


code:
def rational(x, p, q):
    """
    The general rational function description.
    p is a list with the polynomial coefficients in the numerator
    q is a list with the polynomial coefficients (except the first one)
    in the denominator
    The first coefficient of the denominator polynomial is fixed at 1.
    """
    return np.polyval(p, x) / np.polyval([1] + q, x)

def rational3_3(x, p0, p1, p2, q1, q2):
    return rational(x, [p0, p1, p2], [q1, q2])

x = np.linspace(0, 10, 100)
y = rational(x, [-0.2, 0.3, 0.5], [-1.0, 2.0])
ynoise = y * (1.0 + np.random.normal(scale=0.1, size=x.shape))
popt, pcov = curve_fit(rational3_3, x, ynoise, p0=(0.2, 0.3, 0.5, -1.0, 2.0))
print popt

plt.plot(x, y, label='original')
plt.plot(x, ynoise, '.', label='data')
plt.plot(x, rational3_3(x, *popt), label='fit')

rawDescription: Rational function curve fitting in python


code:
import re

str = u'haha i am going home'
substr1 = u'haha'
substr2 = u'ha'

match = re.search(r'\b%s\b' % substr1 ,str)

if match:
    print "found substring 1"

match = re.search(r'\b%s\b' % substr2 ,str)

if match:
    print "found substring 2"

rawDescription: Finding position of utf8 substring in string in python


code:
import os, glob
files = glob.glob('*.jpg')
files = [os.path.join("C:\\data", file) for file in files]
result = "( " + " ".join(files) + " )"
print result  # Prints ( C:\data\a.jpg C:\data\b.jpg C:\data\c.jpg )

rawDescription: get file path using backslash (\) in windows in python

description: Get file path using backslash (\) in windows in python


code:
db = server['test']
for doc in db:
    print doc
    for key in db[doc].keys():
        print key

rawDescription: how to introspect a couchdb document for its set of fields via couchdb-python

description: Introspect a couchdb document for its set of fields via couchdb-python


code:
import asyncore
import socket

class EchoHandler(asyncore.dispatcher_with_send):

    def handle_read(self):
        data = self.recv(8192)
        if data:
            self.send(data)

class EchoServer(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)

    def handle_accept(self):
        pair = self.accept()
        if pair is not None:
            sock, addr = pair
            print 'Incoming connection from %s' % repr(addr)
            handler = EchoHandler(sock)

server = EchoServer('localhost', 8080)
asyncore.loop()

rawDescription: Nonblocking client-server in python

description: Nonblocking client-server in python


code:
import os
import time
color_setting_file = file("cl.dat")
color = color_setting_file.read()
print "The file says the color is " + color

if str(color) == "blue":
        os.system('color 9')
        print "set blue"
if str(color) == "green":
        os.system('color a')
        print "set green"
if str(color) == "white":
        os.system('color 7')
        print "set white"
if str(color) == "red":
        os.system('color 4')
        print "set red"
if str(color) == "yellow":
        os.system('color 6')
        print "set yellow"
if str(color) == "pink":
        os.system('color 47')
        print "set pink"
else:
        print("None of the above.")
time.sleep(10)

rawDescription: Python Can't compare a file's contents with if statement


code:
class Yes:
    a = 1 # initialize class var.
    def __init__(self):
        self.a = 1 # point of this is what?

    def yes(self):
        if Yes.a==1: # check class var
            print "Yes"
        else:
            print "No, but yes"

class No(Yes):

    def no(self):
        if Yes.a==1: # check class var
            print "No"
        else:
            print "Yes, but no"
        Yes.a-=1 # alter class var

rawDescription: Python changing class variables

description: Python changing class variables


code:
import lxml.etree as et
from lxml.etree import HTMLParser
from StringIO import StringIO

def parse(self, response):
    parser = HTMLParser(encoding='utf-8', recover=True)
    tree = et.parse(StringIO(response.body), parser)
    for element in tree.xpath('//script'):
        element.getparent().remove(element)

    print et.tostring(tree, pretty_print=True, xml_declaration=True)

rawDescription: Remove unnecessary tag content from html source using scrapy


code:
import json

text = r"""return {
{ 6163, 0, "tv", false, {1302}, "ESPN Deportes", "ESPN Deportes es el", nil,"tv","936",nil,"4x3", mediaRestrictions={"m2g" } },
{ 57075, 0, "tv", false, {1302}, "Video Rola", "Video \"Música Para Tus Ojos\", uedes ver.", nil,"tv","948",nil,"4x3", mediaRestrictions={"m2g" } },
{ 717242, 0, "tv", false, {1302,1301,1288}, "Hits", "asdlfj", nil,"cliplinear","6310",nil,"4x3", mediaRestrictions={"m2g" } },
{ 122719, 0, "tv", false, {1302,1301,1288}, "Bombone", "asdf", nil,"tv","74",nil,"4x3", mediaRestrictions={"m2g" } },
}"""

obj = json.loads(text.replace("return","").replace("mediaRestrictions=","").replace("{","[").replace("}","]").replace("nil","null").replace("\n","").replace(",]","]").strip())

print obj

# [[6163, 0, u'tv', False, [1302], u'ESPN Deportes', u'ESPN Deportes es el', None, u'tv', u'936', None, u'4x3', [u'm2g']], [57075, 0, u'tv', False, [1302], u'Video Rola', u'Video "M\xfasica Para Tus Ojos", uedes ver.', None, u'tv', u'948', None, u'4x3', [u'm2g']], [717242, 0, u'tv', False, [1302, 1301, 1288], u'Hits', u'asdlfj', None, u'cliplinear', u'6310', None, u'4x3', [u'm2g']], [122719, 0, u'tv', False, [1302, 1301, 1288], u'Bombone', u'asdf', None, u'tv', u'74', None, u'4x3', [u'm2g']]]

for x in obj:
  print x[5], x[8], x[9]

#ESPN Deportes tv 936
#Video Rola tv 948
#Hits cliplinear 6310
#Bombone tv 74

rawDescription: Python: parsing help needed!

description: Python: parsing help needed!


code:
def print_return(value):
    print value
    return value

rawDescription: print value before return

description: Print value before return


code:
import multiprocessing
from multiprocessing import Queue

def worker(i, qu):
    """worker function"""
    while 1:
        try:
            val=qu.get(timeout)
        except  Queue.Empty: break# Yay no race condition
        print 'Worker:',i, ' start with file:',val
        j=1
        for k in range(i*10000,(i+1)*10000): # some time consuming process
            for j in range(i*10000,(i+1)*10000):
                j=j+k
        print 'Worker:',i, ' end with file:',val

if __name__ == '__main__':
    jobs = []

    qu=Queue()
    for j in range(100,110): # files numbers are from 100 to 110
        qu.put(j)

    for i in range(3): # 3 multiprocess
        p = multiprocessing.Process(target=worker, args=(i,qu))
        jobs.append(p)
        p.start()
    for p in jobs: #<--- join on all processes ...
        p.join()

rawDescription: Python multiprocessing with Queue (split loads dynamically)


code:
from Tkinter import *
import mp3play
import tkFileDialog
import Tkinter
import tkFont
import Tkinter as tk

class musicplay:
    def __init__(self):
        self.music = None
        self.play_list = []
        self.trackLocations = []

        self.root = tk.Tk()
        self.root.title("EmoPlayer")

        self.root.configure(background='black')
        self.root.geometry('300x100+750+300')

        self.filename = Tkinter.StringVar()
        self.name = Tkinter.StringVar()
        self.play_list = Tkinter.StringVar()

        menubar = Menu(self.root)
        filemenu = Menu(menubar, tearoff=0, bg="black", fg="Orange")
        menubar.add_cascade(label='File', menu = filemenu)
        filemenu.add_command(label='Open', command = self.open_file)
        filemenu.add_separator()
        filemenu.add_command(label='Exit', command = self.Exit)
        self.root.config(menu=menubar)

        open_file = Button(self.root, width = 6, height = 1,
                           text = 'Mood',fg='Orange', bg='black')
        open_file.grid(row=0, column=3)

        play_button = Button(self.root, width = 5, height = 1, text='Play',
                             fg='Orange', command = self.play, bg="black")
        play_button.grid(row=0, column=0, sticky = W)

        stop_button = Button(self.root, width = 5, height = 1, text='Stop',
                             fg='Orange', command = self.stop, bg="black")
        stop_button.grid(row=0, column=1, sticky = W)

        pause_button = Button(self.root, width = 5, height = 1, text='Pause',
                              fg='Orange', command = self.pause, bg="black")
        pause_button.grid(row=0, column=2)

        self.volume_slider = Scale(self.root, label='Volume',
                              orient = 'horizontal', fg = 'Orange',
                              command = self.vol, bg="black")
        self.volume_slider.grid(row=0, column=4)

        file_name_label = Label(self.root, font=('Comic Sans', 8),
                                fg = 'Orange', wraplength = 300,
                                textvariable=self.name, bg="black")
        file_name_label.grid(row=3, column=0, columnspan=8)

        play_list_window = Toplevel(self.root, height = 150, width = 100)
        play_list_window.title("Playlist")
        self.play_list_display = Listbox(play_list_window, selectmode=EXTENDED,
                                    width = 50, bg="Dark Slate grey",
                                    fg="Orange")
        self.play_list_display.bind("<Double-Button-1>", self.tune_changed)
        self.play_list_display.pack()
        play_list_window.mainloop()

        self.root.mainloop()

    def open_file(self):
        """
        Opens a dialog box to open .mp3 filemusic,
        then sends filename to file_name_label.
        """
        self.filename.set(tkFileDialog.askopenfilename(
            defaultextension = ".mp3",
            filetypes=[("All Types", ".*"), ("MP3", ".mp3")]))
        self.playlist = self.filename.get()
        playlist_pieces = self.playlist.split("/")
        self.play_list.set (playlist_pieces[-1])
        playl = self.play_list.get()
        self.play_list_display.insert(END, playl)
        print self.filename.get()
        self.music = mp3play.load(self.filename.get())
        pieces = self.filename.get().split("/")
        self.trackLocations += [self.filename.get()]
        self.name.set(pieces[-1])

    def play(self):
        """Plays the .mp3 file"""
        self.music.play()

    def stop(self):
        """Stops the .mp3 file"""
        self.music.stop()

    def pause(self):
        """Pauses or unpauses the .mp3 file"""
        if self.music.ispaused():
            self.music.unpause()
        else:
            self.music.pause()

    def vol(self, event):
        """Allows volume to be changed with the slider"""
        v = Scale.get(self.volume_slider)
        try:
            self.music.volume(v)
        except:
            pass

    def tune_changed(self, event):
        idx = event.widget.curselection()[0]
        self.music = mp3play.load(self.trackLocations[int(idx)])
        print ("Now playing %s" % event.widget.get(idx))

    def Exit(self):
        exit()

if __name__ == "__main__":
    musicplay()

rawDescription: music player playlist

description: Music player playlist


code:
import random as rd
import numpy as np

l, w = 12, 12   # matrix has dimensions l=12, w=12
matriz= np.zeros([l, w])

for i in range(l):
    for j in range(w):
        matriz[i,j]=rd.randint(0,10)

vals = []

for i in range(int(l/2)):     # iterate through rows 0 to 4
    for j in range(i+1, w-(i+1)):
        vals.append(matrix[i,j])

# get the mean:
print 'mean is {}'.format(sum(vals)/len(vals))

rawDescription: Mean of a specific part of the matrix

description: Mean of a specific part of the matrix


code:
image = QImage(filename)
data = QByteArray()
buf = QBuffer(data)
image.save(buf, 'PNG')
print data.toBase64()

rawDescription: Convert PyQt4.QtGui.QImage object to base64 PNG data


code:
hostList = [
    'www.domain.com',
    'ns1.domain.com',
    'mail.domain.com',
    'community.domain.com',
    'mx.domain.com',
    'mx3.domain.com',
    'aspmx.l.google.com',
    'forums.domain.com'
    ]

for h in hostList:
    splitHost = h.split('.')
    tld = splitHost.pop()
    dom = splitHost.pop()
    host = '.'.join(splitHost)
    print 'FQHN: : ', h
    print 'Host  : ', host
    print 'Domain: ', dom
    print 'TLD   : ', tld
    print

rawDescription: How to test Domain is it 'www' domain or subdomain or name server domain or mail domain in python?

description: Test Domain is it 'www' domain or subdomain or name server domain or mail domain in python


code:
import wave
import struct
import time

def get_loud_times(wav_path, threshold=10000, time_constant=0.1):
    '''Work out which parts of a WAV file are loud.
        - threshold: the variance threshold that is considered loud
        - time_constant: the approximate reaction time in seconds'''

    wav = wave.open(wav_path, 'r')
    length = wav.getnframes()
    samplerate = wav.getframerate()

    assert wav.getnchannels() == 1, 'wav must be mono'
    assert wav.getsampwidth() == 2, 'wav must be 16-bit'

    # Our result will be a list of (time, is_loud) giving the times when
    # when the audio switches from loud to quiet and back.
    is_loud = False
    result = [(0., is_loud)]

    # The following values track the mean and variance of the signal.
    # When the variance is large, the audio is loud.
    mean = 0
    variance = 0

    # If alpha is small, mean and variance change slower but are less noisy.
    alpha = 1 / (time_constant * float(sample_rate))

    for i in range(length):
        sample_time = float(i) / samplerate
        sample = struct.unpack('<h', wav.readframes(1))

        # mean is the average value of sample
        mean = (1-alpha) * mean + alpha * sample

        # variance is the average value of (sample - mean) ** 2
        variance = (1-alpha) * variance + alpha * (sample - mean) ** 2

        # check if we're loud, and record the time if this changes
        new_is_loud = variance > threshold
        if is_loud != new_is_loud:
            result.append((sample_time, new_is_loud))
        is_loud = new_is_loud

    return result

def play_sentence(wav_path):
    loud_times = get_loud_times(wav_path)
    pygame.mixer.music.load(wav_path)

    start_time = time.time()
    pygame.mixer.music.play()

    for (t, is_loud) in loud_times:
        # wait until the time described by this entry
        sleep_time = start_time + t - time.time()
        if sleep_time > 0:
            time.sleep(sleep_time)

        # do whatever
        print 'loud' if is_loud else 'quiet'

rawDescription: get playing wav audio level as output

description: Get playing wav audio level as output


code:
from datetime import datetime

my_date = raw_input("Enter B'date in mmi/dd/yyyy format:")

b_date = datetime.strptime(my_date, '%m/%d/%Y')

print "Age : %d" % ((datetime.today() - b_date).days/365)

rawDescription: age calculator in python from date (mm/dd/yyyy) and print age in years only

description: Age calculator in python from date (mm/dd/yyyy) and print age in years only


code:
from urllib import urlopen
from bs4 import BeautifulSoup

url = 'http://www.marketwatch.com/investing/stock/goog/financials'
text_soup = BeautifulSoup(urlopen(url).read()) #read in

titles = text_soup.findAll('td', {'class': 'rowTitle'})
for title in titles:
    if 'EPS (Basic)' in title.text:
        print [td.text for td in title.findNextSiblings(attrs={'class': 'valueCell'}) if td.text]

rawDescription: Python Matplotlib Finance: Get the quarterly EPS of a stock


code:
import signal, sys

# install a SIGALRM handler

def handler(signum, frame):
    print "got signal, exiting"
    sys.exit(1)

signal.signal(signal.SIGALRM, handler)

# emit SIGALRM after 5 secs

signal.setitimer(signal.ITIMER_REAL, 5)

# do stuff

i = 1
while True:
    if i % 100000 == 0:
        print i
    i += 1

rawDescription: Postpone code for later execution in python (like setTimeout in javascript)


code:
curList = items
if curList:
    largest = items[0]
    while curList is not None:
        if (curList[0] > largest):
            largest = curList[0]
        curList = curList[1]
    print largest

rawDescription: Extreme Pattern for Lists in Python

description: Extreme Pattern for Lists in Python


code:
import json
import csv
f = file('test.json', 'r')
data = json.load(f)
#result = []
for k,v in data.iteritems():
    print k,v
    #result.append(v)
f = file('output.csv', 'w')
writer = csv.writer(f)
writer.writerows(result)

rawDescription: Parse This Custom Twitter Capture Data With Python and Create Statistics


code:
parent = Parent()
db.session.add(parent)
db.session.flush()

print parent.id  # after flush(), parent object would be automatically
                 # assigned with a unique primary key to its id field

child = Child()
child.parent_id = parent.id
db.session.add(child)

rawDescription: Get inserted key before commit session

description: Get inserted key before commit session


code:
def doit( s ):

    # with some side-effect on a
    a = []

    def f1( s, m ):
        a.append( 1 )
        print 'f1', a, s, m

    def f2( s, m ):
        a.append( 2 )
        print 'f2', a, s, m

    def f3( s, m ):
        a.append( 3 )
        print 'f3', a, s, m

    re1 = re.compile( 'one' )
    re2 = re.compile( 'two' )
    re3 = re.compile( 'three' )

    func_re_list = (
        ( f1, re1 ),
        ( f2, re2 ),
        ( f3, re3 ),
    )
    for myfunc, myre in func_re_list:
        m = myre.match( s )
        if m:
            myfunc( s, m )
            break

doit( 'one' )
doit( 'two' )
doit( 'three' )

rawDescription: How do I search through regex matches in Python?

description: Search through regex matches in Python


code:
import urllib
from bs4 import BeautifulSoup
import re

url = 'https://thewebsitedownload.com'

text = urllib.urlopen(url).read()

soup = BeautifulSoup(text)
link = soup.find_all(href=re.compile("dropbox"))[0]['href']
print link
filename = 'filetobedownloaded.exe'
urllib.urlretrieve(link, filename)

rawDescription: Windows Python How to download dropbox popup from a website?


code:
import random

with open('mytextfile.txt', 'r') as file_obj:
    str_list = [s.strip('\r\n\t "') for s in file_obj.read().split(',')]

print random.choice(str_list)

rawDescription: Reading and printing from a plain text file Python 3


code:
#!/usr/bin/env python

#standard module, needed as we deal with command line args
import sys

from fractions import Fraction
import pyexiv2

#checking whether we got enough args, if not, tell how to use, and exits
#if len(sys.argv) != 2 :
#    print "incorrect argument, usage: " + sys.argv[0] + ' <filename>'
#    sys.exit(1)

#so the argument seems to be ok, we use it as an imagefile
imagefilename = sys.argv[1]

#trying to catch the exceptions in case of problem with the file reading
try:
    metadata = pyexiv2.metadata.ImageMetadata(imagefilename)
    metadata.read();

#trying to catch the exceptions in case of problem with the GPS data reading
    try:
        latitude = metadata.__getitem__("Exif.GPSInfo.GPSLatitude")
        latitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLatitudeRef")
        longitude = metadata.__getitem__("Exif.GPSInfo.GPSLongitude")
        longitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLongitudeRef")

        # get the value of the tag, and make it float number
        alt = float(metadata.__getitem__("Exif.GPSInfo.GPSAltitude").value)

        # get human readable values
        latitude = str(latitude).split("=")[1][1:-1].split(" ");
        latitude = map(lambda f: str(float(Fraction(f))), latitude)
        latitude = latitude[0] + u"\u00b0" + latitude[1] + "'" + latitude[2] + '"' + " " + str(latitudeRef).split("=")[1][1:-1]

        longitude = str(longitude).split("=")[1][1:-1].split(" ");
        longitude = map(lambda f: str(float(Fraction(f))), longitude)
        longitude = longitude[0] + u"\u00b0" + longitude[1] + "'" + longitude[2] + '"' + " " + str(longitudeRef).split("=")[1][1:-1]

        ## Printing out, might need to be modified if other format needed
        ## i just simple put tabs here to make nice columns
        print " \n A text file has been created with the following information \n"
        print "GPS EXIF data for " + imagefilename
        print "Latitude:\t" + latitude
        print "Longitude:\t" + longitude
        print "Altitude:\t" + str(alt) + " m"
    except Exception, e:  # complain if the GPS reading went wrong, and print the exception
        print "Missing GPS info for " + imagefilename
        print e

    # Create a new file or **overwrite an existing file**
    text_file = open('textfile.txt', 'w')
    text_file.write("Latitude" + latitude)
    # Close the output file
    text_file.close()

except Exception, e:   # complain if the GPS reading went wrong, and print the exception
    print "Error processing image " + imagefilename
    print e;

rawDescription: Cannot write to text file python 2.7 invalid syntax?


code:
import time
import random
import datetime

class TimeoutException(Exception):
    def __init__(self, *args, **kwargs):
        Exception.__init__(self, *args, **kwargs)

def busy_work():

    # Pretend to do something useful
    time.sleep(random.uniform(0.3, 0.6))

def train_loadbatch_from_lists(batch_size, timeout_sec):

    time_start = datetime.datetime.now()
    batch_xs = []
    batch_ys = []

    for i in range(0, batch_size+1):
        busy_work()
        batch_xs.append(i)
        batch_ys.append(i)

        time_elapsed = datetime.datetime.now() - time_start
        print 'Elapsed:', time_elapsed
        if time_elapsed > timeout_sec:
            raise TimeoutException()

    return batch_xs, batch_ys

def main():

    timeout_sec = datetime.timedelta(seconds=5)
    batch_size = 10
    try:
        print 'Processing batch'
        batch_xs, batch_ys = train_loadbatch_from_lists(batch_size, timeout_sec)
        print 'Completed successfully'
        print batch_xs, batch_ys
    except TimeoutException, e:
        print 'Timeout after processing N records'

if __name__ == '__main__':
    main()

rawDescription: Skip loop if a function is taking too long?


code:
class A(object):
    def __init__(self, param1, param2, param3):
        print param1, param2, param3

params = {'param1': "foo", 'param2': "bar", 'param3': "hello"}
# no 'new' here, just call the class
my_a = A(**params)

rawDescription: Instantiating objects in python

description: Instantiating objects in python


code:
def Modify( filename , Color , Category ):
        dataset = osgeo.gdal.Open( filename , GA_Update )
        if dataset is None:
            print 'ERROR: gdal.Open( %(filename)s )' % var
            sys.exit( 1 )
        band = dataset.GetRasterBand( 1 )
        band.SetRasterColorInterpretation( GCI_PaletteIndex )
        band.SetRasterColorTable( Color )
        band.SetRasterCategoryNames( Category )

rawDescription: How to automatically add a field directly in a .vrt?

description: Automatically add a field directly in a .vrt


code:
import boto
con = boto.connect_s3()
bucket_name="bucketname"
bucket=con.get_bucket(bucket_name)
keys = bucket.get_all_keys(prefix="region/cz/")
for key in keys:
    print key.name

rawDescription: Accessing keys and objects through python Boto and AWS S3


code:
x = 'summary'
print # new line
print "the election is:", # comma prevents new line
print x
print

rawDescription: Python: newline quandary

description: Python: newline quandary


code:
req = urllib2.Request("http://example.com/", "foo:bar")
print req.get_method()    # => 'POST'
print req.get_data()      # => 'foo:bar'

res = urllib2.urlopen(req)
print res.getcode()       # => 200
print res.headers.items() # => [('transfer-encoding', 'chunked'), ...

rawDescription: printing python Post request

description: Printing python Post request


code:
import urllib2
from BeautifulSoup import *
from urlparse import urljoin

def crawl(pages, depth=None):
    indexed_url = [] # a list for the main and sub-HTML websites in the main website
    for i in range(depth):
        for page in pages:
            if page not in indexed_url:
                indexed_url.append(page)
                try:
                    c = urllib2.urlopen(page)
                except:
                    print "Could not open %s" % page
                    continue
                soup = BeautifulSoup(c.read())
                links = soup('a') #finding all the sub_links
                for link in links:
                    if 'href' in dict(link.attrs):
                        url = urljoin(page, link['href'])
                        if url.find("'") != -1:
                                continue
                        url = url.split('#')[0]
                        if url[0:4] == 'http':
                                indexed_url.append(url)
        pages = indexed_url
    return indexed_url

pagelist=["https://en.wikipedia.org/wiki/Python_%28programming_language%29"]
urls = crawl(pagelist, depth=2)
print urls

rawDescription: How can I download full webpage by a Python program?

description: Download full webpage by a Python program


code:
import grp
import pwd
import os

stat_info = os.stat('/path')
uid = stat_info.st_uid
gid = stat_info.st_gid
print uid, gid

user = pwd.getpwuid(uid)[0]
group = grp.getgrgid(gid)[0]
print user, group

rawDescription: How to get the owner and group of a folder with Python on a Linux machine?

description: Get the owner and group of a folder with Python on a Linux machine


code:
cids = []
for c_node in tree.findall('.//cs/c'):
    test_node = c_node.find('test')
    if test_node is not None and test_node.text == 'False':
        id_node = c_node.find('id')
        cids.append(id_node.text)

print cids

rawDescription: Using Python, how can I get the text of an XML element when a sibling element's tag is the string I am looking for?


code:
#!/usr/bin/python

import wikipedia
page = wikipedia.page("caravaggio")
#links = page.links
#for tuple_ in page:
#    print tuple_
#print dir(page)
print page.content
#print page.coordinates
print 'page.html'
print page.html
print
print 'page.images'
print page.images
print
print 'page.links'
print page.links
print
print 'page.original_title'
print page.original_title
print
print 'page.pageid'
print page.pageid
print
print 'page.parent_id'
print page.parent_id
print
print 'page.references'
print page.references
print
print 'page.revision_id'
print page.revision_id
print
print 'page.section'
print page.section
print
print 'page.sections'
print page.sections
print
print 'page.summary'
print page.summary
print
print 'page.title'
print page.title
print
print 'page.url'
print page.url
print
#print links

rawDescription: How do I pull all image links from a Wikimedia page?

description: Pull all image links from a Wikimedia page


code:
import struct
decoded = []
with open("some_bin_file.rt","rb") as f:
     while True:
          try:
             decoded.append(struct.unpack_from("<Q",f)[0])
             # `<` means little endian; `Q` means unsigned long long (8 bytes)
          except struct.error:
             break

print decoded

rawDescription: Read little endian from file and convert to decimal


rawDescription: Grouping a list into a nested list under a condition - Python


code:
data = [('rambo', 1995), ('lethal weapon', 1992), ('rambo', 1980)]
movies = {}
for row in data:
    movies[row[0]] = row[1]

print len(data) # -> 3
print len(movies) # -> 2
print movies['rambo'] # -> 1980

rawDescription: Python Code Not Listing First Lİne in CSV File


code:
data = [(1, 2), (3, 4), (2, 1), (1, 2), (2, 3), (2, 3)]
from collections import Counter, OrderedDict

# Use Counter to find the number of times the tuple occured
d = Counter(data)

# Use OrderedDict to maintain the order of occurance
# Get tuples from OrderedDict and get count from d, create a new tuple
print [item + (d[item],) for item in OrderedDict.fromkeys(data)]
# [(1, 2, 2), (3, 4, 1), (2, 1, 1), (2, 3, 2)]

rawDescription: Iterate tuples in list and add weight to the tuple


code:
import os
import re
path = 'path/to/your/files/'
for i in os.listdir(path):
    with open(path+i) as f:
        content = f.read()
        pattern = re.compile('CONCLUSION:\s*([\s\w.]*)\n[A-Z\s]*:')
        print pattern.findall(content)[0]

rawDescription: extract certain paragraph from text

description: Extract certain paragraph from text


code:
import os.path
import requests

session = requests.session()

for url in [
    'https://www.duo.uio.no/bitstream/10852/9012/1/oppgave-2003-10-30.pdf',
    'https://www.duo.uio.no/bitstream/10852abcd/90121023/1234/oppgave-2003-10-30.pdf']:
    try:
        resp = session.head(url, allow_redirects=True)
        resp.raise_for_status()
        if resp.headers['content-type'] == 'application/pdf':
            resp = session.get(url)
            if resp.ok:
                with open(os.path.basename(url), 'wb') as outfile:
                    outfile.write(resp.content)
                    print "Saved {} to file {}".format(url, os.path.basename(url))
            else:
                print 'GET request for URL {} failed with HTTP status "{} {}"'.format(url, resp.status_code, resp.reason)
    except requests.HTTPError as exc:
        print "HEAD failed for URL {} : {}".format(url, exc)

rawDescription: Pdf to txt from http request

description: Pdf to txt from http request


code:
import sys,re
flaG,deletE,storE = False,False,""
for linE in open(sys.argv[1]):
    if re.search('pattern1',linE):
        flaG = True
        print storE
        storE = linE
        continue
    if flaG :
        storE += linE
        if re.search('pattern2',linE): deletE = True
        if re.search('pattern3',linE) :
            if not deletE : print storE
            storE = ''
            flaG = False
            deletE = False
    else : print linE,
print storE

rawDescription: Conditionally remove lines between two patterns in a file


code:
def Merge(left, right):
    result = [None] * (len(left) + len(right))
    i, j, k = 0, 0, 0

    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result[k] = left[i]
            #result.append(left[i])
            i += 1
        else:
            result[k] = right[j]
            #result.append(right[j])
            j += 1
        k += 1

## remaining items in remaining list
##    while i < len(left):
##        result[k] = left[i]
##        i += 1; k+= 1;
##
##    while j < len(right):
##        result[k] = right[j]
##        j += 1; k+= 1;
##
    return result

## Ref.: CLRS page 34
def MergeSort(A):
    if len(A) > 1:
        mid = int(len(A)/2)
        left = A[:mid]
        right = A[mid:]
        #MergeSort(left)
        # here should be
        left = MergeSort(left)
        #MergeSort(right)
        # here should be
        right = MergeSort(right)
        return Merge(left, right)
    else:
        return A

if __name__ == "__main__":
    a = [1, 2, 1, 12, 2, 5]
    print "a = %s" % a
    print "sort a = %s" % MergeSort(a)

rawDescription: Buggy Merge Sort

description: Buggy Merge Sort


code:
import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

rawDescription: read the cookies written by a certain site

description: Read the cookies written by a certain site


code:
class MyThread(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.ToKill = False
    def run(self):
        while True:
            self.FooHandler()
            if self.ToKill:
                return None
    def FooHandler(self):
        """ your function here """
        print 3

class Panel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=-1, style=wx.RAISED_BORDER)
        Bsizer = wx.BoxSizer(wx.VERTICAL)
        button=wx.ToggleButton(self, label="Click To Enable")

        Bsizer.Add(button,1,wx.ALL | wx.EXPAND)
        self.SetSizer(Bsizer)
        self.Bind(wx.EVT_TOGGLEBUTTON,self.buttonEvt,id=button.GetId())

    def buttonEvt(self, evt):
        clickedToggleButton = evt.GetEventObject()
        if clickedToggleButton.GetValue():
            self.thread = MyThread()
            self.thread.start()
            clickedToggleButton.SetLabel("Click To Disable")
        else:
            self.thread.ToKill = True
            clickedToggleButton.SetLabel("Click To Enable")

rawDescription: Looping in the GUI

description: Looping in the GUI


code:
from ghost import Ghost
import re

def filterProductLinks(links):  #filter the useless links using regex
   pLinks= list()
   for l in links:
      if re.match(".*productDetails.*",str(l)):
         pLinks.append(l)
   return pLinks #List of item url(40 max)

def getProductLinks(url):   #get the links generated by Java code
   ghost = Ghost(wait_timeout=100)
   ghost.open(url)
   links = ghost.evaluate("""
                    var links = document.querySelectorAll("a");
                    var listRet = [];
                    for (var i=0; i<links.length; i++){
                        listRet.push(links[i].href);
                    }
                    listRet;
                """)
   pLinks= filterProductLinks(links[0])
   return pLinks

#Test
pLinks= getProductLinks('http://www.lider.cl/walmart/catalog/category.jsp?id=CF_Nivel3_000042&pId=CF_Nivel1_000003&navAction=jump&navCount=0#categoryCategory=CF_Nivel3_000042&pageSizeCategory=20&currentPageCategory=1&currentGroupCategory=1&orderByCategory=lowestPrice&lowerLimitCategory=0&upperLimitCategory=0&&504')
for l in pLinks:
   print l
print len(pLinks)

rawDescription: Some html code dissapears when we use request in Python


code:
import urllib2
f = urllib2.urlopen("http://your-url")
size= f.headers["Content-Length"]
print size

rawDescription: How can I get the file size on the Internet knowing only the URL

description: Get the file size on the Internet knowing only the URL


code:
lst = [ 1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0]

from itertools import groupby
from operator import itemgetter

for k,v in groupby(enumerate(lst),key=itemgetter(1)):
    if k:
        v = list(v)
        print v[0][0],v[-1][0]

rawDescription: How do I find the length of a run of numbers in a list? (Is there a faster way than what I'm doing?)

description: Find the length of a run of numbers in a list? (Is there a faster way than what I'm doing?)


code:
print os.stat("filename.data") #ensure that st_size > 0

with open("filename.data","rb") as f:
    print repr(f.read())

rawDescription: Parsing a file with ".data" extension in Python?


code:
class index:
    def GET(self):
        print web.ctx['ip']
        return web.ctx['ip']

rawDescription: Using web.py how can I get someone's IP when they visit my page


code:
info = []
with open('small.txt', 'r') as inputFile:
    for line in inputFile:
        line = line.strip()
        if line != '':
            try:
                (a,b,c,d) = [ll.strip() for ll in line.split(',')]
                info.append([a, int(b), int(c), float(d)])
            except IOError as (errno, strerror):
                print "I/O error %s: %s" % (errno, strerror)
            except ValueError:
                print "Malformed line:" + line
            except:
                print "Unexpected error:", sys.exc_info()[0]
                raise

rawDescription: How would I go about converting parts of a string read-in from a file to an int


code:
import os, re
import glob

pattern = re.compile('word1(.*?)word3', flags=re.S)
for file in glob.glob('*.txt'):
    with open(file) as fp:
        for result in pattern.findall(fp.read()):
            print result

rawDescription: How to run a script on all *.txt files in current directory?

description: Run a script on all *.txt files in current directory


code:
# The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import pdb
import bpython

class BPdb(pdb.Pdb):
    """ PDB with BPython support. """

    def __init__(self):
        pdb.Pdb.__init__(self)
        self.rcLines = []
        self.prompt = '(BPdb) '
        self.intro = 'Use "B" to enter bpython, Ctrl-d to exit it.'

    def postloop(self):
        # We only want to show the intro message once.
        self.intro = None
        pdb.Pdb.postloop(self)

    ### cmd.Cmd commands

    def do_Bpython(self, arg):
        bpython.embed(self.curframe.f_locals, ['-i'])

    def help_Bpython(self):
        print "B(python)"
        print
        print ("Invoke the bpython interpreter for this stack frame. To exit "
               "bpython and return to a standard pdb press Ctrl-d")

    ### shortcuts
    do_B = do_Bpython
    help_B = help_Bpython

rawDescription: Is it possible to use bpython as a full debugger?


rawDescription: Python: Check if datetime is in correct format


code:
import re
try:
    print int(re.compile("(\d+)").match('12//').group(1))
except:
    print "there was no number"

rawDescription: Parse string to int when string contains a number + extra characters


code:
text = "Some sample (with parenthesis) text"
regEx = re.compile(r'([^\(]*)\([^\)]*\) *(.*)')
m = regEx.match(text)
while m:
  text = m.group(1) + m.group(2)
  m = regEx.match(text)
print text

rawDescription: remove content inside parenthesis as well as the parenthesis themselves from a paragraph

description: Remove content inside parenthesis as well as the parenthesis themselves from a paragraph


code:
for i in xrange(0x80, 0xFF):
    print unichr(i)

rawDescription: python unicode beginner : how to print out a series of letters?

description: Python unicode beginner : how to print out a series of letters


code:
list = ['gmail', 'aol', 'hotmail', 'yahoo']
myemail = 'foo@aol.com'
if mystring.split('@')[1].split('.')[0] in list:
    print 'I`m public'

rawDescription: how to best ignore free domain emails for sending a pdf via email(python)

description: Best ignore free domain emails for sending a pdf via email(python)


code:
def my_gen(data):
    for index in range(0, len(data)-1):
        value = data[index]
        value += 2 * value
        #etc
        yield value

my_list = [2, 8, 17, 5, 41, 77, 3, 11]
x = my_gen(my_list)
print x.next()
print x.next()

rawDescription: Python transform while-loop into a generator function


code:
import nltk.data

tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
fp = open("test.txt")
data = fp.read()
print '\n-----\n'.join(tokenizer.tokenize(data))

rawDescription: Python split text on sentences

description: Python split text on sentences


code:
names = ['peter', 'john', 'thomas', 'george']
texts = ['peter is awesome', 'john is lazy', 'thomas is thomas','george is curious']

matched = {n: [] for n in names}

for text in texts:
    for name in names:
        if re.match(name, text):
            matched[name].append(1)
        else:
            matched[name].append(0)

print matched
# {'john': [0, 1, 0, 0], 'thomas': [0, 0, 1, 0], 'peter': [1, 0, 0, 0], 'george': [0, 0, 0, 1]}

rawDescription: Automatic list generation; Python

description: Automatic list generation; Python


code:
import collection
import re

line1 = 'XPAC3出口$<zho>$ASDSA1出口$<chn>$ExitA2$<eng>$YUTY1出口$<fre>'
names = [(n.group(2), n.group(1)) for n in re.finditer("\$?(.*?)\$<(.*?)>", line1, re.UNICODE)]
names = collections.OrderedDict(names)

for key, value in names.iteritems():
    print key, ' ',value

rawDescription: How to maintain order with finditer ()

description: Maintain order with finditer ()


code:
import paramiko
import sys
import os
import subprocess
import cmd
import time
import datetime
import getpass
import re
from netaddr import *

buff = ''
resp = ''
now = datetime.datetime.now()
usr = raw_input('Enter Username:')
pwd = getpass.getpass('Enter Password:')

with open('Fetch.txt') as f:
    for line in f:
        line = line.strip()
        with open(os.devnull, "wb") as limbo:
            ip = line
            result = subprocess.Popen(["ping", "-n", "2", "-w", "200", ip],
                    stdout=limbo, stderr=limbo).wait()
            if result:
                    print ip, "Link Down - Site unreachable"
                    f = open('Down Sites.txt', 'a+')
                    f.write( line + '\n' )
                    f.close()
            else:
                    try:
                        dssh = paramiko.SSHClient()
                        dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                        dssh.connect(line, username=usr, password=pwd,timeout=60)
                        stdin, stdout, stderr = dssh.exec_command('sh run | i hostname')
                        mystring = stdout.read()
                        v = mystring[9:]
                        dssh.connect(line, username = usr, password = pwd)
                        chan = dssh.invoke_shell()
                        chan.send("conf t\n tacacs-server key %s\n"%v)
                        time.sleep(2)
                        resp = chan.recv(9999)
                        f=open('Output.txt',"a+")
                        f.write(resp+ '\n')
                        f.close()
                        print "Command Executed"
                    except Exception as e:
                        err = str(e)
                        f = open('Exceptions.txt', 'a+')
                        f.write(ip + ": " + err + '\n')
                        f.close()
                        print ip, "ERROR:", e
dssh.close()

rawDescription: Python - Retrieve the output of Cisco CLI command and use it as input


code:
#!/usr/bin/python
import apt
import os, sys

if len(sys.argv) != 2:
    print 'Usage: apt-download pkg_name'
    sys.exit()

cache = apt.Cache()
pkg   = cache[sys.argv[1]]
cmd   = 'wget ' + pkg.candidate.uri
print cmd
os.system(cmd)

rawDescription: how to download a package with python-apt?

description: Download a package with python-apt


code:
import time
from threading import Thread

answer = None

def check():
    time.sleep(2)
    if answer != None:
        return
    print "Too Slow"

Thread(target = check).start()

answer = raw_input("Input something: ")

rawDescription: Python 3 Timed Input

description: Python 3 Timed Input


code:
import string
from collections import Counter
s = 'One, two; three! four: five. six@#$,.!'
occurrence = Counter(s.translate(None, string.punctuation).split())
print occurrence

rawDescription: removing punctuation then counting the no of every word occurance using python

description: Removing punctuation then counting the no of every word occurance using python


code:
import sys
max_tries = 3; current_tries = 0
password=input("Enter password:")
while password != 'cat':
    if current_tries > max_tries:
        print "too many tries"
        sys.exit(0)
    print ("password is wrong, try it again")
    password= input ("Enter your password:")
    current_tries +=1

print ("Password correct be happy")

rawDescription: Python: How do you get a programme to prompt the user a certian fixed amount of times for a user input?


code:
from PIL import Image
from PIL import ImageChops
from PIL import ImageDraw

im1 = Image.open('a.jpg')
im2 = Image.open('aa.jpg')

diff = ImageChops.difference(im2, im1).getbbox()

print diff

draw = ImageDraw.Draw(im2)
draw.rectangle(diff, outline = (0,255,0))
print  help(draw.rectangle)
im2 = im2.convert('RGB')
im2.save('aaa.jpg')

rawDescription: Comparing 2 images/pictures by using PIL, some doesn't work


code:
from socketIO_client import SocketIO

def on_response(*args):
    print 'on_response', args

baseurl = "http://devel.hz.udoidio.info"
with SocketIO(baseurl, 5000) as socketIO:
    socketIO.on('new-tx', on_response)
    socketIO.emit('subscribe', 'new-tx')
    socketIO.wait()

rawDescription: How to implement pub/sub socket.io client in python?

description: Implement pub/sub socket.io client in python


code:
from time import gmtime, strftime
print strftime("%z", gmtime())

rawDescription: Get time zone information of the system in Python?


code:
import BaseHTTPServer
import os
import shutil
import sys

FILEPATH = sys.argv[1] if sys.argv[1:] else __file__

class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        with open(FILEPATH, 'rb') as f:
            self.send_response(200)
            self.send_header("Content-Type", 'application/octet-stream')
            self.send_header("Content-Disposition", 'attachment; filename="{}"'.format(os.path.basename(FILEPATH)))
            fs = os.fstat(f.fileno())
            self.send_header("Content-Length", str(fs.st_size))
            self.end_headers()
            shutil.copyfileobj(f, self.wfile)

def test(HandlerClass=SimpleHTTPRequestHandler,
         ServerClass=BaseHTTPServer.HTTPServer,
         protocol="HTTP/1.0"):
    if sys.argv[2:]:
        port = int(sys.argv[2])
    else:
        port = 8000
    server_address = ('', port)

    HandlerClass.protocol_version = protocol
    httpd = BaseHTTPServer.HTTPServer(server_address, HandlerClass)

    sa = httpd.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "...", FILEPATH
    httpd.serve_forever()

if __name__ == '__main__':
    test()

rawDescription: How would I create a Python web server that downloads a file on any GET request?


code:
import tinycss;

css_text="""
.span-class1{
    background: url(images/test.png) no-repeat top left;
    width: 10px;
    height: 10px;
}
"""
css_parser=tinycss.make_parser('page3');

stylesheet=css_parser.parse_stylesheet_bytes(css_text);

for rule in stylesheet.rules:
    #let us reconstruct the css rule
    css_str=rule.selector.as_css()+"{\n";
    for d in rule.declarations:
        prop_css_val='';
        for v in d.value:
            prop_css_val=prop_css_val+' '+v.as_css();
        css_str=css_str+str(d.name)+":"+prop_css_val+";\n"
    css_str=css_str+"}\n"
    print css_str;

rawDescription: Python Tiny CSS - Return Stylesheet (file you can save)?


code:
columns = dict()
columnsTitles = []
rows = dict()
colIdxCounter = 1 # Start with 1 because the first col are ids
rowIdxCounter = 1 # Start with 1 because the columns titles

for i in dataset:
    if not rows.has_key(i[0]):
        rows[i[0]] = rowIdxCounter
        rowIdxCounter += 1
    if not columns.has_key(i[1]):
        columns[i[1]] = colIdxCounter
        colIdxCounter += 1
        columnsTitles.append(i[1])

toRet = [columnsTitles]
for i in range(len(rows)):
    toAppend = []
    for j in range(colIdxCounter):
        toAppend.append("")
    toRet.append(toAppend)

for i in dataset:
    toRet[rows[i[0]]][columns[i[1]]] = i[2]

for i in toRet:
    print i

rawDescription: Format an array of tuples in a nice "table"


code:
import re

regexes = {
  "text": re.compile(r"(.+?)(?:$|\b(?=(Alt|Shft|Spc|Ctrl|Ret|BkSpc|Tab|CpsLk|NmLk|ScrlLk|PgUp|PgDwn|Home|End|Del|Ins|Win|F1?[1-9])\b))"),
  "kwd": re.compile(r"(Alt|Shft|Spc|Ctrl|Ret|BkSpc|Tab|CpsLk|NmLk|ScrlLk|PgUp|PgDwn|Home|End|Del|Ins|Win|F1?[1-9])\b")
}

def tokenise(state):
  while state["src"]:
    state["tok"] = "text" if state["tok"] == "kwd" else "kwd"
    #print "mode: {0:20} {1!r}".format(state["tok"].capitalize(), state["src"])

    m = regexes[state["tok"]].match(state["src"])
    if m:
      match = m.group(0)
      state["src"] = state["src"][m.end():]
      #print "  TOKEN({0}, {1!r})".format(state["tok"], match)
      yield "TOKEN({0}, {1!r})".format(state["tok"], match)

state = {
  "src": "A thing that, Tab, is AltCps or 'Win'. F8 is good, as is: F13.",
  "tok": "text"
}
print repr(state["src"])
print "\n".join(list(tokenise(state)))
print

state = {
  "src": "Alt thing that, Tab, is AltCps or 'Win'. F8 is good, as is: F13.",
  "tok": "text"
}
print repr(state["src"])
print "\n".join(list(tokenise(state)))
print

state = {
  "src": "Alt thing that, Tab, is AltCps or 'Win'. F8 is good, as is: F11",
  "tok": "text"
}
print repr(state["src"])
print "\n".join(list(tokenise(state)))
print

rawDescription: Highlight a bunch of words?

description: Highlight a bunch of words


code:
out = []
buff = []
for c in your_str:
    if c == '\n':
        out.append(''.join(buff))
        buff = []
    else:
        buff.append(c)
else:
    if buff:
       out.append(''.join(buff))

print out

rawDescription: How to convert a string that has newline characters in it into a list in Python?

description: Convert a string that has newline characters in it into a list in Python


code:
date = {}
data = urllib2.urlopen(url)
data_obj = json.loads(data.read())
s = json.dumps(data_obj, sort_keys=True, indent=4)
print s

rawDescription: Python not parsing JSON API return prettily


code:
from bintrees import AVLTree

d = {'a':1, 'b':2, 'c':3}

t = AVLTree(d)

def foo(k, v):
    print k*v

t.foreach(foo)
# a
# bb
# ccc

rawDescription: Bintrees method example

description: Bintrees method example


code:
# Assume you are using the source code I posted
conn = Connection(HOST, USERNAME, PW)
banner = conn.execute('\n') # Fetch banner content
dateResult = conn.execute('date') # Target command result

# since banner is always a subset of dataResult, you can do the following
ret = dataResult.replace(banner, '')
print ret # ret is the answer you want

rawDescription: How to filter ssh banner when using python paramiko

description: Filter ssh banner when using python paramiko


code:
class guibuild:
    def __init__(self):
        self.master = master
        guibuild.progbarlock = False
        self.progbar = Meter(theframe) #makes the progressbar object
        self.progbar.set(0.0) #sets the initial value to 0
        self.progbar.pack(side=LEFT)
        self.counter = 0
        self.i = float(0) #i is the value set to the progressbar

        self.mybutton = Button(theframe, text="My Button", command = self.interval).pack(side = LEFT)

    def stop_progbar(self):
        self.progbar.stop()

    def interval(self):
        if guibuild.progbarlock == False:

            guibuild.progbarlock = True

            the_file = open("sample_running.json")
            data = json.load(the_file)
            curr = data["curr_line"]
            command = data["curr_line_text"]
            total = data["total_lines"]

            print self.counter

            if self.i == 1.0:
                self.stop_progbar
                print "100% - process is done"
                self.master.after_cancel(self.interval)
            elif self.counter == total:
                print "stop" #for debug purposes
                self.i = 1.0
                self.master.after(5000, self.interval)
            elif curr == self.counter:
                print self.counter
                print self.i
                self.master.after(5000, self.interval)
            elif curr == self.counter+1:
                self.i += 1.0/total
                print self.i #debug
                self.progbar.set(self.i) #apply the new value of i to the progressbar
                print "the progressbar should reflect", str(int(round(self.i*100))) +"%progress right now"
                print "the counter will increase"
                self.counter += 1
                print self.counter #debug purposes
                self.stop_progbar
                self.master.after(5000, self.interval)
            else:
                print "something is wrong - running.json is not available"
                self.master.after(5000, self.interval)

            guibuild.progbarlock = False

rawDescription: Tkinter freezing - threads? Progressbar?

description: Tkinter freezing - threads? Progressbar


code:
import struct
val = 0b100
print struct.pack('I', val).encode('base64')

rawDescription: Python: How do I convert from binary to base 64 and back?


code:
import pandas as pd
import numpy as np
import time
import bisect
## df is only here for illustration and date_indicatrice changes upon function call
df     = pd.DataFrame(0, columns=range(6),
                      index=pd.date_range(start = pd.datetime(2010,1,1),
                      end = pd.datetime(2020,1,1), freq="H"))
mat    = pd.DataFrame(0,index=df.index,columns=range(6))
mat_bp = pd.DataFrame(0,index=df.index,columns=range(6*2))

date_indicatrice = [(pd.datetime(2010,1,1), pd.datetime(2010,4,1)),
                    (pd.datetime(2012,5,1), pd.datetime(2019,4,1)),
                    (pd.datetime(2013,4,1), pd.datetime(2019,4,1)),
                    (pd.datetime(2014,3,1), pd.datetime(2019,4,1)),
                    (pd.datetime(2015,1,1), pd.datetime(2015,4,1)),
                    (pd.datetime(2013,6,1), pd.datetime(2018,4,1))]

timer = time.time()

for j, (d1,d2) in enumerate(date_indicatrice):
    ind_start = bisect.bisect_left(mat.index, d1)
    ind_end = bisect.bisect_right(mat.index, d2)
    inds = np.array(xrange(ind_start, ind_end))
    valid_inds = inds[mat.index[ind_start:ind_end].hour >= 8]
    mat.loc[ind_start:ind_end,j]       = 1.
    mat_bp.loc[valid_inds,j*2] = 1.
    mat_bp[j*2+1] = (1 - mat_bp[j*2]) * mat[j]

print time.time()-timer

rawDescription: Code / Loop optimization with pandas

description: Code / Loop optimization with pandas


code:
import unicodecsv as csv
from bs4 import BeautifulSoup
import requests
import StringIO

for numb in range(1, 3):

    urls= "http://www.blocket.se/bostad/uthyres?cg_multi=3020&cg_multi=3100&cg_multi=3120&cg_multi=3060&cg_multi=3070&sort=&ss=&se=&ros=&roe=&bs=&be=&mre=&q=&q=&q=&save_search=1&l=0&md=th&o=" +str(numb) +"&f=p&f=c&f=b&ca=11&w=3"

    r = requests.get(urls)
    soup=BeautifulSoup(r.text, 'html.parser')

    data = soup.find_all("div", {"itemtype": "http://schema.org/Offer"})

    data_list = []
    for item in data:
        data_item = {}
        try:
            data_item['category'] = item.contents[3].find_all("span", {"class": "subject-param category"})[0].text
        except:
            pass
        try:
            data_item['address separator'] =  item.contents[3].find_all("span", {"class": "subject-param address separator"})[0].text
        except:
            pass
        try:
            data_item['first rooms'] = item.contents[3].find_all("span", {"class": "li_detail_params first rooms"})[0].text
        except:
            pass
        try:
            data_item['monthly_rent'] = item.contents[3].find_all("span", {"class": "li_detail_params monthly_rent"})[0].text
        except:
            pass
        try:
            data_item['size'] = item.contents[3].find_all("span", {"class": "li_detail_params size"})[0].text
        except:
            pass
        try:
            data_item['weekly_rent_offseason'] = item.contents[3].find_all("span", {"class": "li_detail_params first weekly_rent_offseason"})[0].text
        except:
            pass
        data_list.append(data_item)
    out = StringIO.StringIO()
    csv_writer = csv.writer(out)
    [csv_writer.writerow(data.values()) for data in data_list]
    print out.getvalue()

rawDescription: Exporting my web scrape results from Python


code:
def primes(max_n):
    numbers = range(3, max_n+1, 2)
    half = (max_n)//2
    initial = 4
    for step in xrange(3, max_n+1, 2):
        for i in xrange(initial, half, step):
            numbers[i-1] = 0
        initial += 2*(step+1)

        if initial > half:
            return [2] + filter(None, numbers)

def rotate(S_list):
    S=[]
    for i in range(len(S_list)):
        S.append(int(S_list[i:]+S_list[:i]))
    return set(S)

def circularPrime(limit):
    All_primes_in_limit = primes(limit)
    circular_prime=[]
    reject_list=['0','2','4','5','6','8']
    All_primes_in_limit=[i for i in All_primes_in_limit if not any(j in reject_list for j in set(str(i)))]
    while All_primes_in_limit:
        ShufleSet=rotate(str(All_primes_in_limit[-1]))
        PrimesSet=set(All_primes_in_limit)
        if not ShufleSet -  PrimesSet:
            circular_prime+=list(ShufleSet)
        All_primes_in_limit=list(PrimesSet-ShufleSet)
    circular_prime.sort()
    return circular_prime

#for limit value 1000000
print circularPrime(1000000)

rawDescription: Circular prime numbers Incorrect Output Python Program


code:
5
42
'hello'
(lambda : 'hello')()
def f():
    print 'this is printed'
    return 'this is returned, and printed by the interpreter'
f()
None

rawDescription: Why does returning in Interactive Python print to sys.stdout?


code:
name = 'harold'
order_id = driver.find_element_by_xpath('//div[@class="boxbody"]//table//tr[td[last()][text()="%s"]]/td[1]/a' % name)
print order_id.text

rawDescription: retrive text in a website table by corresponding value in the same row- selenium and python

description: Retrive text in a website table by corresponding value in the same row- selenium and python


code:
with open(myfile_path) as input_file:
    for line in input_file:
        print line

rawDescription: Python freezes on simple file read and print


code:
from itertools import product

def build_config(db,flag,authType,userPass):
    config = dict(database=db,useExisting=flag)
    config['userCredentials'] = {
        'authType': authType,
        'user': userPass[0],
        'password': userPass[1]
    }
    if authType == 'database':
        config['userCredentials'].update(
            dict(extra=1,param=2))
    return config

database = ['sqlite','mysql','oracle']
useExisting = [True, False]
authType = ['windows','database']
userPass = [('testing1','pass1'),('testing2','pass2')]

for options in product(database,useExisting,authType,userPass):
    config = build_config(*options)
    print config

rawDescription: Generating all possible combinations in a nested dictionary


code:
from collections import deque
d = deque(maxlen=3)
for i in range(1, 7):
    d.append(i)
    print d

rawDescription: Why is python deque initialized using the last maxlen items in an iterable?


code:
import csv
import StringIO

stored_output = StringIO.StringIO()

with open('file.csv', 'rb') as input_csv:
    reader = csv.DictReader(input_csv, delimiter='|', quoting=csv.QUOTE_NONE)
    writer = csv.DictWriter(stored_output, reader.fieldnames, delimiter="|",quoting=csv.QUOTE_NONE, quotechar=None)

    merge_cols = "title1", "title3", "title4"

    writer.writeheader()

    for row in reader:
        row["merge"] = ''.join(row[col] for col in merge_cols)
        writer.writerow(row)

    contents = stored_output.getvalue()
    stored_output.close()
    print contents

with open('file.csv', 'rb') as input_csv:
    input_csv = input_csv.read().strip()

if input_csv != contents.strip():
    with open('file.csv', 'wb') as new_csv:
        new_csv.write("".join(contents))

rawDescription: Attempting to merge three columns in CSV, updating original CSV


code:
def get_connection():
    global db

    if not db:
        db = created_new_connection()
        print "New connection has been created"
    else:
        print "Connection already exists"

    return db

rawDescription: Why the variable is being shared in some Classes but not others?


code:
import random

class Car:
    def __init__ (self, company, doors, id):
        self.company = company
        self.doors = doors
        self.id = id

    def printDoors(self, id):
        print 'Car ' + `self.id` + ' has ' + `self.doors` + ' doors.'

    def findSameDoors(self, id):
        for i in self.company.cars:
            if self.id != i.id and self.doors == i.doors:
                print 'Car ' + `i.id` + ' does too!'

class Company:
    def __init__ (self, types):
        self.types = types
        self.cars = []

    def typesToNum(self):
        result = []
        for i in self.types:
            if i == 'sedan':
                result.append(4)
            elif i == 'convertible':
                result.append(2)
            else:
                result.append(0)
        return result

porsche = Company(['sedan', 'convertible'])
honda = Company(['sedan', 'convertible', 'motorcycle'])

for i in range(10):
    porsche.cars.append(Car(porsche, random.choice(porsche.typesToNum()), i))

for i in range(10):
    honda.cars.append(Car(honda, random.choice(honda.typesToNum()), i))

porsche.cars[0].printDoors(0)
porsche.cars[0].findSameDoors(0)

rawDescription: How to refer to an object's own container

description: Refer to an object's own container


code:
idlink = browser.find_element_by_css_selector("#comic > img")
print idlink.get_attribute("src")

rawDescription: Getting src link of XKCD image?

description: Getting src link of XKCD image