code:
x = raw_input("Enter calc instructions.  ")
a, b, c = x.split()
if b == "-":
    print float(a)-float(c)
elif b == "+":
    print float(a)+float(c)
elif b == "*":
    print float(a)*float(c)
elif b == "/":
    print float(a)/float(c) # replaced b to c

rawDescription: How to convert a string to float (without adding lines)

description: Convert a string to float (without adding lines)


code:
import datetime
def main():
    print "Welcome To the Date Converter"
    print "Please Enjoy Your Stay"
    print
    date_string = raw_input("Please enter a date in MM/DD/YYYY format:  ")
    d=datetime.datetime.strptime(date_string,'%m/%d/%Y')
    print(d.strftime('%B %d, %Y'))

if __name__=='__main__':
    main()

rawDescription: Date converter in python

description: Date converter in python


code:
def is_valid_ip_address(address, version=None):
    """ Check validity of address
        Return True if 'address' is a valid ipv4 or ipv6 address.
    """
    # Validate version:
    if version:
        if not isinstance(version, int):
            raise TypeError, 'Version is not of type "int"'
            return False
        if not (version == 4 or version == 6):
            raise ValueError, 'IP version is set to an invalid number: %s' % version
            return False
    try:
        ipaddr.IPAddress(address.strip(),version)
    except ValueError:
        return False
    return True

def is_valid_ipv4_address(address):
    """ Check validity of address
        Return True if 'address' is a valid ipv4 address.
    """
    return is_valid_ip_address(address,4)

def is_valid_ipv6_address(address):
    """ Check validity of address
        Return True if 'address' is a valid ipv6 address.
    """
    return is_valid_ip_address(address,6)

def is_valid_ip_range(iprange, version=None):
    """ Check validity of iprange
        Return True if 'iprange' is a range of ip addresses in a format that Qulys's API will accept (i.e. "startip-endip" where startip < endip).
    """
    # Validate version:
    if version:
        if not isinstance(version, int):
            raise TypeError, 'Version is not of type "int"'
            return False
        if not (version == 4 or version == 6):
            raise ValueError, 'IP version is set to an invalid number: %s' % version
            return False

    try:
        (start_ip,end_ip) = iprange.split('-')
        start_ip = start_ip.strip()
        end_ip = end_ip.strip()
        if ipaddr.IPAddress(start_ip) == ipaddr.IPAddress(end_ip):
            logging.debug('%s/%s-%s, Error: %s' % (package,module,version,'Start and End IP Address in an IP Range can not be the same IP Address.'))
            return False
        # A valid range requires:
        # 1) The start_ip must be a valid ip address.
        # 2) The end_ip must be a valid ip address.
        # 3) The start_ip must be less than the end_ip.
        # Although socket operations (as are used in qualysconnect.util) are nice, it's not feasible to determine that the start_ip is less than the
        # end_ip without considerable effort.  We'll use the ipaddr.summarize_address_range function to test all three at one time.
        ipaddr.summarize_address_range(ipaddr.IPAddress(start_ip,version),ipaddr.IPAddress(end_ip,version))
    except ipaddr.AddressValueError, e:
        logging.debug('%s/%s-%s, Error: %s' % (package,module,version,e))
        return False
    except ValueError, e:
        logging.debug('%s/%s-%s, Error: %s' % (package,module,version,e))
        return False
    return True

def is_valid_ipv4_range(iprange):
    """ Check validity of iprange
        Return True if 'iprange' is a range of ipv4 addresses in a format that Qulys's API will accept (i.e. "startip-endip" where startip < endip).
    """
    return is_valid_ip_range(iprange,4)

def is_valid_ipv6_range(iprange):
    """ Check validity of iprange
        Return True if 'iprange' is a range of ipv4 addresses in a format that Qulys's API will accept (i.e. "startip-endip" where startip < endip).
    """
    return is_valid_ip_range(iprange,6)

def cidr_to_ip(cidr,version=None):
    """ Convert an ip address or ip range provided in cidr notation (either bitmask or netmask notation) to the ip address or ip range format that is
        accepted by Qualys's API. (e.g. cidr_to_ip('10.0.0.0/24') returns the string '10.0.0.0-10.0.0.255'.
        Returns a String containing an ip address or ip range that can be provided to the Qualys API.
    """
    # Validate version:
    if version:
        if not isinstance(version, int):
            raise TypeError, 'Version is not of type "int"'
            return False
        if not (version == 4 or version == 6):
            raise ValueError, 'IP version is set to an invalid number: %s' % version
            return False
    try:
        cidr_net = ipaddr.IPNetwork(cidr,version)
    except ValueError, e:
        logging.debug('%s/%s-%s, Error: %s' % (package,module,version,e))
        raise ValueError, e
    if cidr_net[0] == cidr_net[-1]:
        return str(cidr_net[0])
    iprange = '%s-%s' % (cidr_net[0],cidr_net[-1])
    return iprange

def cidr_to_ipv4(cidr):
    """ Convert an ipv4 address or ipv4 range provided in cidr notation (either bitmask or netmask notation) to the ip address or ip range format that is
        accepted by Qualys's API. (e.g. cidr_to_ip('192.0.2.0/24') returns the string '192.0.2.0-192.0.2.255'.
        Returns a String containing an ip address or ip range that can be provided to the Qualys API.
    """
    return cidr_to_ip(cidr,4)

def cidr_to_ipv6(cidr):
    """ Convert an ipv6 address or ipv6 range provided in cidr notation (either bitmask or netmask notation) to the ip address or ip range format that is
        accepted by Qualys's API. (e.g. cidr_to_ip('2001:db8::fff/120') returns the string '2001:db8::f00-2001:db8::fff'.
        Returns a String containing an ipv6 address or ipv6 range that can be provided to the Qualys API.
    """
    return cidr_to_ip(cidr,4)

def decode_ip_string(ipstring):
    """ Validates ipstring is in a format that can be provided to the Qualys API, if it is not in a format that can be accepted by the Qualys API, it attempts
        to put it in a format that is acceptable (e.g. converting cidr notation to the ip range notation that Qualys expects)
        Returns a string that is valid to hand to the 'ips' key in the Qualys API.
    """
    cml=[]
    ip_list = ipstring.split(',')
    # Should probably check for any repeated or overlapping IP addresses here, but skipping for now.
    for i in ip_list:
        # This is a kludge, but I couldn't come up with a good way to make the error report the string that generated the error, rather than the
        # potentially modified version of the string that caused the error.
        new_i=i
        if '/' in i:
            new_i = cidr_to_ip(i)
        if (is_valid_ip_address(new_i) or is_valid_ip_range(new_i)):
            cml.append(new_i)
        else:
            raise ValueError, "IP argument cannot be parsed, \'%s\' is not a valid IP Range or IP Address" % i
    return ",".join(cml)

def ip_string_to_cidr(ipstring):
    """ Accepts ipstring - a string list of IPs in the format the Qualys expects or has provided (via API calls) and returns a list of ipaddr.IPNetwork objects."""
    ret_list = []
    ip_list = ipstring.split(',')
    for i in ip_list:
        if is_valid_ip_address(i):
            ret_list.append(ipaddr.IPNetwork(i.strip()))
        elif is_valid_ip_range(i.strip()):
            (start_ip,end_ip) = i.split('-')
            range_list = ipaddr.summarize_address_range(ipaddr.IPAddress(start_ip.strip()), ipaddr.IPAddress(end_ip.strip()))
            for j in range_list:
                ret_list.append(j)
    return ipaddr.collapse_address_list(ret_list)

def ip_list_to_ip_string(iplist):
    return decode_ip_string(",".join([decode_ip_string(str(i)) for i in iplist]))

rawDescription: How to diff a range of IP addresses within a range in Python 2.x?

description: Diff a range of IP addresses within a range in Python 2.x


code:
with open(file) as f:      # open the file
    for line in f:         # iterate over the lines
        if all(i in line for i in ('a', 'b', 'c')): # check if the line contain all (a,b,c)
            print line.split(" ")[0]   # if yes then do splitting on space and print the first value

rawDescription: grep piping python equivalent

description: Grep piping python equivalent


code:
mylist = ['X', 'Y', 'Z']
allvar = ' '.join(mylist)
print allvar

rawDescription: How to get values in python list and combined into one variable - python

description: Get values in python list and combined into one variable - python


code:
from mercurial import ui, hg, commands

myui = ui.ui()
repourl = "https://ninja-ide.googlecode.com/hg/"

commands.clone(myui, repourl, 'ninja')
r = hg.repository(myui, './ninja')
c = r.changectx("tip")

# show some information about the changeset
print c # represented as the changeset hash
print c.user()
print c.description()
print

# let's take a peek at the files
files = c.files()
for f in files:
 fc = c[f]
 print " ", f, len(fc.data())

rawDescription: Mercurial API : repo.changectx(change) doesn't exist!


code:
import re
import sys

teststring1 = "abc"
teststring2 = "  a"

myre = '^\s{0,2}(\w)(\w?)(\w?)$'

if re.search(myre,teststring1):
    print re.search(myre,teststring1).group(1)

if re.search(myre,teststring2):
   print re.search(myre,teststring2).group(1)

rawDescription: Python Conditional Regular Expression

description: Python Conditional Regular Expression


code:
import binascii, urllib, socket, random, struct
from bcode import bdecode
from urlparse import urlparse, urlunsplit

def announce_udp(tracker,payload):
    tracker = tracker.lower()
    parsed = urlparse(tracker)

    # Teporarly Change udp:// to http:// to get hostname and portnumbe
    url = parsed.geturl()[3:]
    url = "http" + url
    hostname = urlparse(url).hostname
    port = urlparse(url).port

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(8)
    conn = (socket.gethostbyname(hostname), port)
    #sock.bind((socket.gethostname(),s_port))

    #Get connection ID
    req, transaction_id = udp_create_connection_request()
    sock.sendto(req, conn);
    buf = sock.recvfrom(2048)[0]
    connection_id = udp_parse_connection_response(buf, transaction_id)

    #Annoucing
    s_port = sock.getsockname()[1] #get port number to which socket is connected
    req, transaction_id = udp_create_announce_request(connection_id, payload,s_port)
    sock.sendto(req, conn)
    print "Announce Request Sent"
    buf = sock.recvfrom(2048)[0]
    print "Response received"
    return udp_parse_announce_response(buf, transaction_id)

def udp_create_announce_request(connection_id, payload, s_port):
    action = 0x1 #action (1 = announce)
    transaction_id = udp_get_transaction_id()
    # print "2.Transaction ID :", transaction_id
    buf = struct.pack("!q", connection_id)                                  #first 8 bytes is connection id
    buf += struct.pack("!i", action)                                        #next 4 bytes is action
    buf += struct.pack("!i", transaction_id)                                #followed by 4 byte transaction id
    buf += struct.pack("!20s", urllib.unquote(payload['info_hash']))        #the info hash of the torrent we announce ourselves in
    buf += struct.pack("!20s", urllib.unquote(payload['peer_id']))          #the peer_id we announce
    buf += struct.pack("!q", int(urllib.unquote(payload['downloaded'])))    #number of bytes downloaded
    buf += struct.pack("!q", int(urllib.unquote(payload['left'])))          #number of bytes left
    buf += struct.pack("!q", int(urllib.unquote(payload['uploaded'])))      #number of bytes uploaded
    buf += struct.pack("!i", 0x2)                                           #event 2 denotes start of downloading
    buf += struct.pack("!i", 0x0)                                           #IP address set to 0. Response received to the sender of this packet
    key = udp_get_transaction_id()                                          #Unique key randomized by client
    buf += struct.pack("!i", key)
    buf += struct.pack("!i", -1)                                            #Number of peers required. Set to -1 for default
    buf += struct.pack("!i", s_port)                                        #port on which response will be sent
    return (buf, transaction_id)

