code:
import wx

class MyFrame(wx.Frame):
    """ Test of vertical wx.StaticLine """
    def __init__(self, parent=None, id=-1, title=None):
        wx.Frame.__init__(self, parent, id, title)
        self.panel = wx.Panel(self, size=(350, 200))

        self.ln = wx.StaticLine(self.panel, -1, style=wx.LI_VERTICAL)
        self.ln.SetSize((30,30))

        print self.ln.IsVertical()

        self.Fit()

app = wx.PySimpleApp()
frame1 = MyFrame(title='wx.StaticLine')
frame1.Center()
frame1.Show()
app.MainLoop()

rawDescription: How to draw vertical line using wxpython

description: Draw vertical line using wxpython


code:
strs = "initialword_content"
strs = strs[12:].replace("_", " ")
print strs

rawDescription: looking to parse a string in python

description: Looking to parse a string in python


code:
def open():
    pass

import __builtin__

print open
print __builtin__.open

rawDescription: Explicit access to Python's built in scope


code:
import os

_MAX_SIZE = 691

def delete_if_blank(listFile):
    # Make a list of files to check.
    with open(listFile) as listFile:
        filesToCheck = filter(None, (line.rstrip() for line in listFile.readlines()))

    # listFile is automatically closed now because we're out of the 'with' statement.

    print "Found %u files to check. Starting check." % len(filesToCheck)

    # Remove each file.
    for filename in filesToCheck:
        if os.stat(filename).st_size < _MAX_SIZE:
            print "Deleting %s" % filename
            os.remove(filename)
        else:
            print "Keeping %s" % filename

rawDescription: Why won't python allow me to delete files?


code:
import csv

delim = '|'

def replace_NAs(row, NA_values=["", ".", "-"]):
    if x in NA_values:
        return "NA"
    else:
        return x

with open('infile') as csvfile:
    reader = csv.reader(csvfile, delimiter=delim)
    for row in reader:
        transformed_row = [replace_NAs(x) for x in row]
        print delim.join(transformed_row)

a|b|c|d|e
1|NA|NA|NA|NA
1.2|2.6|NA|NA|1.7

rawDescription: Python find and replace with NA for delimited text files


code:
from threading import *
import time

def my_function():
    print 'Running ...' # replace

class EventSchedule(Thread):
    def __init__(self, function):
        self.running = False
        self.function = function
        super(EventSchedule, self).__init__()

    def start(self):
        self.running = True
        super(EventSchedule, self).start()

    def run(self):
        while self.running:
            self.function() # call function
            time.sleep(5) # wait 5 secs

    def stop(self):
        self.running = False

thread = EventSchedule(my_function) # pass function
thread.start() # start thread

rawDescription: Python forking inside multithreading

description: Python forking inside multithreading


code:
class Main:
    def __init__(self):
        self._age = None
        self._xyz = None
    def method(self):
        print self._age, self._xyz
test = Main()
test.method()

rawDescription: Java Class Variables & __init__ method in Python


code:
space = " "
print "John and{}Mark went to{}London".format(space*5,space*3)

rawDescription: Specifying spaces between words

description: Specifying spaces between words


code:
for ln in file:
    ln = ln.rstrip('\n')
    if COMMENT.match(ln):
        print "%s%s%s" % ('\033[01;32m', ln, '\033[0m')
    else:
        print ln

rawDescription: python: printing colored string not working properly

description: Python: printing colored string not working properly


code:
data = "[Hi all], [this is] [an example] "
import re
print re.findall("\[(.*?)\]", data)    # ['Hi all', 'this is', 'an example']

rawDescription: Splitting a string with brackets using regular expression in python


code:
import email

e = """Sender: test@test.dk
From: test@test.dk
HelloWorld: test

test email
"""

a = email.message_from_string(e)

print a.keys()

rawDescription: What fields are available after parsing an email message?


code:
Clusters = {"Cluster_X" :{"accession1": 8, "accession2": 3, "accession3": 7}," Cluster_Y" :{"accession1": 7, "accession2": 10}}

for c in Clusters:
    l = [[m,k] for k, m in Clusters[c].items()]
    l.sort()
    print 'median:', l[len(l)//2][0], ' key:', l[len(l)//2][1]

rawDescription: Get median of values in nested dictionary


code:
import ctypes
class SYSTEMTIME(ctypes.Structure):
    _fields_ = [
        ('wYear', ctypes.c_int16),
        ('wMonth', ctypes.c_int16),
        ('wDayOfWeek', ctypes.c_int16),
        ('wDay', ctypes.c_int16),
        ('wHour', ctypes.c_int16),
        ('wMinute', ctypes.c_int16),
        ('wSecond', ctypes.c_int16),
        ('wMilliseconds', ctypes.c_int16)]

SystemTime = SYSTEMTIME()
lpSystemTime = ctypes.pointer(SystemTime)
ctypes.windll.kernel32.GetLocalTime(lpSystemTime)
print SystemTime.wHour, SystemTime.wMinute

rawDescription: Make Python respond to Windows timezone changes


code:
import Tkinter as tk

class MyApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.entry.pack()
        close_button = tk.Button(self, text="Close", command=self.close)
        close_button.pack()
        self.string = ""

    def close(self):
        global result
        self.string = self.entry.get()
        self.destroy()

    def mainloop(self):
        tk.Tk.mainloop(self)
        return self.string

print "enter a string in the GUI"
app = MyApp()
result = app.mainloop()
print "you entered:", result

rawDescription: Python Tkinter Button/Entry combination

description: Python Tkinter Button/Entry combination


code:
from collections import defaultdict
defaultdict_dict=lambda :defaultdict(defaultdict_dict)
data = defaultdict(defaultdict_dict)

for snapshot in current_snapshots:
   try:
      data[snapshotYear][snapshotMonth][snapshotDay].append(snapshot)
   except AttributeError:
      data[snapshotYear][snapshotMonth][snapshotDay] = [snapshot]

print json.dumps(data)

rawDescription: If Result of For Loop is Equivalent Python


code:
a = raw_input("Enter line: ")
space = ""
# did you want to pre-set the trap to True? #
trap_set = False
while a != space:
    if 'Set the trap.' in a:
        trap_set = True
      # no reason to print trap if just setting #
      #  print "Trap!" #
    elif 'Mouse!' in a:
        if  trap_set == False:
            print "The mouse escaped."
        elif trap_set == True:
            print 'trap'
            trap_set = False
    a = raw_input("Enter line: ")

rawDescription: Python understanding error

description: Python understanding error


code:
if all(i in bits for i in input):
    print 'Valid input'

rawDescription: Best way to check if a collection only contains elements in another collection?

description: Check if a collection only contains elements in another collection


code:
dictionary = corpora.Dictionary.load('dictionary.dict')
corpus = corpora.MmCorpus("corpus.mm")
lda = models.LdaModel.load("model.lda") #result from running online lda (training)

index = similarities.MatrixSimilarity(lda[corpus])
index.save("simIndex.index")

docname = "docs/the_doc.txt"
doc = open(docname, 'r').read()
vec_bow = dictionary.doc2bow(doc.lower().split())
vec_lda = lda[vec_bow]

sims = index[vec_lda]
sims = sorted(enumerate(sims), key=lambda item: -item[1])
print sims

rawDescription: Python Gensim: how to calculate document similarity using the LDA model?


code:
import re

def replacer(matchobj):
    mat = matchobj.group()
    return "".join(item for items in zip("\\" * len(mat), mat) for item in items)

print re.sub(r"((\$)\2+)", replacer, "pa$$$$word")
# pa\$\$\$\$word

print re.sub(r"((\$)\2+)", replacer, "pa$$$word")
# pa\$\$\$word

print re.sub(r"((\$)\2+)", replacer, "pa$$word")
# pa\$\$word

print re.sub(r"((\$)\2+)", replacer, "pa$word")
# pa$word

rawDescription: Change pa$$word to pa\$\$word in Python

description: Change pa$$word to pa\$\$word in Python


code:
for x in range(1,9):
    for y in range(1,6):
        s.addMsgHandler("/Channels/toggleChannels/"+`y`+"/"+`x`, toggleChannels)

def toggleChannels(addr,tags,data,source):
    split = addr.split("/")
    x = split.pop()
    y = split.pop()

rawDescription: Can I create OSC message handlers containing wildcards?

description: Create OSC message handlers containing wildcards


code:
if driver.find_elements_by_css_selector("img[src$='icon_supported.png'].ng-hide") :
    print "image hidden"
else :
    print "image displayed"

rawDescription: How to verify in selenium if the image is shown on the page?

description: Verify in selenium if the image is shown on the page


code:
import codecs

data       = "Let's just pretend that this is binary data, ok?"
uuencode   = codecs.getencoder("uu")
data_uu, n = uuencode(data)
uudecode   = codecs.getdecoder("uu")
decoded, m = uudecode(data_uu)

print """* The initial input:
%(data)s
* Encoding these %(n)d bytes produces:
%(data_uu)s
* When we decode these %(m)d bytes, we get the original data back:
%(decoded)s""" % globals()

rawDescription: How to separate content from a file that is a container for binary and other forms of content

description: Separate content from a file that is a container for binary and other forms of content


code:
def test():
    print ('testing')
    browser = webdriver.Chrome()
    browser.get('http://urlforpage.com')
    meetings = browser.find_elements_by_xpath('/html/body/div[2]/table[2]/tbody/tr/td')
    for meet in meetings:
        if meet.get_attribute('class') == 'bold':
            print 'Venue: {venue}'.format(venue=meet.text)
        else:
            try:
                anchor = meet.find_element_by_tag_name('a')
                print 'link: {link}, text: {text}'.format(link = anchor.get_attribute('href'), text = anchor.text)
            except NoSuchElementException:
                pass  # Are you worried if something is neither a title (bold) nor contains an anchor?

test()

rawDescription: Python and Selenium - Scrape data from multiple siblings


code: print "Internet\t{}\t{:>18s}\t{:>7s}\t{:>8s}".format(ip, mac,'ARPA' ,interface)

rawDescription: printing table from list of data

description: Printing table from list of data


code:
text="""<script type="text/javascript" language="JavaScript">
ArtistName = "FUN.";
SongName = "We Are Young";
</script> """

import re

print dict(re.findall(r'((?:Artist|Song)Name)\s=\s"([^"]*)"', text))
# {'ArtistName': 'FUN.', 'SongName': 'We Are Young'}

rawDescription: Search for string in text file in-between two key words


code:
import subprocess

wid = None
xprop_out = subprocess.check_output(['xprop', '-root'])

for line in xprop_out.splitlines():
    if '_NET_ACTIVE_WINDOW(WINDOW)' in line:
        wid = line.split()[-1]

if wid:
    subprocess.check_call(['xdotool', 'windowfocus', wid])
    subprocess.check_call(['xdotool', 'key', 'ctrl+shift+t'])
    subprocess.check_call(['wmctrl', '-i', '-a', wid])
else:
    print 'Failed to find window ID'

rawDescription: Open new bash tab window via Python

description: Open new bash tab window via Python


code:
import lxml.html

tree = lxml.html.fromstring(htmlcode)
for link in tree.findall(".//a"):
    url = link.get("href")
    if url.endswith(".mp3"):
        print url

rawDescription: I need a regex for the href attribute for an mp3 file url in python


code:
import random

words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
print [random.sample(words, 1)[0] for i in range(10)]

rawDescription: Generating a list of segmented random words from a list


code:
from itertools import islice, izip_longest

with open('input') as fin:
    # Skip header(s) at start
    after5 = islice(fin, 5, None)
    # Take remaining data and group it into groups of 4 lines each... The
    # first 2 are float data, the 3rd is two integers together, and the 4th
    # is the blank line between groups... We use izip_longest to ensure we
    # always have 4 items (padded with None if needs be)...
    for lines in izip_longest(*[iter(after5)] * 4):
            # Convert first two lines to float, and take 3rd line, split it and
            # convert to integers
        print map(float, lines[:2]) + map(int, lines[2].split())

#[0.0, 0.0, 0, 1]
#[0.0, 0.01, 0, 1]

rawDescription: python alternative to scan('file', what=list(...)) in R

description: Python alternative to scan('file', what=list(...)) in R


code:
from lxml import etree
import StringIO

data= StringIO.StringIO('<root xmlns="http://some.random.schema">OneTwoThree</root>')
docs = etree.iterparse(data,tag='{http://some.random.schema}a')
for event, elem in docs:
    print event, elem

rawDescription: lxml iterparse in python can't handle namespaces

description: Lxml iterparse in python can't handle namespaces


code:
def retrieve_tweets(numtweets=10, *args):
    """
    This function optionally takes one or more arguments as keywords to filter tweets.
    It iterates through tweets from the stream that meet the given criteria and sends them
    to the database population function on a per-instance basis, so as to avoid disaster
    if the stream is disconnected.

    Both SampleStream and FilterStream methods access Twitter's stream of status elements.
    """
    filters = []
    for key in args:
        filters.append(str(key))
    if len(filters) == 0:
        stream = tweetstream.SampleStream(username, password)
    else:
        stream = tweetstream.FilterStream(username, password, track=filters)
    try:
        count = 0
        while count < numtweets:
            for tweet in stream:
                # a check is needed on text as some "tweets" are actually just API operations
                # the language selection doesn't really work but it's better than nothing(?)
                if tweet.get('text') and tweet['user']['lang'] == 'en':
                    if tweet['retweet_count'] == 0:
                        # bundle up the features I want and send them to the db population function
                        bundle = (tweet['id'], tweet['user']['screen_name'], tweet['retweet_count'], tweet['text'])
                        db_initpop(bundle)
                        break
                    else:
                        # a RT has a different structure.  This bundles the original tweet.  Getting  the
                        # retweets comes later, after the stream is de-accessed.
                        bundle = (tweet['retweeted_status']['id'], tweet['retweeted_status']['user']['screen_name'], \
                                  tweet['retweet_count'], tweet['retweeted_status']['text'])
                        db_initpop(bundle)
                        break
            count += 1
    except tweetstream.ConnectionError, e:
        print 'Disconnected from Twitter at '+time.strftime("%d %b %Y %H:%M:%S", time.localtime()) \
        +'.  Reason: ', e.reason

def db_initpop(bundle):
    """
    This function places basic tweet features in the database.  Note the placeholder values:
    these can act as a check to verify that no further expansion was available for that method.
    """
    #unpack the bundle
    tweet_id, user_sn, retweet_count, tweet_text = bundle
    curs.execute("""INSERT INTO tblTweets VALUES (null,?,?,?,?,?,?)""", \
        (tweet_id, user_sn, retweet_count, tweet_text, 'cleaned text', 'cleaned retweet text'))
    conn.commit()
    print 'Database populated with tweet '+str(tweet_id)+' at '+time.strftime("%d %b %Y %H:%M:%S", time.localtime())

rawDescription: Trying to use Tweepy/Twitters Streaming API and psycopg2 to populate a PostgreSQL database. Very close, one line off


code:
import wx

class TestFrame(wx.Frame):

    def __init__(self):
        self.count = 0
        wx.Frame.__init__(self, None, -1, "test frame", size=(200, 100))
        self.panel = wx.Panel(self, -1)
        button = wx.Button(self.panel, -1, "b", pos=(10, 40))
        self.text = wx.TextCtrl(self.panel, -1, `self.count`, size=(50, 25))
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.incr_text)
        self.timer.Start(1000)

    def incr_text(self, event):
        self.count += 1
        f = self.FindFocus()
        if not f==self.text:
            self.text.SetValue(`self.count`)

