code:
class Car(object):
    def __init__(self,input):
        self.carName = input

    def showName(self):
        print self.carName
def main():
    a = Car("bmw")
    a.showName()
if __name__ == "__main__":
    main()

rawDescription: Python object creation

description: Python object creation


code:
phrase = "this is string example....wow!!!"
word = "example"

word_len = len(word) # word length is 7
phrase_len = len(phrase) # phrase length is 32

#We loop through the phrase using a "window" size equal to the word length
#If we find a match, we return the first and last index of the "current" window
for i in range(phrase_len - word_len+1):
    current = phrase[i:i+word_len]
    if current == word:
        print i,i+word_len-1

#prints 15, 21

rawDescription: How to get left and right most indexes from matching word inside of string

description: Get left and right most indexes from matching word inside of string


code:
for el in searchresults_text:
   print el.text

rawDescription: Selenium Python Using find elements how do i get the text value of each element


code:
def test_employment_form_complete(self):
        """
        Complete employment form passes validation
        """
        applicant = Applicant(job_id=1)
        applicant.save()
        data = {
            'applicant': 1,
        'company': 'test company',
        'town': 'test town',
        'salary': '1000000',
        'job_title': 'test job name',
        'responsibilities': 'test responsibilities',
        'date_from': '01/01/1990',
        'date_to': '01/02/1991',
        'reason_for_leaving': 'test reason for leaving'
        }
        employment_form = EmploymentForm(instance=applicant, data=data)
        result = employment_form.is_valid()
        print "errors %s" % employment_form.errors
        self.assertEqual(result, True)

rawDescription: Error Unit testing a ModelForm

description: Error Unit testing a ModelForm


code:
def myfuncone(id, **kwargs):
    print kwargs.keys()

import functools
myfuncone_with_context = functools.partial(myfuncone, context=mycontextone)
app.add_url_rule('/myproj/one', methods=['GET'],
                 view_func=myfuncone_with_context)

rawDescription: Can Flask remember and return additional context with the request routing?


code:
import multiprocessing
import Queue

TIMEOUT = 5

def big_loop(bob):
    import time
    time.sleep(4)
    return bob*2

def wrapper(queue, bob):
    result = big_loop(bob)
    queue.put(result)
    queue.close()

def run_loop_with_timeout():
    bob = 21 # Whatever sensible value you need
    queue = multiprocessing.Queue(1) # Maximum size is 1
    proc = multiprocessing.Process(target=wrapper, args=(queue, bob))
    proc.start()

    # Wait for TIMEOUT seconds
    try:
        result = queue.get(True, TIMEOUT)
    except Queue.Empty:
        # Deal with lack of data somehow
        result = None
    finally:
        proc.terminate()

    # Process data here, not in try block above, otherwise your process keeps running
    print result

if __name__ == "__main__":
    run_loop_with_timeout()

rawDescription: kill a function after a certain time in windows

description: Kill a function after a certain time in windows


code:
import os

files = []
folders = []
for (path, dirnames, filenames) in os.walk('Data'):
    folders.extend(os.path.join(path, name) for name in dirnames)
    files.extend(os.path.join(path, name) for name in filenames)

print files
print folders

rawDescription: Getting paths of each file of a directory into an Array in python


code:
from selenium import webdriver
from time import sleep
driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.HTMLUNITWITHJS)
driver.get('http://www.omegle.com/')
interval = 10  #or whatever interval you want
while True:
    element = driver.find_element_by_id("onlinecount")
    print element.text.split()[0]
    sleep(interval)

rawDescription: Use Selenium Webdriver to get periodically updated content


code:
import urllib
import threading
import datetime

pages = ['http://google.com', 'http://yahoo.com', 'http://msn.com']

#------------------------------------------------------------------------------
# Getting the pages WITHOUT threads
#------------------------------------------------------------------------------
def job(url):
    response = urllib.urlopen(url)
    html = response.read()

def runjobs():
    for page in pages:
        job(page)

start = datetime.datetime.now()
runjobs()
end = datetime.datetime.now()

print "jobs run in {} microseconds WITHOUT threads" \
      .format((end - start).microseconds)

#------------------------------------------------------------------------------
# Getting the pages WITH threads
#------------------------------------------------------------------------------
def job(url):
    response = urllib.urlopen(url)
    html = response.read()

def runjobs():
    threads = []
    for page in pages:
        t = threading.Thread(target=job, args=(page,))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

start = datetime.datetime.now()
runjobs()
end = datetime.datetime.now()

print "jobs run in {} microsecond WITH threads" \
      .format((end - start).microseconds)

rawDescription: python apscheduler, an easier way to run jobs?

description: Python apscheduler, an easier way to run jobs


code:
class Foo(object):
    def frob(self, arg):
        print "Foo.frob"
        if hasattr(super(Foo, self), 'frob'):
            super(Foo, self).frob(arg)

class Bar(object):
    def frob(self, arg):
        print "Bar.frob"
        if hasattr(super(Bar, self), 'frob'):
            super(Bar, self).frob(arg)

class Baz(Foo, Bar):
    def frob(self, arg):
        print "Baz.frob"
        super(Baz, self).frob(arg)

b = Baz()
b.frob(1)

rawDescription: Can Super deal with multiple inheritance?


code:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
print root.find(".//ref").tail

rawDescription: python ElementTree the text of element who has a child

description: Python ElementTree the text of element who has a child


code:
import os
def GetFiles(dir,f):
    basedir = dir
    subdirs = []
    for fname in os.listdir(dir):
        fileName = os.path.join(basedir, fname)
        if os.path.isfile(fileName):
            if fileName.endswith(".txt"):
                f.write(fileName+"\n")
                print fileName
        elif os.path.isdir(fileName):
            subdirs.append(fileName)
    for subdir in subdirs:
        GetFiles(subdir,f)
f=open("test.txt",'w')
GetFiles('./',f)
f.close()

rawDescription: Printing the output that is a list of file names to a text file


code:
d = {'a': '', 'b': '', 'c': ''}
stuff = []
stuff.append(d)
print stuff
d['a'] = 'other'
print stuff
stuff.append(d)
print stuff
d['a'] = 'yet another'
print stuff

rawDescription: Filling a python dictionary in for loop returns same values


code:
""" Random Walker """
import random as rd
import time

def procedure():
    n = int(input('Number of Individuals at Table: '))

    t0C = time.clock()
    t0 = time.time()

    iters = 10000
    final = [0] * n
    total = 0
    for j in xrange(iters):
        last = 0
        count = 1
        seen = set([0])
        while len(seen) < n:
            count += 1;
            new = last + rd.choice([-1, 1])
            if new < 0:
                new += n
            elif new >= n:
                new -= n
            seen.add(new)
            last = new
        final[last] += 1
        total += count

    final = [round(float(f) / iters, 4) for f in final]
    total = round(float(total) / iters, 3)

    """Writing To A File"""

    print(40 * '-')
    print(" ")
    print("   Percentages: ")
    print(" ")
    print("   S#:" + "      S#:".join(map(str, range(n))))
    print("   " + "%   ".join(map(str, final)) + "%")
    print(" ")
    print("   Average Number of Passes of Plate: {}".format(total))
    print(" ")
    print(40 * '-')

    # measure process time
    print time.clock() - t0C, "seconds process time"

    # measure wall time
    print time.time() - t0, "seconds wall time"

if __name__ == "__main__":
    procedure()

rawDescription: Random walker code python

description: Random walker code python


code:
import re
user = 'Sam'
password = 'Somepass'
with open("test.txt",'r') as file:
    if re.search('\s*{0}\s+{1}\s*'.format(user, password), file.read(), flags=re.M):
        print 'yes'
    else:
        print 'no'

rawDescription: This regex seems to be not working in Python


code:
import re

pattern = re.compile(r'VERSION\s*=\s*(\d+)')  # \s: space, \d: digits

with open('Makefile') as mkfh:
    for line in mkfh:
        matched = pattern.match(line)
        if matched:
            print matched.group(1)
            break

rawDescription: efficiently read major version number from a file

description: Efficiently read major version number from a file


code: print "0x%X" % value

rawDescription: How can I get Python to use upper case letters to print hex values?

description: Get Python to use upper case letters to print hex values


code:
start = ('a', 'b')
for ending in itertools.combinations(set(alphabet) - set(start), 3):
    print start + ending

rawDescription: Python: create combinations of N where 2 of the items are constant


code:
from Repository import Repository

__all__ = ['Repository']

def main(path):
    import sys
    _module_ = sys.modules[__name__]
    if hasattr(_module_, 'WORKING_PATH'):
        for m in __all__:
            if __name__ + "." + m in sys.modules:
                m = sys.modules[__name__ + "." + m]
                reload(m)
    else:
        _module_.WORKING_PATH = path

if __name__ == 'yap':
    print "yap loaded"

rawDescription: Force class reloading when the module is reloaded


code:
from PIL import Image
img = Image.open(basefile)
layer = Image.open(layerfile) # this file is the transparent one
print layer.mode # RGBA
img.paste(layer, (xoff, yoff), mask=layer)
# the transparancy layer will be used as the mask
img.save(outfile)

rawDescription: Transparent PNG in PIL turns out not to be transparent


code:
while 1:
    serial_line = ser.readline()
    dumpfile.write(str(serial_line))
    print serial_line #for debug
    if len(serial_line) == 0:
      break

rawDescription: Read output from serial with pyserial.

description: Read output from serial with pyserial.


code:
info = []
for model in modelslist:
    htmltext = urllib.urlopen("http://dx.com/p/GetProductInfoRealTime?skus="+model)
    htmltext = json.load(htmltext)
    if htmltext['success'] == True:
        def get_data(dict_index, key):
            return htmltext[u"data"][dict_index][key]
        for description in descriptionlist:
            info.append(description)
            info.append(get_data(0,description))
print info

rawDescription: Python json dictionary to array

description: Python json dictionary to array


code:
process=subprocess.Popen([PathToProcess],stdin=subprocess.PIPE,stdout=subprocess.PIPE);
for i in xrange(StepsToComplete):
    print "Forcing step # %s"%i
    process.stdin.write("\n")
    result=process.stdout.readline()

rawDescription: Starting and Controlling an External Process via STDIN/STDOUT with Python


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''\
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

কথায় বলে- মাছে ভাতে বাঙালি।