def udp_parse_announce_response(buf, sent_transaction_id):
    #print "Response is:"+str(buf)
    if len(buf) < 20:
        raise RuntimeError("Wrong response length while announcing: %s" % len(buf))
    action = struct.unpack_from("!i", buf)[0] #first 4 bytes is action
    res_transaction_id = struct.unpack_from("!i", buf, 4)[0] #next 4 bytes is transaction id
    if res_transaction_id != sent_transaction_id:
        raise RuntimeError("Transaction ID doesnt match in announce response! Expected %s, got %s"
            % (sent_transaction_id, res_transaction_id))
    print "Reading Response"
    if action == 0x1:
        print "Action is 3"
        ret = dict()
        offset = 8; #next 4 bytes after action is transaction_id, so data doesnt start till byte 8
        ret['interval'] = struct.unpack_from("!i", buf, offset)[0]
        print "Interval:"+str(ret['interval'])
        offset += 4
        ret['leeches'] = struct.unpack_from("!i", buf, offset)[0]
        print "Leeches:"+str(ret['leeches'])
        offset += 4
        ret['seeds'] = struct.unpack_from("!i", buf, offset)[0]
        print "Seeds:"+str(ret['seeds'])
        offset += 4
        peers = list()
        x = 0
        while offset != len(buf):
            peers.append(dict())
            peers[x]['IP'] = struct.unpack_from("!i",buf,offset)[0]
            print "IP: "+socket.inet_ntoa(struct.pack("!i",peers[x]['IP']))
            offset += 4
            if offset >= len(buf):
                raise RuntimeError("Error while reading peer port")
            peers[x]['port'] = struct.unpack_from("!H",buf,offset)[0]
            print "Port: "+str(peers[x]['port'])
            offset += 2
            x += 1
        return ret,peers
    else:
        #an error occured, try and extract the error string
        error = struct.unpack_from("!s", buf, 8)
        print "Action="+str(action)
        raise RuntimeError("Error while annoucing: %s" % error)

def udp_create_connection_request():
    connection_id = 0x41727101980                   #default connection id
    action = 0x0                                    #action (0 = give me a new connection id)
    transaction_id = udp_get_transaction_id()
    print "1.Transaction ID :", transaction_id
    buf = struct.pack("!q", connection_id)          #first 8 bytes is connection id
    buf += struct.pack("!i", action)                #next 4 bytes is action
    buf += struct.pack("!i", transaction_id)        #next 4 bytes is transaction id
    return (buf, transaction_id)

def udp_parse_connection_response(buf, sent_transaction_id):
    if len(buf) < 16:
        raise RuntimeError("Wrong response length getting connection id: %s" % len(buf))
    action = struct.unpack_from("!i", buf)[0] #first 4 bytes is action

    res_transaction_id = struct.unpack_from("!i", buf, 4)[0] #next 4 bytes is transaction id
    if res_transaction_id != sent_transaction_id:
        raise RuntimeError("Transaction ID doesnt match in connection response! Expected %s, got %s"
            % (sent_transaction_id, res_transaction_id))

    if action == 0x0:
        connection_id = struct.unpack_from("!q", buf, 8)[0] #unpack 8 bytes from byte 8, should be the connection_id
        return connection_id
    elif action == 0x3:
        error = struct.unpack_from("!s", buf, 8)
        raise RuntimeError("Error while trying to get a connection response: %s" % error)
    pass

def udp_get_transaction_id():
    return int(random.randrange(0, 255))

rawDescription: BitTorrent Client : Getting Peer List From Trackers [Python]


code:
soup = BeautifulSoup(response.content)
paragraphs = soup.find_all('p')
print paragraphs[1]

rawDescription: How to properly print out unicode text after processing with bs4 and requests?

description: Properly print out unicode text after processing with bs4 and requests


code:
from tempfile import mkstemp
from shutil import move
from os import remove, close

def add_player_points():
    file_path = "test.txt"
    name = raw_input("\n\tPlease enter the name of the player whose points you wish to add: ")
    #Create temp file
    fh, abs_path = mkstemp()
    with open(abs_path,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                stripped_line = line.strip()
                split_string = stripped_line.split(",")
                print name == split_string[0]
                if name == split_string[0]:
                    opponent = raw_input("\n\t Enter the name of the opponent: ")
                    points = raw_input("\n\t Enter how many points you would like to add?: ")
                    temp = int(split_string[5]) + int(points)  # fool proofing the code
                    split_string[5] = str(temp)
                    stripped_line = ','.join(split_string)# line you shove back into the file.
                    print stripped_line
                    new_file.write(stripped_line +'\n')
                else:
                    new_file.write(line)
    close(fh)
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

rawDescription: How do I add a user inputted number into my text file list?

description: Add a user inputted number into my text file list


code:
class FirstClass(object):
    def __init__ (self, value="I am the value from FirstClass"):
        print value

    def meth(self):
        print "I am meth from FirstClass"

    def meth2(self):
        print "I am meth2 from FirstClass"

class SecondClass(FirstClass):
    def __init__ (self):
        print "I am in SecondClass"
        super(SecondClass, self).__init__(value="I am the value from SecondClass")

    def meth(self):
        print "I am meth from SecondClass"

a=FirstClass() # prints "I am the value from FirstClass"
b=SecondClass() # prints *both* "I am in SecondClass" *and* "I am the value from SecondClass

a.meth() # prints "I am meth from FirstClass"
b.meth() # prints "I am meth from SecondClass"

a.meth2() # prints "I am meth2 from FirstClass"
b.meth2() # *also* prints "I am meth2 from FirstClass", because you didn't redefine it.

rawDescription: Am I using super() correctly?

description: Am I using super() correctly


code:
fn = "example.mp3"
multipart = MIMEMultipart('alternative')
multipart['Subject'] = 'Tutorate!'
multipart['To'] = 'Selfie'
multipart['From'] = 'Selfie'

text = "Hello, how are you, goodbye."
textpart = MIMEText(text)
multipart.attach(textpart)
htmlpart = MIMEText("<html>" + text + "</html>", 'html')
multipart.attach(htmlpart)

part = MIMEBase('audio', "mp3")
part.set_payload( open(fn,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(fn))
multipart.attach(part)

io = StringIO.StringIO()
g = Generator(io, False)  # second argument means "should I mangle From?"
g.flatten(multipart)
v = io.getvalue()

class SMTPTutorialClient(smtp.ESMTPClient):
    mailFrom = "selfie@~"
    mailTo = "selfie@~"
    def getMailFrom(self):
        result = self.mailFrom
        self.mailFrom = None
        return result

    def getMailTo(self):
        return [self.mailTo]

    def getMailData(self):
        #print v
        return StringIO.StringIO(v)

    def sentMail(self, code, resp, numOk, addresses, log):
        print 'Sent', numOk, 'messages'

        from twisted.internet import reactor
        reactor.stop()

rawDescription: Python and Twisted: making utf-8 html mail with message-id


rawDescription: How to split elements of list with regex

description: Split elements of list with regex


code:
import csv
r=csv.reader(open("a.tsv"), delimiter="\t", quotechar='"')
print r.next()

rawDescription: How do I parse a tab delimited file that may have values across multiple lines?

description: Parse a tab delimited file that may have values across multiple lines


code:
import re

regx = re.compile('[a-z]+\[_FILE:(.*?)_\]')

ch = 'abcd[_FILE:foo.txt_]efghi[_FILE:bar.txt_]jklm[_FILE:foo2.txt_] '

print regx.findall(ch)

rawDescription: Match string segments in regular expressions


code:
import sys
from rbtools.api.client import RBClient

if __name__ == '__main__':
    client = RBClient('http://reviewboard/')
    root = client.get_root()

    review = root.get_review_request(review_request_id=sys.argv[1])
    for reviewer in review.target_people:
        print '{}, {}'.format(reviewer.title, reviewer.href)

rawDescription: Python RBTools: get reviewers

description: Python RBTools: get reviewers


code:
done = False

for c1 in range(int(start_ip[0]), 255):
    for c2 in range(int(start_ip[1]), 255):
        for c3 in range(int(start_ip[2]), 255):
            for c4 in range(int(start_ip[3]), 255):
                if "%d.%d.%d.%d" % (c1, c2, c3, c4) == "%d.%d.%d.%d" % (int(end_ip[0]), int(end_ip[1]), int(end_ip[2]), int(end_ip[3])):
                    done = True
                    break
                else:
                    print "%d.%d.%d.%d" % (c1, c2, c3, c4)
            if(done):
                break
        if(done):
            break
    if(done):
        break

rawDescription: How to loop through an IP range?

description: Loop through an IP range


code:
import csv
import StringIO

predfile = StringIO.StringIO(
'''x1,x2
1,2
3,4''')

def func(x1, x2):
    x1 = int(x1)
    x2 = int(x2)
    return 1 + 2*x1 + 3*x2

reader = csv.DictReader( predfile , delimiter=',' ) # header is handled automatically
for row in reader:
    print func(**row)

rawDescription: How to use python to score large file: alternatives to `exec`

description: Use python to score large file: alternatives to `exec`


code:
tot = 0
for i in xrange(1, 11):
    tot += i
    print '{:<20}{} {}.'.format(str(i) + '.',  'sum so far:', tot)

rawDescription: Python string format width

description: Python string format width


code:
class Some(object):
  a = 97
  b = 98
  def f(self):
    return self.a + self.b + self.c

class Other(object):
  c = 99

class Thing(Some, Other, object):
  pass

o = Thing()
p = Thing()
p.a, p.b, p.c = 65, 66, 67

print o.a, o.b, o.c, o.f() # 97 98 99 294
print p.a, p.b, p.c, p.f() # 65 66 67 198

rawDescription: Access class when used as class-level variable in Python


rawDescription: How to compare these two strings in Python?

description: Compare these two strings in Python


code:
if __name__ == '__main__':
    print a, b, c

rawDescription: Why does Python run my code bottom to top?


code:
import os.path, time
import smtplib

if (time.time() - os.path.getmtime('/path/to/file.log') > (10 * 60)):
    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail('from_me@somewhere.com', 'to_bajiboo@elsewhere.com', 'My log file has not been updated for a while')
    except SMTPException:
        print 'Error: unable to send email'

rawDescription: Monitoring a log file using python

description: Monitoring a log file using python


code:
import wx

class MyFrame(wx.Frame):
    """a frame with a panel"""
    def __init__(self, parent=None, id=wx.ID_ANY, title=None):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title)
        self.xcolor = (0, 0, 0)
        self.panel = wx.Panel(self, size=(350, 200))
        self.panel.Bind(wx.EVT_PAINT, self.on_paint)
        self.button2 = wx.Button(self.panel, id=wx.ID_ANY, label='Button2',
                                             pos=(8, 38), size=(175, 28))
        self.button2.Bind(wx.EVT_BUTTON, self.onColorDlg)

        self.Fit()

    def onColorDlg(self, event):
        """
        This is mostly from the wxPython Demo!
        """
        dlg = wx.ColourDialog(None)
        dlg.GetColourData().SetChooseFull(True)

        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetColourData()
            self.xcolor = data.GetColour().Get()
            print 'You selected: %s\n' % str(self.xcolor)

        dlg.Destroy()
        self.panel.Refresh()

    def on_paint(self, event):
        dc = wx.PaintDC(self.panel)
        dc.SetPen(wx.Pen(self.xcolor, 2))
        rect = wx.Rect(50, 50, 100, 100)
        dc.DrawRoundedRectangleRect(rect, 8)

# test it ...
app = wx.PySimpleApp()
frame1 = MyFrame(title='rounded-rectangle & circle')
frame1.Center()
frame1.Show()
app.MainLoop()

rawDescription: How to use Refresh with a wx.ColourDialog in wxpython?

description: Use Refresh with a wx.ColourDialog in wxpython


code:
# Helper function to add the O_NONBLOCK flag to a file descriptor
def make_async(fd):
    fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)