if __name__=="__main__":
    app = wx.PySimpleApp()
    TestFrame().Show()
    app.MainLoop()

rawDescription: Prevent a timer from updating a text box if the key cursor is in the box


code:
class entryExit(object):

    def __init__(self, f):
        self.f = f

    def __call__(self):
        print "Entering", self.f.__name__
        self.f()
        print "Exited", self.f.__name__

@entryExit
def func1():
    print "inside func1()"

@entryExit
def func2():
    print "inside func2()"

rawDescription: how to implement a interface to keep track of runtime of each sub-sections and also the total run time of the section in python

description: Implement a interface to keep track of runtime of each sub-sections and also the total run time of the section in python


code:
from bs4 import BeautifulSoup

mystr = 'Access it!'
soup = BeautifulSoup(mystr, 'html.parser')

a = soup.find('a')
if a: # a will be None if there are no  tags
    try:
        detail = a['detail']
        print "Detail: {}".format(detail)
        print "Content: {}".format(a.text)
    except KeyError: # will throw KeyError if no key named 'detail'
        print "No details"
        print "Content: {}".format(a.text)
else:
    print "No  tags"

rawDescription: Parsing a brief string with BeautifulSoup


code:
import pandas as pd

df_comment = pd.read_csv('comment.csv')
df_score   = pd.read_csv('score.csv')

cnt = 0
for i in  df_comment['comment']:
        kp = []
        for  j in i.split(' '):
                if j in [k for k in df_score['word']]:
                        pos = [x for x, y in enumerate(df_score['word']) if y==j]
                        kp.append(df_score['score'][pos[0]])
        cnt= cnt+1

        print cnt, i, sum(kp)

rawDescription: finding scores from csv file

description: Finding scores from csv file


code:
for key, result in cb.get_multi(keys).items():
    print "Value is", result.value

rawDescription: How to parse MultiResult object with Couchbase Python SDK?

description: Parse MultiResult object with Couchbase Python SDK


code:
print '%x' % 0b11111111   # -> 'ff'  (from binary)
print '%x' % 0377         # -> 'ff'  (from octal)
print '%x' % 255          # -> 'ff'  (from decimal)
print '%x' % 0xff         # -> 'ff'  (from hex)

rawDescription: what about the python expression's princple

description: What about the python expression's princple


code:
import csv

alist, blist = [], []

with open("csv1.csv", "rb") as fileA:
    reader = csv.reader(fileA, delimiter=',')
    for row in reader:
        for row_str in row:
            alist += row_str.strip().split()

with open("organs.csv", "rb") as fileB:
    reader = csv.reader(fileB, delimiter=',')
    for row in reader:
        blist += row

first_set = set(alist)
second_set = set(blist)

print first_set.intersection(second_set)

rawDescription: Compare two CSV files and look for matches Python


code:
from re import findall

print findall(r'\w[\w.]*\w', 'WARC-_Target-URI: http://www.allchocolate.com/health/basics/')

rawDescription: Regex that would give certain words python


code:
def set_a(my_a):
        my_a.a = 5
        my_a.b = 6

def main():
    def set_b(my_a):
            my_a.a = 3
            my_a.b = 4

    my_instance = MyClass()
    print my_instance.a, my_instance.b
    set_b(my_instance)
    print my_instance.a, my_instance.b
    set_a(my_instance)
    print my_instance.a, my_instance.b

if __name__ == "__main__":
        main()

rawDescription: Access Class Instance from Function Scope


code:
from crontab import CronTab

tab = CronTab(user=True)
cmd1 = 'echo Hello'
cmd2 = 'echo CronTab'

job1 = tab.new(cmd1)
job1.minute.every(1)
job1.enable()

job2 = tab.new(cmd2)
job2.hour.every(1)
job2.enable()

print list(tab.commands)  # ['echo Hello', 'echo CronTab']

# Explicitly specify we want the user's crontab:
tab2 = CronTab(user=True)

print list(tab2.commands)  # ['echo Hello', 'echo CronTab']

rawDescription: Python Crontab Overwrites the previous job instead of creating a new one


code:
from bs4 import BeautifulSoup

data = """[dd/mm/yy]:message_data
<starttag>
    <some_field>some_value</some_field>
     ....
</starttag>
[dd/mm/yy]:message_data
[dd/mm/yy]:message_data"""

soup = BeautifulSoup(data);
starttag = soup.findAll("starttag")
for tag in starttag:
    print tag.find("some_field").text
    # => some_value

rawDescription: Mixed xml / text parsing python

description: Mixed xml / text parsing python


code:
import struct

def s_record_encode(fileobj, recordtype, address, buflen):
    """S-Record encode bytes from file.

    fileobj      file-like object to read data (if any)
    recordtype   'S0' to 'S9'
    address      integer address
    buflen       maximum output buffer size
    """
    # S-type to (address_len, has_data)
    record_address_bytes = {
        'S0':(2, True), 'S1':(2, True), 'S2':(3, True), 'S3':(4, True),
        'S5':(2, False), 'S7':(4, False), 'S8':(3, False), 'S9':(2, False)
    }

    # params for this record type
    address_len, has_data = record_address_bytes[recordtype]

    # big-endian address as string, trimmed to length
    address = struct.pack('>L', address)[-address_len:]

    # read data up to 255 bytes minus address and checksum len
    if has_data:
        data = fileobj.read(0xff - len(address) - 1)
        if not data:
            return '', 0
    else:
        data = ''

    # byte count is address + data + checksum
    count = len(address) + len(data) + 1
    count = struct.pack('B', count)

    # checksum count + address + data
    checksummed_record = count + address + data
    checksum = struct.pack('B', sum(ord(d) for d in checksummed_record) & 0xff ^ 0xff)

    # glue record type to hex encoded buffer
    record = recordtype + (checksummed_record + checksum).encode('hex').upper()

    # return buffer and how much data we read from the file
    return record, len(data)

def s_record_test():
    from cStringIO import StringIO

    # from an example, this should encode to given string
    fake_file = StringIO("\x0A\x0A\x0D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
    encode_to = "S1137AF00A0A0D0000000000000000000000000061"
    fake_file.seek(0)
    record, buflen = s_record_encode(fake_file, 'S1', 0x7af0, 80)
    print 'record', record
    print 'encode_to', encode_to
    assert record == encode_to

    fake_file = StringIO()
    for i in xrange(1000):
        fake_file.write(struct.pack('>L', i))
    fake_file.seek(0)

    address = 0

    while True:
        buf, datalen = s_record_encode(fake_file, 'S2', address, 100)
        if not buf:
            break
        print address, datalen, buf
        address += datalen

rawDescription: How can I moderate how much data I get from a file stream in python?

description: Moderate how much data I get from a file stream in python


code:
import arcpy # csv
from arcpy import env

print "Creating and defining variables."
env.workspace = r"C:\Users\Desktop\data"
env.overwriteOutput = 1

theme = 'interestAreas.shp'
with arcpy.da.SearchCursor(theme, ['SHAPE@']) as Curs:
    for i in Curs: # iterate through the rows in the cursor object
        polygon = i[0]
        ext = polygon.extent

        # Find min X, Y and max X, Y for each polygon and write it to the file:
        print 'xmin is: ', ext.XMin
        print 'ymin is: ', ext.YMin
        print 'xmax is: ', ext.XMax
        print 'ymax is: ', ext.YMax
        minX = ext.XMin
        minY = ext.YMin

rawDescription: how to move from one polygon to another in file in python?

description: Move from one polygon to another in file in python


code:
def add(a, b):
    print "ADDING %.2f + %.2f" % (a, b)
    return a + b

number_a = float(raw_input())
number_b = float(raw_input())

add(number_a, number_b)

rawDescription: Outputting floating numbers

description: Outputting floating numbers


code:
list1 = [[1,1],'info11','info21']
list2 = [[2,1],'info12','info22']
list3 = [list1,list2]
list4 = [1,1]

for i in list3:
    if list4 in i:
        print i[1:]

rawDescription: Check value in sublist and return the correct sublist


code:
import requests

params = {'key1':'val1', 'key2':'val2'}
payload = {'test': 'test'}
r = requests.post("http://httpbin.org/post",params=params,data=payload)

print r.text

rawDescription: How to send mix of GET and POST in python

description: Send mix of GET and POST in python


code:
import string

secret = """FMMP
NZ OBNF JT KPTIVB
KPIO TVDLT BTT
GVOEBNFOUBMT PG DPNQVUJOH"""

characters = list(string.uppercase)
cipher = dict(zip(characters[1:]+[characters[0]], characters))

decrypted = "".join(map(lambda x: cipher.get(x,x), secret))

print decrypted

rawDescription: Python decryption with lists

description: Python decryption with lists


code:
import numpy as np
from collections import Counter

a=['John', 'John', 'John', 'Mark', 'Mark', 'Mark', 'Joe']
b= ['John', 'Mark', 'Joe', 'Joe', 'Joe', 'Jack']
c= ['Mark', 'Joe', 'Jack', 'Jack', 'Tony']

ac = Counter(a)
bc = Counter(b)
cc = Counter(c)

allLists = [list(), list(), list()]

allNames = set(ac.keys() + bc.keys() + cc.keys());

for name in allNames:

    aCount = ac[name];
    bCount = bc[name];
    cCount = cc[name];

    allCounts = np.array([aCount, bCount, cCount]);

    maxIndex = allCounts.argsort()[::-1][0];

    allLists[maxIndex] += [name];

alist, blist, clist = allLists[:]

print alist, blist, clist

rawDescription: How to get the dictionary name for each key with the highest value across multiple dictionaries

description: Get the dictionary name for each key with the highest value across multiple dictionaries


code:
repo = Repo("...")
for c in repo.iter_commits():
  print c.hexsha
  print c.summary
  for p in c.parents:
    handle_diff(c.diff(p))

rawDescription: What's the difference between gitpython's diff and git log's diff?


code:
x=int(a,2)
num_bits = 10
print x - (1 << num_bits)

rawDescription: Python - Most effective way to implement two's complement?


code:
import sys
print len(sys.stdin.read()) # anything to consume piped input
sys.stdin = open("CON:", "r")
x = raw_input("sdfklj ")

rawDescription: How do I accept piped input and then user-prompted input in a Python script?

description: Accept piped input and then user-prompted input in a Python script


code:
from datetime import datetime, timedelta

monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))