কবি ঈশ্বর গুপ্ত আরেক ধাপ এগিয়ে বলেন, 'ভাত-মাছ খেয়ে বাঁচে বাঙ্গালি সকল/ ধানে ভরা ভ
''', 'lxml')
soup
soup.get_text()
print soup.get_text()

rawDescription: decode utf-8 content in python

description: Decode utf-8 content in python


code:
N = 100  # starting line number
n = 10   # size of a chunk
with open(fname) as f:
    f = islice(f, N, None)  # creates an iterator that starts after N lines
    while True:
        next_n_lines = list(islice(f, n))
        for line in next_n_lines:
            print line.rstrip()
        if not next_n_lines:
            break

rawDescription: Read a file from a specic line and N lines at a time


code: print map(sum, vrt)

rawDescription: Read list in python

description: Read list in python


code:
import numpy as np
import matplotlib.pyplot as plt

from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist.floating_axes as floating_axes
import mpl_toolkits.axisartist.angle_helper as angle_helper
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist.grid_finder import MaxNLocator

# define how your plots look:

def setup_axes(fig, rect, theta, radius):

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()

    # Find grid values appropriate for the coordinate (degree).
    # The argument is an approximate number of grids.
    grid_locator1 = angle_helper.LocatorD(2)

    # And also use an appropriate formatter:
    tick_formatter1 = angle_helper.FormatterDMS()

    # set up number of ticks for the r-axis
    grid_locator2 = MaxNLocator(4)

    # the extremes are passed to the function
    grid_helper = floating_axes.GridHelperCurveLinear(tr,
                                extremes=(theta[0], theta[1], radius[0], radius[1]),
                                grid_locator1=grid_locator1,
                                grid_locator2=grid_locator2,
                                tick_formatter1=tick_formatter1,
                                tick_formatter2=None,
                                )

    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
    fig.add_subplot(ax1)

    # adjust axis
    # the axis artist lets you call axis with
    # "bottom", "top", "left", "right"
    ax1.axis["left"].set_axis_direction("bottom")
    ax1.axis["right"].set_axis_direction("top")

    ax1.axis["bottom"].set_visible(False)
    ax1.axis["top"].set_axis_direction("bottom")
    ax1.axis["top"].toggle(ticklabels=True, label=True)
    ax1.axis["top"].major_ticklabels.set_axis_direction("top")
    ax1.axis["top"].label.set_axis_direction("top")

    ax1.axis["left"].label.set_text("R")
    ax1.axis["top"].label.set_text(ur"$\alpha$ [\u00b0]")

    # create a parasite axes
    aux_ax = ax1.get_aux_axes(tr)

    aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax
    ax1.patch.zorder=0.9 # but this has a side effect that the patch is
                         # drawn twice, and possibly over some other
                         # artists. So, we decrease the zorder a bit to
                         # prevent this.

    return ax1, aux_ax

#
# call the plot setup to generate 3 subplots
#

fig = plt.figure(1, figsize=(8, 4))
fig.subplots_adjust(wspace=0.3, left=0.05, right=0.95)

ax1, aux_ax1 = setup_axes(fig, 131, theta=[0, 90], radius=[0, 1])
ax2, aux_ax2 = setup_axes(fig, 132, theta=[0, 90], radius=[0, 1])
ax3, aux_ax3 = setup_axes(fig, 133, theta=[0, 90], radius=[0, 1])

#
# generate the data to plot
#
theta = np.linspace(0,90) # in degrees
radius = np.cos(6.*theta * pi/180.0)**2.0

#
# populate the three subplots with the data
#
aux_ax1.plot(theta, radius, 'r')
aux_ax2.plot(theta, radius, 'b')
aux_ax3.plot(theta, radius, 'g')

plt.show()

rawDescription: How to clip polar plot in pylab/pyplot

description: Clip polar plot in pylab/pyplot


code:
# Original Author: Gergely Erdelyi <gergely.erdelyi@d-dome.net>
from idaapi import *

class MyDbgHook(DBG_Hooks):
    """ This class implements the various callbacks required.
    """

    def dbg_process_start(self, pid, tid, ea, name, base, size):
        print("Process started, pid=%d tid=%d name=%s" % (pid, tid, name))

    def dbg_process_exit(self, pid, tid, ea, code):
        print("Process exited pid=%d tid=%d ea=0x%x code=%d" % (pid, tid, ea, code))

    def dbg_library_unload(self, pid, tid, ea, info):
        print("Library unloaded: pid=%d tid=%d ea=0x%x info=%s" % (pid, tid, ea, info))
        return 0

    def dbg_process_attach(self, pid, tid, ea, name, base, size):
        print("Process attach pid=%d tid=%d ea=0x%x name=%s base=%x size=%x" % (pid, tid, ea, name, base, size))

    def dbg_process_detach(self, pid, tid, ea):
        print("Process detached, pid=%d tid=%d ea=0x%x" % (pid, tid, ea))
        return 0

    def dbg_library_load(self, pid, tid, ea, name, base, size):
        print "Library loaded: pid=%d tid=%d name=%s base=%x" % (pid, tid, name, base)

    def dbg_bpt(self, tid, ea):
        print "Break point at 0x%x pid=%d" % (ea, tid)
        # return values:
        #   -1 - to display a breakpoint warning dialog
        #        if the process is suspended.
        #    0 - to never display a breakpoint warning dialog.
        #    1 - to always display a breakpoint warning dialog.
        return 0

    def dbg_suspend_process(self):
        print "Process suspended"

    def dbg_exception(self, pid, tid, ea, exc_code, exc_can_cont, exc_ea, exc_info):
        print("Exception: pid=%d tid=%d ea=0x%x exc_code=0x%x can_continue=%d exc_ea=0x%x exc_info=%s" % (
            pid, tid, ea, exc_code & idaapi.BADADDR, exc_can_cont, exc_ea, exc_info))
        # return values:
        #   -1 - to display an exception warning dialog
        #        if the process is suspended.
        #   0  - to never display an exception warning dialog.
        #   1  - to always display an exception warning dialog.
        return 0

    def dbg_trace(self, tid, ea):
        print("Trace tid=%d ea=0x%x" % (tid, ea))
        # return values:
        #   1  - do not log this trace event;
        #   0  - log it
        return 0

    def dbg_step_into(self):
        print("Step into")
        self.dbg_step_over()

    def dbg_run_to(self, pid, tid=0, ea=0):
        print "Runto: tid=%d" % tid
        idaapi.continue_process()

    def dbg_step_over(self):
        eip = GetRegValue("EIP")
        print("0x%x %s" % (eip, GetDisasm(eip)))

        self.steps += 1
        if self.steps >= 5:
            request_exit_process()
        else:
            request_step_over()

# Remove an existing debug hook
try:
    if debughook:
        print("Removing previous hook ...")
        debughook.unhook()
except:
    pass

# Install the debug hook
debughook = MyDbgHook()
debughook.hook()
debughook.steps = 0

# Stop at the entry point
ep = GetLongPrm(INF_START_IP)
request_run_to(ep)

# Step one instruction
request_step_over()

# Start debugging
run_requests()

rawDescription: what is the equivalent of ni si in IDA python?

description: What is the equivalent of ni si in IDA python


code:
import numpy as np
data = np.random.randn(3000000,50)
newData = data.reshape(300,10000,50) # This is as [300,10000,50] array

print newData[0,...] # Show the first matrix, 1 of 300

rawDescription: Converting 2d array into 3d array in python


code:
import urllib2
from StringIO import StringIO
from lxml import etree
url = "http://www.bnm.gov.my/index.php?ch=109&pg=294&mth=3&yr=2012&eId=box1"
ufile = urllib2.urlopen(url)
root = etree.parse(ufile, etree.HTMLParser())
for e in root.getiterator('tr'):
    fc = e[0]       # first child
    if fc.tag == 'td' and fc.text == '2.1':
        link = fc.getnext().getnext()[0]  # first child of 2nd sibling
        print link.attrib["href"]

rawDescription: use of cssselect for fetching the url using lxml

description: Use of cssselect for fetching the url using lxml


code:
import cmd

class MainConsole(cmd.Cmd):
    def __init__(self,console_id):
       cmd.Cmd.__init__(self)
       self.console_id = console_id
    def do_something(self, line):
       print "do something!",self.console_id
       return

    def do_something2(self, line):
       print "do something2!",self.console_id
       return

class SubConsole1(cmd.Cmd):

    def __init__(self, maincon):
        cmd.Cmd.__init__(self)
        self.maincon = maincon
        self.register_main_console_methods()

    def do_super_commands(self,line):
        print "do supercommand",self.maincon

    def register_main_console_methods(self):
        main_names = dir(self.maincon)
        for name in main_names:
            for prefix in 'do_','help_','complete_', :
                if name.startswith(prefix) and name not in dir(self):
                    self.__dict__[name] = getattr(self.maincon, name)

    def get_names(self):
        result = cmd.Cmd.get_names(self)
        result+=self.maincon.get_names()
        return result

SubConsole1(MainConsole("mainconsole")).cmdloop()

rawDescription: python Cmd module autocompletion error in nested interpreters

description: Python Cmd module autocompletion error in nested interpreters


code:
import clr
import System
clr.AddReference("Microsoft.VisualBasic")
from Microsoft.VisualBasic import Financial

values = System.Array[float]([ -70000.0, 22000.0, 25000.0, 28000.0, 31000.0 ])
fixedRetRate = 0.0625
(netPVal, refValues) = Financial.NPV(fixedRetRate, values)
print netPVal

rawDescription: How to implement NPV, IRR, etc. in IronPython

description: Implement NPV, IRR, etc. in IronPython


code:
import urllib2
import base64
theurl = 'http://abc.com/A.xml'

username='AAA'
password='BBB'

req = urllib2.Request(theurl)

base64string = base64.encodestring(
            '%s:%s' % (username, password))[:-1]
authheader =  "Basic %s" % base64string
req.add_header("Authorization", authheader)
try:
    handle = urllib2.urlopen(req)
except IOError, e:
    print "It looks like the username or password is wrong."
xml = handle.read()
inputXml  = etree.fromstring(xml)

rawDescription: secure xml parsing in python

description: Secure xml parsing in python


code:
from lxml import html
import requests

page = requests.get('http://en.wikipedia.org/wiki/List_of_cities_in_China')
tree = html.fromstring(page.text)

huabeiTree=tree.xpath('//table[@class="wikitable sortable"]')
list_of_cities_table = huabeiTree[0] # table[0] is what we need

# Iterate over the table, get all the <tr> nodes
#then get the values of cities with tr[0][0].text
for tr in list_of_cities_table:
    if tr[0].tag == 'td':
        print tr[0][0].text

rawDescription: Extracting all cities in Wikipedia

description: Extracting all cities in Wikipedia


code:
import re

string="""
####1
ttteest
####1
ttttteeeestt

####2

ttest
####2
"""

end='.*\n'
line=[]
for m in re.finditer(end, string):
    line.append(m.end())

pattern = '.*?####(.*?)####'
match=re.compile(pattern, re.MULTILINE|re.DOTALL)
for m in re.finditer(match, string):
    print 'lineno :%d, %s' %(next(i for i in range(len(line)) if line[i]>m.start(1)), m.group(1))

rawDescription: python regex, match in multiline, but still want to get the line number

description: Python regex, match in multiline, but still want to get the line number


code:
from PyQt4 import Qt, QtGui, QtCore

app=QtGui.QApplication([])
w=QtGui.QWidget()
QtGui.QVBoxLayout(w)

buttons = []
for i in range(5):
    new_button = QtGui.QPushButton("click me %d" % i, w)
    w.layout().addWidget(new_button)

    # here is the dynamically created function
    # use keyword arguments to keep track of the button
    # or any other variable
    def button_clicked(button=new_button):
        print "User clicked on", button.text()
    QtCore.QObject.connect(new_button, Qt.SIGNAL("clicked()"), button_clicked)

w.show()
app.exec_()

rawDescription: PyQT How to build UI according to List?

description: PyQT How to build UI according to List


code:
class LazyMeta(type):
    def __init__(cls, name, bases, attr):
        super(LazyMeta, cls).__init__(name, bases, attr)
        def prop( x ):
            return property(lambda self: self._lazy_eval(x))
        for x in attr['lazyattrs']:
            setattr(cls, x, prop(x))

class Base(object):
    __metaclass__ = LazyMeta
    lazyattrs = []
    def _lazy_eval(self, attr):
        #Do complex stuff here
        return attr

class Child(Base):
    lazyattrs = ['foo', 'bar']

me = Child()

print me.foo
print me.bar

rawDescription: Can I create class properties during __new__ or __init__?

description: Create class properties during __new__ or __init__


code:
with open("filename") as f:
    cols = [float(row.split("-")[-2]) for row in f.readlines()]
print min(cols), max(cols), sum(cols) / len(cols)

rawDescription: Find the min max and average of one column of data in python


code:
class catchtime:
    def __enter__(self):
        self.t = time.clock()
        return self

    def __exit__(self, type, value, traceback):
        self.e = time.clock()

    def __float__(self):
        return float(self.e - self.t)

    def __coerce__(self, other):
        return (float(self), other)

    def __str__(self):
        return str(float(self))

    def __repr__(self):
        return str(float(self))

with catchtime() as t:
    pass

print t
print repr(t)
print float(t)
print 0+t
print 1*t

1.10000000001e-05
1.10000000001e-05
1.10000000001e-05
1.10000000001e-05
1.10000000001e-05

rawDescription: Python context manager that measures time


code:
from collections import defaultdict
filenames2fuzz = defaultdict(list)

for dir_entry in os.listdir(path):
    dir_entry_path = os.path.join(path, dir_entry)
    if os.path.isfile(dir_entry_path):
        first5lines = []
        condition_matched_in_file = False
        with open(dir_entry_path, 'r') as my_file:
            for line_nbr, line in enumerate(my_file):
                if line_nbr < 5:
                    first5lines.append(line)
                for part in line.split():
                    if "color=" in part:
                        print part
                        string1= "Filename:", dir_entry_path
                        print(string1)
                        condition_matched_in_file = True

                        fuzziness = fuzz.ratio(string1, first5lines[0])
                        filenames2fuzz[dir_entry_path].append(fuzziness)
                        print(fuzziness)
        if condition_matched_in_file:
            print('\n'.join(first5lines))

# Now that you have a dictionary that holds all filenames with
# their fuzziness values, you can easily find the first 5 lines again
# of the file that has the best fuzziness value.

best_fuzziness_ratio = 0  # as far as I can tell, the docs indicate it is between 0 and 100
for k, v in filenames2fuzz.items():
    if max(v) > best_fuzziness_ratio:
        best_fuzzy_file = k
        best_fuzziness_ratio = max(v)
print('File {} has the highest fuzzy value '
    'of {}. \nThe first 5 lines are:\n'
    ''.format(best_fuzzy_file, best_fuzziness_ratio))
with open(best_fuzzy_file) as f:
    for i in range(5):
        print(f.readline())

rawDescription: python find max value and print first 5 lines of file

description: Python find max value and print first 5 lines of file


code:
import ctypes

VK_CAPITAL = 0x14

if ctypes.windll.user32.GetKeyState(VK_CAPITAL) & 1:
    print "Caps Lock On"
else:
    print "Caps Lock Off"

rawDescription: Win7 query hardware keyboard Caps Lock current state


code:
print "Opening communications serial...\n"
ser = serial.Serial('/dev/ttyUSB1',115200,timeout=1)
ser.open()
#check continous loop
print "Starting main loop\n"

while True:
  message = CheckUnreadMsgs(ser)
  a = message.find('\n') + 63
  b = len(message)
  msg = message[a:b]
  m = re.search("(pow.*)",msg)
  if m:
      mm = (m.group(1))
      if "on" in mm:
         print "Power On"
      elif "off" in mm:
         print "Power Off"

rawDescription: Extracted SMS body and passing it in a condition (Python)


code:
def foo(var):
    print var

module.foo_module(foo)

def foo_module(foo):
    foo("Hello world!")

rawDescription: Import module that contains main module functions


rawDescription: Python number of elements inside a list

description: Python number of elements inside a list


code:
for image in soup.findAll("img"):
        print "Old Image Path: %(src)s" % image
        #Get file name
        filename = image["src"].split("/")[-1]
        #Get full path name if url has to be parsed
        parsedURL[2] = image["src"]
        image["src"] = '%s\%s' % (phonepath,filename)
        #Old File path (local to computer)
        #image["src"] = '%s\%s' % (out,filename)
        print 'New Path: %s' % image["src"]
        #       print image
        outpath = os.path.join(out, filename)

        #retrieve images
        if parsedURL[2].lower().startswith("http"):
            #urlretrieve(image["src"], outpath)
            urlretrieve(parsedURL[2], outpath)
            print image["src"].lower()
        else:
            print "HTTP INFO " + urlparse.urlunparse(parsedURL)
            print "HTTP INFO " + image["src"].lower()
            urlretrieve(urlparse.urlunparse(parsedURL), outpath) #Constructs URL from tuple (parsedURL)
            #print image["src"].lower()

rawDescription: Unable to open images downloaded using beautiful soup library


code:
path,=cursor.fetchone()
print path

rawDescription: How to replace () and , from the fatched data of mysql database

description: Replace () and , from the fatched data of mysql database


code:
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get("http://www.tabele-kalorii.pl/kalorie,Actimel-cytryna-miod-Danone.html")
table = driver.find_element_by_xpath(u"//table[tbody/tr/td/h3 = 'Wartości odżywcze']")
for row in table.find_elements_by_css_selector("tr.tr-gorna-kreska"):
    cells = [td.text for td in row.find_elements_by_tag_name("td")]
    print cells

rawDescription: Can't get value from xpath python

description: Can't get value from xpath python


code:
import msvcrt, os, sys

msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
while True:
    ch = sys.stdin.read(1)
    print ord(ch)  # CRLF should appear as 13 followed by 10

rawDescription: Python: svndumpfilter2 and new line characters on Windows


rawDescription: wxpython event handling: GetValue after key is pressed

description: Wxpython event handling: GetValue after key is pressed


code:
import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
print goal_dir  # prints C:/here/I/am/../../my_dir
print os.path.normpath(goal_dir)  # prints C:/here/my_dir
print os.path.realpath(goal_dir)  # prints C:/here/my_dir
print os.path.abspath(goal_dir)  # prints C:/here/my_dir

rawDescription: Python joining current directory and parent directory with os.path.join


rawDescription: Remove duplicate sublists from a list

description: Remove duplicate sublists from a list


code:
def roll(m):
    rolls = []
    tot = 0
    while tot < m:
        r = rdm.randint(1,6)
        tot += r
        rolls.append(r)
    return tot, rolls, r
tot, rolls, r = roll(m)
print "The number of rolls was", len(rolls)
print "The total is", tot

rawDescription: while loop not looping in python

description: While loop not looping in python


code:
#!/usr/bin/env python
query = ["football", "basketball", "martial arts", "baseball"]
lists = [["apple", "football", "basketball court"], ["ball"], ["martial-arts", "baseball", "banana", "food", "doctor"]]
from random import random

def fake_levenshtein(word1, word2):
    return random()

def avg_list(l):
        return reduce(lambda x, y: x + y, l) / len(l)

for l in lists:
    score = []
    for w1 in l:
        for w2 in query:
            score.append(fake_levenshtein(w1, w2))
    print avg_list(score)

rawDescription: Similarity score of two lists with strings


code:
from PIL import Image, ImageDraw, ImageFont

FULL_SIZE = 100
filename = 'font_posn_test.png'
fontname = '/usr/share/fonts/truetype/msttcorefonts/arial.ttf'
textsize = 40
text = "5"

image = Image.new("RGBA", (FULL_SIZE, FULL_SIZE))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(fontname, textsize)
print font.getoffset(text)
print font.font.getsize(text)
font_width, font_height = font.getsize(text)

font_y_offset = font.getoffset(text)[1] # <<<< MAGIC!

draw.rectangle(((0, 0), (font_width, font_height)), fill="black")
draw.text((0, 0 - font_y_offset), text, font=font, fill="red")
image.save(filename, "PNG")

rawDescription: Python image library - font positioning

description: Python image library - font positioning


code:
users_grpd_flattened = (pairs.groupByKey().
    map(lambda (k, vals): "{0}, {1}".format(k, ' '.join(str(x) for x in vals))))

rawDescription: Saving PairedRDD as a text file

description: Saving PairedRDD as a text file


code:
import numpy as np

A = np.random.normal(size=(3,4))

x = np.random.normal(size=(4,20))

y = np.dot(A,x)

print y.shape

rawDescription: compute matrix product for multiple inputs

description: Compute matrix product for multiple inputs


code:
import shelve
myshelf = shelve.open("filename") # Might turn into filename.db
myshelf["A"] = "First letter of alphabet"
print myshelf["A"]
# ...
myshelf.close()   # You should do this explicitly when you're finished

rawDescription: I need a class that creates a dictionary file that lives on disk


code:
from nltk.corpus import wordnet as wn
from nltk.tokenize import word_tokenize

def max_wupa(context_sentence, ambiguous_word):
  """
  WSD by Maximizing Wu-Palmer Similarity.

  Perform WSD by maximizing the sum of maximum Wu-Palmer score between possible
  synsets of all words in the context sentence and the possible synsets of the
  ambiguous words (see http://goo.gl/XMq2BI):
  {argmax}_{synset(a)}(\sum_{i}^{n}{{max}_{synset(i)}(Wu-Palmer(i,a))}

  Wu-Palmer (1994) similarity is based on path length; the similarity between
  two synsets accounts for the number of nodes along the shortest path between
  them. (see http://acl.ldc.upenn.edu/P/P94/P94-1019.pdf)
  """

  result = {}
  for i in wn.synsets(ambiguous_word):
    result[i] = sum(max([i.wup_similarity(k) for k in wn.synsets(j)]+[0]) \
                    for j in word_tokenize(context_sentence))
  result = sorted([(v,k) for k,v in result.items()],reverse=True)
  return result

bank_sents = ['I went to the bank to deposit my money',
'The river bank was full of dead fishes']
ans = max_wupa(bank_sents[0], 'bank')
print ans
print ans[0][1].definition

rawDescription: Semantic Relatedness Algorithms - python


code:
import sys

try:
    while 1:
        print 'To infinity and beyond!'
    # etc etc...

except KeyboardInterrupt:
    print 'Handling the keyboard interrupt...'

rawDescription: keybord interrupt event listener

description: Keybord interrupt event listener


code:
def valid_month(month):
    for x in months:
        if x[1:] == month[1:] and x[0].capitalize() == month[0].capitalize():
            print x

rawDescription: How to make a case sensitive string compare in Python?

description: Make a case sensitive string compare in Python


code:
from apscheduler.schedulers.blocking import BlockingScheduler

def some_job():
    print "Decorated job"

scheduler = BlockingScheduler()
scheduler.add_job(some_job, 'interval', hours=1)
scheduler.start()

rawDescription: Scheduling Python Script to run every hour accurately


code:
# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

rawDescription: Is it possible to pass messages to/from an .exe using Python?


code:
class spaceParser(object):
    result = {}
    last_title = ""
    last_content = ""

    def process_content(self, content_line):
        if self.last_title:
            self.last_content = self.last_content + content_line.strip()
            self.result[self.last_title] = self.last_content

    def process_title(self, content_line):
        self.last_title = content_line.strip()
        self.last_content = ""

    def parse(self, raw_file):
        for line in raw_file:
            #look for patterns based in tabulation
            if line[0:4] == "    ":
                #content type
                self.process_content(line)
            elif line[0:2] == "  ":
                #title type
                self.process_title(line)
            else:
                #other types
                pass
        #append the last one
        self.process_content("")

parser = spaceParser()
with open('appendix.txt', 'r') as raw_file:
    parser.parse(raw_file)

print parser.result

rawDescription: Get the section of each heading on heading:section pair in dict


code:
if xo.st in sts:
    print sts.index(xo.st)

rawDescription: Python: Get index if in statement evaluates true


code:
from pwd import getpwnam

print getpwnam('someuser')[2]
# or
print getpwnam('someuser').pw_uid

rawDescription: Python: finding uid/gid for a given username/groupname (for os.chown)


code:
from xml.dom.minidom import parseString

XML = """
<nodeA>
    <nodeB>Text hello</nodeB>
    <nodeC><noText></noText></nodeC>
</nodeA>
"""

def replaceText(node, newText):
    if node.firstChild.nodeType != node.TEXT_NODE:
        raise Exception("node does not contain text")

    node.firstChild.replaceWholeText(newText)

def main():
    doc = parseString(XML)

    node = doc.getElementsByTagName('nodeB')[0]
    replaceText(node, "Hello World")

    print doc.toxml()

    try:
        node = doc.getElementsByTagName('nodeC')[0]
        replaceText(node, "Hello World")
    except:
        print "error"

if __name__ == '__main__':
    main()

rawDescription: Python minidom/xml : How to set node text with minidom api


code: print rcvPkt[0].getlayer(IP).src

rawDescription: Getting source IP of packet using Scapy

description: Getting source IP of packet using Scapy


code:
for k, v in values.iteritems():
    if k: # if k has a value indicating this is a header:
        continue  # skip it
    if not isinstance(v, float):
        print 'bad value: ', k, v

rawDescription: How can I have access to values in a table with values() or iteritems()

description: Have access to values in a table with values() or iteritems()


code:
from selenium import webdriver
import time, re
from selenium.webdriver.support.ui import Select
import lxml.html
from bs4 import BeautifulSoup

driver = webdriver.Firefox()
driver.get("http://surge.srcc.lsu.edu/s1.html")

# definition for switching frames
def frame_switch(css_selector):
  driver.switch_to.frame(driver.find_element_by_css_selector(css_selector))

frame_switch("iframe")

html_source = driver.page_source

nameSelect = Select(driver.find_element_by_xpath('//select[@id="storm_name"]'))
stormCount = len(nameSelect.options)

for i in range(1, stormCount):
    print("starting loop on option storm " + nameSelect.options[i].text)
    nameSelect.select_by_index(i)
    time.sleep(3)

    yearSelect = Select(driver.find_element_by_xpath('//select[@id="year"]'))
    yearCount = len(yearSelect.options)
    for j in range(1, yearCount):
        print("starting loop on option year " + yearSelect.options[j].text)
        yearSelect.select_by_index(j)

        time.sleep(10)

        soup = BeautifulSoup(driver.page_source, 'html.parser')

        # get the needed table body
        print soup.find_all("tbody", {"class" : re.compile(".*")})[1].prettify()

        # print out each column

        get_table = soup.find_all("tbody", {"class" : re.compile(".*")})[1]
        columns = get_table.find_all("tr")

        for column in columns:
           print column.getText()

rawDescription: Dynamic Table Scraping with selenium in python


code: print data[:, 0:1].shape

rawDescription: The shape of a sliced array

description: The shape of a sliced array


code:
import sys

with open(sys.argv[1], 'r') as input:
    test_cases = input.read().strip().splitlines()

for orig_number in test_cases:
    iteration = 0
    while True:
        if orig_number == orig_number[::-1]:
            print iteration, orig_number
            break
        iteration += 1
        orig_number = str(int(orig_number) + int(orig_number[::-1]))

rawDescription: Cannot concatenate 'str' and 'int' objects but I can run it fine through my own IDLE?


code:
class Repeater(object):
    def __init__(self, sequence):
        self._sequence = sequence

    def __iter__(self):
        for item in self._sequence.__iter__():
            self._repeat = False
            yield item
            if self._repeat:
                yield item

    def repeat(self):
        self._repeat = True

list = ['a', 'b', 'c']
repeater = Repeater(list)

for item in repeater:
    print item
    if (item == 'b'):
        repeater.repeat();

rawDescription: Setting the list item in a Python for loop


code:
out = gdb.execute("maint print target-stack", to_string=True)
print "Local core dump file" in out

rawDescription: GDB+Python: Determining target type

description: GDB+Python: Determining target type


rawDescription: string representation of a numpy array with commas separating its elements

description: String representation of a numpy array with commas separating its elements


code:
def get(url):
    if url[:7] == 'http://':
        if url[7:11] == 'www.':
            print url
            response = requests.get(url)
            if response.status_code == 200:
                return 'ok'

            else:
                return 'error'
        else:
            print(url)
            url = 'http://www.' + url[7:]
            return get(url)
    else:
        print(url)
        url = 'http://' + url
        return get(url)

print get('example.com')

rawDescription: Why do requests return "None"?

description: Why do requests return "None"


code:
NUM_CPUS = None # defaults to all available cores

def PSC(fnom):
    return fnom, len(fnom)

if __name__ == "__main__":
    import multiprocessing as mp
    pool = mp.Pool(NUM_CPUS)
    list_of_strings = list("abcdefghijklm")
    cond = {}
    for fnom, result in pool.imap_unordered(PSC, list_of_strings):
        cond[fnom] = result
    pool.close()
    pool.join()
    print cond

rawDescription: Python Multiprocessor and a list of variables to be passed to a function


code:
class decorator(object):
    def __init__(self, functor):
        self.functor = functor

        #  lets copy some key attributes from the original function
        self.__name__ = functor.__name__
        self.__doc__ = functor.__doc__

    def __call__(self, *args, **kwargs):
        return self.functor(*args, **kwargs)

    def __repr__(self):
        return '<function %s created by ...>' % self.functor.__name__

@decorator
def f():
    return 'spam'

print f()  # spam
print repr(f)  # <function hehe created by ...>

rawDescription: How do I change the representation of a Python function?

description: Change the representation of a Python function


code:
#!/usr/bin/python

from StringIO import StringIO
import paramiko

class SshClient:
    "A wrapper of paramiko.SSHClient"
    TIMEOUT = 4

    def __init__(self, host, port, username, password, key=None, passphrase=None):
        self.username = username
        self.password = password
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if key is not None:
            key = paramiko.RSAKey.from_private_key(StringIO(key), password=passphrase)
        self.client.connect(host, port, username=username, password=password, pkey=key, timeout=self.TIMEOUT)

    def close(self):
        if self.client is not None:
            self.client.close()
            self.client = None

    def execute(self, command, sudo=False):
        feed_password = False
        if sudo and self.username != "root":
            command = "sudo -S -p '' %s" % command
            feed_password = self.password is not None and len(self.password) > 0
        stdin, stdout, stderr = self.client.exec_command(command)
        if feed_password:
            stdin.write(self.password + "\n")
            stdin.flush()
        return {'out': stdout.readlines(),
                'err': stderr.readlines(),
                'retval': stdout.channel.recv_exit_status()}

if __name__ == "__main__":
    client = SshClient(host='host', port=22, username='username', password='password')
    try:
       ret = client.execute('dmesg', sudo=True)
       print "  ".join(ret["out"]), "  E ".join(ret["err"]), ret["retval"]
    finally:
      client.close()

rawDescription: SSH - Python with paramiko issue

description: SSH - Python with paramiko issue


code:
try:
    page = requests.get(Scrape.site_to_scrape['git']+gitUser)
    tree = html.fromstring(page.text)

    full_name = tree.xpath('//span[@class="vcard-fullname"]/text()')

    print 'Full Name: ', full_name

except:
    print "Syntax: python site_scrape.py -g <git user name here>"

rawDescription: Parse a span class with BeautifulSoup (or rather xpath)


code:
s = ['one', 'two', 'three']

string = s[1]+","+s[2]
print string

rawDescription: How to add elements of list with particular indexes to a string?

description: Add elements of list with particular indexes to a string


code:
def distx(w1,w2):
    if len(w1) != len(w2):return 100000
    score=0
    for i in range(len(w1)):
       score += int(w1[i] != w2[i])
    return score

word_list = ["fine","fond","line","lose","lone"]

def changeling(guess,target,steps):
    my_steps = []
    print "Guess:",guess
    if target == guess:return [guess]
    try:word_list.remove(guess)
    except:pass
    my_steps.append(guess)
    if target != guess and steps >= 0:
        this_step = []
        one_step_away = [w for w in word_list if distx(guess,w) == 1]
        for k  in one_step_away:
            print "     %s->"%guess,k
            this_step.append(changeling(k,target,steps-1))
    my_steps.append( this_step )
    return my_steps
tmp = changeling("find","lose",4)
print tmp

rawDescription: Recursion with Lists

description: Recursion with Lists


code:
def dump_args(func):
    "This decorator dumps out the arguments passed to a function before calling it"
    argnames = func.func_code.co_varnames[:func.func_code.co_argcount]
    fname = func.func_name
    def echo_func(*args,**kwargs):
        print fname, "(", ', '.join(
            '%s=%r' % entry
            for entry in zip(argnames,args[:len(argnames)])+[("args",list(args[len(argnames):]))]+[("kwargs",kwargs)]) +")"
    return echo_func

@dump_args
def test(a, b = 4, c = 'blah-blah', *args, **kwargs):
    pass

rawDescription: Decorator to print function call details - parameters names and effective values


code:
import sys
import os
import shutil

# terminology:
# path = full path to a file, i.e. directory + file name
# directory = directory, possibly starting with a drive
# file name = the last component of the path

sourcedrive = 'D:'
destdrive = 'C:'

log_list_file = open('test_logs.txt', 'r')
for line in log_list_file:
    sourcepath = line.split()[0]  # XXX is this correct?
    if sourcepath.startswith(sourcedrive):
        destpath = sourcepath.replace(sourcedrive, destdrive, 1)
    else:
        print >>sys.stderr, 'Skipping %s: Not on %s' % (sourcepath, sourcedrive)
        continue

    destdir = os.path.dirname(destpath)

    if not os.path.isdir(destdir):
        try:
            os.makedirs(destdir)
        except (OSError, IOError, Error), e:
            print >>sys.stderr, 'Error making %s: %s' % (destdir, e)
            continue

    try:
        shutil.move(sourcepath, destpath)
    except (OSError, IOError, Error), e:
        print >>sys.stderr, 'Error moving %s to %s: %s' % (sourcepath, destpath, e)

rawDescription: shutil moving files keeping the same directory structure

description: Shutil moving files keeping the same directory structure


code:
import itertools
scores = {}
for a,b in itertools.permutations(('human', 'loud', 'big'), 2):
    scores["{0} + {1}".format(a,b)] = 0
print scores

rawDescription: Creating Dictionary in Python via Multiple for Loops


code:
#!/usr/bin/env python
import wx
import thread
import Queue
from time import sleep

class MyFrame1 ( wx.Frame ):

        def __init__( self, parent ):
                wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )

                self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )

                bSizer1 = wx.BoxSizer( wx.VERTICAL )

                self.m_panel1 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
                bSizer2 = wx.BoxSizer( wx.VERTICAL )

                self.m_button1 = wx.Button( self.m_panel1, wx.ID_ANY, u"MyButton", wx.DefaultPosition, wx.DefaultSize, 0 )
                bSizer2.Add( self.m_button1, 0, wx.ALL, 5 )

                self.m_panel1.SetSizer( bSizer2 )
                self.m_panel1.Layout()
                bSizer2.Fit( self.m_panel1 )
                bSizer1.Add( self.m_panel1, 1, wx.EXPAND |wx.ALL, 5 )

                self.m_panel2 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
                bSizer3 = wx.BoxSizer( wx.VERTICAL )

                self.m_textCtrl1 = wx.TextCtrl( self.m_panel2, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE )
                bSizer3.Add( self.m_textCtrl1, 1, wx.ALL|wx.EXPAND, 5 )

                self.m_panel2.SetSizer( bSizer3 )
                self.m_panel2.Layout()
                bSizer3.Fit( self.m_panel2 )
                bSizer1.Add( self.m_panel2, 1, wx.EXPAND |wx.ALL, 5 )

                self.SetSizer( bSizer1 )
                self.Layout()

                self.Centre( wx.BOTH )

                # Connect Events
                self.m_button1.Bind( wx.EVT_BUTTON, self.do_something )

        def __del__( self ):
                pass

        # Virtual event handlers, overide them in your derived class
        def do_something( self, event ):
                event.Skip()

class MyFrame( MyFrame1 ):
    def __init__( self, parent ):
        MyFrame1.__init__( self, parent )

    def do_something(self, event):
        thread.start_new_thread(self.do_something_thread, ())

    def do_something_thread(self):
        self.Result = Queue.Queue()
        thread.start_new_thread(self.do_loop, ())
        self.m_textCtrl1.AppendText("searching for something... ")
        self.found= 0
        for character in self.cursor():
            self.m_textCtrl1.AppendText(character)
            self.Update()
            sleep(0.1)
            self.m_textCtrl1.Undo()
            if (self.found == 1):
                self.m_textCtrl1.AppendText('\n')
                break
        num = self.Result.get()
        print num

    def cursor(self):
        characters='.oOo'
        i = 0
        while 1:
            yield characters[i]
            i = (i + 1) % len(characters)

    def do_loop(self):
        x = 0
        while (x < 20007):
            print x
            x = x + 1
            if x == 20000:
                self.Result.put(x)
                self.found = 1
                break

class threadtest(wx.App):
    def OnInit(self):
        self.m_frame = MyFrame(None)
        self.m_frame.Show()
        self.SetTopWindow(self.m_frame)
        return True

app = threadtest(0)
app.MainLoop()

rawDescription: GUI With Thread Losing Focus in Windows

description: GUI With Thread Losing Focus in Windows


code:
class Comment(object):
    def __init__(self, pk, parent_pk, content):
        self.pk = pk
        self.parent_pk = parent_pk
        self.content = content

    def depth(self):
        depth = 0
        comment = self
        # this is just a recursive lookup converted to iterative
        while comment.parent_pk:
            # replace the array indexing with traversing up a tree
            comment = comments[comment.parent_pk - 1]
            depth += 1
        return depth

def print_nested(comments):
    for comment in comments:
        print comment.depth() * 2 * " " + comment.content

comments = [
    Comment(1, None, "foo"),
    Comment(2, 1, "foo bar"),
    Comment(3, None, "spam"),
    Comment(4, 3, "spam cheese"),
    Comment(5, 4, "spam cheese monty"),
    Comment(6, None, "muse"),
]

print_nested(comments)

rawDescription: Displaying list of items /w respect to nesting


code:
import pygame
from pygame.color import Color
from Queue import Queue
from threading import Thread

q = Queue()

def worker():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    def my_callback(channel):
        q.put(True)
    GPIO.add_event_detect(2,GPIO.BOTH, callback=my_callback)

    while True:
        print "Waiting for input."
        sleep(60)
    GPIO.cleanup()

t = Thread(target=worker)
t.daemon = True
t.start()

pygame.init()

screen = pygame.display.set_mode([640,640])
clock  = pygame.time.Clock()
font   = pygame.font.SysFont("consolas", 25, True)
count  = 0
pygame.display.set_caption("Test")

done = False
while not done:
    screen.fill(Color('black'))
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done = True
    try:
        q.get()
        count += 1
    except: pass
    output_string = "ACTUAL          %s"  % count
    text = font.render(output_string, True, Color('red'))
    screen.blit(text, [250,420])
    clock.tick(20)
    pygame.display.flip()

rawDescription: using threading in pygame

description: Using threading in pygame


code:
car_list = [['BMW', 4, False, 200], ['Mercedes', 3, False, 250], ['Renault', 2, False, 150], ['Audi', 3, False, 180]]

def add_new_car(horsepower, brand, car_list):
    for lists in car_list:
        if lists[0] == brand:
            lists[1] += 1
            break
    else:
        new_list = []
        new_list.append(brand)
        new_list.append(1)
        new_list.append(True)
        new_list.append(horsepower)
        car_list.append(new_list)

brand = 'Mercedes'
horsepower = 170

add_new_car(horsepower, brand, car_list)
print car_list

rawDescription: Python nested for loops

description: Python nested for loops


code:
class A(object):
    __a = 32
    def func(self):
        return self.__a

class B(A):
    __a = 41
    def bar(self):
        return self.__a

    def bar2(self):
        return self._A__a

print A().func()
print B().func()
print B().bar()
print B().bar2()

rawDescription: What is the sense of private names in a class


code:
#No shebang line, please run in Linux shell % python img_count.py

#Python libs
import threading, urllib2, re
import Queue, json, time, pprint

#Global lists
JSON_LIST = list()
URLS = list()

def get_movies():
    url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json?apikey=    <apikey>"
    response = urllib2.urlopen(url)
    data = json.loads(response.read())
    return data

def get_imgs(html):
    total = 0
    # This next line is not ideal. Would much rather use a lib such as Beautiful Soup for this
    total += len(re.findall(r"<img[^>]*>", html))
    return total

def read_url(url, queue):
    data = urllib2.urlopen(url).read()
    queue.put(data)

def fetch_urls():
    result = Queue.Queue()
    threads = [threading.Thread(target=read_url, args = (url,result)) for url in URLS]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
    return result

if __name__ == "__main__":
    start = time.time()
    movies = get_movies()
    for movie in movies["movies"]:
        url = "http://www.imdb.com/title/tt" + movie['alternate_ids']['imdb']
        URLS.append(url)
    queue = fetch_urls()
    while movies["movies"]:
        movie = movies["movies"].pop()
        job = queue.get()
        total = get_imgs(job)
        json_dict = {
                "title": movie['title'],
                "url": "http://www.imdb.com/title/tt" + movie['alternate_ids']['imdb'],
                "imdb_id": movie['alternate_ids']['imdb'],
                "count": total
                }
        JSON_LIST.append(json_dict)
    pprint.pprint(JSON_LIST)
    end = time.time()
    print "\n"
    print "Elapsed Time (seconds):", end - start

rawDescription: Parsing Large Chunks of HTML with re.findall()


code:
class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super(B, self).__init__()

B()

rawDescription: Python, invoke super constructor

description: Python, invoke super constructor


code:
import numpy as np

#make some fake data
m = np.random.random((8,4))

#get the sum you described
print 0.25*np.max(m, axis=1).sum()

#next, get the index the max value, for each row
xs = np.argmax(m, axis=1)
#use these as indexes into a string, e.g.
s = "GAUC"
print "".join(s[x] for x in xs)

rawDescription: Add up the maximum value in each row of a matrix


code:
import gevent
import threading

class separate_library(object):
    def __init__(self):
        import gevent.monkey; gevent.monkey.patch_all()

    def do_work(self):
        t = threading.Thread(target=self.spawn_gthreads)
        t.setDaemon(False)
        t.start()

    def spawn_gthreads(self):
        from gevent import spawn
        gthreads = [spawn(self._do,x) for x in range(10)]
        gevent.joinall(gthreads)

    def _do(self,sec):
        from gevent import sleep
        sleep(sec)
        print 'Done!'

if __name__ == '__main__':
    lib = separate_library()
    lib.do_work()

rawDescription: Allow Greenlet to finish work at end of main module execution


code:
import numpy as np
from scipy import sparse
from scipy.sparse import linalg
import matplotlib.pyplot as plt

def numgrid(n):
    """
    NUMGRID Number the grid points in a two dimensional region.
    G = NUMGRID('R',n) numbers the points on an n-by-n grid in
    an L-shaped domain made from 3/4 of the entire square.
    adapted from C. Moler, 7-16-91, 12-22-93.
    Copyright (c) 1984-94 by The MathWorks, Inc.
    """
    x = np.ones((n,1))*np.linspace(-1,1,n)
    y = np.flipud(x.T)
    G = (x > -1) & (x < 1) & (y > -1) & (y < 1) & ( (x > 0) | (y > 0))
    G = np.where(G,1,0) # boolean to integer
    k = np.where(G)
    G[k] = 1+np.arange(len(k[0]))
    return G

def delsq(G):
    """
    DELSQ  Construct five-point finite difference Laplacian.
    delsq(G) is the sparse form of the two-dimensional,
    5-point discrete negative Laplacian on the grid G.
    adapted from  C. Moler, 7-16-91.
    Copyright (c) 1984-94 by The MathWorks, Inc.
    """
    [m,n] = G.shape
    # Indices of interior points
    G1 = G.flatten()
    p = np.where(G1)[0]
    N = len(p)
    # Connect interior points to themselves with 4's.
    i = G1[p]-1
    j = G1[p]-1
    s = 4*np.ones(p.shape)

    # for k = north, east, south, west
    for k in [-1, m, 1, -m]:
       # Possible neighbors in k-th direction
       Q = G1[p+k]
       # Index of points with interior neighbors
       q = np.where(Q)[0]
       # Connect interior points to neighbors with -1's.
       i = np.concatenate([i, G1[p[q]]-1])
       j = np.concatenate([j,Q[q]-1])
       s = np.concatenate([s,-np.ones(q.shape)])
    # sparse matrix with 5 diagonals
    return sparse.csr_matrix((s, (i,j)),(N,N))

if __name__ == '__main__':
    print numgrid(6)
    print delsq(numgrid(6)).todense()
    G = numgrid(32)
    D = delsq(G)
    N = D.shape[0]
    rhs = np.ones((N,1))
    u = linalg.spsolve(D, rhs) # vector solution
    U = np.zeros(G.shape) # map u back onto G space
    U[G>0] = u[G[G>0]-1]
    plt.contour(U)
    plt.show()

rawDescription: numpy method to do ndarray to vector mapping as in Matlab's delsq demo?

description: Numpy method to do ndarray to vector mapping as in Matlab's delsq demo


code:
workflows = Table('workflows', Base.metadata,
                  Column('id', Integer, primary_key=True),
                 )

actions = Table('actions', Base.metadata,
                Column('workflow_id', Integer, ForeignKey(workflows.c.id), primary_key=True),
                Column('name', String, primary_key=True),
               )

action_dependencies = Table('action_dependencies', Base.metadata,
                            Column('workflow_id', Integer, ForeignKey(workflows.c.id), primary_key=True),
                            Column('parent_action', String, ForeignKey(actions.c.name), primary_key=True),
                            Column('child_action', String, ForeignKey(actions.c.name), primary_key=True),
                            ForeignKeyConstraint(['workflow_id', 'parent_action'], ['actions.workflow_id', 'actions.name']),
                            ForeignKeyConstraint(['workflow_id', 'child_action'], ['actions.workflow_id', 'actions.name']),
                           )
class Workflow(Base):
    __table__ = workflows
    actions = relationship("Action", order_by="Action.name", backref="workflow")

class Action(Base):
    __table__ = actions
    children = relationship("Action",
                            secondary=action_dependencies,
                            primaryjoin=and_(actions.c.name == action_dependencies.c.parent_action,
                                actions.c.workflow_id == action_dependencies.c.workflow_id),
                            secondaryjoin=and_(actions.c.name == action_dependencies.c.child_action,
                                actions.c.workflow_id == action_dependencies.c.workflow_id),
                            backref="parents"
                           )

# create db schema
Base.metadata.create_all(engine)

# create entities
w_1 = Workflow()
w_2 = Workflow()
a_11 = Action(name="ac-11", workflow=w_1)
a_12 = Action(name="ac-12", workflow=w_1)
a_21 = Action(name="ac-21", workflow=w_2)
a_22 = Action(name="ac-22", workflow=w_2)
session.add(w_1)
session.add(w_2)
a_22.parents.append(a_21)
session.commit()
session.expunge_all()
print '-'*80

# helper functions
def get_workflow(id):
    return session.query(Workflow).get(id)
def get_action(name):
    return session.query(Action).filter_by(name=name).one()

# test another OK
a_11 = get_action("ac-11")
a_12 = get_action("ac-12")
a_11.children.append(a_12)
session.commit()
session.expunge_all()
print '-'*80

# test KO (THIS SHOULD FAIL VIOLATING FK-constraint)
a_11 = get_action("ac-11")
a_22 = get_action("ac-22")
a_11.children.append(a_22)
session.commit()
session.expunge_all()
print '-'*80

rawDescription: SQLAlchemy: Relation table with composite primary key


code:
import time

for i in l:
    print i
    time.sleep(1)

rawDescription: How can I slow down a loop in Python?

description: Slow down a loop in Python


code:
for i in [0, 1]:
    try:
        print '10 / %i: ' % i, 10 / i
    except:
        print 'Uh-Oh'
    else:
        print 'Yay!'

rawDescription: running code if try statements were successful in python

description: Running code if try statements were successful in python


code:
def glist(path):
    global nlist
    for idx, name in enumerate(listdir(path)):
        print '{} {}'.format(idx, name)
    nlist.append(name)

rawDescription: Counting a list starting from 0

description: Counting a list starting from 0


code:
import os

try:
    riggingToolRoot = os.environ["RIGGING_TOOL_ROOT"] #I guess this is the beginning of your path where blueprint is located
except:
    print "RIGGING_TOOL_ROOT environment variable not correctly configured"
else:
    import sys

    print riggingToolRoot  #This will be printed in both cases
    path = riggingToolRoot + "/Modules"

    #1: path is not yet in sys.path, condition True
    #2: we previously addded path to sys.path and it will stay like this until we restart Maya, condition False. path will not be appended to sys.path a second time, this is useless
    if not path in sys.path:
        sys.path.append(path)

    if not "System.blueprint_UI" in sys.modules:
        #1: We never imported System.blueprint_UI
        #1: Let's do it
        #1: Note that blueprint_UI is just a local variable, it is not stored anywhere in sys.modules
        import System.blueprint_UI as blueprint_UI
    else:
        #2: When you import a module, it is located in sys.modules
        #2: Try printing it, your can see all the modules already imported (Maya has quite a lot)
        #2: Anyway, the condition is False as the module has been imported previously
        reload(blueprint_UI)

    #In both case, the module is imported and updated, we can now run the UI function and print "We are in the constructor"
    UI = blueprint_UI.Blueprint_UI()

rawDescription: How do I get python to reload this module in Maya 2015? The constructor only runs the first time

description: Get python to reload this module in Maya 2015? The constructor only runs the first time


rawDescription: Django Latin Characters do not work

description: Django Latin Characters do not work


code:
pres = {
    "Reagan": (1981, 8),
    "Bush": (1989, 4),
    "Bill Clinton": (1993,8),
}

unemploy = {
    1989:   (6682,  6359,   6205,   6468,   6375,   6577,   6495,   6511,   6590,   6630,   6725,   6667),
    1990:   (6752,  6651,   6598,   6797,   6742,   6590,   6922,   7188,   7368,   7459,   7764,   7901),
    1991:   (8015,  8265,   8586,   8439,   8736,   8692,   8586,   8666,   8722,   8842,   8931,   9198),
    1992:   (9283,  9454,   9460,   9415,   9744,   10040,  9850,   9787,   9781,   9398,   9565,   9557),
}

def avg_unemployment_for_pres_term(name):
    if pres.get(name) is None:
        return 0

    the_pres = pres[name]

    first_year = the_pres[0]
    last_year = first_year + the_pres[1]

    years = []

    for year in range(first_year, last_year):
        unemp_rates = unemploy.get(year, (0,))
        years.append(sum(unemp_rates)/len(unemp_rates))

    return sum(years) / len(years)

def avg_unemployment_for_pres_year(name, year):
    if pres.get(name) is None:
        return 0

    the_pres = pres[name]

    unemp_rates = unemploy.get(year, (0,))
    return sum(unemp_rates)/len(unemp_rates)

print avg_unemployment_for_pres_term("Bush")  # 7958
print avg_unemployment_for_pres_year("Bush", 1989)  # 6523

rawDescription: Sum of tupled values in dictionary over several keys from 2 dicitonaries


rawDescription: Print alternate number representations in pdb


code:
with open('dump.txt','r') as f:
    for line in f:
        print line.lstrip()

rawDescription: Python Remove Whitespace

description: Python Remove Whitespace


code:
from HTMLParser import HTMLParser
parser = HTMLParser()
parser.unescape('опа')
print parser.unescape('опа')

rawDescription: Convert string from xmlcharrefreplace back to utf-8


code:
l = ["line1","line2","line3","line4"]
print l[2:] # print from 2nd element (including) onwards
["line3","line4"]

rawDescription: Python: removing specific lines from an object


code:
from xml.dom.minidom import parse

dom1 = parse("test.xml")

for node in dom1.getElementsByTagName('t'):
    print node.childNodes[0].nodeValue

rawDescription: Python - XML parsing

description: Python - XML parsing


code:
import pygame
from pygame.locals import *

import random

#----------------------------------------------------------------------

class Tokens(pygame.sprite.Sprite):

    def __init__(self, color, x, y, width, height):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface([width, height])
        self.image.fill(color)

        self.rect = self.image.get_rect(x=x, y=y)

#----------------------------------------------------------------------

# constants (uppercase names)

GRAY  = (220, 220, 220)
BLACK = (  0,   0,   0)
BLUE  = (  0,   0, 255)
RED   = (255,   0,   0)
WHITE = (255, 255, 255)

#----------------------------------------------------------------------

f = open("results", "a")
f.write("trial number, answer, reaction time, correct answer, number of balls in left circle at response, number of balls in middle circle at response, number of balls in right circle at response\n")
f.close()

g = 0

# initial x y coords for token

x_coords = [265, 305, 345, 385, 425, 265, 305, 345, 385, 425, 265, 305, 345, 385, 425, 265, 305, 345, 385]
y_coords = [170, 170, 170, 170, 170, 210, 210, 210, 210, 210, 250, 250, 250, 250, 250, 290, 290, 290, 290]

#----------------------------------------------------------------------

# start program

pygame.init()

screen = pygame.display.set_mode((720, 480))

clock = pygame.time.Clock()

state_reset = True

current_time = pygame.time.get_ticks()
end_time = current_time + 60*15*1000 # ms

# --- mainloop ---

while current_time < end_time:

    if state_reset:
        # chooses amount of tokens

        tokens_to_move = random.choice( (11,15,19) )

        tokens_left = 0
        tokens_right = 0

        # create tokens

        tokens_list = []
        tokens_group = pygame.sprite.Group()

        for i in range(tokens_to_move):
            token = Tokens((255,120,0), x_coords[i], y_coords[i], 20, 20)
            tokens_list.append( token )
            tokens_group.add( token )

        move_speed = 1000

        current_time = pygame.time.get_ticks()
        time_to_move = current_time + move_speed # ms

        selected_side = None

        state_selected = False
        state_reset = False

    # --- DRAWS ---

    screen.fill(GRAY)

    pygame.draw.rect(screen, BLACK, Rect((30,140), (200,200)))
    pygame.draw.rect(screen, BLACK, Rect((260,140), (200,200)))
    pygame.draw.rect(screen, BLACK, Rect((490,140), (200,200)))

    if state_selected:
        if selected_side == 'left':
            pygame.draw.rect(screen, BLUE, Rect((30,140), (200,200)))

        elif selected_side == 'right':
            pygame.draw.rect(screen, BLUE, Rect((490,140), (200,200)))

    tokens_group.draw(screen)

    pygame.display.update()

    # --- CHANGES ---

    if state_selected:
        if selected_time <= current_time:
            state_selected = False

    # moves token

    if tokens_to_move:
        if time_to_move <= current_time:
            time_to_move = current_time + move_speed
            tokens_to_move -= 1
            print 'tokens_to_move:', tokens_to_move
            if random.randint(1,2) == 1:
                tokens_list[tokens_to_move].rect.x -= 230
                tokens_left += 1
            else:
                tokens_list[tokens_to_move].rect.x += 230
                tokens_right += 1
    else:
        state_reset = True

    # --- EVENTS ---

    for event in pygame.event.get():
        if event.type == KEYDOWN:
            g += 1

            if event.key == K_ESCAPE:
                pygame.quit()
                exit()

            elif event.key == pygame.K_SPACE:
                print 'reset'
                state_reset = True

            if not selected_side:
                if event.key == K_LEFT:
                    answer = "left"
                    f = open("results", "a")
                    f.write(str(g) + ", left\n")
                    f.close()
                    selected_side = 'left'
                    print("You picked left!")
                    selected_time = current_time + 1000 # ms
                    move_speed = 0.1
                    state_selected = True

                elif event.key == K_RIGHT:
                    answer = "right"
                    f = open("results", "a")
                    f.write(str(g) + ", right\n")
                    f.close()
                    selected_side = 'right'
                    print("You picked right!")
                    selected_time = current_time + 1000 # ms
                    move_speed = 0.1
                    state_selected = True

    # --- CLOCK ---

    clock.tick(20) # 20 FPS

    current_time = pygame.time.get_ticks()
    #print 'current_time:', current_time

rawDescription: Python/Pygame Why aren't my sprites moving?


code:
s = r'a\tb\nc'
print s.decode('string_escape')

rawDescription: how do I convert text containing \r\n to represent carriage return and line feed in python

description: Convert text containing \r\n to represent carriage return and line feed in python


code:
seconds = 0
for timer in range(1,301):
    #whatever ...
    seconds += 1
    print seconds/60, seconds % 60

rawDescription: adding one second to a "timer" when a variable increases by 1

description: Adding one second to a "timer" when a variable increases by 1


code:
from PyQt4 import QtGui
import os

class Test(QtGui.QMainWindow):
    def __init__(self):
        super(Test, self).__init__()

        self.initUI()

    def initUI(self):
        YDrive = QtGui.QAction("Y", self)
        YDrive.triggered.connect(self.setYDir)

        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(YDrive)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Message box')
        self.show()

    def buttonClicked(self):
        print "clicked"

    def setYDir(self):
        myWorkDrive = "/tmp"
        shows = os.listdir(myWorkDrive)
        i = 0
        for elements in shows:
            btn1 = QtGui.QPushButton(elements, self)
            btn1.move(30, 50 + i)
            i += 30
            btn1.clicked.connect(self.buttonClicked)
            btn1.show()
        self.resize(self.width(), 50 + i)

if __name__ == '__main__':
    app = QtGui.QApplication([])
    t = Test()
    t.show()
    app.exec_()

rawDescription: Creating a button for PyQT window at each loop


code:
import os
import subprocess

cmd = 'ls'

if os.fork() == 0:
        process = subprocess.Popen(cmd, shell=True, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
        print "subprocess pid: %d" % process.pid
        stdout = process.communicate()
        print stdout
else:
        print 'parent...'

rawDescription: Python: spawn subprocess with several requirements


code:
if d*100 - int(d*100):
    print str(d)
else:
    print ".2f" % d

rawDescription: Python Format Decimal with a minimum number of Decimal Places


code:
access_token='Access_token'
import facebook
graph=facebook.GraphAPI(access_token)
groups = graph.get_connections(id='me', connection_name='groups')
data = groups['data']
for s in data:
    l = s.values()
    object_id= l[6]
    try:
        graph.put_object(object_id, 'feed',message="hola")
        print('Done, Posted in %s'%l[1].encode('utf-8',errors='ignore'))
    except Exception as e:
        print(e)

print 'Done, Posted in all groups'

rawDescription: how to post in facebook group that's im member on it using facebook-sdk python

description: Post in facebook group that's im member on it using facebook-sdk python


code:
for i, d in enumerate(DICE):
    print choice(d),   # comma prevents newline
    if not (i+1) % 4:  # i+1 modulus 4 will evaluate to [1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0]
        print ''       # empty string forces new line, when above was 0

rawDescription: Boggle game - putting randomly selected letters from an array of 16 arrays in a 4x4 grid (Python)


code:
while True:
    print ("Enter the number of the recommendations you want to " +
            "be displayed. You can leave blank for the " +
            "default number of recommendations(10)"),
    number_of_recs = 10 # we set the default value
    user_input = raw_input()
    if user_input.strip() == '':
        break # we leave default value as it is
    try:
        # we try to convert string from user to int
        # if it fails, ValueError occurs:
        number_of_recs = int(user_input)

        # *we* raise error 'manually' if we don't like value:
        if number_of_recs < 0:
            raise ValueError
        else:
            break # if value was OK, we break out of the loop
    except ValueError:
        print "You must enter a positive integer"
        continue

print number_of_recs

rawDescription: Having trouble requesting input in python


code:
import wx

class ListTest(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title, size=(380, 230))

        panel = wx.Panel(self, -1)

        self.list = wx.ListCtrl(panel, -1, style=wx.LC_REPORT)
        self.list.InsertColumn(0, 'col 1', width=140)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(self.list, 1, wx.EXPAND)
        panel.SetSizer(hbox)
        self.Centre()
        self.Show(True)

        self.Bind(wx.EVT_CHAR_HOOK, self.onKey)

    def onKey(self, evt):
        if evt.GetKeyCode() == wx.WXK_DOWN:
            self.list.InsertStringItem(0, "level 1")
            self.list.InsertStringItem(1, "level 2")
            self.list.SetBackgroundColour(wx.RED)
            self.list.Refresh()

            print self.list.GetItemText(0)
            print self.list.GetItemText(1)
        else:
            evt.Skip()

app = wx.App()
ListTest(None, 'list test')
app.MainLoop()

rawDescription: a problem about wxpython listctrl

description: A problem about wxpython listctrl


code:
import urllib2
from BeautifulSoup import BeautifulSoup

url1 = "http://www.thrashermagazine.com/skateparks/search-results_m94/?cat=61&jr_state=CA&order=alpha&query=all"
content1 = urllib2.urlopen(url1).read()
soup = BeautifulSoup(content1)
print [e.text for e in soup.findAll('a')]

rawDescription: BeautifulSoup webscraping...getting just the text


code:
I = 'abc' # 1
II = 'def' # 2
III = 'ghi' # 3
x = 'afh' # Random possibility: It could be an input.
L = []
LL = []

lists = I, II, III

for c in x:
    for i, seq in enumerate(lists):
        if c in seq:
            L.append(i+1)

LL = [lists[i-1] for i in L]

print L
print LL

rawDescription: Append all possibilities from sequences with numbers


code:
print sql.literal_column('ARRAY[2]').op('<@')(table.c.lineage)
# ARRAY[2] <@ "treeItems".lineage

rawDescription: How can I determine if one PGArray is included in another using SQLAlchemy sessions?

description: Determine if one PGArray is included in another using SQLAlchemy sessions


code:
import matplotlib.pyplot as plt
import numpy as np

result = {'apr': 13, 'jun': 13, 'jul': 13, 'aug': 13, 'sep': 13, 'oct': 13}
for m, n in result.items():
    print 'The number for', m, "is", n
plt.plot(result.values())
plt.ylabel('Number')
plt.xlabel('Time (Months)')
plt.title('Number per month')
plt.xticks(range(len(result)), result.keys())
plt.show()

rawDescription: Creating a line plot in python using data from a-for loop


code:
import os
print os.path.abspath(os.curdir)

rawDescription: How do I refer to the current directory in functions from the Python 'os' module?

description: Refer to the current directory in functions from the Python 'os' module


code:
def make_class(value):
  class Foo(object):
    foo_var = value

    def speak(self):
      print self.foo_var
  return Foo

FooBar = make_class("bar")
FooQux = make_class("qux")

FooBar().speak()
FooQux().speak()

rawDescription: Python Dynamic Subclassing

description: Python Dynamic Subclassing


rawDescription: indexing numpy multidimensional arrays

description: Indexing numpy multidimensional arrays


code:
import pymc as mc
import numpy as np

data = np.random.normal(-200,15,size=1000)

mean = mc.Uniform('mean', lower=min(data), upper=max(data))
std_dev = mc.Uniform('std_dev', lower=0, upper=50)

@mc.stochastic(observed=True)
def custom_stochastic(value=data, mean=mean, std_dev=std_dev):
    return np.sum(-np.log(std_dev) - 0.5*np.log(2) -
                  0.5*np.log(np.pi) -
                  (value-mean)**2 / (2*(std_dev**2)))

model = mc.MCMC([mean,std_dev,custom_stochastic])
model.sample(iter=5000)

print "!"
print(model.stats()['mean']['mean'])
print(model.stats()['std_dev']['mean'])

rawDescription: Defining a custom PyMC distribution

description: Defining a custom PyMC distribution


code:
import sys
import subprocess
import random
import time
import threading
import Queue

class AsynchronousFileReader(threading.Thread):
    '''
    Helper class to implement asynchronous reading of a file
    in a separate thread. Pushes read lines on a queue to
    be consumed in another thread.
    '''

    def __init__(self, fd, queue):
        assert isinstance(queue, Queue.Queue)
        assert callable(fd.readline)
        threading.Thread.__init__(self)
        self._fd = fd
        self._queue = queue

    def run(self):
        '''The body of the tread: read lines and put them on the queue.'''
        for line in iter(self._fd.readline, ''):
            self._queue.put(line)

    def eof(self):
        '''Check whether there is no more content to expect.'''
        return not self.is_alive() and self._queue.empty()

def consume(command):
    '''
    Example of how to consume standard output and standard error of
    a subprocess asynchronously without risk on deadlocking.
    '''

    # Launch the command as subprocess.
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    # Launch the asynchronous readers of the process' stdout and stderr.
    stdout_queue = Queue.Queue()
    stdout_reader = AsynchronousFileReader(process.stdout, stdout_queue)
    stdout_reader.start()
    stderr_queue = Queue.Queue()
    stderr_reader = AsynchronousFileReader(process.stderr, stderr_queue)
    stderr_reader.start()

    # Check the queues if we received some output (until there is nothing more to get).
    while not stdout_reader.eof() or not stderr_reader.eof():
        # Show what we received from standard output.
        while not stdout_queue.empty():
            line = stdout_queue.get()
            print 'Received line on standard output: ' + repr(line)

        # Show what we received from standard error.
        while not stderr_queue.empty():
            line = stderr_queue.get()
            print 'Received line on standard error: ' + repr(line)

        # Sleep a bit before asking the readers again.
        time.sleep(.1)

    # Let's be tidy and join the threads we've started.
    stdout_reader.join()
    stderr_reader.join()

    # Close subprocess' file descriptors.
    process.stdout.close()
    process.stderr.close()

def produce(items=10):
    '''
    Dummy function to randomly render a couple of lines
    on standard output and standard error.
    '''
    for i in range(items):
        output = random.choice([sys.stdout, sys.stderr])
        output.write('Line %d on %s\n' % (i, output))
        output.flush()
        time.sleep(random.uniform(.1, 1))

if __name__ == '__main__':
    # The main flow:
    # if there is an command line argument 'produce', act as a producer
    # otherwise be a consumer (which launches a producer as subprocess).
    if len(sys.argv) == 2 and sys.argv[1] == 'produce':
        produce(10)
    else:
        consume(['python', sys.argv[0], 'produce'])

rawDescription: Get output from a python subprocess job into tornado


code:
import dis
def my_function():
    def little_function():
            print "Hello, World!"

dis.dis(my_function)

rawDescription: Function inside function - every time?

description: Function inside function - every time


code:
from shapely.geometry import MultiPoint
print MultiPoint(points).bounds

rawDescription: Is there an envelope class in shapely?

description: Is there an envelope class in shapely


code:
import multiprocessing
import time
import signal
import sys

def init_worker():
    signal.signal(signal.SIGINT, signal.SIG_IGN)

def worker():
    while(True):
        time.sleep(1.1234)
        print "Working..."

if __name__ == "__main__":
    pool = multiprocessing.Pool(50, init_worker)
    try:
        for i in range(50):
            pool.apply_async(worker)

        time.sleep(10)
        pool.close()
        pool.join()

    except KeyboardInterrupt:
        print "Caught KeyboardInterrupt, terminating workers"
        pool.terminate()
        pool.join()

rawDescription: Catch Ctrl+C / SIGINT and exit multiprocesses gracefully in python


code:
descr = "this is a test description"
changespec = "change: New\ndescription: " + descr

p = subprocess.Popen(["p4","change","-i"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

(out, err) = p.communicate(changespec)
print out

rawDescription: Is there a way to create a new P4 changelist using python subprocess?


code:
XMLtext = '''
<root>
 <Relationship>
    <AssociableNode AssociationType="ManagedElement_to_ftpBackupStore" TO_FDN="FtpServer=BACKUP,FtpService=BACKUP" />
    <AssociableNode AssociationType="ManagedElement_to_ftpLicenseKeyStore" TO_FDN="FtpServer=LICENSE,FtpService=LICENSE" />
    <AssociableNode AssociationType="ManagedElement_to_ftpSwStore" TO_FDN="FtpServer=SOFTWARE,FtpService=SOFTWARE_RBS" />
    <AssociableNode AssociationType="Group_to_MeContext" TO_FDN="Group=CR94180381" />
    <AssociableNode AssociationType="MgmtAssociation" TO_FDN="ManagementNode=ONRM" />
    <AssociableNode AssociationType="StnFunction_to_NodeBFunction" FROM_FDN="SubNetwork=$parent,MeContext=$VAR_N1E_NM,ManagedElement=1,NodeBFunction=1" TO_FDN="SubNetwork=IPRAN,ManagedElement=TCU_MTUC_VODO_B_BRIJEG,StnFunction=STN_ManagedFunction" />
    <AssociableNode AssociationType="Group_to_MeContext" TO_FDN="SubNetwork=$parent,Group=RBS" />
 </Relationship>