# Helper function to read some data from a file descriptor, ignoring EAGAIN errors
def read_async(fd):
    try:
        return fd.read()
    except IOError, e:
        if e.errno != errno.EAGAIN:
            raise e
        else:
            return ''

process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
make_async(process.stdout)
make_async(process.stderr)

stdout = str()
stderr = str()
returnCode = None

while True:
    # Wait for data to become available
    select.select([process.stdout, process.stderr], [], [])

    # Try reading some data from each
    stdoutPiece = read_async(process.stdout)
    stderrPiece = read_async(process.stderr)

    if stdoutPiece:
        print stdoutPiece,
    if stderrPiece:
        print stderrPiece,

    stdout += stdoutPiece
    stderr += stderrPiece
    returnCode = process.poll()

    if returnCode != None:
        return (returnCode, stdout, stderr)

rawDescription: How can I print and display subprocess stdout and stderr output without distortion?

description: Print and display subprocess stdout and stderr output without distortion


code:
import os
import psutil

def memory_usage_psutil():
    # return the memory usage in percentage like top
    import psutil
    process = psutil.Process(os.getpid())
    mem = process.memory_percent()
    return mem

consume_memory = range(20*1000*1000)

while True:
    print memory_usage_psutil()

rawDescription: How to get the percentage of memory usage of a process?

description: Get the percentage of memory usage of a process


code:
data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
for sublist in data:
    if sublist[1] == search:
        print "Found it!", sublist
        break
# Prints: Found it! ['a', 'c']

rawDescription: Python search in lists of lists

description: Python search in lists of lists


code:
"""
Usage:
    program [options]

General options:
  These things are rather general, so placed in this group of option.

    -h, --help            Show this help message.
    --version             Show the version and exit.
    -c, --configuration=CONF
                          Configuration (file) [default: None]

Directory and path related stuff:
  Whatever relates to file or directory, comes here.

    -f, --files=FILESLIST
                          Comma-delimited list of input data files
                          [default: 169888_ttH_el.root]
    -t, --tree=TREE       Tree in input data files [default: mini]
    -t, --topanalysis=DIRECTORY
                          Directory of TopRootCore or TopAnalysis
                          [default: /home/user/Dropbox/TopAnalysis]
Other things:
  Remaining options live here.

    -v, --variables=VARIABLESLIST
                          Comma-delimited list of variables to plot
                          [default: trk_pt]
    -u, --username=USERNAME
                          Username
    -s, --superlongoption=TEST
                          This is a very long option that requires a bit of text
                          to explain it.
                          [default: 101001011011101010010100110101010]
"""
if __name__ == "__main__":
    from docopt import docopt
    args = docopt(__doc__)
    print args

rawDescription: How can text in the options configuration of Docopt be wrapped?


code:
for index, (key, value) in enumerate(mydict.items()):
    print index, key, value

rawDescription: Python loop index of key, value for-loop when using items()


code:
from itertools import count
import urllib, urllib2, sys, argparse
from xgoogle.search import GoogleSearch, SearchError

stringArr = ["string 1",
             "string 2",
             "string 3",
             "string etc"]

def searchIt(url):
    try:
        if(args.verbose>='1'):
            print "[INFO] Opening URL: "+url
        response = urllib.urlopen(url)
    except urllib2.URLError, e:
        print "[ERROR] "+e.reason
        return False
    if checkForStr(response.read()):
        if(args.verbose=='0'):
            print "[INFO] String found in URL: "+url
    else:
        if(args.verbose>='1'):
            print "[INFO] No string found in URL: "+url

def checkForStr(html):
    return any(checkStr in html for checkStr in stringArr)

def main():
    try:
        gs = GoogleSearch(args.keyword)
        gs.results_per_page = 100
        for i in count():
            results = gs.get_results()
            if not results: # no more results (pages) were found
                break
            for r in results: # process results for page
                searchIt(r.url) # check for string
        # finished
    except SearchError, e:
        print "[ERROR] Search failed: %s" % e

if __name__ == '__main__':
    try:
        parser = argparse.ArgumentParser()
        parser.add_argument('-v', dest='verbose', default='0', help='Verbosity level', choices='012')
        group = parser.add_argument_group('required arguments')
        group.add_argument('-k', dest='keyword', help='Keyword to use on google query', required=True)
        args = parser.parse_args()
        main()
    except KeyboardInterrupt:
        print "Suspended by user..."
        sys.exit()

rawDescription: I think I have a memory leak in my python script


code:
test = ['he', 'she', 'them']
string = 'hello'
if any(test_item  in string for test_item in test):
    print 'yes'

rawDescription: If string contains an list item

description: If string contains an list item


code:
import calendar

c = calendar.Calendar().yeardatescalendar(2014)
#print c

#first week
print c[0][0][0]
[datetime.date(2013, 12, 30), datetime.date(2013, 12, 31), datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3), datetime.date(2014, 1, 4), datetime.date(2014, 1, 5)]

#last week
print c[-1][-1][-1]
[datetime.date(2014, 12, 29), datetime.date(2014, 12, 30), datetime.date(2014, 12, 31), datetime.date(2015, 1, 1), datetime.date(2015, 1, 2), datetime.date(2015, 1, 3), datetime.date(2015, 1, 4)]

#filter datetimes by list comprehension
print [x for x in c[0][0][0] if x.year == 2014]
[datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3), datetime.date(2014, 1, 4), datetime.date(2014, 1, 5)]

print [x for x in c[-1][-1][-1] if x.year == 2014]
[datetime.date(2014, 12, 29), datetime.date(2014, 12, 30), datetime.date(2014, 12, 31)]

#replace first and last week
c[0][0][0] = [x for x in c[0][0][0] if x.year == 2014]
c[-1][-1][-1] = [x for x in c[-1][-1][-1] if x.year == 2014]

print c[0][0][0]
[datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3), datetime.date(2014, 1, 4), datetime.date(2014, 1, 5)]

print c[-1][-1][-1]
[datetime.date(2014, 12, 29), datetime.date(2014, 12, 30), datetime.date(2014, 12, 31)]

rawDescription: Extracting datetime info from yeardatescalendar in python


code:
from datetime import datetime
import itertools

sales = [
    ('2013-05-01', 100),
    ('2013-05-02', 200),
    ('2013-05-03', 150),
    ('2013-05-03', 120),
    ('2013-05-04', 200),
    ('2013-08-01', 250),
]

def toWeek(sale):
    '''(date,volume) -> date of the Sunday of that week'''
    sunday = datetime.strptime(sale[0], '%Y-%m-%d').strftime('%Y-%U-0')
    return datetime.strptime(sunday, '%Y-%U-%w').strftime('%Y-%m-%d')

grouped_sales = itertools.groupby(sales, toWeek)

aggregate_sales = (
    (week, sum(day_sales for date, day_sales in week_sales))
    for week, week_sales in grouped_sales)

print list(aggregate_sales)

rawDescription: aggregate data by week using python

description: Aggregate data by week using python


code:
import mmap
from struct import *

def main():
    filename = raw_input("Input file name: ")
    f = open(filename, "r+b")
    offList, compList = getOffsets(f)
    for i in range(len(offList)):
        print "offset: ", offList[i], "\t Compression: ", compList[i]
    print "ran right"
    stripLabelAndMacro(f, offList, 3)
    offList, compList = getOffsets(f)
    for i in range(len(offList)):
        print "offset: ", offList[i], "\t Compression: ", compList[i]
    f.close()
    #test stripping end crap

def getOffsets(f):
    fmap = mmap.mmap(f.fileno(),0)
    offsets = []
    compressions = []
    #get TIFF version
    ver = int(unpack('H', fmap[2:4])[0])
    if ver == 42:
        #get first IDF
        offset = long(unpack('L', fmap[4:8])[0])
        while (offset != 0):
            offsets.append(offset)
            #get number of tags in this IDF
            tags = int(unpack('H', fmap[offset:offset+2])[0])
            i = 0
            while (i<tags):
                tagID = int(unpack('H',fmap[offset+2:offset+4])[0])
                #if the tag is a compression, get the compression SHORT value and
                #if recognized use a string representation
                if tagID == 259:
                    tagValue = int(unpack('H', fmap[offset+10:offset+12])[0])
                    if tagValue == 1:
                        compressions.append("None")
                    elif tagValue == 5:
                        compressions.append("LZW")
                    elif tagValue == 6:
                        compressions.append("JPEG")
                    elif tagValue == 7:
                        compressions.append("JPEG")
                    elif tagValue == 34712 or tagValue == 33003 or tagValue == 33005:
                        compressions.append("JP2K")
                    else:
                        compressions.append("Unknown")
                i+=1
                offset += 12

            offset = long(unpack('L', fmap[offset+2:offset+6])[0])
    return offsets, compressions

#Tested, Doesn't break TIFF
def stripLabel(f, offsetList, labelIndex):
    fmap = mmap.mmap(f.fileno(),0)
    offsetLabel = offsetList[labelIndex]
    offsetMacro = offsetList[labelIndex+1]
    offsetEnd = fmap.size()
    macroSize = offsetEnd - offsetMacro
    for i in range(macroSize):
        fmap[offsetLabel+i] = fmap[offsetMacro+i]
    fmap.flush()
    fmap.resize(offsetLabel+macroSize-1)
    fmap.close()

rawDescription: Remove/Delete Page from multipage TIFF file


code:
print re.search(regx, string2).group(1) // 24
print re.search(regx, string2).group(2) // 200

rawDescription: python regular expression, extracting set of numbers from a string

description: Python regular expression, extracting set of numbers from a string


code:
a = [1, 2, 4]
print a
b = a[:2] + [3] + a[2:]
print a
print b

rawDescription: Insert an element at specific index in a list and return updated list


rawDescription: encoding / decoding special characters in python 2.7

description: Encoding / decoding special characters in python 2.7


code:
myStr = 'START1(stuff); II(morestuff); 8(lessstuff)'
print re.findall(r'(?:START)?(\w+)\(([^)]*)\)', myStr)

rawDescription: python re backreference repeated elements

description: Python re backreference repeated elements


code:
import itertools

def covnersion_Anim(xPos,trueVal,*args):
    mTuple = args
    plt_bulk_lst = []
    plt_head_lst = []
    color_list = ['Green','Blue','Orchid','Cyan','Goldenrod','Salmon','Orange','Violet','Magenta']
    f = plt.figure(figsize =(17,8))
    ax = plt.gca()
    ax.set_xlim([min(xPos),max(xPos)])
    ax.set_ylim([0,1])
    ms = 5
    for j,c in zip(range(len(mTuple)),itertools.cycle(color_list)):
        plt_bulk_lst.append(ax.plot([],[],color=c,ms=ms,marker='x',linestyle='none')[0])
        plt_head_lst.append(ax.plot([xPos[0]],[mTuple[j][0]],color='Dark'+c,ms=ms,marker='o',linestyle='none')[0])
    real_plt, = plot([],[],color='red')

    for j in range(1,len(xPos)):
        print j
        for hd_plt,blk_plt,m in zip(plt_head_lst,plt_bulk_lst,mTuple):
            hd_plt.set_xdata([xPos[j]])
            hd_plt.set_ydata([m[j]])

            blk_plt.set_ydata(m[:j])
            blk_plt.set_xdata(xPos[:j])

            real_plt.set_xdata(xPos[:j])
            real_plt.set_ydata(trueVal[:j])

        plt.pause(1)

    return f