print 'Weeks:', (monday2 - monday1).days / 7

rawDescription: How to calculate difference between two dates in weeks in python

description: Calculate difference between two dates in weeks in python


code:
from ctypes import *
from ctypes.wintypes import *
from sys import exit

def customresize(array, new_size):
    return (array._type_*new_size).from_address(addressof(array))

wlanapi = windll.LoadLibrary('wlanapi.dll')

ERROR_SUCCESS = 0

class GUID(Structure):
    _fields_ = [
        ('Data1', c_ulong),
        ('Data2', c_ushort),
        ('Data3', c_ushort),
        ('Data4', c_ubyte*8),
        ]

WLAN_INTERFACE_STATE = c_uint
(wlan_interface_state_not_ready,
 wlan_interface_state_connected,
 wlan_interface_state_ad_hoc_network_formed,
 wlan_interface_state_disconnecting,
 wlan_interface_state_disconnected,
 wlan_interface_state_associating,
 wlan_interface_state_discovering,
 wlan_interface_state_authenticating) = map(WLAN_INTERFACE_STATE, xrange(0, 8))

class WLAN_INTERFACE_INFO(Structure):
    _fields_ = [
        ("InterfaceGuid", GUID),
        ("strInterfaceDescription", c_wchar * 256),
        ("isState", WLAN_INTERFACE_STATE)
        ]

class WLAN_INTERFACE_INFO_LIST(Structure):
    _fields_ = [
        ("NumberOfItems", DWORD),
        ("Index", DWORD),
        ("InterfaceInfo", WLAN_INTERFACE_INFO * 1)
        ]

WLAN_MAX_PHY_TYPE_NUMBER = 0x8
DOT11_SSID_MAX_LENGTH = 32
WLAN_REASON_CODE = DWORD
DOT11_BSS_TYPE = c_uint
(dot11_BSS_type_infrastructure,
 dot11_BSS_type_independent,
 dot11_BSS_type_any) = map(DOT11_BSS_TYPE, xrange(1, 4))
DOT11_PHY_TYPE = c_uint
dot11_phy_type_unknown      = 0
dot11_phy_type_any          = 0
dot11_phy_type_fhss         = 1
dot11_phy_type_dsss         = 2
dot11_phy_type_irbaseband   = 3
dot11_phy_type_ofdm         = 4
dot11_phy_type_hrdsss       = 5
dot11_phy_type_erp          = 6
dot11_phy_type_ht           = 7
dot11_phy_type_IHV_start    = 0x80000000
dot11_phy_type_IHV_end      = 0xffffffff

DOT11_AUTH_ALGORITHM = c_uint
DOT11_AUTH_ALGO_80211_OPEN         = 1
DOT11_AUTH_ALGO_80211_SHARED_KEY   = 2
DOT11_AUTH_ALGO_WPA                = 3
DOT11_AUTH_ALGO_WPA_PSK            = 4
DOT11_AUTH_ALGO_WPA_NONE           = 5
DOT11_AUTH_ALGO_RSNA               = 6
DOT11_AUTH_ALGO_RSNA_PSK           = 7
DOT11_AUTH_ALGO_IHV_START          = 0x80000000
DOT11_AUTH_ALGO_IHV_END            = 0xffffffff

DOT11_CIPHER_ALGORITHM = c_uint
DOT11_CIPHER_ALGO_NONE            = 0x00
DOT11_CIPHER_ALGO_WEP40           = 0x01
DOT11_CIPHER_ALGO_TKIP            = 0x02
DOT11_CIPHER_ALGO_CCMP            = 0x04
DOT11_CIPHER_ALGO_WEP104          = 0x05
DOT11_CIPHER_ALGO_WPA_USE_GROUP   = 0x100
DOT11_CIPHER_ALGO_RSN_USE_GROUP   = 0x100
DOT11_CIPHER_ALGO_WEP             = 0x101
DOT11_CIPHER_ALGO_IHV_START       = 0x80000000
DOT11_CIPHER_ALGO_IHV_END         = 0xffffffff

WLAN_AVAILABLE_NETWORK_CONNECTED = 1
WLAN_AVAILABLE_NETWORK_HAS_PROFILE = 2

WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES = 0x00000001
WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES = 0x00000002

class DOT11_SSID(Structure):
    _fields_ = [
        ("SSIDLength", c_ulong),
        ("SSID", c_char * DOT11_SSID_MAX_LENGTH)
        ]

class WLAN_AVAILABLE_NETWORK(Structure):
    _fields_ = [
        ("ProfileName", c_wchar * 256),
        ("dot11Ssid", DOT11_SSID),
        ("dot11BssType", DOT11_BSS_TYPE),
        ("NumberOfBssids", c_ulong),
        ("NetworkConnectable", c_bool),
        ("wlanNotConnectableReason", WLAN_REASON_CODE),
        ("NumberOfPhyTypes", c_ulong),
        ("dot11PhyTypes", DOT11_PHY_TYPE * WLAN_MAX_PHY_TYPE_NUMBER),
        ("MorePhyTypes", c_bool),
        ("wlanSignalQuality", c_ulong),
        ("SecurityEnabled", c_bool),
        ("dot11DefaultAuthAlgorithm", DOT11_AUTH_ALGORITHM),
        ("dot11DefaultCipherAlgorithm", DOT11_CIPHER_ALGORITHM),
        ("Flags", DWORD),
        ("Reserved", DWORD)
        ]

class WLAN_AVAILABLE_NETWORK_LIST(Structure):
    _fields_ = [
        ("NumberOfItems", DWORD),
        ("Index", DWORD),
        ("Network", WLAN_AVAILABLE_NETWORK * 1)
        ]

WlanOpenHandle = wlanapi.WlanOpenHandle
WlanOpenHandle.argtypes = (DWORD, c_void_p, POINTER(DWORD), POINTER(HANDLE))
WlanOpenHandle.restype = DWORD

WlanEnumInterfaces = wlanapi.WlanEnumInterfaces
WlanEnumInterfaces.argtypes = (HANDLE, c_void_p,
                               POINTER(POINTER(WLAN_INTERFACE_INFO_LIST)))
WlanEnumInterfaces.restype = DWORD

WlanGetAvailableNetworkList = wlanapi.WlanGetAvailableNetworkList
WlanGetAvailableNetworkList.argtypes = (HANDLE, POINTER(GUID), DWORD, c_void_p,
                                        POINTER(POINTER(WLAN_AVAILABLE_NETWORK_LIST)))
WlanGetAvailableNetworkList.restype = DWORD

WlanFreeMemory = wlanapi.WlanFreeMemory
WlanFreeMemory.argtypes = [c_void_p]

if __name__ == '__main__':
    NegotiatedVersion = DWORD()
    ClientHandle = HANDLE()
    ret = WlanOpenHandle(1, None, byref(NegotiatedVersion), byref(ClientHandle))
    if ret != ERROR_SUCCESS:
        exit(FormatError(ret))
    # find all wireless network interfaces
    pInterfaceList = pointer(WLAN_INTERFACE_INFO_LIST())
    ret = WlanEnumInterfaces(ClientHandle, None, byref(pInterfaceList))
    if ret != ERROR_SUCCESS:
        exit(FormatError(ret))
    try:
        ifaces = customresize(pInterfaceList.contents.InterfaceInfo,
                              pInterfaceList.contents.NumberOfItems)
        # find each available network for each interface
        for iface in ifaces:
            print "Interface: %s" % (iface.strInterfaceDescription)
            pAvailableNetworkList = pointer(WLAN_AVAILABLE_NETWORK_LIST())
            ret = WlanGetAvailableNetworkList(ClientHandle,
                                        byref(iface.InterfaceGuid),
                                        0,
                                        None,
                                        byref(pAvailableNetworkList))
            if ret != ERROR_SUCCESS:
                exit(FormatError(ret))
            try:
                avail_net_list = pAvailableNetworkList.contents
                networks = customresize(avail_net_list.Network,
                                        avail_net_list.NumberOfItems)
                for network in networks:
                    print "SSID: %s, quality: %02d%%" % (
                        network.dot11Ssid.SSID[:network.dot11Ssid.SSIDLength],
                        network.wlanSignalQuality)
            finally:
                WlanFreeMemory(pAvailableNetworkList)
    finally:
        WlanFreeMemory(pInterfaceList)

rawDescription: How can I retrieve the signal strength of nearby wireless LAN networks on Windows using Python?

description: Retrieve the signal strength of nearby wireless LAN networks on Windows using Python


rawDescription: Python populating input arguments for a function with *args


code:
while True:
    operator = raw_input('Do you want to add, subtract, multiply, or divide? ')
    first = raw_input('Enter your first term: ')
    second = raw_input('Enter your second term: ')
    if operator.lower.startswith('a'):
        print first+second
    elif operator.lower.startswith('m'):
        print first*second
    elif operator.lower.startswith('s'):
        print first-second
    elif operator.lower.startswith('d'):
        print float(first)/second

rawDescription: Is there some way i could perform multiple operations without reopening it again and again?


code:
import pyqtgraph as pg
import numpy as np

x = np.arange(0,1,0.1)
y = [0,0,0,2,2,8,9,2,0,0]
print len(x), len(y)

plt = pg.plot(x,y,pen='r')
curve2 = pg.PlotCurveItem(x,y[:-1],pen='b',stepMode=True)
plt.addItem(curve2)

rawDescription: pyqtgraph: plot with a similar functionality as matplotlib drawstyle

description: Pyqtgraph: plot with a similar functionality as matplotlib drawstyle


code:
"""Use custom meta hook to import modules available as strings.
Cp. PEP 302 http://www.python.org/dev/peps/pep-0302/#specification-part-2-registering-hooks"""
import sys
import imp

modules = {"a" :
"""def hello():
    return 'Hello World A!'""",
"b":
"""def hello():
    return 'Hello World B!'"""}

class StringImporter(object):

   def __init__(self, modules):
       self._modules = dict(modules)

   def find_module(self, fullname, path):
      if fullname in self._modules.keys():
         return self
      return None

   def load_module(self, fullname):
      if not fullname in self._modules.keys():
         raise ImportError(fullname)

      new_module = imp.new_module(fullname)
      exec self._modules[fullname] in new_module.__dict__
      return new_module

if __name__ == '__main__':
   sys.meta_path.append(StringImporter(modules))

   # Let's use our import hook
   from a import hello
   print hello()
   from b import hello
   print hello()

rawDescription: python:Import module from memory

description: Python:Import module from memory


code:
from BeautifulSoup import BeautifulSoup
page = BeautifulSoup('<foo bar="asdf" blah="123">xyz</foo>')
for attr, value in page.find('foo').attrs:
    print attr, "=", value

# Prints:
# bar = asdf
# blah = 123

rawDescription: How do I iterate over the HTML attributes of a Beautiful Soup element?

description: Iterate over the HTML attributes of a Beautiful Soup element


code:
import traceback

class ContextManagerContent(object):

    def __enter__(self):
        return

    def __exit__(self, _type, value, _traceback):
        stack = traceback.extract_stack()
        f, last_line = self._get_origin_info(stack)

        with open(f) as fin:
            lines = list(fin)

        search = 'with {cls_name}'.format(cls_name=self.__class__.__name__)
        for i, x in enumerate(lines[:last_line + 1][::-1]):
            if search in x:
                first_line = len(lines) - i
                break

        selected_lines = lines[first_line:last_line + 1]
        print ''.join(selected_lines)

    def _get_origin_info(self, stack):
        origin = None
        for i, x in enumerate(stack[::-1]):
            if x[2] == '__exit__':
                origin = stack[::-1][i + 1]
                break

        return origin[0], origin[1] - 1