</root>
'''

from xml.etree import ElementTree as ET
root = ET.XML(XMLtext)

for relationship in root.findall('.//Relationship'):
    for associable in relationship.findall('AssociableNode'):
        if not associable.get('TO_FDN', '').startswith("FtpServer="):
            relationship.remove(associable)

print ET.tostring(root)

rawDescription: Removing elements with etree

description: Removing elements with etree


code:
patterns = (
    #(<pattern>, <function>, <do_continue>)
    ('ab', lambda a: a, True),
    ('abc', lambda a: a, False),
)

def MatchAndDo(string, patterns):
    for p in patterns:
        res = re.match(p[0], string)
        if res is None:
            continue

        print "Matched '{}'".format(p[0])
        p[1](p[0]) # Do stuff
        if not p[2]:
            return

MatchAndDo('abc', patterns)

rawDescription: Better flow control with re.match in python


code:
class Abc(object):
    pass

def new_funct(self):
    print 1234

Abc.instance_funct = new_funct
a = Abc()
a.instance_funct()

rawDescription: Python: How to extend a class?

description: Python: How to extend a class


code:
import socket
from struct import pack
host='ip_to_connect_to'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port_to_connect_to))
answer=s.recv(1024)
print answer
padding=800 * "A"

s.send(padding)

rawDescription: Use script to send string through socket


code:
from gi.repository import Gtk, GObject

class Window(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.button = Gtk.Button("Hi Printer")
        self.button.connect("pressed", self.on_button_clicked)
        self.button.connect("released", self.on_button_released)
        self.add(self.button)
        self.connect("delete-event", Gtk.main_quit)

    def on_button_clicked(self, widget):
        # kick off time out
        timeout = 50
        self._timeout_id = GObject.timeout_add(timeout, self.print_hi)

    def on_button_released(self, widget):
        # remove timeout
        GObject.source_remove(self._timeout_id)
        self._timeout_id = 0 # better safe than sorry

    def print_hi(self):
        print 'hi'
        # repeat until the source is removed
        return True

window = Window()
window.show_all()
Gtk.main()

rawDescription: There is any event for a Gtk.Button that would execute the code repeatedly while the button is being pressed?


code:
# SomeClasses.py

# One of the few legitimate uses of import * outside of an interactive session.
from _SomeClasses import *
a = A()

# _SomeClasses.py
class A(object):
    def __init__(self):
        print "Hi! A is instantiated!"

class B(object):
    def __init__(self):
        print "Hi! B is instantiated!"

rawDescription: Python class is created when module is imported


code:
#Continuing on what is given in the question, here is one solution
file = open('20151122g.dat', 'r')
maxl = None
maxv = 0
for l in file:
    if l.startswith("Query"):
        if not maxl is None:
            print maxl
            maxl = None
            maxv = 0
        print(l)
        continue
    if l.startswith("Hit"):
        col = l.split()
        val = int(col[4])
        if maxv < val:
            maxv = val
            maxl = l
        pass
    pass
if not maxl is None:
    print(maxl)

rawDescription: How to Iterate to Find the Line with Highest Score?


code:
import copy

#Inital 1-item groups
def groupTuples(tupleList):
    groups = []
    for t in tupleList:
        groups.append([t])
    return groups

#Merge two groups
def splice(list1, list2, index):
    for item in list2:
        list1.insert(index, item)
        index += 1
    return list1

def network(groups = []):
    #Groups get modified by reference, need a shallow copy for reference
    oldGroups = copy.copy(groups)
    for group in groups:
        for index, secondGroup in enumerate(groups):
            if group == secondGroup:
                #Splice can get caught in a loop if passed the same item twice.
                continue
            #Last item of First Group matches First item of Second Group
            if group[-1][1] == secondGroup[0][0]:
                splice(group, secondGroup, len(group))
                groups.pop(index)
            #First item of First Group matches Last item of Second Group
            elif group[0][0] == secondGroup[-1][1]:
                splice(group, secondGroup, 0)
                groups.pop(index)

    if groups == oldGroups:
        return groups #No change.
    else:
        return network(groups)

l = [(1,2,0),(2,3,1),(4,6,2),(3,5,3),(1,7,4),(7,9,5),(6,8,6),(12, 13,7),(5, 12,8)]
result = network(groupTuples(l))
print result

rawDescription: Python Distribute List of Tuple Items by Matching Recursively


code:
for i in range(0, ran_x, 1):
    for j in range(0, ran_y, 1):
        diff[i,j] = rescaled[i,j] - im_1_check[j,i]
        print rescaled[i,j], im_1_check[j,i], diff[i,j]

rawDescription: Comparing a matrix with the corresponding image


code:
while 1:
    try:
       line = svc._QS(fdb.ibase.isc_info_svc_line)
    except fdb.OperationalError:
       # It is routine for actions such as RESTORE to raise an
       # exception at the end of their output.  We ignore any such
       # exception and assume that it was expected, which is somewhat
       # risky.  For example, suppose the network connection is broken
       # while the client is receiving the action's output...
       break
    if not line: # we reached the end of output
       break
    print line

rawDescription: How to use Firebird audit and trace services with Python?

description: Use Firebird audit and trace services with Python


code:
import numpy
import scipy
import pyfits

# Use Pyfits to read in a file.
im = pyfits.open("example.fits")

# pyfits opens a "list" of all header extensions in the file.
isinstance(im,list)

# my example is a simple 2d image. so I want the first header unit
im0 = im[0]

# you access the data shape this way
print im0.data.shape

# simple check of the image variance
print numpy.var(im0.data)

# now I'm just repeating the same as your example
poisson = str(raw_input("Poisson noise amount: "))
poissonNoise = numpy.random.poisson(poisson, im0.data.shape).astype(float)
test = im0.data + poissonNoise

# check things out and write to new file
print numpy.var(test)

# you could do this.
im0.data = test

# write that new image back out with the old header.
pyfits.writeto("/tmp/test.fits", data=test, header=im0.header)

# prove it worked.
check = pyfits.open("/tmp/test.fits")

numpy.var(check[0].data)

rawDescription: Adding poisson noise to a fits file

description: Adding poisson noise to a fits file


code:
from Crypto.PublicKey import DSA
from Crypto.Util import asn1

key = DSA.generate(1024)

# export

seq = asn1.DerSequence()
seq[:] = [ 0, key.p, key.q, key.g, key.y, key.x ]

exported_key = "-----BEGIN DSA PRIVATE KEY-----\n%s-----END DSA PRIVATE KEY-----" % seq.encode().encode("base64")

print exported_key

# import

seq2 = asn1.DerSequence()
data = "\n".join(exported_key.strip().split("\n")[1:-1]).decode("base64")
seq2.decode(data)
p, q, g, y, x = seq2[1:]

key2 = DSA.construct((y, g, p, q, x))

assert key == key2

rawDescription: How to generate the PEM serialization for the public RSA/DSA key

description: Generate the PEM serialization for the public RSA/DSA key


code:
import xapian
db = xapian.WritableDatabase("my-db", xapian.DB_CREATE_OR_OPEN)
tg = xapian.TermGenerator()

doc = xapian.Document()
tg.set_document(doc)
tg.index_text("John Doe", 1, "A")
db.add_document(doc)

qp = xapian.QueryParser()
qp.add_prefix("author", "A")
q = qp.parse_query('author:"John Doe"')

enq = xapian.Enquire(db)
enq.set_query(q)
for match in enq.get_mset(0, 10):
    print "%8.8i: %f" % (match.docid, match.weight,)

rawDescription: Search by probabilistic fields in Xapian and Python


code:
import glob
print glob.glob('dir/customers*.csv')

rawDescription: What replaces the asterisk in Python?

description: What replaces the asterisk in Python


code:
keys = []
for subcontext in response.context:
  for d in subcontext.dicts:
    for k in d.keys():
      if k not in keys:
        keys.append(k)

print keys

rawDescription: Django ContextList keys

description: Django ContextList keys


code:
from collections import defaultdict

L = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
d = defaultdict(int)
for i in L:
    d[i] += 1
result = max(d.iteritems(), key=lambda x: x[1])
print result
# (4, 6)
# The number 4 occurs 6 times

rawDescription: Python - find the item with maximum occurrences


code:
class Worker(object):
    payme = False
    period = None
    def __init__(self, name, sal):
        self.name = name
        self.sal = sal

    def pay(self, period=None):
        if not self.payme:
            print 'Not Implemented'
            return
        if self.period:
            return self.period*self.sal
        elif not period:
            print 'Please, give a period'
            return
        elif period:
            return period*self.sal

    def __add__(self, other):
        # here adding the salary (sal), but you can add whatever you wish...
        return self.sal + other.sal

class SalariedWorker( Worker ):
    payme = True
    period = 40

class HourlyWorker( Worker ):
    payme = True

rawDescription: Developing classes and subclasses for hourly and salaried working


code:
whitelist = ["name", "metric", "namespace", "statistic", "comparison", "threshold",    "period", "evaluation_periods", "unit", "description", "dimensions", "alarm_actions", "insufficient_data_actions", "ok_actions"]
x = []
for alarm in alarms:
    single_dict = {} # new dictionary object each time
    for attr in whitelist:
        single_dict[attr] = getattr(alarm, attr)

    print single_dict
    x.append(single_dict)

rawDescription: create a list of dictionaries boto AWS

description: Create a list of dictionaries boto AWS


rawDescription: Round Number with different length

description: Round Number with different length


code:
import ctypes, os, pythoncom
from win32com.client import Dispatch

def drivespace(drive, xl_path, col):
    #get space in bytes
    free_bytes = ctypes.c_ulonglong(0)
    ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(drive), \
                                               None, None, ctypes.pointer(free_bytes))

    #calculate space in GB
    free_GB = free_bytes.value/1024/1024/1024
    print(free_GB)

    #input data to Excel
    xl = Dispatch('Excel.Application')
    xl.visible = 0
    wb = xl.Workbooks.Open(xl_path)
    ws = wb.Worksheets(1)

    # initialise values
    empty = False
    row = 1

    # loop until first empty cell in this column
    while not empty:
        val = ws.Range(col+str(row)).value
        print val
        if val == None:
            print "Found first empty cell! Writing Value..."
            ws.Range(col+str(row)).value = free_GB
            empty = True
        row += 1

    wb.Close(True)
    xl.Quit()

    #release held Excel process
    pythoncom.CoUninitialize()

def main():
    drive = 'C:\\'
    xl_path = os.path.join(os.getenv('so'),'free_space_to_excel','Book1.xlsm')
    xl_column = 'A'
    drivespace(drive, xl_path, xl_column)

if __name__ == '__main__':
    main()

rawDescription: RESOLVED Using Python to print the amount of space left in a network shared drive


code:
# genfind.py
#
# A function that generates files that match a given filename pattern

import os
import shutil
import fnmatch

def gen_find(filepat,top):
    for path, dirlist, filelist in os.walk(top):
        for name in fnmatch.filter(filelist,filepat):
            yield os.path.join(path,name)

# Example use

if __name__ == '__main__':
    src = 'O:\DATA\ASTER GDEM\Original\North America\UTM Zone 14\USA\Extracted' # input
    dst = 'O:\DATA\ASTER GDEM\Original\North America\UTM Zone 14\USA\Analyses' # desired     location

    filesToMove = gen_find("*dem.tif",src)
    for name in filesToMove:
        shutil.move(name, dst)

rawDescription: Moving specific files in subdirectories into a directory - python


code:
def defunc(vals, start, rnge):
    n = len(vals)
    new = []

    for i in xrange((start - rnge), (start + rnge)+ 1):
        new.append(vals[i%n])
    return new

def myfunc(vals, rnge):
    n = len(vals)
    for i in range(n):
        print defunc(vals,i,rnge)

rawDescription: How do I use modular arithmetic on indices?

description: Use modular arithmetic on indices


code:
import signal, time

# Set time limit to 5 minutes.
time_limit = 300

class TimeoutException(Exception):
    pass

# Create signal countdown.
def signal_handler(signum, frame):
    raise TimeoutException("Idle for too long! Exit!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(time_limit)

# Reset signal countdown every time to write to file.
def print_to_file(msg):
    print(msg) #or other writing method.
    signal.alarm(time_limit)

try:
    # Do your stuff here, for example:
    print_to_file('a')
    time.sleep(time_limit + 1)
except TimeoutException, msg:
    # Nothing happened for 5 minutes!
    print msg
else:
    signal.alarm(0)

rawDescription: Python: How to write to a file and continuously monitor it's file size changes?


code:
args = dict(ee311=3, cpre281=3, math207=3.67, ee332=3, jlmc101=4)
cumulative(**args)
print "Your semester 5 gpa is:", sem_5(**args)[0]

rawDescription: Passing same arguments to multiple functions - Python


code:
rdd = sc.parallelize([("a1","b1","c1","d1","e1"), ("a2","b2","c2","d2","e2")])
result = rdd.map(lambda x: (x[0], list(x[1:])))
print result.collect()

rawDescription: PySpark - Convert an RDD into a key value pair RDD, with the values being in a List


code:
def one_of(alternatives):
    return lambda val: val in alternatives

def within(frm, to):
    return lambda val: frm <= val <= to

def gte(const):
    return lambda val: val >= const

def lte(const):
    return lambda val: val <= const

def exact(const):
    return lambda val: val == const

def select(data, **kwargs):
    for item in data:
        if all(chk(item[key]) for key, chk in kwargs.items()):
            yield item

data = [
    {'id': 1, 'name': 'Ann', 'age': 25},
    {'id': 2, 'name': 'Tom', 'age': 10},
    {'id': 3, 'name': 'John', 'age': 40},
    {'id': 4, 'name': 'Tom', 'age': 18},
]

for person in select(data, age=gte(15), id=within(3, 4), name=exact('Tom')):
    print person['name']

rawDescription: Python approach to dataset manipulation

description: Python approach to dataset manipulation