covnersion_Anim(range(12),rand(12),rand(12),rand(12),rand(12))

rawDescription: 'Animated' 2D scatter

description: 'Animated' 2D scatter


code:
import pickle
def capture_album_links():
    for page in index_pages: # index_pages is a list of URLs
        resp = connect_tor(page)
        soup = BeautifulSoup(resp.read(), from_encoding=resp.info().getparam('charset'))
        try:
            # with will automatically close your files
            with open("last_passworded_album.p", "rb") as f1, open("last_accessible_album.p", "rb") as f2:
                x = pickle.load(f1)
                y = pickle.load(f2)
        # catch specific errors
        except (pickle.UnpicklingError,IOError) as e:
            print(e)
            print "There is no pickle file"
            # continue on error or x and y won't be defined
            continue
        for a in soup.find_all('a', href=True):
            if root_url + a['href'] in {x, y}:
                return # just return to end both loops
            elif "passchk.php" in a['href']:
                passworded_albums.append(root_url + a['href'])
            elif "search.php" in a['href'] or "switch.php" in a['href']:
                continue
            else:
                if ".html" in a['href']:
                    accessible_albums.append(root_url + a['href'])

rawDescription: Escape out of nested loop in Python

description: Escape out of nested loop in Python


code:
test = """
<option1> {
<variable1>=<value1>; //<comment>
<variable2>=<value2>;
..
<variableN>=<valueN>; //<comment>
}

<option2> {
<variable1>=<value1>; //<comment>
<variable2>=<value2>;
..
<variableN>=<valueN>; //<comment>
}

...
...

<optionN> {
<variable1>=<value1>; //<comment>
<variable2>=<value2>;
..
<variableN>=<valueN>; //<comment>
}

"""

from HTMLParser import HTMLParser

# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
    option = ""
    key = ""
    value = ""
    r = {}
    def handle_starttag(self, tag, attrs):
        self.currentTag = tag
        print "Encountered a start tag:", tag
        if "option" in tag:
            #self.r = {}
            self.option = tag
            self.r[self.option] = {}
        elif "{" in self.currentData or "=" not in self.currentData and "//" not in self.currentData:
            self.key = tag
            self.r[self.option][self.key] = ""
        elif "=" in self.currentData:
            self.value = tag
            self.r[self.option][self.key] = self.value
            #print self.r
    def handle_endtag(self, tag):
        self.currentData = None
        print "Encountered an end tag :", tag
    def handle_data(self, data):
        self.currentData = data
        print "Encountered some data  :", data
        #find a condition to yield result here "}" ?

# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
parser.feed(test)
print parser.r

rawDescription: Parsing big text files with python specific syntax


code:
class C(object):
    @memoized
    def foo(): pass

o1 = C()
o2 = copy.copy(o1)
print o1.foo.cache is o2.foo.cache

rawDescription: I found a memoization code snippet, and I'm wondering how it would behave under copy.copy


code:
data = open("googlel.csv", "rb")
orig = csv.reader(data, delimiter = ';')
goodrows = []
for feed in gotfeeds:
   for link,comments in feed.items():
       data.seek(0)
       for row in orig:
           print link
           if link in row[1]:
               row.append(comments)
               goodrows.append(row)

rawDescription: Reading from CSVs in Python repeatedly?

description: Reading from CSVs in Python repeatedly


code:
import networkx as netx
import networkx.algorithms as al

# build graph
g = netx.DiGraph()
edges = [(1,2),(2,3),(3,4),(4,1),(1,2),(2,5),(5,3),(3,4),(4,1)]
g.add_edges_from(edges)

# find cycles
cycles = al.simple_cycles(g)

# assuming that the exterior cycle will contain the most nodes
for cycle in cycles:
    print len(cycle)

rawDescription: Removing interior loops of a network

description: Removing interior loops of a network


rawDescription: wxGTK+ wxComboBox deselection

description: WxGTK+ wxComboBox deselection


code:
from itertools import chain
print list(chain((1,2,3), [2, 5, 3], (3,1,3), [3, 2344, 3]))

rawDescription: More Pythonic way to turn any number of different lists or tuples into one list


code:
from collections import OrderedDict
from tabulate import tabulate
parameter_list = []
parameter_list.append(OrderedDict([('C', False), ('A', 'Hello'), ('B', 'you')]))
parameter_list.append(OrderedDict([('C', False), ('A', 'Salue'), ('B', 'Tu')]))
print tabulate(parameter_list, headers='keys')

rawDescription: `tabulate` order columns by keys

description: `tabulate` order columns by keys


code:
from __future__ import nested_scopes

import os, time

def watch_directories (paths, func, delay=1.0):
    """(paths:[str], func:callable, delay:float)
    Continuously monitors the paths and their subdirectories
    for changes.  If any files or directories are modified,
    the callable 'func' is called with a list of the modified paths of both
    files and directories.  'func' can return a Boolean value
    for rescanning; if it returns True, the directory tree will be
    rescanned without calling func() for any found changes.
    (This is so func() can write changes into the tree and prevent itself
    from being immediately called again.)
    """

    # Basic principle: all_files is a dictionary mapping paths to
    # modification times.  We repeatedly crawl through the directory
    # tree rooted at 'path', doing a stat() on each file and comparing
    # the modification time.

    all_files = {}
    def f (unused, dirname, files):
        # Traversal function for directories
        for filename in files:
            path = os.path.join(dirname, filename)

            try:
                t = os.stat(path)
            except os.error:
                # If a file has been deleted between os.path.walk()
                # scanning the directory and now, we'll get an
                # os.error here.  Just ignore it -- we'll report
                # the deletion on the next pass through the main loop.
                continue

            mtime = remaining_files.get(path)
            if mtime is not None:
                # Record this file as having been seen
                del remaining_files[path]
                # File's mtime has been changed since we last looked at it.
                if t.st_mtime > mtime:
                    changed_list.append(path)
            else:
                # No recorded modification time, so it must be
                # a brand new file.
                changed_list.append(path)

            # Record current mtime of file.
            all_files[path] = t.st_mtime

    # Main loop
    rescan = False
    while True:
        changed_list = []
        remaining_files = all_files.copy()
        all_files = {}
        for path in paths:
            os.path.walk(path, f, None)
        removed_list = remaining_files.keys()
        if rescan:
            rescan = False
        elif changed_list or removed_list:
            rescan = func(changed_list, removed_list)

        time.sleep(delay)

if __name__ == '__main__':
    def f (changed_files, removed_files):
        print changed_files
        print 'Removed', removed_files

    watch_directories(['.'], f, 1)

rawDescription: Monitoring filesystem events using Python without other lowlevel libs


rawDescription: Python: Dictionary with list of dictionaries


code:
from copy import copy

def exact_change(target_amount, L):
    L = sorted(L, reverse=True)
    for v in L:
        if v == target_amount:
            return True
        else:
            if v < target_amount:
                L.remove(v)
                return exact_change(target_amount-v, L)
    else:
        return False

print exact_change( 42, [25, 1, 25, 10, 5, 1] )

print exact_change( 42, [25, 1, 25, 10, 5] )

rawDescription: Exact change in python via recursion

description: Exact change in python via recursion


code:
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
gobject.threads_init()
dbus.mainloop.glib.threads_init()
DBUSMAINLOOP = gobject.MainLoop()

print 'Creating DBus Thread'
DBUSLOOPTHREAD = threading.Thread(name='glib_mainloop', target=DBUSMAINLOOP.run)
DBUSLOOPTHREAD.start()

print 'Starting REST'
cherrypy.config.update({ 'server.socket_host': Common.DBUS_SERVER_ADDR, 'server.socket_port': Common.DBUS_SERVER_PORT, })
cherrypy.quickstart(USBRest())

rawDescription: DBus-Cherrypy merge issue

description: DBus-Cherrypy merge issue


code:
import poplib

#connect to server
mailserver = poplib.POP3_SSL('pop.gmail.com')
mailserver.user('recent:YOURUSERNAME') #use 'recent mode'
mailserver.pass_('YOURPASSWORD') #consider not storing in plaintext!

#newest email has the highest message number
numMessages = len(mailserver.list()[1])

#confirm this is the right one, can comment these out later
newestEmail = mailserver.retr(numMessages)
print newestEmail

#most servers will not delete until you quit
mailserver.dele(numMessages)
mailserver.quit()

rawDescription: Deleting the most recently received email via Python script?


code:
import os
from wand.image import Image
from wand.display import display

path = "____absolute_dir_path____ (ex. /home/kim/work/)"

dirList=os.listdir(path)
for fname in dirList:
    print fname
    with Image(filename=path+fname) as img:
        print img.size

rawDescription: How to open multiple images using Wand and Python

description: Open multiple images using Wand and Python


code:
x="""

aaa@example.jpg

--bbb@example.com--

ccc@example.com--

--ddd@example.com

"""
print re.findall(r"-*([\w\-\.]{1,100}@(?:\w[\w\-]+\.)+(?!jpg)[\w]+)-*",x)

rawDescription: Python regex to remove capture email between dashes or ignore emails ending with .jpg etc


code:
with open('E:\ASCII\data.txt', 'r') as f:
    for line in f.read().splitlines():
        print repr(line)

rawDescription: ASCII files get erased after opening in Python


code:
import pylab as pl
import numpy as np
a = np.random.rand(10, 10)
pl.imshow(a)
cb = pl.colorbar(pad=0.1,  orientation='horizontal')

l, b, w, h = cb.ax.get_position().bounds
print l, b, w, h
cb.ax.set_aspect("auto")
#w = 0.05            # width of the colorbar (from the vertical example)
h = 0.05             # height of the colorbar
ax2 = pl.twiny(ax=cb.ax)
cb.ax.set_position([l, b, w, h])
ax2.set_position([l, b, w, h])
cb.ax.set_xlim(0, 1) # you are now dealing with an horizontal colorbar
                     # so you should define the x lim, not the y lim
ax2.set_xlim(-10, 10)
pl.show()

rawDescription: Two ranges on a horizontal oriented colorbar ticks are 'floating away' from colorbar


code:
import signal
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import GLib, Gdk, Gtk, GObject

class LoseFocusHandler:
  def onClick(self, window):
    print "Losing focus yet?"
    old_window[0].focus(0)

def focus_handler(gdk_window, event):
    # At this point, our window does not have focus yet, but is
    # about to. This hence works:
    old_window[0] = gdk_window.get_screen().get_active_window()

if __name__ == "__main__":
  GObject.threads_init()

  old_window = [ Gdk.Screen.get_default().get_active_window() ]

  builder = Gtk.Builder()
  builder.add_from_file("losefocus.glade")
  builder.connect_signals(LoseFocusHandler())
  window1 = builder.get_object("window1")
  window1.connect("focus-in-event", focus_handler)
  window1.show_all()

  signal.signal(signal.SIGINT, signal.SIG_DFL)
  Gtk.main()

rawDescription: How to unfocus (blur) Python-gi GTK+3 window on Linux

description: Unfocus (blur) Python-gi GTK+3 window on Linux


code:
class NameShowMixin(object):
    def showName(self):
        openWindow()
        print self.name

rawDescription: DRYing up classes that duplicate methods


code:
def cropbbox(imagewidth, imageheight, thumbwidth, thumbheight):
    """ cropbbox(imagewidth, imageheight, thumbwidth, thumbheight)

        Compute a centered image crop area for making thumbnail images.
          imagewidth, imageheight are source image's dimensions
          thumbwidth, thumbheight are thumbnail image's dimensions

        Returns bounding box pixel coordinates of the cropping area
        in this order (left, upper, right, lower).
    """
    # determine scale factor
    fx = float(imagewidth)/thumbwidth
    fy = float(imageheight)/thumbheight
    f = fx if fx < fy else fy

    # calculate size of crop area
    cropheight, cropwidth = int(thumbheight*f), int(thumbwidth*f)

    # for centering compute half the size difference of the image & crop area
    dx = (imagewidth-cropwidth)/2
    dy = (imageheight-cropheight)/2

    # return bounding box of crop area
    return dx, dy, dx+cropwidth, dy+cropheight