with ContextManagerContent():
    print '123'
    print '456'
    print '789'

rawDescription: Is there any way to get source code inside context manager as string?


code:
import requests

r = requests.get('http://192.168.1.1/basic/home_dhcplist.htm', auth=('username', 'password'))

if 'Prasads' in r.text():
    print "found"
else:
    print "not found"

rawDescription: How to access the password protected Router Page from Python?

description: Access the password protected Router Page from Python


code:
generator = (x for x in something if search in str(x.title).lower())
for item in generator:
   print item

rawDescription: Search list that contain object attribute and print/return object Python


code: print list(itertools.product([0, 1, 2], repeat=5))

rawDescription: possible outcomes for a List

description: Possible outcomes for a List


code:
rules = app.url_map._rules
for rule in rules:
    print rule.endpoint, rule, rule.defaults

rawDescription: Flask: Get URLs for each View class in module


code:
lst = ['
\n
\n  a	\n  b	\n  c	\n
\n
\n  1	\n  2	\n  3	\n
\n
\n  d	\n  e	\n  f	\n
\n

', '
\n
\n  a	\n  b	\n  c	\n
\n
\n  1	\n  2	\n  3	\n
\n
\n  d	\n  e	\n  f	\n
\n

', '
\n
\n  a	\n  b	\n  c	\n
\n
\n  1	\n  2	\n  3	\n
\n
\n  d	\n  e	\n  f	\n
\n

']
print ''.join(lst)

rawDescription: How to use *args to create multiple html tables from lists?

description: Use *args to create multiple html tables from lists


code:
def fibo1(par):
    var1 = 0
    var2 = 1
    list = []
    while var2 < par:
        list.append(var2)
        var3 = var1 + var2
        var1 = var2
        var2 = var3
    return list

def main():
    number = int(raw_input("What is the number? "))
    print fibo1(number)

main()

rawDescription: Returning a list in Python

description: Returning a list in Python


code:
import json

class Subscriber(object):
    firstname = None
    lastname = None

class Post(object):
    author = None
    title = None

def decode_from_dict(cls,vals):
    obj = cls()
    for key, val in vals.items():
        setattr(obj, key, val)
    return obj

SERIALIZABLE_CLASSES = {'Subscriber': Subscriber,
                        'Post': Post}

def decode_object(d):
    for field in d:
        if field in SERIALIZABLE_CLASSES:
            cls = SERIALIZABLE_CLASSES[field]
            return decode_from_dict(cls, d[field])
    return d

results = '''[{"Subscriber": {"firstname": "Neal", "lastname": "Walters"}},
              {"Post": {"author": {"Subscriber": {"firstname": "Neal",
                                                  "lastname": "Walters"}}},
                        "title": "Decoding JSON Objects"}]'''
result = json.loads(results, object_hook=decode_object)
print result
print result[1].author

rawDescription: How to inspect mystery deserialized object in Python

description: Inspect mystery deserialized object in Python


code:
# number to find summation of all primes below number
hi = 2000000

# create a set excluding even numbers
numbers = set(xrange(3, hi + 1, 2))

for number in xrange(3, int(hi ** 0.5) + 1):
    if number not in numbers:
        #number must have been removed because it has a prime factor
        continue

    num = number
    while num < hi:
        num += number
        if num in numbers:
            # Remove multiples of prime found
            numbers.remove(num)

print 2 + sum(numbers)

rawDescription: Sum of primes below 2,000,000 in python

description: Sum of primes below 2,000,000 in python


code:
import os

def empty_dirs(root_dir='.', recursive=True):
    empty_dirs = []
    for root, dirs, files in os.walk(root_dir, topdown=False):
        #print root, dirs, files
        if recursive:
            all_subs_empty = True  # until proven otherwise
            for sub in dirs:
                full_sub = os.path.join(root, sub)
                if full_sub not in empty_dirs:
                    #print full_sub, "not empty"
                    all_subs_empty = False
                    break
        else:
            all_subs_empty = (len(dirs) == 0)
        if all_subs_empty and is_empty(files):
            empty_dirs.append(root)
            yield root

def is_empty(files):
    return (len(files) == 0 or files == ['desktop.ini'])

def find_empty_dirs(root_dir='.', recursive=True):
    return list(empty_dirs(root_dir, recursive))

print find_empty_dirs(recursive=False)

rawDescription: How to find recursively empty directories in Python?

description: Find recursively empty directories in Python


code:
def fun_name():
    i = 0
    numbers = []
    while i < 6:
        print "At the top of i is %d" % i
        numbers.append(i)
        i = i + 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" % i

    print "The numbers: "

    for num in numbers:
        print num

rawDescription: convert a while-loop into a function

description: Convert a while-loop into a function


code:
import os
def run():
   for code in range(0, 256):
     print "\x1b[38;05;{code}m {code} Test".format(code=code)

run()

rawDescription: Changing BASH script to Python

description: Changing BASH script to Python


code:
import urllib2
import re

url = 'http://anidb.net/perl-bin/animedb.pl?show=animelist&adb.search=%22Cowboy%20Bebop%22&do.search=search'
headers = {"User-agent": "Mozilla/5.0"}
request = urllib2.Request(url, None, headers)
result = urllib2.urlopen(request)
r =  re.search("aid=(\d+)", result.geturl())
print r.group(1)

rawDescription: Getting part of URL after redirect

description: Getting part of URL after redirect


code:
class MyClass(object):
    """ Documentation for MyClass goes here. """

    def __init__(self):
        """
        doc string
        """

i = MyClass()
print i.__doc__ # same as MyClass.__doc__

rawDescription: Python, documentation strings within classes


code:
def some_function():
    print "some_function called"
    return ['foo', 'bar', 'baz']

for datum in some_function():
    print datum

rawDescription: Does iterating over returned data call the function every time in Python?


rawDescription: Insert a newline character every 64 characters using Python


code:
import json
print json.dumps('I said, "Hello, world!"')

rawDescription: Why is escaping of single quotes inconsistent on file read in Python?


code:
import codecs
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB,BernoulliNB
from sklearn import svm
from sklearn.grid_search import GridSearchCV

testfile = 'testing_words.txt'

word_vectorizer = CountVectorizer(analyzer='word')
trainset = word_vectorizer.fit_transform(codecs.open(trainfile,'r','utf8'))
tags = training_labels

mnb = svm.LinearSVC() # or any other classifier
# check out the sklearn online docs to see what params choice we have for your
# particular choice of estimator, for SVM, C, class_weight are important ones to tune
params_space = {'C': np.logspace(-5, 0, 10), 'class_weight':[None, 'auto']}
# build a grid search cv, n_jobs=-1 to use all your processor cores
gscv = GridSearchCV(mnb, params_space, cv=10, n_jobs=-1)
# fit the model
gscv.fit(trainset, tags)
# give a look at your best params combination and best score you have
gscv.best_estimator_
gscv.best_params_
gscv.best_score_

codecs.open(testfile,'r','utf8')
testset = word_vectorizer.transform(codecs.open(testfile,'r','utf8'))
results = gscv.predict(testset)

print results

rawDescription: How can I alter the parameters in my algorithms for better performance?

description: Alter the parameters in my algorithms for better performance


code:
import urllib2
from bs4 import BeautifulSoup as BS
html = urllib2.urlopen('http://www.fastfurnishings.com/SearchResults.asp?Search=3-Piece+Reversible+Bonded+Leather+Match+Sofa+Set+in+Cream')
soup = BS(html)
print soup.find('td', {'valign':'top', 'width':'33%', 'align':'center'}).a['href']

rawDescription: learning python regex and webscraping and stuck

description: Learning python regex and webscraping and stuck


code:
import SocketServer
from BaseHTTPServer import BaseHTTPRequestHandler

def some_function():
    print "some_function got called"

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/captureImage':
            # Insert your code here
            some_function()

        self.send_response(200)

httpd = SocketServer.TCPServer(("", 8080), MyHandler)
httpd.serve_forever()

rawDescription: Python respond to HTTP Request

description: Python respond to HTTP Request


code:
count = sum(1 for i in items if i > 3)
correct = sum(1 for i in items if i > 5)

score = float(correct) / count
print '%.2f' % score

rawDescription: Pythonic proportion calculation of two conditions


code:
import paramiko
from scp import SCPClient
import time

# Define connection info
host_ip = 'xx.xx.xx.xx'
user = 'xxxxxxxx'
pw = 'xxxxxxxx'
port = 22

# Paths
input_loc = '/nfs_home/appers/extracts/*/*.xml'
output_loc = '/user/lcmsprod/output/cnielsen/'
python_path = "/usr/lib/python_2.7.3/bin/python"
hdfs_home = '/nfs_home/appers/cnielsen/'
output_log = r'C:\Users\cnielsen\Desktop\MR_Test\MRtest011316_0.txt'

# File names
xml_lookup_file = 'product_lookups.xml'
mapper = 'Mapper.py'
reducer = 'Reducer.py'
helper_script = 'Process.py'
product_name = 'test1'
output_ref = 'test65'
target_file = 'test_011416_3.txt'

# ----------------------------------------------------
def createSSHClient(host_ip, port, user, pw):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(host_ip, port, user, pw)
    return client
# ----------------------------------------------------
def buildMRcommand(product_name):
    space = " "
    mr_command_list = [ 'hadoop', 'jar', '/share/hadoop/tools/lib/hadoop-streaming.jar',
                        '-files', hdfs_home+xml_lookup_file,
                        '-file', hdfs_home+mapper,
                        '-file', hdfs_home+reducer,
                        '-mapper', "'"+python_path, mapper, product_name+"'",
                        '-file', hdfs_home+helper_script,
                        '-reducer', "'"+python_path, reducer+"'",
                        '-input', input_loc,
                        '-output', output_loc+output_ref]

    MR_command = space.join(mr_command_list)
    print MR_command
    return MR_command
# ----------------------------------------------------
def unbuffered_lines(f):
    line_buf = ""
    while not f.channel.exit_status_ready():
        line_buf += f.read(1)
        if line_buf.endswith('\n'):
            yield line_buf
            line_buf = ""
# ----------------------------------------------------
def stream_output(stdin, stdout, stderr):
    writer = open(output_log, 'w')
    # Using line_buffer function
    for l in unbuffered_lines(stderr):
        e = '[stderr] ' + l
        print '[stderr] ' + l.strip('\n')
        writer.write(e)

    # gives full listing..
    for line in stdout:
        r = '[stdout]' + line
        print '[stdout]' + line.strip('\n')
        writer.write(r)
    writer.close()
# ----------------------------------------------------
def run_MapReduce(ssh):
    stdin, stdout, stderr = ssh.exec_command(buildMRcommand(product_name))
    stream_output(stdin, stdout, stderr)
    return 1
# ----------------------------------------------------
def run_list_dir(ssh):
    list_dir = "ls "+hdfs_home+" -l"
    stdin, stdout, stderr = ssh.exec_command(list_dir)
    stream_output(stdin, stdout, stderr)
# ----------------------------------------------------
def run_getmerge(ssh):
    getmerge = "hadoop fs -getmerge "+output_loc+output_ref+" "+hdfs_home+target_file
    print getmerge
    stdin, stdout, stderr = ssh.exec_command(getmerge)
    for line in stdout:
        print '[stdout]' + line.strip('\n')
    time.sleep(1.5)
    return 1
# ----------------------------------------------------
def scp_download(ssh):
    scp = SCPClient(ssh.get_transport())
    print "Fetching SCP data.."
    scp.get(hdfs_home+target_file, local_dir)
    print "File download complete."
# ----------------------------------------------------
def main():
    # Get the ssh connection
    global ssh
    ssh = createSSHClient(host_ip, port, user, pw)
    print "Executing command..."

    # Command list
    ##run_list_dir(ssh)
    ##run_getmerge(ssh)
    ##scp_download(ssh)

    # Run MapReduce
    MR_status = 0
    MR_status = run_MapReduce(ssh)

    if MR_status == 1:
        gs = 0
        gs = run_getmerge(ssh)
        if gs == 1:
            scp_download(ssh)

    # Close ssh connection
    ssh.close()

if __name__ == '__main__':
    main()

rawDescription: How to run PSCP cmd window step in my Python script

description: Run PSCP cmd window step in my Python script


code:
x = u'a'
y = u'abc'[:1]
print x == y, x is y

rawDescription: In Python, are single character strings guaranteed to be identical?


code:
s0 = [set([16,9,2,10]), set([16,14,22,15]), set([14,7])]   # true, 16 and 14
s1 = [set([16,9,2,10]), set([16,14,22,15]), set([7,8])]    # false

def connected(sets):
    L = len(sets)

    if not L: return True
    if L == 1: return False

    passed = [False] * L
    i = 0
    while True:
        while passed[i]:
            i += 1
            if i == L:
                return True

        for j, s in enumerate(sets):
            if j == i: continue
            if sets[i] & s:
                passed[i] = passed[j] = True
                break
        else:
            return False

print connected(s0)
print connected(s1)

rawDescription: Python set intersection question

description: Python set intersection question


code:
import json

array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
print data['fruits']
# the print displays:
# [u'apple', u'banana', u'orange']

rawDescription: Convert JSON array to Python list

description: Convert JSON array to Python list


code:
print u'\uC815\uC815'
print len(u'\uC815\uC815')
print len(u'\uC815\uC815'.encode('UTF-8'))
print len(u'\uC815\uC815'.encode('UTF-16-LE'))
print len(u'\uC815\uC815'.encode('UTF-16'))
print len(u'\uC815\uC815'.encode('UTF-32-LE'))
print len(u'\uC815\uC815'.encode('UTF-32'))

rawDescription: Get the number of bytes needed for a Unicode string


code:
import requests
response = requests.get('http://google.com/test')
response.status_code
if response.status_code == 404:
    print "/test/ does not exist on the website: google.com"

rawDescription: How do I find a page in python?

description: Find a page in python


code:
import numpy as np

v = np.random.randint(0, 10, 3)
print v

M = np.outer(v,v)
print M

rawDescription: Creating a matrix from vector replication, python


code:
1
5
7

from fractions import gcd

def coprime(n1, n2):
    return gcd(n1, n2) == 1 # same as if gcd(n1, n2) == 1:return True else: return False

with open("out.txt","a+") as f: # with automatically closes your files
    # add all previous numbers into a set, casting to int using map
    # map(int, f)  equivalent to [int(ele) for ele in f] in python2
    nums_set = set(map(int, f)) # with 1 5 and 7 in the file nums_set = set([1, 5, 7])
    i = 0
    j = 0

    num = int(raw_input("Please enter number "))
    limit = int(raw_input("Please enter limit "))

    while i < limit:
        if j not in nums_set and coprime(num,j):
            f.write("{}\n".format(j))
            print "{} is written on the text file.".format(j)
            i += 1
            j += 1
            # add current j's from this run to the set to avoid reopening and rechecking he file
            nums_set.add(j)
        else:
            j += 1

rawDescription: Python - read numbers from text file in a function


code:
from lxml import etree

source = """
<root>
<parent>
    <ID>1</ID>
    <child1>Value1</child1>
    <child2>value11</child2>
    <child3>
       <subchild>value111</subchild>
    </child3>
</parent>
<parent>
    <ID>2</ID>
    <child1>value2</child1>
    <child2>value22</child2>
    <child2>value333</child2>
</parent>
<parent>
    <ID>3</ID>
    <child1>value3</child1>
    <child2>value33</child2>
</parent>
<parent>
    <ID>4</ID>
    <child1>value4</child1>
    <child2>value44</child2>
</parent>
</root>
"""

document = etree.fromstring(source)
inserts = []

id_number = 3

for parent in document.findall('parent'):
    insert = {}
    cont = 0
    for element in parent.iterdescendants():
        if element.tag == 'ID':
            if element.text == str(id_number):
                cont = 1
        if element.getchildren() == []:
            insert[element.tag] = element.text
    if cont:
        inserts.append(insert)

print inserts

rawDescription: XML to MYSQL Using Python

description: XML to MYSQL Using Python


code:
l = [\
        {'a':25, 'b':0, 'c':25, 'd':66, 'e':41, 'f':47, 'g':40, 'h':12, 'i':69, 'j':76, 'k':1},\
        {'a':25, 'b':0, 'c':25, 'd':66, 'e':41, 'f':47, 'g':40, 'h':12, 'i':69, 'j':76, 'k':1}\
]
r = ['a=g=i', 'a=b', 'a=c']
res = []

# test all given rules
for n in range(0, len(r)):
        # i'm assuming equality here - you'd have to change this to accept other operators if needed
        c = r[n].split('=')
        vals = []
        # build up a list of values given our current rule
        for e in c:
                vals.append(l[0][e])
        # using len(set(v)) gives us the number of distinct values
        res.append({'rangeID': 0, 'ruleID':n, 'violation':'Y' if len(set(vals)) == 1 else 'N'})

print res

rawDescription: seek a better design suggestion for a trial-and-error mechanism in python?

description: Seek a better design suggestion for a trial-and-error mechanism in python


code:
from tornado import ioloop
import datetime

def f():
    print "Hi!"

i= ioloop.IOLoop.instance()
dt = datetime.timedelta(seconds=4)

ioloop.PeriodicCallback(f, 2000).start()
t = threading.Thread(target=i.start)
t.start()

rawDescription: IPython - Is it possible to use the Tornado ioloop?


code:
"""
opf: output file
inf: input file

use with instead of .open .close: http://effbot.org/zone/python-with-statement.htm

for naming rules and coding style in Python: https://www.python.org/dev/peps/pep-0008/
"""

import pickle

username = raw_input('Please enter a username:\n')
password = raw_input('Please enter a password:\n')

with open('username.txt', 'wb') as opf:
    pickle.dump(username, opf)

with open('username.txt') as inf:
    load_usernames = pickle.load(inf)
    print load_usernames

with open('password.txt', 'wb') as opf:
    pickle.dump(password, opf)

with open('password.txt') as inf:
    load_passwords = pickle.load(inf)
    print load_passwords

rawDescription: Am I using pickle correctly?-Python

description: Am I using pickle correctly?-Python


code:
from multiprocessing.pool import ThreadPool as Pool
import random
import time

def do_something(x):
    delay = random.randint(1,3)
    time.sleep(delay)
    return x,delay

for i, result in pool.imap_unordered(do_something, range(10)):
    print i, result

rawDescription: How to increase the efficiency when repetitively using connect()?

description: Increase the efficiency when repetitively using connect()


rawDescription: Python 2.7 findall() function to exclude finding for regular expression


rawDescription: Reshaping a numpy.array in Fortran-contiguous order


code:
sFields = gp.ListFields(linktofeatureclass)
for field in sFields:
    print field.Name, field.Type, field.Scale

rawDescription: ArcGIS: accessing python list output from listFields geoprocessor


code:
def example():
    generator = api.user-followed_by(as_generator=True, max_pages=None)
    for page in generator:
        print page #page will have the next 50 users, etc

rawDescription: Instagram API python user followed by

description: Instagram API python user followed by


code:
import mock
import setuptools

with mock.patch.object(setuptools, 'setup') as mock_setup:
    import setup  # This is setup.py which calls setuptools.setup

# called arguments are in `mock_setup.call_args`
args, kwargs = mock_setup.call_args
print kwargs.get('install_requires', [])

rawDescription: How to extract dependencies information from a setup.py

description: Extract dependencies information from a setup.py


code:
if __name__ == '__main__':
    from mpl import main
    raise SystemExit(main())

from matplotlib import use
use('GTK')
from matplotlib import pyplot

from matplotlib.backends import backend_gtk

from twisted.internet import gtk2reactor
gtk2reactor.install()

from twisted.internet import reactor, task

class TwistedGtkShow(backend_gtk.Show):
    running = False
    def mainloop(self):
        if not self.running:
            self.running = True
            reactor.run()

def main():
    pyplot.plot([1,2,3,4])
    pyplot.ylabel('some numbers')

    def proof():
        print 'Twisted!'
    task.LoopingCall(proof).start(3)

    TwistedGtkShow()()

rawDescription: How to run two python blocking functions matplotlib.show() and twisted.reactor.run()?

description: Run two python blocking functions matplotlib.show() and twisted.reactor.run()


code:
duration=input("Enter day duration here:")
amount=input("Enter the amount here:")

def make_decision(duration,amount):

    if (duration<=0 or amount <=0):
        print "Invalid value"
    elif (duration<30):
        if (amount>=50):
            corresponding_value = "Medium"

        elif (amount<50):
            corresponding_value = "Low"

    elif (duration>=30):
        if (amount>=50):
            corresponding_value = "High"
        elif (amount<50):
            corresponding_value = "High"

    return corresponding_value

# this is one option
print make_decision(duration,amount)
# another option could be
# result = make_decision(duration, amount)
# print result

rawDescription: Why my function doesn't return a value?

description: Why my function doesn't return a value


code:
def MyClass(object):
    def __init__(number):
        self.number=number

my_objects = []

for i in range(100) :
    my_objects.append(MyClass(i))

#later

for obj in my_objects :
    print obj.number

rawDescription: Creating a list of objects in Python

description: Creating a list of objects in Python


code:
import wave

info = wave.open('test.wav', 'r')
frames = info.getnframes()
rate = info.getframerate()
duration = frames / float(rate)

print duration

import wave
import io
import requests

url = "http://localhost/test.wav"
r = requests.get(url)
#To get a file like object from r.content we use "io.BytesIO"
infofile = wave.open(io.BytesIO(r.content), 'r')
frames = infofile.getnframes()
rate = infofile.getframerate()
duration = frames / float(rate)

print duration

rawDescription: Get length of MP3 file handle in Python

description: Get length of MP3 file handle in Python


code:
for row in sorted(data, key=getKey):
    print row['name']

rawDescription: How can I sort an array of sql produced tuples in Python

description: Sort an array of sql produced tuples in Python


code:
import asyncore, socket
from tlslite.api import *

s = open("./clientX509Cert.pem").read()
x509 = X509()
x509.parse(s)
certChain = X509CertChain([x509])

s = open("./clientX509Key.pem").read()
privateKey = parsePEMKey(s, private=True)

class http_client(TLSAsyncDispatcherMixIn, asyncore.dispatcher):
    ac_in_buffer_size = 16384

    def __init__(self, host, path):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect( (host, 80) )

        TLSAsyncDispatcherMixIn.__init__(self, self.socket)
        self.tlsConnection.ignoreAbruptClose = True
        handshaker = self.tlsConnection.handshakeClientCert(
            certChain=certChain,
            privateKey=privateKey,
            async=True)
        self.setHandshakeOp(handshaker)

        self.buffer = 'GET %s HTTP/1.0\r\n\r\n' % path

    def handle_connect(self):
        pass

    def handle_close(self):
        self.close()

    def handle_read(self):
        print self.recv(8192)

    def writable(self):
        return (len(self.buffer) > 0)

    def handle_write(self):
        sent = self.send(self.buffer)
        self.buffer = self.buffer[sent:]

c = http_client('www.readyhosting.com', '/')

asyncore.loop()

rawDescription: How do I use TLS with asyncore?

description: Use TLS with asyncore


code:
for match in re.finditer(statement, text):
    print match.span(1)

rawDescription: Python regex, match group span (start and end)


code:
import sys
import zorba_api

def example1(zorba):
  xquery = zorba.compileQuery("1+2")
  print xquery.printPlanAsXML()
  print xquery.execute()
  return

def example2(zorba):
  xquery = zorba.compileQuery("(1,2,3,4,5)")
  iter = xquery.iterator()
  iter.open()
  item = zorba_api.Item_createEmptyItem()
  while iter.next(item):
    print item.getStringValue()
  iter.close()
  iter.destroy()
  return

def example3(zorba):
  try:
    xquery = zorba.compileQuery("1 div 0")
    print xquery.execute()
  except RuntimeError, e:
    print e
  return

rawDescription: XQuery library under Python

description: XQuery library under Python


code:
import smtplib, sys

def notify(fromname, fromemail, toname, toemail, subject, body, password):
    fromaddr = fromname+" <"+fromemail+">"
    toaddrs = [toname+" <"+toemail+">"]
    msg = "From: "+fromaddr+"\nTo: "+toemail+"\nMIME-Version: 1.0\nContent-type: text/plain\nSubject: "+subject+"\n"+body

    # Credentials (if needed)
    username = fromemail
    password = password

    # The actual mail send
    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(username,password)
        server.sendmail(fromaddr, toaddrs, msg)
        server.quit()
        print "success"
    except smtplib.SMTPException:
        print "failure"

fromname = "Your Name"
fromemail = "yourgmailaccount@gmail.com"
toname = "Recipient"
toemail = "recipient@other.com"
subject = "Test Mail"
body = "Body....."

notify(fromname, fromemail, toname, toemail, subject, body, password)

rawDescription: Sending an Email with Python Issue

description: Sending an Email with Python Issue


code:
def base128_encode(n): # int/long to byte string
    if n > 0:
        arr = []
        while n:
            n, rem = divmod(n, 128)
            arr.append(chr(rem))
        return ''.join(reversed(arr))
    elif n == 0:
        return '\x00'
    else:
        raise ValueError

print [ord(c) for c in base128_encode(840)]  # --> [6, 72]

rawDescription: Python. Object Identifier conversion ASN1


code:
import os

outp = os.popen('php ./index.php')
text = outp.read() # this will block until php finishes
                   # and returns with all output in text
print text

rawDescription: Python and executing php files?

description: Python and executing php files


code:
# cdist example: (nx,dim) (ny,dim) -> (nx,ny)

from __future__ import division
import sys
import numpy as np
from scipy.spatial.distance import cdist

#...............................................................................
dim = 10
nx = 1000
ny = 100
metric = "euclidean"
seed = 1

    # change these params in sh or ipython: run this.py dim=3 ...
for arg in sys.argv[1:]:
    exec( arg )
np.random.seed(seed)
np.set_printoptions( 2, threshold=100, edgeitems=10, suppress=True )

title = "%s  dim %d  nx %d  ny %d  metric %s" % (
        __file__, dim, nx, ny, metric )
print "\n", title

#...............................................................................
X = np.random.uniform( 0, 1, size=(nx,dim) )
Y = np.random.uniform( 0, 1, size=(ny,dim) )
dist = cdist( X, Y, metric=metric )  # -> (nx, ny) distances
#...............................................................................

print "scipy.spatial.distance.cdist: X %s Y %s -> %s" % (
        X.shape, Y.shape, dist.shape )
print "dist average %.3g +- %.2g" % (dist.mean(), dist.std())
print "check: dist[0,3] %.3g == cdist( [X[0]], [Y[3]] ) %.3g" % (
        dist[0,3], cdist( [X[0]], [Y[3]] ))

# (trivia: how do pairwise distances between uniform-random points in the unit cube
# depend on the metric ? With the right scaling, not much at all:
# L1 / dim      ~ .33 +- .2/sqrt dim
# L2 / sqrt dim ~ .4 +- .2/sqrt dim
# Lmax / 2      ~ .4 +- .2/sqrt dim

rawDescription: Euclidean distance between points in two different Numpy arrays, not within


code:
import re
list = ["Protein XVZ [Human]","Protein ABC [Mouse]","go UDP[3] glucosamine N-acyltransferase [virus1]","Protein CDY [Chicken [type1]]","Protein BBC [type 2] [Bacteria] [cat] [mat]","gi p19-gag protein [2] [Human T-lymphotropic virus 2]"]
pattern = re.compile("\[(.*?)\]$")
for string in list:
    match = re.search(pattern,string)
    lastBracket = re.split("\].*\[",match.group(1))[-1]
    print lastBracket

rawDescription: Extract text between last occurrence of braces


code:
words1 = set(open("some1.txt").read().split())
words2 = set(open("some2.txt").read().split())

duplicates  = words1.intersection(words2)
uniques = words1.difference(words2).union(words2.difference(words1))

print "Duplicates(%d):%s"%(len(duplicates),duplicates)
print "\nUniques(%d):%s"%(len(uniques),uniques)

rawDescription: Diff and intersection reporting between two text files


code:
from math import sin, cos, asin, sqrt, degrees, radians

Earth_radius_km = 6371.0
RADIUS = Earth_radius_km

def haversine(angle_radians):
    return sin(angle_radians / 2.0) ** 2

def inverse_haversine(h):
    return 2 * asin(sqrt(h)) # radians

def distance_between_points(lat1, lon1, lat2, lon2):
    # all args are in degrees
    # WARNING: loss of absolute precision when points are near-antipodal
    lat1 = radians(lat1)
    lat2 = radians(lat2)
    dlat = lat2 - lat1
    dlon = radians(lon2 - lon1)
    h = haversine(dlat) + cos(lat1) * cos(lat2) * haversine(dlon)
    return RADIUS * inverse_haversine(h)

def bounding_box(lat, lon, distance):
    # Input and output lats/longs are in degrees.
    # Distance arg must be in same units as RADIUS.
    # Returns (dlat, dlon) such that
    # no points outside lat +/- dlat or outside lon +/- dlon
    # are <= "distance" from the (lat, lon) point.
    # Derived from: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates
    # WARNING: problems if North/South Pole is in circle of interest
    # WARNING: problems if longitude meridian +/-180 degrees intersects circle of interest
    # See quoted article for how to detect and overcome the above problems.
    # Note: the result is independent of the longitude of the central point, so the
    # "lon" arg is not used.
    dlat = distance / RADIUS
    dlon = asin(sin(dlat) / cos(radians(lat)))
    return degrees(dlat), degrees(dlon)

if __name__ == "__main__":

    # Examples from Jan Matuschek's article

    def test(lat, lon, dist):
        print "test bounding box", lat, lon, dist
        dlat, dlon = bounding_box(lat, lon, dist)
        print "dlat, dlon degrees", dlat, dlon
        print "lat min/max rads", map(radians, (lat - dlat, lat + dlat))
        print "lon min/max rads", map(radians, (lon - dlon, lon + dlon))

    print "liberty to eiffel"
    print distance_between_points(40.6892, -74.0444, 48.8583, 2.2945) # about 5837 km
    print
    print "calc min/max lat/lon"
    degs = map(degrees, (1.3963, -0.6981))
    test(*degs, dist=1000)
    print
    degs = map(degrees, (1.3963, -0.6981, 1.4618, -1.6021))
    print degs, "distance", distance_between_points(*degs) # 872 km

rawDescription: Python geocode filtering by distance

description: Python geocode filtering by distance


code:
""" A wire between input and output. """
import pyaudio
import sys
import webbrowser

# open the page
webbrowser.open(AUTOPLAY_URL)

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5

p = pyaudio.PyAudio()

stream = p.open(format = FORMAT,
            channels = CHANNELS,
            rate = RATE,
            input = True,
            output = True,
            frames_per_buffer = chunk)

print "* recording"
for i in range(0, 44100 / chunk * RECORD_SECONDS):
    data = stream.read(chunk)
    stream.write(data, chunk)
print "* done"

stream.stop_stream()
stream.close()
p.terminate()

rawDescription: Converting a Youtube Upload into Podcast


code:
credit = raw_input("Please input your change, CAREFUL! This Machine only accepts 10p,20p,50p and £1: ")
list1= ["1", "2", "3", "4", "5"]
price1 = 0.65
price2 = 0.70
price3 = 0.50
price4 = 0.70
price5 = 0.80
while credit == 0:
   credit = raw_input("Please input your change: ")
products = " 1) Kinder Bueno\n 2) Doritos Chilli Heatwave\n 3) Nestle Yorkie Bar\n 4) Coca Cola(Can)\n 5) Volvic Stawberry Water"
print credit
print "The product selection is the following"
print products
selection = raw_input("Please select a product: ")
if selection == list1[0]:
   new_credit = int(credit) - price1  # NOTE THE CHANGE HERE :)
   print new_credit

rawDescription: Error Message: TypeError: unsupported operand type(s) for -: 'str' and 'float'


code:
# simple test program (from the XML-RPC specification)
from xmlrpclib import ServerProxy, Transport, Error

class SpecialTransport(Transport):

    def send_content(self, connection, request_body):

        print "Add your headers here!"

        connection.putheader("Content-Type", "text/xml")
        connection.putheader("Content-Length", str(len(request_body)))
        connection.endheaders()
        if request_body:
            connection.send(request_body)

# server = ServerProxy("http://localhost:8000") # local server
server = ServerProxy("http://betty.userland.com", transport=SpecialTransport())

print server

try:
    print server.examples.getStateName(41)
except Error, v:
    print "ERROR", v

rawDescription: How to send custom http_headers for RPC calls using python xmlrpclib?

description: Send custom http_headers for RPC calls using python xmlrpclib


rawDescription: Use Python Re module to extract text from multiline


code:
import commctrl, win32con
from ctypes import *

# represent the TBBUTTON structure
# note this is 32 bit, 64 bit padds 4 more reserved bytes
class TBBUTTON(Structure):
    _pack_ = 1
    _fields_ = [
        ('iBitmap', c_int),
        ('idCommand', c_int),
        ('fsState', c_ubyte),
        ('fsStyle', c_ubyte),
        ('bReserved', c_ubyte * 2),
        ('dwData', c_ulong),
        ('iString', c_int),
    ]

# get the handle to the sytem tray
hWnd = windll.user32.FindWindowA("Shell_TrayWnd", None)
hWnd = windll.user32.FindWindowExA(hWnd, None, "TrayNotifyWnd", None)
hWnd = windll.user32.FindWindowExA(hWnd, None, "SysPager", None)
hWnd = windll.user32.FindWindowExA(hWnd, None, "ToolbarWindow32", None)

# get the count of icons in the tray
numIcons = windll.user32.SendMessageA(hWnd, commctrl.TB_BUTTONCOUNT, 0, 0)

# allocate memory within the system tray
pid = c_ulong();
windll.user32.GetWindowThreadProcessId(hWnd, byref(pid))
hProcess = windll.kernel32.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, pid)
lpPointer = windll.kernel32.VirtualAllocEx(hProcess, 0, sizeof(TBBUTTON), win32con.MEM_COMMIT, win32con.PAGE_READWRITE)

# init our tool bar button and a handle to it
tbButton = TBBUTTON()
butHandle = c_int()

for i in range(numIcons):
    # query the button into the memory we allocated
    windll.user32.SendMessageA(hWnd, commctrl.TB_GETBUTTON, i, lpPointer)
    # read the memory into our button struct
    windll.kernel32.ReadProcessMemory(hProcess, lpPointer, addressof(tbButton), 20, None)
    # read the 1st 4 bytes from the dwData into the butHandle var
    # these first 4 bytes contain the handle to the button
    windll.kernel32.ReadProcessMemory(hProcess, tbButton.dwData, addressof(butHandle), 4, None)

    # get the pid that created the button
    butPid = c_ulong()
    windll.user32.GetWindowThreadProcessId(butHandle, byref(butPid))

    # i leave it to you to get the process from the pid
    # that should be trivial...
    print butPid

rawDescription: windows executables corresponding to system tray icons?

description: Windows executables corresponding to system tray icons


code:
from datetime import datetime
from pytz import timezone
import pytz

date_format='%m/%d/%Y %H:%M:%S %Z'
date = datetime.now(tz=pytz.utc)
print 'Current date & time is:', date.strftime(date_format)

date = date.astimezone(timezone('US/Pacific'))

print 'Local date & time is  :', date.strftime(date_format)