if __name__=='__main__':

    print "==="
    bbox = cropbbox(1024, 768, 128, 128)
    print "cropbbox(1024, 768, 128, 128):", bbox

    print "==="
    bbox = cropbbox(768, 1024, 128, 128)
    print "cropbbox(768, 1024, 128, 128):", bbox

    print "==="
    bbox = cropbbox(1024, 1024, 96, 128)
    print "cropbbox(1024, 1024, 96, 128):", bbox

    print "==="
    bbox = cropbbox(1024, 1024, 128, 96)
    print "cropbbox(1024, 1024, 128, 96):", bbox

rawDescription: What's the simplest way in Python to resize an image to a given bounded area?


code:
import copy
a = [1,2,3]
b = copy.copy(a)
b.append(4)

print a,b

rawDescription: Python - Append to a copy variable

description: Python - Append to a copy variable


code:
#! /usr/bin/env python

def octavesort0(num, lo, hi):
    i = 2.0
    x = num
    while not lo <= x <= hi:
        x = num / i
        #print i, x
        i += 1.0
    return x

def octavesort1(num, lo, hi):
    i = 2.0
    x = num
    while not lo <= x <= hi:
        x = num / i
        #print i, x
        i *= 2.0
    return x

octavesort = octavesort1

def main():
    lo, hi = 500, 1000
    print octavesort(23456, lo, hi)

if __name__ == '__main__':
    main()

rawDescription: Creating a function in Python that gets divided until it is in a certain range


code:
class Bot:
    def fight(self):
       print "fighting is fun!"

class Scheduler:
    def schedule_action(self,action):
       bot = Bot()
       getattr(bot,action)()

scheduler = Scheduler()
scheduler.schedule_action('fight')

rawDescription: Python script is running. I have a method name as a string. How do I call this method?


code:
from Tkinter import *

cb_strings = ['item 1', 'item 2', 'item 3', 'item 4']

def sel():
   print "You selected the option " + str(var.get())

root = Tk()
var = StringVar()
var.set(cb_strings[0])

for item in cb_strings:
    button = Radiobutton(root, text=item, variable=var, value=item, command=sel)
    button.pack(anchor=W)

root.mainloop()

rawDescription: Creating radio buttons from a list in python?


code:
from itertools import groupby, islice
from operator import itemgetter

ans = []
for x, g1 in groupby(lot, itemgetter(0)):
    for y, g2 in islice(groupby(g1, itemgetter(2)), 0, 3):
        ans.extend(list(g2))

print ans
# [('a', 'x1', 10), ('a', 'x2', 9), ('a', 'x3', 9), ('a', 'x4', 8), ('a', 'x5', 8),
#  ('b', 'x1', 10), ('b', 'x2', 9), ('b', 'x3', 8)]

rawDescription: n-largest elements in an sequence (need to retain duplicates)

description: N-largest elements in an sequence (need to retain duplicates)


code:
while len(numbers) > 0:
    current = numbers[0]
    print current
    primes.append(current)
    numbers.remove(current)

rawDescription: Python won't unbuffer print statements

description: Python won't unbuffer print statements


code:
def run(func):
    for line in sys.stdin:
        print func(line)

rawDescription: How to pass a function to another function in python

description: Pass a function to another function in python


code:
for tweet in tweets:
  print re.sub(r'http://\S+\s?','',tweet)

rawDescription: How to delete a url in each string from a dataset

description: Delete a url in each string from a dataset


code:
import sys
import argparse

class AbsAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if len(values) % 2 == 0:
            # If valid, store the values.
            setattr(namespace, self.dest, values)

            # You could convert the flat list to a list of 2-tuples, if needed:
            #   zip(values[::2], values[1::2])
        else:
            # Otherwise, invoke a parser error with a message.
            parser.error('abs must be supplied as pairs')

ap = argparse.ArgumentParser()
ap.add_argument('z')
ap.add_argument('abs', nargs = '+', action = AbsAction)
opt = ap.parse_args()
print opt

rawDescription: Parsing command line arguments with argparse


code:
chunks = [stringList[i: i+chunksize]
          for i in xrange(0, len(stringList), chunksize)]

for result in pool.imap(self.do_task, chunks):
    print result

rawDescription: Python multiprocessing pool not chunking properly


code:
xls = pd.ExcelFile('C:\Users\cb\Machine_Learning\cMap_Joins.xlsm')

df = xls.parse('Sheet1', skiprows=4, index_col=None, na_values=['NA'])

rawDescription: reading excel to a python data frame starting from row 5 and including headers

description: Reading excel to a python data frame starting from row 5 and including headers


code:
str = u"Ñandu"
str[0] == u"\xd1"
if str[0] == u"\xd1": print "Begins with \xd1!"

rawDescription: How to check is first character is ñ - Django

description: Check is first character is ñ - Django


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

a = A()
a.foo
A.foo
A.__dict__['foo']
A.bar = A.foo
A.bar
A.__dict__['bar']
a.bar
a.bar.__func__

rawDescription: User-defined methods and the __func__ attribute


code:
import pandas as pd
import numpy as np
import io

temp=u"""(info) text (yay!)
I love text
Text is fun
(more info) more text
lotsa text (boo!)"""

df = pd.read_csv(io.StringIO(temp), header=None, names=['original'])
print df
#                  original
#0       (info) text (yay!)
#1              I love text
#2              Text is fun
#3  (more info) more text
#4        lotsa text (boo!)

df['col1'] = df['original'].str.extract(r"\(([A-Za-z0-9 _]+)\)")
df['col2'] = df['original'].str.replace(r"\(([A-Za-z0-9 _]+)\)", "")
print df
#                original       col1               col2
#0     (info) text (yay!)       info        text (yay!)
#1            I love text        NaN        I love text
#2            Text is fun        NaN        Text is fun
#3  (more info) more text  more info          more text
#4      lotsa text (boo!)        NaN  lotsa text (boo!)

rawDescription: Extracting text from elements in Pandas column, writing to new column


code:
def is_triangle(a, b, c):
    if (a > b + c) or (b > a + c) or (c > a + b):
        print "No"
    else:
        print "Yes"

rawDescription: Python exercise

description: Python exercise


code:
import requests, json
from pprint import pprint as pp2

#----------------------------------------------------------------------
def login(username, password):
    """logs into reddit, saves cookie"""

    print 'begin log in'
    #username and password
    UP = {'user': username, 'passwd': password, 'api_type': 'json',}
    headers = {'user-agent': '/u/STACKOVERFLOW\'s API python bot', }

    #POST with user/pwd
    client = requests.session()
    r = client.post('http://www.reddit.com/api/login', data=UP)

    #if you want to see what you've got so far
    #print r.text
    #print r.cookies

    #gets and saves the modhash
    j = json.loads(r.text)
    client.modhash = j['json']['data']['modhash']
    print '{USER}\'s modhash is: {mh}'.format(USER=username, mh=client.modhash)

    #pp2(j)

    return client

client = login(USER, PASSWORD)

#mod mail url
url = r'http://www.reddit.com/r/mod/about/message/inbox/'
r = client.get(url)

#here's the HTML of the page
pp2(r.text)

rawDescription: How to mirror a reddit moderator page with python

description: Mirror a reddit moderator page with python


code:
import threading

lock = threading.Lock()
sent = {}
req_seq = 0

def proxy_mangle_request(req):
    global req_seq
    lock.acquire()
    req_seq += 1
    thread_id = threading.current_thread().ident
#    print "thread id = {}".format(thread_id)
    req.seq = req_seq
    sent[thread_id] = req
    lock.release()

    return req

def proxy_mangle_response(res):
    thread_id = threading.current_thread().ident
#    print "Got response for thread_id {}".format(thread_id)
    print "Request: {}".format(sent[thread_id].seq)
    lock.acquire()
    del sent[thread_id]
    lock.release()

    print "Response: {}".format(res)
    return res

rawDescription: Figuring out which response belongs to which request using proxpy


code:
import re
from collections import defaultdict

WORD_COUNTS = defaultdict(int)
WORDS = ["car", "cat", "cow", "hi", "hello"]
MAX_WORD_LEN = len(max(WORDS, key=len))
REGEX = ("|".join(WORDS))
RE_OBJ = re.compile(REGEX)

def count_words(stream):
    last_stream_remainder = ""

    while True:
        data = stream.get_chunk()

        # Breaking point
        if data is None:
            break

        if not data:
            continue

        data = last_stream_remainder + data
        for match in RE_OBJ.finditer(data):
            WORD_COUNTS[match.group(0)] += 1

        # to cover the corner case like remainder from last
        # chunk can attach with new one and make a word
        if match:
            if match.end() >= len(data):
                continue
            else:
                last_match = min((len(data) - match.end()), MAX_WORD_LEN)
                last_stream_remainder = data[-last_match:]
        else:
            last_stream_remainder = data[-MAX_WORD_LEN:]

class StreamReader(object):
    STREAM_DATA = ["car1cat1lftrysomecow1shi1iamgoinghello1pleasegoocar2sarehere",
                   "car3car4car5cat2cat3h", "i2thisishello2hello3he", "", "llo4", None]

    def get_chunk(self):
        return self.STREAM_DATA.pop(0)

stream = StreamReader()
count_words(stream)

print WORD_COUNTS.items()
# [('car', 5), ('hi', 3), ('hello', 4), ('cow', 1), ('cat', 3)]

rawDescription: Count number of occurrences of a given list of strings in a data stream


code:
from ctypes import *

def WrapClass(c):
    class C(c): pass
    C.__name__ = "wrapped_" + c.__name__
    return C

class S(Structure):
    _fields_ = [("x", POINTER(c_int)), ("y", WrapClass(c_int))]

o = S()
print o.x
print o.y
print o.y.value

rawDescription: Python: ctypes structure: how to access attributes as if they were ctypes and not via the given wrapper?


rawDescription: Python pointers or queue share

description: Python pointers or queue share


code:
import gtk
import vte

term = vte.Terminal()

term.feed("a\r\nb")

def get_text(term):
    print repr(term.get_text(lambda *a: True).rstrip())
    gtk.main_quit()

term.connect('contents-changed', get_text)
gtk.main()

rawDescription: python VTE Terminal weirdness

description: Python VTE Terminal weirdness


code:
from django.utils.safestring import SafeUnicode
su = SafeUnicode("This is my original Safe string")
just_the_strong = SafeUnicode(su[20:])
print just_the_strong
type(just_the_strong)

rawDescription: django: how to get a substring from django.utils.safestring.SafeUnicode

description: Django: how to get a substring from django.utils.safestring.SafeUnicode


code:
import numpy as np
import numpy.lib.recfunctions as rfn

dtype = [('index', int), ('text', object)]
table = np.loadtxt(path_to_file, dtype=dtype, usecols=(0,2), delimiter='\t')

dtype = [('index', int), ('score', float)]
array = np.array(vec, dtype=dtype)

joined = rfn.join_by('index', table, array)

for row in joined:
      print row['index'], row['score'], row['text']

rawDescription: Grab matching column from text file in python list


code:
fruit = [
  ["apple", "round", "large", "red"],
  ["banana", "long", "large", "yellow"],
  [ "apple", "round", "large", "bad_apple"]
]
for ind, ele in enumerate(fruit[:-1]):
    if "apple" in ele and any("bad_apple" in x for x in fruit[ind+1]):
        print "foo"