rawDescription: need to convert UTC (aws ec2) to PST in python

description: Need to convert UTC (aws ec2) to PST in python


code:
# reset the `totalintron` for the current `exonnumber`
totalintron = 0

# only iterate `exonnumber - 1` (which is guaranteed to be len(y) - 1 at max)
for index in range(exonnumber - 1):
    first_max = max(y[index])
    second_min = min(y[index + 1])
    intron = second_min - first_max
    # don’t print `intron`, we only care about the total
    totalintron = totalintron + intron

print totalintron

rawDescription: Specifying amount of numbers to sum in loop


code:
#!/usr/bin/env python

d = {
    'key1' : ['A', 'B', 'C'],
    'key2' : ['B', 'A', 'G'],
    'key3' : ['Z', 'H', 'I']
}

l = ['A', 'A', 'B', 'D']

uniq_l = set(l) # you don't need to check duplicates twice

for key, value in d.items():
    if value[0] in uniq_l:
        print "Match", key, value

# Output:
# Match key2 ['B', 'A', 'G']
# Match key1 ['A', 'B', 'C']

rawDescription: Perform actions on dictionary values that match items in a list?


code:
urls = (
    '/(.+)', 'your_handler_class'
)

class your_handler_class:
    def GET(self, page):
        print web.template.render('%s.html' % page)

rawDescription: web.py define /x to go to x.html in templates?

description: Web.py define /x to go to x.html in templates


code:
import signal
import os
import time
import threading
import random

class TerminationManager(object):

    def __init__(self):
        self._running = True
        self._requests = 0
        self._lock = threading.Lock()
        signal.signal(signal.SIGTERM, self._start_shutdown)

    def _start_shutdown(self, signum, stack):
        print 'Received:', signum
        self._running = False

    def start_request(self):
        with self._lock:
            self._requests += 1

    def stop_request(self):
        with self._lock:
            self._requests -= 1

    def is_running(self):
        return self._running or self._requests > 0

    def running_requests(self):
        return self._requests

class DummyWorker(threading.Thread):

    def __init__(self, app_manager):
        super(DummyWorker, self).__init__()
        self._manager = app_manager

    def run(self):
        while self._manager.is_running():
            # Emulate random work and delay between requests.
            if random.random() > 0.9:
                self._manager.start_request()
                time.sleep(random.randint(1, 3))
                self._manager.stop_request()
            else:
                time.sleep(1)
        print "Stopping worker"

manager = TerminationManager()
print 'My PID is:', os.getpid()

for _ in xrange(10):
    t = DummyWorker(manager)
    t.start()

while manager.is_running():
    print 'Waiting with {} running requests'.format(manager.running_requests())
    time.sleep(5)

print 'All done!'

rawDescription: How do I handle dyno restarts when using Django?

description: Handle dyno restarts when using Django


code:
#!/usr/bin/env python
print """Content-type: text/html

<title>Redirect</title>

%s/%s
"""%(os.environ['HTTP_HOST'], os.environ['REQUEST_URI'])

rawDescription: CGI Script that prints out an incoming param


code:
import numpy as np
import scipy.optimize

mat = np.random.randn(5, 7)

def F(x):
    y = np.dot(mat, x)
    return np.resize(np.array([ y[0]**2 + y[1]**3 + 12, y[2] + 17]), 7)

while True:
    x0 = np.random.randn(7)
    r = scipy.optimize.leastsq(F, x0)
    err = F(r[0])
    norm =  np.dot(err, err)
    if norm < 1e-6:
        break

print err

rawDescription: SciPy optimization for under-constrained system


code:
from __future__ import division

def print_purchase(arg1, arg2, arg3):
    print """You bought %r products and paid %r,
             for an average of %d""" % (arg1, arg2, arg3)
try:
    quantity = float(raw_input("How many products did you buy?"))
    cost = float(raw_input("How much did you pay?"))
except (TypeError, ValueError):
    print ("Not numeric. Try Again.")

print_purchase(quantity, cost, average)
average = quantity/cost

rawDescription: Unsupported operand type in Python

description: Unsupported operand type in Python


code:
"""
Protects a Module against naive monkey patching  -
may be usefull for debugging large projects where global
variables change without notice.

Just call the "ProtectedModule"  class, with no parameters from the end of
the module definition you want to protect, and subsequent assignments to it
should fail.

"""

from types import ModuleType
from inspect import currentframe, getmodule
import sys

class ProtectedModule(ModuleType):
    def __init__(self, module=None):
        if module is None:
            module = getmodule(currentframe(1))
        ModuleType.__init__(self, module.__name__, module.__doc__)
        self.__dict__.update(module.__dict__)
        sys.modules[self.__name__] = self

    def __setattr__(self, attr, value):
        frame = currentframe(1)
        raise ValueError("Attempt to monkey patch module %s from %s, line %d" %
            (self.__name__, frame.f_code.co_filename, frame.f_lineno))

if __name__ == "__main__":
    from xml.etree import ElementTree as ET
    ET = ProtectedModule(ET)
    print dir(ET)
    ET.bla = 10
    print ET.bla

rawDescription: Python imported module is None

description: Python imported module is None


code:
from itertools import combinations
for a, b in combinations(bodies.values(), 2):
    print a, b

rawDescription: How to iterate over each pair of items in a dictionary

description: Iterate over each pair of items in a dictionary


code:
import re

str = """

  Full name Foobar

  Born July 7, 1923, foo, bar

  Current age 27 years 226 days

  Major teams Japan, Jakarta, bazz, foo, foobazz

  Also bar

  foo style hand

  bar style ball

  foo position bak

"""

R_EXTRACT_DATA = re.compile("]*>[\s]*(.*?)[\s]*[\s]*(.*?)[\s]*
", re.IGNORECASE)
R_STRIP_TAGS = re.compile("]*>|", re.IGNORECASE)

def strip_tags(str):
    """Strip un-necessary  tags
    """
    return R_STRIP_TAGS.sub("", str)

def get_info(str):
    """Extract useful info from the given string
    """
    data = R_EXTRACT_DATA.findall(str)
    data_dict = {}

    for x in [(x[0], strip_tags(x[1])) for x in data]:
        data_dict[x[0]] = x[1]

    return data_dict

print get_info(str)

rawDescription: How do i extract my required data from HTML file?

description: Extract my required data from HTML file


code:
i = 5
if i > 5:
    print "i is greater than 5."
else:
    print "i is less than or equal to 5."

hash = {'a': 1, 'b': 2, 'monkey': 3, 42: 'the answer'}
print hash['a']
print hash[42]

for item in hash:
    print item.Key, '=>', item.Value

rawDescription: What statically typed languages are similar to Python?


code:
import pdb
def test():
    print 1
    pdb.set_trace() # you will enter an interpreter here
    print 2

rawDescription: What's the best way to record the type of every variable assignment in a Python program?


code:
import inspect

def foo():
  return 'foo'

def bar():
  yield 'bar'

print inspect.isgeneratorfunction(foo)
print inspect.isgeneratorfunction(bar)

rawDescription: In python is there a way to check if a function is a "generator function" before calling it?


code:
string = "g fmnc wms bgblr rpylqjyrc gr zw fylb."
print string
answer = []
for i in string:
    if i.isalpha():
        if ord(i)>120:
            answer.append(chr(ord(i)-24))
        else:
            answer.append(chr(ord(i)+2))
    else:
        answer.append(i)
print ''.join(answer)

rawDescription: String Manipulation Python

description: String Manipulation Python


code:
import os
from os.path import join, getsize, getmtime

oldest_file, oldest_file_mtime = None, 9999999999
largest_file, largest_file_size = None, 0

for root, dirs, files in os.walk('/your/root'):
    for name in files:
        a_file = join(root, name)
        if getmtime(a_file) < oldest_file_mtime:
            oldest_file_mtime = getmtime(a_file)
            oldest_file = a_file
        if getsize(a_file) > largest_file_size:
            largest_file_size = getsize(a_file)
            largest_file = a_file

print "oldest file is: ", oldest_file
print "largest file is: ", largest_file

rawDescription: Find files which are oldest and have maximum size in python on SUNOS


code:
import requests
from bs4 import BeautifulSoup

url = "http://www.amazon.in/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=python"
source_code = requests.get(url)
plain_text = source_code.content
soup = BeautifulSoup(plain_text, "lxml")
links = soup.findAll('a', {'class': 'a-link-normal s-access-detail-page a-text-normal'})
print len(links)
for link in links:
    title = link.get('title')
    print title

rawDescription: Using BeautifulSoup to extract the title of a link


code:
for elem in cmp_data['company']:
    print elem

rawDescription: Outputting a list one element per line

description: Outputting a list one element per line


code:
from xml.dom import minidom

src = """
<Schedule Season="2010" Timezone="Eastern">
  <Game gameId="1" Week="1" GameDate="2010-09-09" AwayTeam="MIN" HomeTeam="NO" GameTime="8:30 PM"/>
  <Game gameId="2" Week="1" GameDate="2010-09-12" AwayTeam="MIA" HomeTeam="BUF" GameTime="1:00 PM"/>
  <Game gameId="3" Week="1" GameDate="2010-09-12" AwayTeam="DET" HomeTeam="CHI" GameTime="1:00 PM"/>
  <Game gameId="4" Week="1" GameDate="2010-09-12" AwayTeam="OAK" HomeTeam="TEN" GameTime="1:00 PM"/>
</Schedule>
"""

def test_print(dom):
    for node in dom.getElementsByTagName('Game'):
        print node.getAttribute('AwayTeam'),
        print node.getAttribute('HomeTeam'),
        print node.getAttribute('Week'),
        print node.getAttribute('gameId'),
        print node.getAttribute('GameDate'),
        print node.getAttribute('GameTime')
    print ''

dom = minidom.parseString(src)
test_print(dom)

dom = minidom.parse('data.xml')
test_print(dom)

f = open('data.xml', 'r')
dom = minidom.parse(f)
test_print(dom)
f.close()

url = 'http://api.fantasyfootballnerd.com/ffnScheduleXML.php?apiKey=1'
dom = minidom.parse(urllib2.urlopen(url))
test_print(dom)

rawDescription: python minidom parse XML feed with colon in results

description: Python minidom parse XML feed with colon in results


code:
import numpy as np
import scipy.integrate as integrate
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

#define universal variables
c0 = 15.6
c1 = 1.0
c2 = 28.0
m0 = -1.143
m1 = -0.714

#just a little extra, quite unimportant
def f(x):
    f = m1*x+(m0-m1)/2.0*(abs(x+1.0)-abs(x-1.0))
    return f

#the actual function calculating
def dH_dt(H, t=0):
    return np.array([c0*(H[1]-H[0]-f(H[0])),
                  c1*(H[0]-H[1]+H[2]),
                  -c2*H[1]])

#computational time steps
t = np.linspace(0, 30, 1000)
#x, y, and z initial conditions
H0 = [0.7, 0.0, 0.0]

H, infodict = integrate.odeint(dH_dt, H0, t, full_output=True)

print infodict['message']

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(H[:,0], H[:,1], H[:,2])
plt.show()

rawDescription: Solving system of ODE's using python and graphing (Chua's circuit)


code:
from xml.dom import minidom

t = minidom.parseString('')

def patcher(method):
  def patching(self, *args, **kwargs):
    old = self.childNodes
    try:
      if not self.childNodes:
        class Dummy(list):
          def __nonzero__(self):  # Python2
            return True
          def __bool__(self):  # Python3
            return True
        old, self.childNodes = self.childNodes, Dummy([])
      return method(self, *args, **kwargs)
    finally:
      self.childNodes = old
  return patching

t.firstChild.__class__.writexml = patcher(t.firstChild.__class__.writexml)

print t.toprettyxml()

rawDescription: Python - print pretty XML create opening and closing tags for empty tags text


code:
def is_wombats(x):
    if x.lower() == "wombat":
        print "yay wombats"
    else:
        print "no wombats"
    print "I love wombats"
is_wombats("WOMbat")

rawDescription: Executing code after if/else

description: Executing code after if/else


code:
def largest():
    f = pickAFile()
    sound = makeSound(f)
    value = [getSampleValueAt(sound, i) for i in range(1, getLength(sound))]
    print max(value)
    print min(value)
    print value.count(0)

rawDescription: Max Sample Value (sound file) python

description: Max Sample Value (sound file) python


code:
k = [{
    "id": 1,
    "title": "node1",
    "parent": "null"
},
{
    "id": 2,
    "title": "node2",
    "parent": 1
},
{
    "id": 3,
    "title": "node3",
    "parent": 1
},
{
    "id": 4,
    "title": "node4",
    "parent": 2
},
{
    "id": 5,
    "title": "node5",
    "parent": 2
}]

result, t = [], {}

for i in k:
    i['childs'] = []
    if i['parent'] == 'null':
        del i['parent']
        result.append(i)
        t[1] = result[0]
    else:
        t[i['parent']]['childs'].append(i)
        t[i['id']] = t[i['parent']]['childs'][-1]
        del t[i['parent']]['childs'][-1]['parent']

print result

rawDescription: converting list of dictionary to dictionary tree based on parent id

description: Converting list of dictionary to dictionary tree based on parent id


code:
import csv
with open('some.csv', 'rb') as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        print row

rawDescription: Python script to convert csv to dump into database


rawDescription: minimal elements in heap for Python

description: Minimal elements in heap for Python


code:
from datetime import datetime
from pytz import timezone, all_timezones