rawDescription: python: how can I access subsequent lists in a nested list

description: Python: how can I access subsequent lists in a nested list


code:
from selenium import webdriver
url = 'https://www.virustotal.com/en/file/7cf757e0943b0a6598795156c156cb90feb7d87d4a22c01044499c4e1619ac57/analysis/'
mydriver = webdriver.PhantomJS()
mydriver.get(url)
page = mydriver.page_source
print page.encode('utf-8')

rawDescription: how can I get html using python?

description: Get html using python


code:
import Tkinter as tk
import random
import string

class App():

    def __init__(self):

        self.root = tk.Tk()
        self.dict={}
        button1 = tk.Button(self.root, text='print dict', command=self.print_dict)
        button1.pack()
        button2 = tk.Button(self.root, text='insert label', command=self.insert_label)
        button2.pack()
        self.var = tk.StringVar()
        entry = tk.Entry(self.root, textvariable=self.var)
        entry.pack()
        button3 = tk.Button(self.root, text='delete label', command=self.delete_label)
        button3.pack()
        self.root.mainloop()

    def insert_label(self):
        letter = random.choice(string.letters)
        # you could put something like
        # if not letter in self.dict.keys():
        # here to prevent making two of the same labels
        self.dict[letter] = tk.Label(self.root, text=letter)
        self.dict[letter].pack()

    def print_dict(self):
        print self.dict

    def delete_label(self):
        letter = self.var.get()
        try:
            self.dict[letter].pack_forget()
            del self.dict[letter]
            self.var.set('')
        except:
            self.var.set('Label unknown')

App()

rawDescription: Remove labels created from same variable


code:
# Tuples
data = [("cat", [1, 2, 3, 4]), ("dog", [5, 6, 7])]
for name, file_data in data:
    print name, "=>", file_data

# Dictionary (assumes only one instance of name per data point)
data = {"cat": [1, 2, 3, 4], "dog": [5, 6, 7]}
for name, file_data in data.items():
    print name, "=>", file_data

# Class instances (ignore this one if you haven't done any OO before)
# (You don't need it if you don't *know* you need it).
class MyDataType(object):
    def __init__(self, name, data):
        self.name = name
        self.data = data

data = [MyDataType("cat", [1, 2, 3, 4]), MyDataType("dog", [5, 6, 7])]
for data_point in data:
    print data_point.name, "=>", data_point.data

rawDescription: Writing multiple .csv files

description: Writing multiple .csv files


code:
import numpy, inspect
def sig(func):
    argspec = inspect.getargspec(func)
    return func.__name__ + inspect.formatargspec(*argspec)

print sig(numpy.polydiv)

rawDescription: get function declaration (present in pydoc output) with __doc__ attribute

description: Get function declaration (present in pydoc output) with __doc__ attribute


code:
import Xlib.display
display = Xlib.display.Display()
window = display.get_input_focus().focus
wmname = window.get_wm_name()
wmclass = window.get_wm_class()
if wmclass is None and wmname is None:
    window = window.query_tree().parent
    wmname = window.get_wm_name()
print "WM Name: %s" % ( wmname, )

rawDescription: How do I detect the currently focused application?

description: Detect the currently focused application


code:
import os

before = os.listdir('/home/jason/Downloads')

# Download the file using Selenium here

after = os.listdir('/home/jason/Downloads')
change = set(after) - set(before)
if len(change) == 1:
    file_name = change.pop() #file name stored as string
else:
    print "More than one file or no file downloaded"

rawDescription: Downloading csv file using selenium python and deleting it


code:
for _ in range(0, 3):
    print "hi"

rawDescription: Python ForLoop syntax

description: Python ForLoop syntax


code:
for level_max, level in [(33, 'green'), (66, 'amber'), (100, 'red')]:
    if cpu <= level_max:
        print level
        break

rawDescription: Checking a value falls between three ranges in Python


code:
import numpy as np

image_ids = ['A','B','C','D'] #Identifiers for each image.
distances = np.array([0.01,0.2,0.3,0.001]) #Computed distances for each image in the image_ids array

ordered_indexes = np.argsort(distances)
for i,least_distance_id in enumerate(ordered_indexes):
    print "Position:"+ str(i)+ " ID:"+image_ids[least_distance_id] + " Distance:"+str(distances[least_distance_id]) #Print the ids and distances

rawDescription: image retrieval from its values(euclidean distance) in python opencv

description: Image retrieval from its values(euclidean distance) in python opencv


code:
print "Title: %s " % (title.text)
print "Summary: %s " % (desc.text)

rawDescription: Python and BeautifulSoup URL parse

description: Python and BeautifulSoup URL parse


code:
import os
print os.environ['CCDeviceID']

rawDescription: Using environment variables in Python

description: Using environment variables in Python


code:
user = wx.TextEntryDialog(None, "Login", "Username", "")
if user.ShowModal() == wx.ID_OK:
    print 'here'
    password = wx.TextEntryDialog(None, "Password", "Password", "")
    if password.ShowModal() == wx.ID_OK:
        print 'there'

rawDescription: wxpython - Multiple TextEntryDialog windows

description: Wxpython - Multiple TextEntryDialog windows


code:
loop = asyncio.get_event_loop()

asyncio.async(loop.run_in_executor(None, lambda: MyClass()))
asyncio.async(loop.run_in_executor(None, lambda: MyClass()))

rawDescription: How do I run parallel jobs in python3 with asyncio?

description: Run parallel jobs in python3 with asyncio


code:
for dirpath, dirnames, files in os.walk('.'):
    if files:
        print dirpath, 'has files'
    if not files:
        print dirpath, 'is empty'

rawDescription: How to check to see if a folder contains files using python 3

description: Check to see if a folder contains files using python 3


code:
t = Twython(app_key=settings.TWITTER_CONSUMER_KEY,
            app_secret=settings.TWITTER_CONSUMER_SECRET,
            oauth_token=oauth_token,
            oauth_token_secret=oauth_token_secret)

print t.show_user(screen_name=account_name)

rawDescription: Twitter API/Twython - show user to get user profile image


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.uix.button import Button
from kivy.clock import Clock
from kivy.properties import StringProperty

dirlist = ['aaa', 'bbb', 'ccc', 'ddd']

class MyButton(Button):
    prop = StringProperty('')
    def on_press(self):
        print "Class-defined on_press handler (I'm {})".format(self.text)

def other_on_press_handler(sender):
    print "other_on_press_handler, from {}".format(sender.text)

def some_func(text):
    print "yeah: " + text

class LoadMenu(Screen):
    def __init__(self, **kwargs):
        super(LoadMenu, self).__init__(**kwargs)
        Clock.schedule_once(self.update)

    def on_press_handler(self, sender):
        print "on_press_handler, from {}".format(sender.text)
        self.parent.current = 'sc2'

    def yet_another_on_press_handler(self, sender):
        print "yet_another_on_press_handler, from {}".format(sender.text)
        self.parent.current = 'sc2'

    def update(self, dt):
        for x in range(len(dirlist)):
            my_b = Button(text = dirlist[x], on_press=self.on_press_handler)
            self.parent.ids.button_container.add_widget(my_b)
            if x > 1:
                my_b.bind(on_press=other_on_press_handler)
            if x == 3:
                my_b.bind(on_press=lambda sender: some_func("Whoa, lambda was here ({})".format(sender.text)))
        for x in range(len(dirlist)):
            my_b = MyButton(text = 'my '+ dirlist[x], prop="{} {}".format(dirlist[x], x))
            self.parent.ids.button_container.add_widget(my_b)
            my_b.bind(on_press=self.yet_another_on_press_handler)

root = Builder.load_string("""
ScreenManager:
    LoadMenu:
        name: 'sc1'
        GridLayout:
            cols: 4
            id: button_container
    Screen:
        name: 'sc2'
        BoxLayout:
            Button:
                text: "Go back"
                on_press: root.current = 'sc1'
""")

class MyApp(App):
    def build(self):
        return root

if __name__ == '__main__':
    a = MyApp()
    a.run()

rawDescription: Change screens with python logic (Kivy Screen manager)


code: print "{}\t{}\t{}".format(n, int(bu.total_seconds() * 1000),int(qui.total_seconds() * 1000))

rawDescription: how can i use tabs between variables in python to create a single row with 3 columns?

description: Use tabs between variables in python to create a single row with 3 columns


code:
Guess1_Easy_Substitute= raw_input("Which Word Do You Think Was The Substitute Word?:")
while Guess1_Easy_Substitute != wordList[5]:
    Guess1_Easy_Substitute= raw_input("Try again! Which Word Do You Think Was The Substitute Word?:")
    if Guess1_Easy_Substitute == wordList[5]:
        print "You win"

rawDescription: Python 2.7.7 Breaking?

description: Python 2.7.7 Breaking


code:
from sys import exit

more='y'
name = raw_input("What is your first name? ")
lastName = raw_input("What is your last name? ")
fullName = '%s %s' % (name, lastName)
nameList = list(fullName)

print 'Your full name is %s. Would you like to edit your name? If yes, type "y" and if no type "n".\n' % fullName
ans = raw_input()
if ans == 'n':
    print('Have a nice day.')
    exit(0)

while more != 'n':

    ans=raw_input('Would you like to A) change a letter B) remove a \
letter or C) add a letter?\
\n\n(Note: For all changes write the position of the letter to be affected \
starting at 1 and going from left to right.)\n')
    if ans in ('A','a'):
        change=input('Which letter would you like to change? ')
        change -= 1
        ans=raw_input('What would you like to change it to? ')
        nameList[change]=ans
        fullName = ''.join(nameList)
    elif ans in ('B','b'):
        remove=input('Which letter would you like to remove? ')
        remove -= 1
        del nameList[remove]
        fullName = ''.join(nameList)
    elif ans in ('C','c'):
        add=input('After which letter would you like to add one? ')
        ans=raw_input('What letter would you like to add? ')
        nameList.insert(add,ans)
        fullName = ''.join(nameList)

    more=raw_input("Your name is now " + fullName + ".\n" + "Would you \
like to do anything else? Type 'y' if yes or 'n' if no. ")

rawDescription: How to get out of my loop in Python (and shorten my code)?

description: Get out of my loop in Python (and shorten my code)


code:
prompt = "> "
decision = "What do you do?"
not_assigned = "Say wa?"

class Game:

    def __init__(self):
        self.bodySearched = False
        self.engine_room()

    def engine_room(self):
        print "You are in a dark room with the sound of moaning engines."
        print "You see a corridor to your left and one to your right and an elevator straight ahead of you."
        print decision
        self.choice = raw_input(prompt)

        if self.choice == "go left":
            self.viewing_room()

        elif self.choice == "go right":
            self.right_corridor_dead_end()

        elif self.choice == "use elevator":
            print "you get in the elevator and go up."
            self.main_hallway()

        else:
            print not_assigned
            self.engine_room()

    def right_corridor_dead_end(self):
        print "You walk down the corridor only to be blocked by a collapsed ceiling."
        print decision
        self.choice = raw_input(prompt)

        if choice == "go back":
            self.engine_room()

        else:
            print not_assigned

    def viewing_room(self):
        print "You walk down the corridor and enter and a large room with a window covering the size of the wall."
        print "Straight ahead is another door"
        print decision
        self.choice = raw_input(prompt)

        if not self.bodySearched:
            if self.choice == "open door":
                print "The door is locked"
                self.viewing_room()

            elif self.choice == "go back":
                self.engine_room()

            else:
                print not_assigned

        if self.bodySearched:
            if self.choice == "open door":
                print "The door opens you walk through"
                self.storage_room()

            else:
                print not_assigned
                self.viewing_room()

    def main_hallway(self):
            print "You enter a large brightly lit room with 3 rooms connected to it and another elevator straight ahead."
            print "The rooms are named, the two on the left are the armoury and lab rooms and to the right are the cabins."
            print decision
            self.choice = raw_input(prompt)

            if choice == "go to lab room":
                self.lab_room()

            elif choice == "go back":
                self.engine_room()

    def lab_room(self):
        print "You enter the lab room which is cluttered with unexplainable machines."
        print "To the back of the room you see the dead body of a man with no obvious cause"
        print "He might have something useful on him"
        print decision
        self.choice = raw_input(prompt)

        if self.choice == "search body":
            self.bodySearched = True
            print "You find a keycard that says 'storage' on it."
            self.lab_room()

        elif self.choice == "go back":
            self.main_hallway()

newGame = Game()

rawDescription: Python: How can I return a function as True and apply it to an earlier function to change the true/false statement


code:
import re
fin = open("./file.txt")

for line in fin:
    if re.match("Line 1:", line):
      # note we need to match "Line 1:" (including colon) so we don't match "Line 10"
      m = re.match(".*Type(.)", line)
      type = m.group(1)
      # we now know what type this group is
    if re.match("Line 3:", line):
      m = re.match(".*3:(.*)$", line)
      outputString = m.group(1)
      # have first half of output string
    if re.match("Line 8:", line):
      m = re.match(".*8:(.*)$", line)
      outputString += m.group(1)
      # have second half of output string, and we know where it needs to go:
      print "concatenated string of type ", type," is ", outputString
      # now send it where you want it to go... one of two open files, perhaps?

fin.close()

rawDescription: Read file in blocks

description: Read file in blocks


code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *

import time
import matplotlib as mpl
import matplotlib.pyplot as plt

import numpy as np
import scipy.optimize as opt

class Imline(QObject):
    '''
    Plot interactive line
    '''

    def __init__(self, plt, image = None, scale = 1, *args, **kwargs):
        '''
        Initialize imline
        '''
        super(Imline, self).__init__(None)

        # set plot
        self.__plt = plt
        self.scale = scale

        # initialize start and end points
        self.startX = None
        self.startY = None
        self.endX = None
        self.endY = None

        # initialize line2d
        self.__line2d = None
        self.mask = None

        # store information to generate mask
        if(image is not None):
            height, width = image.shape

        else:
            height = None
            width = None

        self.__width = width
        self.__height = height

        # set signals and slots
        self.__c1 = self.__plt.figure.canvas.mpl_connect('button_press_event', self.__mousePressEvent)
        self.__c2 = self.__plt.figure.canvas.mpl_connect('motion_notify_event', self.__mouseMoveEvent)
        self.__c3 = self.__plt.figure.canvas.mpl_connect('button_release_event', self.__mouseReleaseEvent)

        self.imlineEventFinished = SIGNAL('imlineEventFinished')

    def __mousePressEvent(self, event):
        '''
        Starting point
        '''

        # get xy data
        xdata = event.xdata
        ydata = event.ydata

        # check if mouse is outside the figure
        if((xdata is None) | (ydata is None) | (self.startX is not None) | (self.startY is not None) | (self.endX is not None) | (self.endY is not None)):
            return

        # start point
        self.startX = xdata
        self.startY = ydata

    def __mouseMoveEvent(self, event):
        '''
        Draw interactive line
        '''

        # get xy data
        xdata = event.xdata
        ydata = event.ydata

        # check if mouse is outside the figure
        if((xdata is None) | (ydata is None) | (self.startX is None) | (self.startY is None) | (self.endX is not None) | (self.endY is not None)):
            return

        # remove line
        if(self.__line2d is not None):
            self.__line2d[0].remove()

        # set x, t
        x = [self.startX, xdata]
        y = [self.startY, ydata]

        # plot line
        self.__plt.axes.hold(True)
        xlim = self.__plt.axes.get_xlim()
        ylim = self.__plt.axes.get_ylim()
        self.__line2d = self.__plt.axes.plot(x, y, color = [1, 0, 0])
        self.__plt.axes.set_xlim(xlim)
        self.__plt.axes.set_ylim(ylim)

        # update plot
        self.__plt.draw()
        self.__plt.show()

    def __mouseReleaseEvent(self, event):
        '''
        End point
        '''

        # get xy data
        xdata = event.xdata
        ydata = event.ydata

        # check if mouse is outside the figure
        if((xdata is None) | (ydata is None) | (self.endX is not None) | (self.endY is not None)):
            return

        # remove line
        if(self.__line2d is not None):
            self.__line2d[0].remove()

        self.endX = xdata
        self.endY = ydata

        P = np.polyfit([self.startX, self.endX], [self.startY, self.endY],1 )
        self.__m = P[0]
        self.__q = P[1]

        # update plot
        self.__plt.draw()
        self.__plt.show()

        # disconnect the vents
        self.__plt.figure.canvas.mpl_disconnect(self.__c1)
        self.__plt.figure.canvas.mpl_disconnect(self.__c2)
        self.__plt.figure.canvas.mpl_disconnect(self.__c3)

        # emit SIGNAL
        self.emit(SIGNAL('imlineEventFinished'))

    def createMask(self):
        '''
        Create mask from painted line
        '''

        # check height width
        if((self.__height is None) | (self.__width is None)):
            return None

        # initialize mask
        mask = np.zeros((self.__height, self.__width))

        # get m q
        m = self.__m
        q = self.__q

        print m, q

        # get points
        startX = np.int(self.startX)
        startY = np.int(self.startY)
        endX = np.int(self.endX)
        endY = np.int(self.endY)

        # ensure startX < endX
        tempStartX = startX
        if(startX > endX):
            startX = endX
            endX = tempStartX

        # ensure startY < endY
        tempStartY = startY
        if(startY > endY):
            startY = endY
            endY = tempStartY

        # save points
        self.startX = startX
        self.endX = endX
        self.startY = startY
        self.endY = endY

        # intialize data
        xData = np.arange(startX, endX)
        yData = np.arange(startY, endY)

        # scan on x
        for x in xData:
            row = round(m*x + q)
            if(row < startY):
                row = startY
            if(row > endY):
                row = endY
            mask[row, x] = 1

        # scan on y
        for y in yData:
            col = round((y - q) / m)
            if(col < startX):
                col = startX
            if(col > endX):
                col = endX
            mask[y, col] = 1

        # get boolean mask
        mask = mask == 1

        # return boolean mask
        return mask

rawDescription: Python interactive selection tools like in MATLAB


code:
import datetime
import bisect
import collections

data=[ (datetime.datetime(2010, 2, 26, 12, 8, 17), 5594813L),
  (datetime.datetime(2010, 2, 26, 12, 7, 31), 5594810L),
  (datetime.datetime(2010, 2, 26, 12, 6, 4) , 5594807L),
]
interval=datetime.timedelta(minutes=1,seconds=30)
start=datetime.datetime(2010, 2, 26, 12, 6, 4)
grid=[start+n*interval for n in range(10)]
bins=collections.defaultdict(list)
for date,num in data:
    idx=bisect.bisect(grid,date)
    bins[idx].append(num)
for idx,nums in bins.iteritems():
    print('{0} --- {1}'.format(grid[idx],len(nums)))

rawDescription: Python: group results by time intervals

description: Python: group results by time intervals


code:
from collections import defaultdict

d = defaultdict(list)

d['something'].append(3)
print d['something']
# > [3]

rawDescription: More concise way to append a value to a dict array-element?


code:
import win32com.client
wmi = win32com.client.GetObject("winmgmts:")
for port in wmi.InstancesOf("Win32_SerialPort"):
    print port.DeviceID, port.Name

rawDescription: Detect device names on serial ports in Python


code:
# this follows your pseudocode most closely, but it is *not*
# the most efficient since it creates the interpolation
# functions on each call to bilinterp
from scipy import interpolate
import numpy
data = numpy.arange(0., 16.).reshape((4,4))  #2D array
prices = numpy.arange(10000., 50000., 10000.)
cars = numpy.arange(1., 5.)
def bilinterp(price,car):
    return interpolate.interp1d(cars, interpolate.interp1d(prices, a)(price))(car)
print bilinterp(22000,2)

rawDescription: Data storage to ease data interpolation in Python


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://udemycoupon.discountsglobal.com/coupon-category/free-2/")

#select by css
#try *
css_lnks = [i.get_attribute('href') for i in driver.find_elements_by_css_selector('[id*=coupon-link]')]
#or try ^
#css_lnks = [i.get_attribute('href') for i in driver.find_elements_by_css_selector('[id^=coupon-link]')]

#select by xpath
xpth_lnks = [i.get_attribute('href') for i in driver.find_elements_by_xpath("//a[contains(@id,'coupon-link-')]")]

print xpth_lnks
print css_lnks

rawDescription: Selenium find_elements_by_css_selector returns an empty list


code:
try:
    x = data['first']['second']['third']
    assert x
except KeyError, AssertionError:
    pass

rawDescription: Checking if nested attribute exists

description: Checking if nested attribute exists


code:
x = numpy.arange(10)
y = numpy.zeros(x.shape)

y[1:] = x[1:] - x[:-1]

print y

rawDescription: first order differences along a given axis in NumPy array

description: First order differences along a given axis in NumPy array


code:
RC_Fixed = '12345'
link = "http://database.com/RC/" + RC_Fixed
print "" + RC_fixed + ""

rawDescription: how to append data to a variable and make it clickable hyperlink

description: Append data to a variable and make it clickable hyperlink


code:
import json
d = {}
d.setdefault( 'key1',{})
d.setdefault( 'key2',{}).setdefault('inner key',{})['inner inner key'] = 'value'

print json.dumps(d, sort_keys=True, indent=4)

rawDescription: How to set two keys for dictionary using setdefault

description: Set two keys for dictionary using setdefault


code:
for i in range(2, 11):
    print 1.0*(1 % i) / i

rawDescription: Python quotient vs remainder

description: Python quotient vs remainder


code:
from scrapy.spider import BaseSpider
from scrapy.http import Request
import re
from urlparse import urljoin
from scrapy.selector import HtmlXPathSelector
from threatexpert.items import ThreatExpert
import inspect
class usmallspider(BaseSpider):
    name = 'threatexpert'
    start_urls = ["http://www.threatexpert.com/reports.aspx?tf=2&sl=1"]

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    urls = response.xpath('//a[contains(@href, "page")]/@href').extract()
    for url in urls:
        url = urljoin(response.url, url)
        print url
        if url:
            yield Request(url, callback=self.parse_links)

def parse_links(self, response):
    hxs = HtmlXPathSelector(response)
    urls = response.xpath('//a[contains(@href, "md5")]/@href').extract()
    for url in urls:
        url = urljoin(response.url, url)
        if url:
            yield Request(url, callback = self.parse_items)

def parse_items(self, response):
    itm=[]
    item = MallUk1Item()
    hxs = HtmlXPathSelector(response)
    item['md5'] = response.xpath('//html/body/ul[1]/ul/ul/li[1]/text()').re(r"File MD5: ([\w, ]+)")
    itm.append(item)
    return itm

rawDescription: scrapy parsing first page

description: Scrapy parsing first page


code:
from datetime import datetime, timedelta

def parse_time(s):
    ''' Parse 12-hours format '''
    return datetime.strptime(s, '%I:%M %p')

starttime = parse_time('8:00 AM')
endtime   = parse_time('3:00 AM')
if endtime < starttime:
   # add 1 day to the end so that it's after start
   endtime += timedelta(days=1)

checked_time = parse_time('7:00 AM')

# Can compare:
print starttime <= checked_time < endtime

rawDescription: Create Range of Hours in Python