def to_timezone(dt, tz):
  assert dt.tzinfo is not None
  assert tz in all_timezones
  return dt.astimezone(timezone(tz))

print to_timezone(datetime.now(timezone('UTC')), 'Europe/Amsterdam')

rawDescription: Python difference between timezones

description: Python difference between timezones


code:
import math
import csv

x = 2.0
with open('out.csv', 'wb') as f:
    writer = csv.writer(f, delimiter=',')
    while x < 100.0:
        print x, '\t', math.log(x)/math.log(2)
        writer.writerow([x, math.log(x)/math.log(2)])
        x = x + x

rawDescription: Export a table in CSV file

description: Export a table in CSV file


code:
for i in dict.keys():
    print "Group", i
    for j in dict[i].keys():
        print "Item", j, "Value", dict[i][j]

rawDescription: accessing specific elements from python dictionary

description: Accessing specific elements from python dictionary


code:
import operator
ops = { "+": operator.add, "-": operator.sub } # etc.

print ops["+"](1,1) # prints 2

rawDescription: Python:: Turn string into operator

description: Python:: Turn string into operator


rawDescription: How to format a tupled list in Python 2.7?

description: Format a tupled list in Python 2.7


code:
word = raw_input("Enter the magic word:")
word = word if word.startswith('b') else 'b' + word
print "your magic word is %s" % (word)

rawDescription: How to check for a letter in raw_input

description: Check for a letter in raw_input


code:
for file in list_file:
  outStat="path_for_sum_output"
  arcpy.Statistics_analysis(file,outStat, [["field_value", "SUM"]])
  rowsStat = arcpy.SearchCursor(outStat)
  for row in rowsStat:
     sum=row.getValue('Sum_field_value')

  #formate name of file so the format match with field ID_old of the feature class
  namelist=file.split('_')
  myname=' '.join(namelist)
  print myname

  fc='big_file'
  cursor=arcpy.da.UpdateCursor(fc,['Sum_value'], "ID_old = '" +myname+ "'")
  for row in cursor:
      row[0]= sum
      cursor.updateRow(row)
      print row

rawDescription: python-in-arcmap, how to query using row ID and look for field values from another feature class

description: Python-in-arcmap, how to query using row ID and look for field values from another feature class


code:
from lxml import html
root = html.parse(open('your/file.html')).getroot()

sibling_content = lambda x: [b.getparent().getnext().text_content() for b in
                             root.cssselect("td b:contains('{0}')".format(x))]

fields = ['notificationNodeName', 'packageName', 'notificationEnabled']

for item in zip(*[sibling_content(field) for field in fields]):
    print item

rawDescription: Best way to remove remove values from variable? create an array, or using regex? or with Xpath?

description: Remove remove values from variable? create an array, or using regex? or with Xpath


code:
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

def on_click(event):
    if event.inaxes is not None:
        print event.xdata, event.ydata
    else:
        print 'Clicked ouside axes bounds but inside plot window'

fig, ax = plt.subplots()
fig.canvas.callbacks.connect('button_press_event', on_click)
plt.show()

#Define map projection
m = Basemap(projection='cyl', llcrnrlat=-90, urcrnrlat=90,
            llcrnrlon=-180, urcrnrlon=180, resolution='c')
m.drawcoastlines()

rawDescription: Using basemap as a figure in a Python GUI


code:
from datetime import datetime
input = "Sat Sep 19 15:18:51 2015"
# See if you can replace parse_format string with "%c"
parse_format = "%a %b %d %H:%M:%S %Y"
output_format = "%Y%m%d"
datetimeobj = datetime.strptime(input, parse_format)
output = datetimeobj.strftime(output_format)
print output

rawDescription: Reformat string containing date and time to date only in Python 2.7


code:
from flask import Flask, render_template_string
from flaskext.wtf import Form, SelectField

app = Flask(__name__)
app.debug = True
app.secret_key = 's3cr3t'

class AddToReportForm(Form):
    selectReportField = SelectField(u'Reports', choices=[('test1', 'test')])

@app.route('/test', methods=['GET', 'POST'])
def test():
    form = AddToReportForm()
    if form.validate_on_submit():
        print 'OK'
    return render_template_string('''\
<form method=post name="test">
{{ form.hidden_tag()}}
{{ form.selectReportField }}
<input type="submit">
</form>
''', form=form)

app.run(host='0.0.0.0')

rawDescription: Flask-WTF SelectField with CSRF protection enabled


code:
import json

l1 = ['aa','bb','cc']
s = json.dumps(l1)
l2 = json.loads(s)

print s
print l1 == l2

rawDescription: Python - String to list

description: Python - String to list


code:
#!/usr/bin/python
#imports dictionary of pairs, then replaces those which aren't Title_

import csv

infile1dict = {} # dict for the library to replace as (key, value)
with open('infile1.tsv','r') as tsvin:
    tsvin = csv.reader(tsvin, delimiter='\t') # imports the file as a tsv
    for row in tsvin: # each row in the tab-delimited input file
        infile1dict.update({row[0]:row[1]}) # use 1st row (0) as key, use 2nd row (1) as value in the dictionary
    print (infile1dict)

inlist = [] # list to be tested against the dict library
with open('infile2.tsv','r') as inlist:
    inlist = [line.strip() for line in inlist.readlines()] # strips off the \n, grabs each line as an item
    print (inlist)

outlist = [] # list for each item to be added into
for item in inlist:
    if 'Title_' in item:
        print 'Item %s will go directly into the output list.' % item
        itmstr = "".join(item) # converts item tuple to item string for append function
        outlist.append(itmstr) # adds item to the output list from input file list
    if not 'Title_' in item:
        print 'Item %s will be replaced with the dictionary.' % item
        correction = infile1dict.get(item, "The inlist's item was not a key in the dictionary.")
        outlist.append(correction) # adds the correction string to the list
        print('\t'.join(map(str,outlist)))
with open('out-complete.txt', 'w') as outobj:
    outobj.writelines('\n'.join(map(str,outlist)))

rawDescription: How do I fix a list (sometimes incorrect) using a dictionary?

description: Fix a list (sometimes incorrect) using a dictionary


code:
def friends_count(candidate):
    di = {k:sum(1 for x in v if x) for k,v in candidate.items()}
    for key in sorted(di): print "%s %s" % (key.rjust(20," "),str(di[key]).rjust(4," "))

rawDescription: printing format in python - expected left allignment

description: Printing format in python - expected left allignment


code:
text = "$email = 'hello '.$user1_35.' we would like to annoy you '.$Tod-ay.' for 20 minutes.';"
res = re.findall("'\.(\$[\w-]*)\.'", text)
print res #['$user1_35', '$Tod-ay']

rawDescription: Find php string concatenation using python regex


code:
def scroll_down_element(self, element, times):
    try:
        action = ActionChains(self.browser)
        action.move_to_element(element).perform()
        element.click()
        for _ in range(times):
            element.send_keys(Keys.SPACE)
            sleep(0.1)
    except Exception as e:
        print 'error scrolling down web element', e

rawDescription: Scroll down html table using selenium and python


code:
data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
new_list = []

while data_list:
    minimum = data_list[0]  # arbitrary number in list
    for x in data_list:
        if x < minimum:
            minimum = x
    new_list.append(minimum)
    data_list.remove(minimum)

print new_list

rawDescription: python: order a list of numbers without built-in sort, min, max function

description: Python: order a list of numbers without built-in sort, min, max function


code:
username = driver.find_element_by_id("cu_first_name")
value = username.get_attribute('value')

print value

rawDescription: How can I extract an HTML form value?

description: Extract an HTML form value


code:
names = ['brad', 'scott', 'bryan']
colors = ['red', 'orange', 'green']
ages = [20, 25, 23]
for name, color, age in zip(names, colors, ages):
    print name, color, age

rawDescription: Map values of 3 lists in python

description: Map values of 3 lists in python


code:
class A(object):
    def test(self):
        print "orig"
first_a = A()
first_a.test()
def decorated_test(fn):
    def new_test(*args, **kwargs):
        fn(*args, **kwargs)
        print "new"
    return new_test
A.test = decorated_test(A.test)
new_a = A()
new_a.test()
first_a.test()

rawDescription: Python add to a function dynamically

description: Python add to a function dynamically


code:
import pyinotify
import re
import os

wm = pyinotify.WatchManager()
mask = pyinotify.IN_MODIFY

class EventHandler (pyinotify.ProcessEvent):

    def __init__(self, file_path, *args, **kwargs):
        super(EventHandler, self).__init__(*args, **kwargs)
        self.file_path = file_path
        self._last_position = 0
        logpats = r'I2G\(JV\)'
        self._logpat = re.compile(logpats)

    def process_IN_MODIFY(self, event):
        print "File changed: ", event.pathname
        if self._last_position > os.path.getsize(self.file_path):
            self._last_position = 0
        with open(self.file_path) as f:
            f.seek(self._last_position)
            loglines = f.readlines()
            self._last_position = f.tell()
            groups = (self._logpat.search(line.strip()) for line in loglines)
            for g in groups:
                if g:
                    print g.string

handler = EventHandler('some_log.log')
notifier = pyinotify.Notifier(wm, handler)

wm.add_watch(handler.file_path, mask)
notifier.loop()

rawDescription: python monitor a log file non blocking

description: Python monitor a log file non blocking


code:
import sys
import tweepy

## OAuth keys go here.

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)

printed_ids = []

def ask_bot():
    old_id = 0
    for tweet in api.mentions():
        if tweet.id not in printed_ids:
            print "@%s: %s" % (tweet.author.screen_name, tweet.text)
            printed_ids.append(tweet.id)
        else:
            pass

rawDescription: Python save state in a for loop for a twitter bot


code:
def bin(x):
    """
    bin(number) -> string

    Stringifies an int or long in base 2.
    """
    if x < 0:
        return '-' + bin(-x)
    out = []
    if x == 0:
        out.append('0')
    while x > 0:
        out.append('01'[x & 1])
        x >>= 1
        pass
    try:
        return '0b' + ''.join(reversed(out))
    except NameError, ne2:
        out.reverse()
    return '0b' + ''.join(out)

rawDescription: Backport of builtin function bin() for python 2.4


code:
s = [None]*10
def func():
    for i in range(10):
        def update(i=i):
            print i,
        s[i] = update

func()
for i in range(10):
    s[i]()

rawDescription: About the running result of the following code (Python, less than 10 lines)


rawDescription: Selecting some rows of an nparray under column constraints


code:
from collections import OrderedDict

l = ['a', 'a', 'a', 'b', 'b', 'c', 'd']
d = OrderedDict()

for x in l:
    d[x] = True

# prints a b c d
for x in d:
    print x,
print

rawDescription: Ordered Sets Python 2.7

description: Ordered Sets Python 2.7


code:
source = open('urls.txt')
key_values = ("http://",""), ("https://",""), ("www.",""), ("\n","")

#Remove stuff
print "Cleaning list"
def multiple_replacer(key_values):
  replace_dict = dict(key_values)
  replacement_function = lambda match: replace_dict[match.group(0)]
  pattern = re.compile("|".join([re.escape(k) for k, v in key_values]), re.M)
  return lambda string: pattern.sub(replacement_function, string)

multi_line = multiple_replacer(key_values)

print "Querying Database..."
records = []
for line in source:
  brand_url = multi_line(line)
  #Run Query with cleaned list
  mysql_query = ("select ub.url as 'URL', b.name as 'Name', b.id as 'ID' from api.brand b join api.url_brand ub on b.id=ub.brand_id where ub.url like '%%%s%%' and b.deleted=0 group by 3;" % brand_url)
  brands = my_query('prod', mysql_query)
  #Append results to dict (records)
  for row in brands:
      records.append({"URL":row['URL'],"Name":row['Name'],"ID":row['ID']})

#Create DataFrame
df = pd.DataFrame.from_dict(records)

#Create CSV
output = df.to_csv('ongoing.csv',index=False)

rawDescription: Q: Pandas dataframe from for loop

description: Q: Pandas dataframe from for loop


code:
b = QtCore.QByteArray.fromPercentEncoding('abc%20.def%C3%A4.ghi')
b.data()
s = b.data().decode('utf8')
print s

rawDescription: PyQt QString masks special characters and does not display correctly


code: print tuple(address_result[0]) == ('1819 Harras Blvd', '', 'Atlantic City', 'NJ', '08401')

rawDescription: python comparing database results against strings

description: Python comparing database results against strings