description: Create Range of Hours in Python


code:
HTML = """"

this is the

    text that i want to

    .

    .

    get from html file

    .

    .

someone

"""
soup = BeautifulSoup(HTML)
print soup.p.get_text()

rawDescription: how to get text of <p> without <br/> using lxml in python?

description: Get text of <p> without <br/> using lxml in python


code:
from itertools import cycle, izip

list1 = ['string1','string2','string3','string4','string5','string6','string7','string8']
list2 = ['a', 'b', 'c']

for fst, snd in izip(list1, cycle(list2)):
    print fst + snd # or whatever

#string1a
#string2b
#string3c
#string4a
#string5b
#string6c
#string7a
#string8b

rawDescription: Python, toggle variables in a script

description: Python, toggle variables in a script


code:
v1 = V1Meta()

past_date = '2012-11-01'

query = (v1.Story
           .where(Number="S-01211")
           .asof('2012-11-01')
           .select('Number', 'Name', 'Owners.Name', 'Scope.Name')
        )

for story in query:
    print story.data['Scope.Name']   # prints current value

rawDescription: Asset history in VersionOne

description: Asset history in VersionOne


code:
import lxml.etree as et

xml="""
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsa="http://schemas.google.com/gsa/2007">
  <gsa:content name="reportName">bbb</gsa:content>
  <gsa:content name="collectionName">default_collection</gsa:content>
  <gsa:content name="reportDate">date_3_25_2009</gsa:content>
 </entry>
"""

NS = {'rootns': 'http://www.w3.org/2005/Atom',
      'gsa': 'http://schemas.google.com/gsa/2007'}

tree = et.fromstring(xml)

for el in tree.xpath('//gsa:content', namespaces=NS):
    print el.attrib['name']

print len(tree.xpath('//rootns:entry', namespaces=NS))

rawDescription: how do I escape a forward slash in xpath?

description: Escape a forward slash in xpath


code:
old_stdout = sys.stdout

log_file = open("message.log","w")

sys.stdout = log_file

print "this will be written to message.log"

sys.stdout = old_stdout

log_file.close()

rawDescription: redirect prints to log file

description: Redirect prints to log file


code:
class C(object):
  def __init__(self, x):
    self._x = x

  def get_x(self):
    return self._x
  def set_x(self, x):
    self._x = x
  x = property(get_x, set_x)

obj = C(5)
obj.x = 6    # set
print obj.x  # get

rawDescription: Python: Call function if setter is called?


code:
lst = ['apple','cherry','coffee','apple','coffee','coffee']

res = {}
for obj in lst:
    if obj not in res:
        res[obj] = 0
    res[obj] += 1

print res

rawDescription: python algorithm, find duplicates in list

description: Python algorithm, find duplicates in list


code:
def main():
    t = threading.Thread(target=func)
    t.daemon = True
    t.start()
    try:
        while True:
            t.join(1)
    except KeyboardInterrupt:
        print "^C is caught, exiting"

rawDescription: How to stop a thread python

description: Stop a thread python


code:
a = ephem.separation((panel_az, panel_alt), (sun_az, sun_alt))
print a

rawDescription: Angle between two pairs of azimuth and altitude?


code:
# dbconfig.py
host = '127.0.0.1'
user = 'stack'
password = 'overflow'

# db.py

import dbconfig
print dbconfig.host
print dbconfig.user
print dbconfig.password

rawDescription: Include a .py-file, still not ruining cronjob (Python, beginner)?


code:
for div in range(2,candidate//2,1):
    if candidate % div == 0:
        prime = False
        print candidate, "is not prime - divisible by", div
        return next_prime(candidate)

rawDescription: Python function returning None after recursion


code:
count = 0
total = 0
ask = raw_input("Do you want to enter a number? (Y/N)")
try:
    while ask == "Y":
        numbers = float(raw_input("Enter number"))
        count = count + 1
        total = total + numbers
        con_ask = raw_input("Do you want to continue entering a number? (Y/N)")
        if con_ask == "Y":
            continue
        elif con_ask == "N":
            print "The average of", count, "numbers is", total / count
            break
except:
    print "Zero Division Occured. Average cannot be calculated"

rawDescription: Use Python to find average of some numbers


code:
class FactoryMetaclassObject(type):
    def __init__(cls, name, bases, attrs):
        """__init__ will happen when the metaclass is constructed:
        the class object itself (not the instance of the class)"""
        pass

    def __call__(*args, **kw):
        """
        __call__ will happen when an instance of the class (NOT metaclass)
        is instantiated. For example, We can add instance methods here and they will
        be added to the instance of our class and NOT as a class method
        (aka: a method applied to our instance of object).

        Or, if this metaclass is used as a factory, we can return a whole different
        classes' instance

        """
        return "hello world!"

class FactorWorker(object):
  __metaclass__ = FactoryMetaclassObject

f = FactorWorker()
print f.__class__

rawDescription: Implementing the factory design pattern using metaclasses in python


code:
mystr = 'AC'
mylist = list(mystr)
flag = len(mystr) * [False]

d = {'A':'C', 'C':'B'}
for key in d.keys():
    for ind, char in enumerate(mylist):
        if flag[ind] == False and key == char:
            mylist[ind] = d[key]
            flag[ind] = True
    #do some calculation

mystr = "".join(mylist)

print mystr

rawDescription: python replace character without replacing already replaced characters

description: Python replace character without replacing already replaced characters


code:
#!/usr/bin/env python

import optparse

def main():
    server = "[fec1::1]:80"

    if server.find("[", 0, 2) == -1:
       print "IPv4"
       if server.find(":", 0, len(server)) == -1:
          ip = server
          port = ""
       else:
          ip, port = server.split(':')
    else:
       print "IPv6"
       index = server.find("]", 0, len(server))
       if index == -1:
          print "Something wrong"
          new_ip = ""
          port = ""
       else:
          if server.find(":", index, len(server)) == -1:
             new_ip = server
             port = ""
          else:
             new_ip, port = server.rsplit(':', 1)
       print new_ip
       ip = new_ip.strip('[]')

    print ip
    print port

if __name__ == '__main__':
    main()

rawDescription: Handling IP and port in python and bash

description: Handling IP and port in python and bash


code:
valid_values = [(int, i) for i in [-1, 0, 1, 2, 3]]
invalid_values = [True, False, "foo"]
for value in [v[1] for v in valid_values] + invalid_values:
  if (type(value), value) in valid_values:
    print value, "is valid"
  else:
    print value, "is invalid"

rawDescription: Python "in" does not check for type?

description: Python "in" does not check for type


code:
def _partition(mylist, start, end):
    count = 0
    pos = start
    for i in xrange(start, end):
        count += 1
        if mylist[i] < mylist[end]:
            mylist[i], mylist[pos] = mylist[pos], mylist[i]
            pos += 1
    mylist[pos], mylist[end] = mylist[end], mylist[pos]
    return pos, count

def _quicksort(mylist, start, end):
    count = 0
    if start < end:
        pos, count = _partition(mylist, start, end)
        count += _quicksort(mylist, start, pos - 1)
        count += _quicksort(mylist, pos + 1, end)
    return count

def quicksort(mylist, start=None, end=None):
    if start is None:
        start = 0
    if end is None:
        end = len(mylist) - 1
    return _quicksort(mylist, start, end)

x = [2,3,1]
count = quicksort(x)
print x, count

rawDescription: Quick Sort Comparison Counter in Python

description: Quick Sort Comparison Counter in Python


code:
import itertools, string

t = string.Template("$size widget that $verb $noun")
for size, verb, noun in itertools.product(sizes, verbes, nounes):
    print t.safe_substitute(size=size, verb=verb, noun=noun)

rawDescription: How do I parse a templated string in Python?

description: Parse a templated string in Python


code:
import time
from multiprocessing import Process, Manager

def test_f(test_d):
   """  frist process to run
        exit this process when dictionary's 'QUIT' == True
   """
   while not test_d["QUIT"]:
      print "     test_f", test_d["QUIT"]
      time.sleep(1.0)

def test_f2(name):
    """ second process to run.  Runs until the for loop exits
   """
    for j in range(0, 10):
       print name, j
       time.sleep(0.5)

    print "second process finished"

if __name__ == '__main__':
   ##--- create a dictionary via Manager
   manager = Manager()
   test_d = manager.dict()
   test_d["QUIT"] = False

   ##---  start first process and send dictionary
   p = Process(target=test_f, args=(test_d,))
   p.start()

   ##--- start second process
   p2 = Process(target=test_f2, args=('P2',))
   p2.start()

   ##--- sleep 2 seconds and then change dictionary
   ##     to exit first process
   time.sleep(2.0)
   print "\nterminate first process"
   test_d["QUIT"] = True
   print "test_d changed"
   print "data from first process", test_d

   ##---  may not be necessary, but I always terminate to be sure
   time.sleep(5.0)
   p.terminate()
   p2.terminate()

   """ Thanks Doug Hellmann
       Note: It is important to join() the process after terminating it.
       in order to give the background machinery time to update the.
       status of the object to reflect the termination
   """
   p.join()
   p2.join()

rawDescription: Run long process continously using Tkinter (Python 2.7)


code:
for pm in root.Document.Placemark:
    point = [p for p in pm.getchildren() if p.tag.endswith('Point')]
    if point:
        coords = point[0].coordinates.text
    else:
        poly = [p for p in pm.getchildren() if p.tag.endswith('Polygon')]
        if poly:
            coords = poly[0].outerBoundaryIs.LinearRing.coordinates.text
    print pm.name, coords

rawDescription: KML parsing child elements using django

description: KML parsing child elements using django


code:
widget = Widget.get(pk=something)

serializer = WidgetSerializer(widget, data=data, partial=True) #you need partial if you want to update only some fields
if serializer.is_valid():
    serializer.save()
else:
    print serializer.errors

rawDescription: Django REST Framework nested serializer won't update


code:
import pygame
import random
import sys

class Ball:
    def __init__(self,X,Y):
    	self.velocity = [1,1]
    	self.ball_image = pygame.image.load ('Beachball.jpg'). convert()
    	self.ball_boundary = self.ball_image.get_rect (center=(X,Y))
    	self.sound = pygame.mixer.Sound ('Thump.wav')

if __name__ =='__main__':
    width = 800
    height = 600
    background_colour = 0,0,0
    pygame.init()
    frame = pygame.display.set_mode((width, height))
    pygame.display.set_caption("Bouncing Ball animation")
    num_balls = 1000
    ball_list = []
    for i in range(num_balls):
    	ball_list.append( Ball(random.randint(0, width),random.randint(0, height)) )
    while True:
    	for event in pygame.event.get():
    		print event
    		if event.type == pygame.QUIT:
    			sys.exit(0)
    	frame.fill (background_colour)
    	for ball in ball_list:
    		if ball.ball_boundary.left < 0 or ball.ball_boundary.right > width:
    			ball.sound.play()
    			ball.velocity[0] = -1 * ball.velocity[0]
    		if ball.ball_boundary.top < 0 or ball.ball_boundary.bottom > height:
    			ball.sound.play()
    			ball.velocity[1] = -1 * ball.velocity[1]

    		ball.ball_boundary = ball.ball_boundary.move (ball.velocity)
    		frame.blit (ball.ball_image, ball.ball_boundary)
    	pygame.display.flip()

rawDescription: How to add a second bouncing ball to the window?

description: Add a second bouncing ball to the window


code:
def main():
    alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.?! \t\n\r"
    PrintDescription()
    a = None
    while a not in ('e', 'd', 'q'):
        if a:
            print "Try again!"
        else:
            StartMenu()
        a = raw_input("")
    if a == 'q':
        sys.exit(0)

rawDescription: A little assistance with my program please (Beginner)