code:
import os
path = '/path/2/foo'
filenames = os.listdir(path)

rawDescription: ipython, from bash to variable

description: Ipython, from bash to variable


code:
class Tutor:
    firstName = ""
    lastName = ""
    age = 0
    primarySubjects = []
    secondarySubjects = []

rawDescription: Creating a Class with variable properties


code:
numbers = list(range(1, 101)) # all the numbers in the bag, from 1 to 100
random.shuffle(numbers)       # shake the bag
bingo_num = numbers.pop()     # pull out next number (inside your loop)

rawDescription: Repeated Random Numbers

description: Repeated Random Numbers


code:
import os

def onemore():
    f = __file__ + '.counter'
    if os.path.exists(f):
        with open(f) as thefile:
            counter = int(thefile.read())
    else:
        counter = -1
    counter += 1
    with open(f, 'w') as thefile:
        thefile.write(str(counter) + '\n')
    return counter

rawDescription: Python: JobID counter

description: Python: JobID counter


code: [index[0], slice(None), index[1], index[2]]

rawDescription: Array Assignment in numpy / : colon equivalent


code:
local_path = tempfile.mkdtemp().decode("utf-8")
self.addCleanup(shutil.rmtree, local_path)
acl = "d:u:{0}:rwX".format(os.geteuid())
subprocess.check_call(["setfacl", "-m", acl, local_path])

rawDescription: Ensuring a test case can delete the temporary directory it created


rawDescription: Using Integer as Array Name in Python

description: Using Integer as Array Name in Python


code:
#!/usr/bin/env python
import os
from gi.repository import Gtk
from gi.repository import AppIndicator3

class AppIndicatorExample:
    def __init__(self, indicator_id):
        self.ind = AppIndicator3.Indicator.new(str(indicator_id), os.path.abspath('sample_icon.svg'), AppIndicator3.IndicatorCategory.SYSTEM_SERVICES)
        self.ind.set_status(AppIndicator3.IndicatorStatus.ACTIVE)

        # create a menu
        self.menu = Gtk.Menu()

        item = Gtk.MenuItem(str(indicator_id))
        item.show()
        self.menu.append(item)

        image = Gtk.ImageMenuItem(Gtk.STOCK_QUIT)
        image.connect("activate", self.quit)
        image.show()
        self.menu.append(image)

        self.menu.show()

        self.ind.set_menu(self.menu)

    def quit(self, widget, data=None):
        Gtk.main_quit()

if __name__ == "__main__":
    indicator = AppIndicatorExample(1)
    indicator2 = AppIndicatorExample(2)
    indicator3 = AppIndicatorExample(3)
    indicator4 = AppIndicatorExample(4)
    indicator5 = AppIndicatorExample(5)
    indicator6 = AppIndicatorExample(6)
    indicator7 = AppIndicatorExample(7)
    indicator8 = AppIndicatorExample(8)

    Gtk.main()

rawDescription: Ctreate two or more panel indicator using python gtk3 appindicator


code:
import pylab as pl
import numpy as np

a = np.array([[0,1]])
pl.figure(figsize=(9, 1.5))
img = pl.imshow(a, cmap="Blues")
pl.gca().set_visible(False)
cax = pl.axes([0.1, 0.2, 0.8, 0.6])
pl.colorbar(orientation="h", cax=cax)
pl.savefig("colorbar.pdf")

rawDescription: Standalone colorbar (matplotlib)

description: Standalone colorbar (matplotlib)


code:
def draw_circle(event,x,y,flags,param):
 global ix,iy,drawing

 if event == cv2.EVENT_LBUTTONDOWN:
   drawing= True
   ix,iy=x,y
 elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
   if drawing:
     cv2.line(img,(ix,iy),(x,y),(0,0,0), 3)
     ix,iy = x,y
 elif event == cv2.EVENT_LBUTTONUP:
   drawing == False

rawDescription: how to solve discontinuous line when drawing with python

description: Solve discontinuous line when drawing with python


code:
test = test.reset_index()
del test['index']

rawDescription: Cannot reset Pandas index

description: Cannot reset Pandas index


rawDescription: PIL paste image without blur

description: PIL paste image without blur


code:
class Monolithic(TestCase):
  def step1(self):
      ...

  def step2(self):
      ...

  def _steps(self):
    for name in sorted(dir(self)):
      if name.startswith("step"):
        yield name, getattr(self, name)

  def test_steps(self):
    for name, step in self._steps():
      try:
        step()
      except Exception as e:
        self.fail("{} failed ({}: {})".format(step, type(e), e))

rawDescription: Python unittest.TestCase execution order


rawDescription: What is this array and can I change it to a list?


code:
def get_tl(self,x):

    def tl():
        self.label_tl = Label(self, text="length:").grid(row=1,column=0)
        self.show_tl = Label(self, text=self.var_tl.get()).grid(row=1,column=1)

    if x == "Random (max = 6)":
        self.var_tl.set(randint(1,6))
        tl()
    else:

        ask_tl = Toplevel()
        def destroy_t_set_tl():
            self.var_tl.set(entry_tl_t.get())
            ask_tl.destroy()
            tl()

        label_tl_t = Label(ask_tl, text="length:").pack(side=LEFT)
        entry_tl_t = Entry(ask_tl, width=25)
        entry_tl_t.pack(side=LEFT)
        button_enter_tl_t = Button(ask_tl, text="Enter", command=destroy_t_set_tl).pack(side=LEFT)

def get_values(self):

    self.total_label = Label(self, text=self.var_tl.get()).grid(row=4,column=0)

rawDescription: Python Tkinter label widget doesn't update


rawDescription: Set linewidth and facecolor of an AnchoredOffsetbox?


code:
import datetime

def num_monday_the_first_between(start, end):
    y, m, d = start.year, start.month, 1
    count = 0
    while (y, m, d) <= (end.year, end.month, end.day):
        if datetime.date(y, m, d).isoweekday() == 1:
            count += 1
        m += 1
        if m == 13:
            m = 1
            y += 1
    return count

print(num_monday_the_first_between(datetime.date(2015,1,1), datetime.date(2015,12,31)))
# Result: 1 (June)

rawDescription: Calculate how many Monday the 1st between two dates


code:
import numpy as np
dQdx = np.asarray([0, 0, 0.2, 0.1])
dQdt = np.asarray([0.1 , 0, 0.4, 0])
V = np.where(np.logical_and(dQdt, dQdx), dQdt/dQdx, 0)
V

rawDescription: Numpy: Calculate an expression at specific array positions


rawDescription: List of List to ndarray

description: List of List to ndarray


code:
from bs4 import BeautifulSoup
import requests

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
r=requests.get('http://www.transfermarkt.com/arsenalfc/startseite/verein/11/saison_id/2015', headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
print(soup.prettify())

rawDescription: Scraping using beautiful soup not working for a particular URL as expected


code:
import wave

CHANNELS = 1
swidth = 2
Change_RATE = 2

spf = wave.open('VOZ.wav', 'rb')
RATE=spf.getframerate()
signal = spf.readframes(-1)

wf = wave.open('changed.wav', 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(swidth)
wf.setframerate(RATE*Change_RATE)
wf.writeframes(signal)
wf.close()

rawDescription: Increase/Decrease Play Speed of a WAV file Python


code:
from __future__ import print_function
def f(x, y): pass
f(print(1), print(2))
[print(1), print(2)]
{1:print(1), 2:print(2)}
def f(x=print(1), y=print(2)): pass

rawDescription: Is it safe to rely on python function arguments evaluation order?


code:
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

def disableImages(self):
    ## get the Firefox profile object
    firefoxProfile = FirefoxProfile()
    ## Disable CSS
    firefoxProfile.set_preference('permissions.default.stylesheet', 2)
    ## Disable images
    firefoxProfile.set_preference('permissions.default.image', 2)
    ## Disable Flash
    firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so',
                                  'false')
    ## Set the modified profile while creating the browser object
    self.browserHandle = webdriver.Firefox(firefoxProfile)

rawDescription: Do not want images to load and CSS to render on Firefox in Selenium WebDriver tests with Python


code:
import nltk
sentence = """At eight o'clock on Thursday morning
Arthur didn't feel very good."""
tokens = nltk.word_tokenize(sentence)
tokens
tagged = nltk.pos_tag(tokens)
tagged[0:6]

rawDescription: Language Processing - Using R or Python?

description: Language Processing - Using R or Python


code:
x = 0x188
# Find the value of the lowest bit, to clear.
least_power_of_2_x = ((x ^ (x-1)) + 1) >> 1
least_power_of_2_x
0x8

# Clear that bit
x = x ^ least_power_of_2_x
x
0x180

# Use same algorithm to find the next least
next_least = ((x ^ (x-1)) + 1) >> 1
next_least
0x80

# Now, you have the bit you actually care about. Find its index, 1-indexed.
next_least_index = len(bin(next_least)) - 2
next_least_index
8

rawDescription: Index of second least significant set bit


rawDescription: Best way to write understandable and Python-friendly code

description: Write understandable and Python-friendly code


code:
plt.gca().get_xaxis().set_major_formatter(FuncFormatter(lambda x, p: format(int(x/1000), ',')))
plt.show()

rawDescription: How do I scale xtick values axis in pyplot

description: Scale xtick values axis in pyplot


code: from multiprocessing.pool import ThreadPool

rawDescription: Python thread pool similar to the multiprocessing Pool?


code:
class StackLL:

    def __init__(self):
        self.head = None

    def pushSLL(self, item):
        temp = Node(str(item))
        temp.setNext(self.head)
        self.head = temp

    def dump(self):
        length = max(len(node.data) for node in self.allNodes()) if self.head else 0
        print('\u2510{}\u250c'.format(' '*length))
        for node in self.allNodes():
            print('\u2502{:<{}}\u2502'.format(node.data, length))
        print('\u2514{}\u2518'.format('\u2500'*length))

    def allNodes(self):
        node = self.head
        while node is not None:
            yield node
            node = node.next

s = StackLL()
s.pushSLL('Arc')
s.pushSLL('Circle')
s.pushSLL('Rect')
s.dump()

rawDescription: Python: Print using ascii codes

description: Python: Print using ascii codes


code:
import numpy
arr = numpy.array(im)
return gtk.gdk.pixbuf_new_from_array(arr, gtk.gdk.COLORSPACE_RGB, 8)

rawDescription: Converting PIL Image to GTK Pixbuf

description: Converting PIL Image to GTK Pixbuf


code:
class MySubclass(MyBaseClass):
    mybaseclass = models.OneToOneField(MyBaseClass, parent_link=True, related_name='thissubclass')

rawDescription: Custom related name for a Django model parent link?


code:
Room().ask_question(
    'How are you?',
    ('Fine!', print_this, ('ok',)),
    ('Not fine!', print_this, ('I\'m sorry',))
)

def ask_question(self, *arg):
    #... some logic missing... need to handle looping through `arg` here
    # but as an example...
    # first arg is the first tuple-- ('Fine!', print_this, ('ok',))
    # 2nd element of this tuple is the print_this function
    # 3rd element of this tuple are the args to pass to the function
    do_something = arg[1][1]
    do_something_args = arg[1][2]

    do_something(*do_something_args)

rawDescription: Call a function passed inside a list which is inside a class


code:
import atexit
import os
import gc
import random

class BigClass1(object):
    """atexit function tied to instance method"""
    def __init__(self, cache_filename):
        self.cache_filename = cache_filename
        self.cache_file = open(cache_filename, 'wb')
        self.data = [random.random() for i in range(10000000)]
        atexit.register(self.cleanup)

    def cleanup(self):
        self.cache_file.close()
        os.remove(self.cache_filename)

class BigClass2(object):
    def __init__(self, cache_filename):
        """atexit function decoupled from instance"""
        self.cache_filename = cache_filename
        cache_file = open(cache_filename, 'wb')
        self.cache_file = cache_file
        self.data = [random.random() for i in range(10000000)]

        def cleanup():
            cache_file.close()
            os.remove(cache_filename)

        atexit.register(cleanup)

if __name__ == "__main__":
    import pdb; pdb.set_trace()

    big_data1 = BigClass1('cache_file1')
    del big_data1
    gc.collect()

    big_data2 = BigClass2('cache_file2')
    del big_data2
    gc.collect()

rawDescription: What are the implications of registering an instance method with atexit in Python?


code: data2.boxplot(widths=0.05,  showbox=False, whiskerprops={'lw': 0})

rawDescription: Panda's boxplot but not showing the box

description: Panda's boxplot but not showing the box


code:
def only_once(a):
    d = {}
    for item in a:
        if item not in d:
            d[item] = 0
        d[item] += 1
    return [item for item in a if d[item] == 1]

rawDescription: Using a dictionary that takes a list, a, as an argument and returns a list containing the elements of a that occur exactly once


code:
words = ['hello', 'world', 'you', 'look', 'nice']
', '.join('"{0}"'.format(w) for w in words)

rawDescription: Join a list of strings in python and wrap each string in quotation marks


code:
import numpy as np
import numpy.ma as ma

x = np.array([1,2,3,4,5],dtype=np.double)
arr = [[1,2],[0,4,3],[1,4,0],[0,3,4],[1,4]]

max_arr_length = max([ len(item) for item in arr ])

arr_padded = [ np.pad(i,(0,max_arr_length-len(i)), mode='constant',
    constant_values=-1) for i in arr ]
arr_masked = ma.masked_equal(arr_padded,-1)

ans_masked = ma.masked_array(x[arr_masked] - x[:, None], mask=arr_masked.mask)

rawDescription: Broadcasting across an indexed array Numpy


code:
result = re.sub(r"""(?x)
    (?<!\\)     # Make sure that there is no backslash before the current position
    \\          # Match a backslash
    (?=         # only if...
     (?:\\\\)*  # an even number of backslashes follows (including zero)
     (?!\\)     # and no further backslashes follow after that
    )           # (End of lookahead assertion)""",
    r"\\\\", subject)

rawDescription: How to escape all unescaped slashes in Python

description: Escape all unescaped slashes in Python


rawDescription: Regex adding characters before another word (from a list of choices)


code:
ns = parser.parse_args()
ns.extra_file = ns.extra_file if ns.extra_file else ns.filename

rawDescription: argparse: setting optional argument with value of mandatory argument

description: Argparse: setting optional argument with value of mandatory argument


code:
df1.index.time > datetime.time(17)
df1.index + np.where((df1.index.time > datetime.time(17)), pd.offsets.Day(1).nanos, 0)

rawDescription: How to do resample of intraday timeseries data with dateOffset in Pandas/Numpy?

description: Do resample of intraday timeseries data with dateOffset in Pandas/Numpy


code:
from django.db.models import Sum
colleges = College.objects.all().annotate(total_points=Sum('myuser__points'))

rawDescription: How do I make this query in django? (aggregation / annotation)

description: Make this query in django? (aggregation / annotation)


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

plt.plot(yearofreleaselist, np.poly1d(np.polyfit(yearofreleaselist, profits, 1))(yearofreleaselist))

rawDescription: Line of Best fit on Matplotlib

description: Line of Best fit on Matplotlib


rawDescription: Python: How to sort a dictionary by key

description: Python: How to sort a dictionary by key


rawDescription: Regular Expression - Python - Remove Leading Whitespace


code:
class foo:

    the_int = 0

    def __init__(self, i):
        self.bar = i

one, two = foo(5), foo(10)

ar = [one, two]

int_array = [i.bar for i in ar[0:2]]

rawDescription: Accessing object data slicing numpy array


rawDescription: Is there a way to see if two lists are the exact same without looping in python?


rawDescription: Arbitrary length bytes to int builtin in Python


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

r1 = 1  #  AU Earth
r2 = 1.524  #  AU Mars
deltanu = 75 * np.pi / 180  #  angle in radians
mu = 38.86984154054163

c = np.sqrt(r1 ** 2 + r2 ** 2 - 2 * r1 * r2 * np.cos(deltanu))

s = (r1 + r2 + c) / 2

am = s / 2

def g(a):
    alphag = 2 * np.pi - 2 * np.arcsin(np.sqrt(s / (2 * a)))
    betag = -2 * np.arcsin(np.sqrt((s - c) / (2 * a)))
    return (np.sqrt(a ** 3 / mu)
            * (alphag - betag - (np.sin(alphag) - np.sin(betag))))

def g2(a):
    alphag = 2 * np.arcsin(np.sqrt(s / (2 * a)))
    betag = 2 * np.arcsin(np.sqrt((s - c) / (2 * a)))
    return (np.sqrt(a ** 3 / mu)
            * (alphag - betag - (np.sin(alphag) - np.sin(betag))))

a = np.linspace(am, 2, 500000)
dt = np.linspace(0, 2, 500000)

fig, ax = plt.subplots(ncols=2)
ax[0].plot(a, g(a), color = 'r')
ax[1].plot(a, g2(a), color = 'r')
ax[0].set_xlim((0.9, 2))
ax[0].set_ylim((0, 2))
ax[1].set_xlim((0.9, 2))
ax[1].set_ylim((0, 2))

plt.show()

rawDescription: Python: My python plot is reflecting across y = 0.5 line


code:
from bottle import Bottle, request

app = Bottle()

@app.route('/country')
def hello():
  return request.headers.get('X-AppEngine-Country')

rawDescription: country code in bottle REQUESTS running on google app engine

description: Country code in bottle REQUESTS running on google app engine


rawDescription: cursor.description "type_code" correspondence with database field types

description: Cursor.description "type_code" correspondence with database field types


code:
str1 = 'WeDrank$varCupCoffeeToday'
str2 = 'WeDrank2CupCoffeeToday'
parts = str1.split('$var')
str2.replace(parts[0],'').replace(parts[1],'')
str1 = 'WeDrank2CupCoffee$var'
str2 = 'WeDrank2CupCoffeeToday'
parts = str1.split('$var')
str2.replace(parts[0],'').replace(parts[1],'')

rawDescription: Find the unmatched string within another string in python


code:
import cv2.cv as cv
import time

cv.NamedWindow("camera", 1)

capture = cv.CaptureFromCAM(0)

i = 0
while True:
    img = cv.QueryFrame(capture)
    cv.ShowImage("camera", img)
    cv.SaveImage('pic{:>05}.jpg'.format(i), img)
    if cv.WaitKey(10) == 27:
        break
    i += 1

rawDescription: Save multiple images with OpenCV and Python


code:
a= 'Hi %s,
 The meeting is scheduled for %s %sth
 if you have an  questions please contact %s' % (cfname, meetingmonth, meetingday, cleadfname)

rawDescription: Use Python to output bold text in .doc

description: Use Python to output bold text in .doc


code:
ids = []
with open('file1') as f:
    ids.extend(id.strip() for id in f)
matches = []
with open('file2') as f:
    for line in f:
        if line.split(',')[0] in ids:
            matches.append(line)
with open('file3', 'w') as f:
    for match in matches:
        f.write(match)

rawDescription: Search the second file from the first and output to third file in python


rawDescription: Gtk3 replace child widget with another widget


code:
if ext == 'gz':
   command = 'gunzip -c {} -k | pg_restore -U {} -h {} -p {}' \
             '-d {}'.format(file, user, server, port, new_dbname)
elif ext == 'bz2':
   command = 'bunzip2 -c {} -k | pg_restore -U {} -h {} -p {}' \
             '-d {}'.format(file, user, server, port, new_dbname)
elif ext == 'zip':
   command = 'unzip -p {} | pg_restore -U {} -h {} -p {} ' \
             '-d {}'.format(file, user, server, port, new_dbname)
else:
   command = 'pg_restore -U {} -h {} -p {} -d {} {}'.format(user,
                server, port, new_dbname, file)

rawDescription: Is there a way to unzip automatically with pg_restore?


code:
pizza_number= int(input("How many Pizzas do you want? (MAX 5): "))
PIZZA_LIST=["Tandoori chicken: $8.50", "Prawn: $8.50", "Ham and cheese: $8.50", "Pepperoni: $8.50", "Hawaiian: $8.50","Beef and onion: $8.50","Meat lovers: $8.50", "Satay chicken: $13.50", "Apricot chicken: $13.50", "Supreme cheese:13.50", "Italian beef: $13.50", "Mediterraneo: $13.50"]
pizzas = []
for i in range(pizza_number):
    for index in range(0, len(PIZZA_LIST)):
        print(index, PIZZA_LIST[index])
    pizza = int(input("Select a pizza: "))
    pizzas.append(pizza)

rawDescription: for loop with input - PYTHON

description: For loop with input - PYTHON


code:
def get_tz_dst_info(tz):
    """
    Gets a 3-tuple of info about DST for a timezone. The returned elements are:
    - a boolean if this timezone observes DST
    - a Decimal UTC offset when not in DST
    - a Decimal UTC offset when in DST

    >>> from pytz import timezone
    >>> get_tz_dst_info(timezone('America/New_York'))
    (True, Decimal('-4'), Decimal('-5'))
    >>> get_tz_dst_info(timezone('Europe/Paris'))
    (True, Decimal('2'), Decimal('1'))
    >>> get_tz_dst_info(timezone('UTC'))
    (False, Decimal('0'), Decimal('0'))
    """
    dec_int_offset = timedelta_utc_offset_to_decimal(
        tz.utcoffset(DECEMBER_DATE)
    )
    jul_int_offset = timedelta_utc_offset_to_decimal(tz.utcoffset(JULY_DATE))
    jul_dst = tz.dst(JULY_DATE)
    dec_dst = tz.dst(DECEMBER_DATE)

    dst_offset = dec_int_offset
    non_dst_offset = jul_int_offset
    if jul_dst >= timedelta(seconds=0):
        dst_offset = jul_int_offset
        non_dst_offset = dec_int_offset
    elif dec_dst >= timedelta(seconds=0):
        dst_offset = jul_int_offset
        non_dst_offset = dec_int_offset
    return (dec_int_offset != jul_int_offset,
            non_dst_offset,
            dst_offset)

rawDescription: Python & pytz: Figure out if a timezone supports DST and what the DST and non-DST UTC offsets are


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

# some example data
threshold = 43.0
values = np.array([30., 87.3, 99.9, 3.33, 50.0])
x = range(len(values))

# split it up
above_threshold = np.maximum(values - threshold, 0)
below_threshold = np.minimum(values, threshold)

# and plot it
fig, ax = plt.subplots()
ax.bar(x, below_threshold, 0.35, color="g")
ax.bar(x, above_threshold, 0.35, color="r",
        bottom=below_threshold)

# horizontal line indicating the threshold
ax.plot([0., 4.5], [threshold, threshold], "k--")

fig.savefig("look-ma_a-threshold-plot.png")

rawDescription: How to create a matplotlib bar chart with a threshold line?

description: Create a matplotlib bar chart with a threshold line


code:
class A(object): pass

a = A()
a.randomattr = 1

rawDescription: Dictionary-like object in Python that allows setting arbitrary attributes


code:
browser.execute_script("foo(arguments[0])", 'someString')
browser.execute_script("foo(arguments[0])", 'string with \n is also ok!\n')

rawDescription: selenium execute_script with newlines

description: Selenium execute_script with newlines


code:
with contextlib.ExitStack() as stack:
    inputs = [stack.enter_context(fileinput.input(files=filename))
              for filename in input_filenames]
    outputs = [stack.enter_context(open(filename, "w"))
               for filename in output_filenames]

    # do stuff with inputs and outputs here

rawDescription: open multiple sets of multiple files in different modes using with

description: Open multiple sets of multiple files in different modes using with


code:
# after establishing a connection
In [15]: msg = "Tweeting from tweepy"

# retain the object returned
In [16]: tweet = api.update_status(status=msg)

# the id (and practically any attribute, print a tweet to view them!)
# can be easily accessed via
In [17]: tweet.id_str
Out[17]: u'646306396464656384'

rawDescription: How to get the tweet id for the tweet generated using tweepy library's update_status method

description: Get the tweet id for the tweet generated using tweepy library's update_status method


code: trace.text = str(a_numpy_array)

rawDescription: How to export numpy ndarray to a string variable?

description: Export numpy ndarray to a string variable


code:
user = users.get_current_user()
if user:
    greeting = ("Welcome, %s! (sign out)" %
                (user.nickname(), users.create_logout_url("/")))
else:
    greeting = ("Sign in or register." %
                users.create_login_url("/"))

self.response.out.write("%s" % greeting)

rawDescription: GAE users.get_current_user() returns None


code:
class Guns:
    global counter
    counter = 0

    def pistolCycle():
        global counter

        buttons[0].config(text=btnpistol_list[counter])

        if counter == len(btnpistol_list)-1:
            counter=0

        counter = counter+1

    def Pistols ():

        buttons[0] = Button(placement, height = '5',width = '20', text="Pistols", command = lambda: Guns.pistolCycle() )
        buttons[0].grid(column = clm[0], row = rw[0])

    def Rifles ():
        x = 0

    def AssultRifles ():
        x = 0
    def SubmachineGuns ():
        x = 0

    def HeavyWeapons ():
        x = 0

    def PlasmaWeapons ():
        x = 0

    for i in range (6):
        b = Button(placement,height = '5',width = '20', text = btnmain_list[i])
        b.grid(column = clm[i], row = rw[i])
        buttons.append(b)

    Pistols()

rawDescription: Python Tkinter preventing button command from executing


code:
import copy
alist = [[0], [1], [2], [3]]
blist = copy.deepcopy(alist)
blist[0].append(1)
alist
blist

rawDescription: Nested python list assignment

description: Nested python list assignment


rawDescription: Setting axis properties on axis-sharing plots


code:
def on_restart(self):
    self.restartExternal()
    self.restartWinow.destroy()

buttonRestart = Button(..., command = self.on_restart)

rawDescription: Python Tkinter Multiple Commands

description: Python Tkinter Multiple Commands


code:
import pygame, sys
from pygame.locals import *

SCREEN_X=400
SCREEN_Y=400
#Screen size

SPRT_RECT_X=0
SPRT_RECT_Y=0
#This is where the sprite is found on the sheet

LEN_SPRT_X=100
LEN_SPRT_Y=100
#This is the length of the sprite

screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y)) #Create the screen
sheet = pygame.image.load('C:\YOURFILE') #Load the sheet

sheet.set_clip(pygame.Rect(SPRT_RECT_X, SPRT_RECT_Y, LEN_SPRT_X, LEN_SPRT_Y)) #Locate the sprite you want
draw_me = sheet.subsurface(sheet.get_clip()) #Extract the sprite you want

backdrop = pygame.Rect(0, 0, SCREEN_X, SCREEN_Y) #Create the whole screen so you can draw on it

screen.blit(draw_me,backdrop) #'Blit' on the backdrop
pygame.display.flip()
#Draw the sprite on the screen

rawDescription: How do you select a sprite image from a sprite sheet in python?

description: Select a sprite image from a sprite sheet in python


rawDescription: PySpark reduceByKey? to add Key/Tuple

description: PySpark reduceByKey? to add Key/Tuple


code:
ax = df.plot()
ax.legend(prop={'size':10})

rawDescription: Panda DataFrame Passing in Parameters For Plotting


code:
u = (
    Table1(
        Table1.id,
        Table1.username,
        Table1.date
    ).select()
    |
    Table2(
        Table2.id,
        SQL(" '' AS username "),
        Table2.date
    ).select()
).select().execute()

rawDescription: Put an empty field in peewee union select


code:
dt = 0.0001 # your T
Fs = 1 / dt # sample rate
xt = np.arange (0, 10, dt)
nt = len (xt) # length of time series, your N

# make signal
st = .5 * np.sin (50 * 2 * np.pi * xt) + .5 * np.sin (80 * 2 * np.pi * xt)

# take fourier transform and shift frequency spectra
S  = np.fft.fftshift(np.fft.fft (st))

## make argument array, frequency [Hz]
#
# extending from -Fs/2 to Fs/2, the Nyquist frequency, with the same
# number of samples as in the time series (xt and st).

freqs = Fs * np.linspace (-1/2, 1/2, nt)

# plot absolute value, scaled with number of samples
# ( note that it is also interesting to plot the complex angle
#   using np.angle () ). together they make a bode-plot.

plt.plot (freqs, np.abs(S) / nt)
plt.xlabel ('Frequency [Hz]')

rawDescription: FFT-results in python dependend on linspace chosen?


code:
if x == 'yes':
    string = "Verocia was a mystical land located just south of Aborne"
    for char in string:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(.03)
else:
    print ('Please restart program whenever you are ready!')

rawDescription: Issue with if/else statement

description: Issue with if/else statement


code:
def show_firm_url(self, obj):
    return '%s' % (obj.firm_url, obj.firm_url)
show_firm_url.allow_tags = True

rawDescription: How to add clickable links to a field in Django admin?

description: Add clickable links to a field in Django admin


code:
spam = [
            A(id=u'BLI52E', time=datetime.datetime(2014, 11, 30, 9, 52, 49, 209102)),
            A(id=u'DHCS4J', time=datetime.datetime(2014, 11, 30, 9, 53, 36, 495319))
       ]
spam.sort(key=lambda x:x.time)

rawDescription: Python Sorting a List of Namedtuples

description: Python Sorting a List of Namedtuples


code:
from matplotlib import rc
rc('text', usetex=True)
plt.xticks(ind+width/2., ("$\lozenge$", "$\square$", "$\plus$", "o", "$\bigtriangledown$") )

rawDescription: Need to use matplotlib scatter markers outside the chart, in labels for a bar graph


code:
from bs4 import BeautifulSoup

test_html = """

Paragraph 1 Lorem ipsum dolor... long text...

Paragraph 2 Lorem ipsum dolor... long text...

Paragraph 3 Lorem ipsum dolor... long text...

"""

test_html = test_html[0:50]
soup = BeautifulSoup(test_html, 'html.parser')

print(soup.prettify())

rawDescription: Remove a portion of HTML text using Python


code:
df2 = df2.rename(columns={'B':'A'})
df1.combine_first(df2)

rawDescription: How to use join to fill missing values of a column - Python Pandas?

description: Use join to fill missing values of a column - Python Pandas


code:
app = wx.App()
window = DataLoggerWindow()
import threading
class WindowThread(threading.Thread):
    def run(self):
        window.Show()
        app.MainLoop()
WindowThread().start()

rawDescription: "Threading" in Python, plotting received data and sending simultaneously


code:
source = [{"a":numpy.array([1,2,3]),"b":numpy.array(['a','b','c'])},
          {"a":numpy.array([4,5]),"b":numpy.array(['d','e','f','g','h'])}]
result = {}
for key in source[0]:
    result[key] = numpy.concatenate([d[key] for d in source])

rawDescription: Python: Efficient concatenation of numpy arrays in dictionaries


rawDescription: python: How to refer to specific item within a list of lists?

description: Python: How to refer to specific item within a list of lists


rawDescription: print rows that have x value in the last column

description: Print rows that have x value in the last column


code:
from copy import copy
from functools import wraps

from rest_framework.metadata import SimpleMetadata
from rest_framework.relations import RelatedField

class MyMetadata(SimpleMetadata):

    def get_field_info(self, field):

        if isinstance(field, RelatedField):
            def kill_queryset(f):
                @wraps(f)
                def wrapped(*args, **kwargs):
                    qs = f(*args, **kwargs)
                    if qs is not None:
                        qs = qs.none()
                    return qs
                return wrapped

            field = copy(field)
            field.get_queryset = kill_queryset(field.get_queryset)

        result = super(MyMetadata, self).get_field_info(field)

        if not result.get('choices'):
            result.pop('choices', None)

rawDescription: Disabling choices on rest_framework's RelatedField


code:
question = Paragraph('What color is the sky?', style)
answer1 = Paragraph('Red', style)
answer2 = Paragraph('Green', style)
answer3 = Paragraph('Blue', style)

Story.append(KeepTogether([question, answer1, answer2, answer3]))

rawDescription: Python Reportlab Paragraph not crossing over next page


code:
from tkinter import *
from tkinter.ttk import *

def isPrime(num):
    return all(num % i for i in range(2, num))

def startSearching():
    primes = []
    for i in range(100000):
        if isPrime(i):
            primes.append(i)
            displayedText.set(len(primes))
            label.update_idletasks()
    displayedText.set('Scan is done.')

root = Tk()

displayedText = StringVar()

label = Label(root, textvariable=displayedText)
label.grid()

root.after(0, startSearching)
root.mainloop()

rawDescription: Show progress in messagebox with Tkinter


rawDescription: Is Python list.extend() Order Presserving?


code:
sorted(({'IP1': ip1, 'IP2': k, 'val':v}
           for ip1,subdct in dct.items()
           for k,v in subdct.items()),
       key=lambda newd: newd['val'])

rawDescription: python sort 2D dictionary by index

description: Python sort 2D dictionary by index


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

station_list=['station1', 'station2', 'station3', 'station63']
measure_list=[
    [200.0, 200.0, 200.0, 200.0, 200.0, 300.0],
    [400.0, 400.0, 300.0, 300.0, 300.0, 300.0, 300.0, 300.0, 300.0],
    [300.0, 400.0, 400.0, 400.0, 400.0],
    [1000.0, 1000.0, 1000.0, 1000.0, 1000.0],
    ]
x = range(len(station_list))

assert len(station_list) == len(measure_list) == len(x)

for i, label in enumerate(station_list):
    y_list = measure_list[i]
    x_list = (x[i],) * len(y_list)

    plt.plot(x_list, y_list, 'o')

# You can specify a rotation for the tick labels in degrees or with keywords.
plt.xticks(x, station_list, rotation='vertical')

# Pad margins so that markers don't get clipped by the axes
# plt.margins(0.2)
plt.xlim(np.min(x) - 0.5, np.max(x) + 0.5)

# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)
plt.show()

rawDescription: Python - plotting list of lists versus an other list


code:
def ListadorPastas(pasta):
    resultado = []
    for root, dirs, files in os.walk(pasta):
        for d in dirs:
          if (len(d)==4 or len(d)>4 and not d[-5].isdigit()
             ) and d[-4:].isdigit():
              resultado.append(d)
    return resultado

rawDescription: os.walk and some tests

description: Os.walk and some tests


code:
from timeit import default_timer as timer

start = timer()

freq = 5 * 60       # Time in seconds
last_time = 0.0
for i in range(int(1e8)):
    ctime = timer()
    if ctime - last_time > freq:
        print(i)
        last_time = ctime

rawDescription: Python - Print index of for loop only once every five minutes


rawDescription: Python problems with file names

description: Python problems with file names


code:
import os

def print_file_contents(file_path):
    assert os.path.exists(file_path), "File does not exist: {}".format(file_path)
    with open(file_path) as f:
        print (f.read())

user_input = raw_input("Enter a file path: ") # just input(...) in Python 3+
print_file_contents(user_input)

rawDescription: Read and print a user selected file's contents


rawDescription: Python: split by (different) n spaces

description: Python: split by (different) n spaces


code:
import re

regex = re.compile('{}'.format(YOUR_IP_ADDR))

count = my_collection.find({'ip_addr_field': regex}).count()

rawDescription: Retrieve IP address data from mongodb in pymongo using regular expression or pattern matching


code:
class StoreSegments01(models.Model):
    segment = models.FileField(upload_to=content_file_name)
    segmentID = models.TextField(max_length=100, default=11)

    def delete(self, *args, **kwargs):
        # first, delete the file
        self.segment.delete(save=False)

        # now, delete the object
        super(StoreSegments01, self).delete(*args, **kwargs)

rawDescription: django: calling delete on object doesn't delete the file

description: Django: calling delete on object doesn't delete the file


code:
user = User.objects.get(username='user1')
last_login = user.last_login

rawDescription: Get last_login time for a certain user? (django)


code:
class Fleet:
  def __init__(self):
    self.shipNamesandNumber = {}

rawDescription: Assign a value to class variable is assiging it for all instances of that object


code:
from collections import Counter

c = Counter(['bob','steve','steve','joe'])

# c == Counter({'steve': 2, 'bob': 1, 'joe': 1})

c.update(['alan','jose','steve'])

# c == Counter({'steve': 3, 'jose': 1, 'bob': 1, 'joe': 1, 'alan': 1})

rawDescription: count over several List

description: Count over several List


rawDescription: Networkx: How to change node indexing

description: Networkx: How to change node indexing


code:
elements = [
    element.strip(' -')
    for element in config["PATHS"]["elements"].strip().split('\n')]

rawDescription: Nicely parsing a multiline config file in python


code:
from kombu import serialization
serialization.registry._decoders.pop("application/x-python-serialize")

rawDescription: How to disallow pickle serialization in celery

description: Disallow pickle serialization in celery


code:
import os
from selenium import webdriver

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir", os.getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-msdos-program")

driver = webdriver.Firefox(firefox_profile=fp)
driver.get("http://www.downloadcrew.com/article/18631-aida64")

driver.find_element_by_xpath("//div[@class='downloadLink']/a/img").click()

rawDescription: How to download file using selenium?

description: Download file using selenium


code:
import datetime

def parse_date(line):
    for template, length in [("[%H:%M:%S %d.%m.%Y]", 21),
                             ("%H:%M:%S-%d.%m.%Y", 19), ...]:
        try:
            return datetime.datetime.strptime(line[:length], template)
        except ValueError:
            pass

rawDescription: Parse line with unknown delimiters

description: Parse line with unknown delimiters


code:
for t in xrange(3, x):
    size = (t - 2) * (t - 3)
    a = np.zeros(size)
    b = np.zeros(size)
    c = np.zeros(size)

    idx = 0
    for u in xrange(2,t):
        for v in xrange(1,u):
            a[idx] = t
            b[idx] = u
            c[idx] = v
            idx += 1

rawDescription: Removing nested loops in numpy

description: Removing nested loops in numpy


code:
df = pd.DataFrame({'Date':pd.date_range('2015-1-1', '2015-12-31')})
df['Period'] = df['Date'].dt.to_period('W-THU')
df['Week_Number'] = df['Period'].dt.week
df.head()

rawDescription: Pandas custom week

description: Pandas custom week


code:
entire_set = len(data) == len(train) + len(test)
logging.log(logging.WARNING if entire_set else logging.INFO,
            "Entire data set allocated => {0}".format(entire_set))

rawDescription: Conditional log level on a statement in python?


code:
@route('/stream')
def index():
    worker = multiprocessing.Process(target=do_stuff)
    worker.start()
    yield redis_server.lpop()

def do_stuff(body):
    while True:
        gevent.sleep(5)
        redis_server.lpush("data")

rawDescription: Streaming Connection Using Python Bottle, Multiprocessing, and gevent


code:
for table in soup.findAll('table'):
    rows=[]
    for row in table.findAll('tr'):
        columns=0
        for column in row.findAll('td'):
            columns+=1
            rows.append(columns)
        if max(rows)>3:
          table.delete()

rawDescription: Can I segment a document in BeautifulSoup before converting it to text based on my analysis of the document?

description: Segment a document in BeautifulSoup before converting it to text based on my analysis of the document


code:
class MyForm(forms.ModelForm):
    my_field = forms.ModelChoiceField(queryset=Foo.objects.select_related('bar'))

rawDescription: django forms prefetch on cleaned data

description: Django forms prefetch on cleaned data


code:
df_data['vals'] = df_data['vals'].map(lambda x: '%2.1f' % x)

df_data.to_csv(outfile, index=False, header=False, float_format='%11.6f')

rawDescription: Print different precision by column with pandas.DataFrame.to_csv()?


code:
for filename in filenames:
    for line in open(filename):
        if any(word in line for word in words):
            pass # do something

rawDescription: (How much) does it matter which is sorted through first when checking 2 lists against each other?


code:
for i, question in enumerate(extra):
            self.fields['custom_%s' % i] = forms.CharField(label=question)

rawDescription: How do I set a forms.CharField text programmatically?

description: Set a forms.CharField text programmatically


code:
def isNum(data):
    try:
        int(data)
        return True
    except ValueError:
        return False

rawDescription: Django, Detecting if variable is a number


code:
x = scipy.arange(4)
y = scipy.array([4,7,6,5])
f = pylab.figure()
ax = f.add_axes([0.1, 0.1, 0.8, 0.8])
ax.bar(x, y, align='center')
ax.set_xticks(x)
ax.set_xticklabels(['Aye', 'Bee', 'Cee', 'Dee'])
f.show()

rawDescription: Individually labeled bars for bar graphs in matplotlib / Python


code:
from __future__ import print_function

class MyTuple(tuple):
    def __new__(cls, lst, data):
        return tuple.__new__(cls, tuple(lst) + (data, ))
    def __len__(self):
        return tuple.__len__(self) - 1

    def __getitem__(self, key):
        print("__getitem__() is called.  start:%s, end:%s" % (key.start, key.stop))
        return super(MyTuple, self).__getitem__(key)

    def __getslice__(self, start, end):
        print("__getslice__() is called.  start:%s, end:%s" % (start,end))
        return super(MyTuple, self).__getslice__(start,end)

m = MyTuple([1,2], 0)

print(m[:-1])

rawDescription: Overriding tuple.__len__ in python

description: Overriding tuple.__len__ in python


code:
from Tkinter import *

books = [
["Bible", "Biblia", 10, 5],
["Bible Teach", "Bible Teach", 10, 10],
["Song Book", "El Song Book", 10, 10],
["Daniel's Prophecy", "Spanish D Prof", 10, 10]
]

def inventoryButton():
    invOutput = ""
    for book in books:
        if book[2] > book[3]:
            invOutput += "Title: " + book[0] + "\n"
            invOutput += "You need to order more books.\n\n"
        else:
            invOutput += "Title: " + book[0] + "\n"
            invOutput += "Status: Inventory is sufficient.\n\n"
    #Set the text of the Label "summary"
    summary["text"] = invOutput

window = Tk()
window.title("Literature Inventory System")
window.geometry("500x500")

button = Button(window, text="Check Inventory", command=inventoryButton)
button.pack()

summary = Label(window)
summary.pack()

window.mainloop()

rawDescription: Can't update label with a string upon clicking button


code:
class staticmethod(object):
    def __init__(self, callable):
        self.f = callable
    def __get__(self, obj, type=None):
        return self.f
    @property
    def __func__(self):
        return self.f

rawDescription: Can someone explain how the source code of staticmethod works in python


code:
rbufsize = -1

def do_POST(self):
  self.rfile._sock = self.rfile
  return CGIHTTPRequestHandler.do_POST(self)

rawDescription: Python local server issue: rfile gets truncated when posting through ajax


code: u"Samsung Galaxy Note II \u2013 Latest Smartphone in India ".split(u'\u2013')

rawDescription: split function for splitting with unicode character

description: Split function for splitting with unicode character


code:
class TestBase(unittest.TestCase):

    def setUp(self):

        global auth, request, session, response, db

        self._application = 'contacts'
        self._controller = 'default'

        self._pyfile = os.path.join(request.env.web2py_path, request.folder, 'controllers', self._controller + '.py')

        self.db_link = 'postgres://......._test'

        db = test_helpers.copy_db(globals(), db_link=self.db_link)
        db.commit()

        current.request = Request(globals())

        current.session = Session()

        current.request.application = self._application
        current.request.controller = self._controller

        auth = Auth(globals(), db)

        auth.define_tables()

        db(db.contacts.id > 0).delete()  # Clear the database
        db.commit()

        # clear all users from auth tables and commit changes
        db(db.auth_user.id > 0).delete()  # Clear the database
        db.commit()

        # execute the controller file, passing in the env globals.
        execfile(self._pyfile, globals())

rawDescription: web2py - Unit testing @auth.requires_login()

description: Web2py - Unit testing @auth.requires_login()


code:
l = [1, 2]
d = {0: l}
t = (l, )
import gc
import pprint
pprint.pprint(gc.get_referrers(l))

rawDescription: Python basic data references, list of same reference


code: data['tweets'][tweetN]['ttd']

rawDescription: Python in x for loop 0,3 use x in a variable


code:
import datetime
now = datetime.datetime.now()
today8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
now < today8am
now == today8am
now > today8am

rawDescription: Python time comparison

description: Python time comparison


code:
d = {'0003': ['Mike', 'Restrepo', 'mtrepot', '87654321'], '0001': ['John', 'Jelenski', 'jelensohn', 'snf23jn4'], '0002': ['Clyde', 'Owen', 'clonew', 'dummy2015']}
[k for k, v in d.items() if 'mtrepot' in v]

rawDescription: How to get a value and its key from a dictionary

description: Get a value and its key from a dictionary


code:
userinp = raw_input("Please type a sentence: ")
words = userinp.split(' ')
search = raw_input("Search for a word: ")
for idx, word in enumerate(words):
    if search == word:
        print("Word found at index:", idx)

rawDescription: Python GCSE - Using Lists

description: Python GCSE - Using Lists


code:
results=[{"s":1,"score":100},{"s":2,"score":101},{"s":3,"score":99},{"s":4,"score":1},{"s":5,"score":1000}]
from operator import itemgetter
sorted(results, key=itemgetter("score"))

rawDescription: sorting in python

description: Sorting in python


code:
import ModuleA
# now ModuleA.myQueue is the Queue object created there

rawDescription: Sharing queue between threads running in different modules


code:
def find_valid_locations(grid, z, a, b):
    check = [(0, 0, 0, 0)]
    w = z + b
    h = z + a
    while check:
        x, y, ox, oy = check.pop()
        if x + w >= len(grid) or y + h >= len(grid[0]):
            continue
        for i, row in enumerate(grid[x+ox:x+w+1], x+ox):
            for j, val in enumerate(row[y+oy:y+h+1], y+oy):
                if val:
                    break
            else:
                continue
            check.append((x, j+1, 0, 0))
            if y == 0:
                check.extend((ii, j+1, 0, 0) for ii in range(x+1, i+1))
                check.append((i+1, y, 0, 0))
            break
        else:
            yield (x, y)
            check.append((x, y+1, 0, h-1))
            if y == 0:
                check.append((x+1, y, w-1, 0))
            continue

rawDescription: Finding an appropriate rectange in a 2-d array


code:
import urllib2
req = urllib2.Request('http://www.python.org/')
#
# Here we request that bytes 18000--19000 be downloaded.
# The range is inclusive, and starts at 0.
#
req.headers['Range']='bytes=%s-%s' % (18000, 19000)
f = urllib2.urlopen(req)
# This shows you the actual bytes that have been downloaded.
content_range=f.headers.get('Content-Range')
print(content_range)
# bytes 18000-18030/18031

rawDescription: Fetch first n bytes from the URL

description: Fetch first n bytes from the URL


code:
special_delim = '%'
for k, v in d.items():
     if isinstance(v, list):
        d[k] = special_delim.join(v)

rawDescription: Generate CSV with multiple values in Python


rawDescription: Hashing arrays in Python

description: Hashing arrays in Python


code:
from pylab import *
from matplotlib.finance import candlestick
import matplotlib.gridspec as gridspec

quotes = [(734542.0, 1.326, 1.3287, 1.3322, 1.3215), (734543.0, 1.3286, 1.3198, 1.3292, 1.3155), (734546.0, 1.321, 1.3187, 1.3284, 1.3186), (734547.0, 1.3186, 1.3133, 1.3217, 1.308)]

fig, ax = subplots()
candlestick(ax,quotes,width = 0.5)
ax.xaxis_date()
ax.autoscale_view()

#NOT WORKING
h = quotes[1][3]
d = quotes[1][0]
ax.annotate('BUY', xy = (d-1,h), xytext = (d-1, h+0.003), arrowprops = dict(facecolor='black',width=1,shrink=0.25))
#NOT WORKING

plt.show()

rawDescription: Annotate something on a matplotlib candlestick chart


code: result = np.trapz(y,x)

rawDescription: Numerical integration for unevenly spaced intervals, Python


code:
x = [1,2,3,4,7,7,5,6,7,8,8]
y = [1,4,5,6,8,9]
from collections import Counter
count=Counter(x)
for i in y:
    del count[i]

list(count.elements())

rawDescription: Remove items from a list if it is in another list while keeping the duplicate - Python


code:
from itertools import combinations

for point1, point2, point3 in combinations(points, 3):
    ...

rawDescription: Choose three different values from list in Python


code:
streamhandler = logging.StreamHandler()
streamhandler.setFormatter(formatter)
memoryhandler = logging.handlers.MemoryHandler(1024*10, logging.DEBUG, streamhandler)
logger.addHandler(memoryhandler)

rawDescription: memory handler of python logging module

description: Memory handler of python logging module


code:
def DestinationThread( a ) :
  while True :
    items = q.get()
    func = items[0]
    args = items[1:]
    func(*args)

rawDescription: how to put a function and arguments into python queue?

description: Put a function and arguments into python queue


rawDescription: recv() function too slow

description: Recv() function too slow


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

def sigmoid(x):
    return 1 / (1 + np.exp(-4*x))

x = np.linspace(-3, 3, 1000)
y = np.array([(1 - n)**(-1) if n < 0 else 1 + n for n in x])
z = sigmoid(x)

plt.ylim(0, 1.5)

plt.plot(x, z, linewidth=2)
plt.plot(x, y, linewidth=2)
plt.show()

rawDescription: Draw two graphs, and add xlimit and ylimit on both axis, if possible


code:
my_queryset_filters = {
    'user': self.request.user,
    'date__year': self.kwargs['year'],
}

Record.objects.filter(**my_queryset_filters)

rawDescription: Django - One view, multiple URLs?

description: Django - One view, multiple URLs


code:
import os
# path = r'S:\Photogr\ASC'
path = 'temp'
file_ext_lst = ['.2dm','.2de','.3dm','.3de','.dgn']
txtfile = r'D:\test\microstation_filenames_paths.txt'

found = dict()
for dirpath, _, filenames in os.walk(path):
    for filename in filenames:
        fullPath = os.path.join(dirpath, filename)
        name,ext = os.path.splitext(filename)
        if ext not in file_ext_lst:
            continue
        if name not in found:
            found[name] = fullPath

with open('unique.txt', 'w') as outf:
    print >>outf, 'Unique files:'
    for name,path in found.iteritems():
        print >>outf, '{:<10} {}'.format(name,path)

rawDescription: Want to write unique filenames and paths to text file, duplicate names will have different extensions


code:
import webapp2

class WSGIApp(webapp2.WSGIApplication):

    def __call__(self, environ, start_response):
        environ['SCRIPT_NAME'] = ''
        return super(WSGIApp, self).__call__(environ, start_response)

# app = WSGIApp(...)

rawDescription: Running webapp2 app in a multiple WSGI apps set up with Werkzeug


code:
real_pi = 3.141592
calc_pi = 3.141259
sum(1 for _ in itertools.takewhile(lambda t:t[0]==t[1], zip(str(calc_pi), str(real_pi))))

rawDescription: Python - Find how many digits a number is accurate to?


code:
serialized_data = my_serializer.data  # original serialized data
return_data = [] # final response which will be returned
for item in serialized_data:
    if isinstance(item, list): # check if a list inside serialized data
        return_data += item # add the elements of the list to 'return_data' list
    else:
        return_data.append(item) # Otherwise just append the item to 'return_data' list

rawDescription: Could serializer's to_representation generate multiple output items in DRF 3?


code:
class Tagging: # Handles Tagging - Create new Tags
    def __init__(self):
        self.content = []
        self.initialTag = ""
    def doTag(self): #Tag people
         self.initialTag = raw_input("Name to Tag: ")
         self.content.append(self.initialTag)
    #Tagging can only be done if the user created new post.

class Commenting: #Handles Commenting - Create new Comments
    def __init__(self):
        self.content = []
        self.initialComment = ""
    def doComment(self): #Commenting on Posts
        self.initialComment = raw_input("Comment: ")
        self.content.append(self.initialComment)
    #Commenting can only be done on Posts. No Post means no Comment. (Same goes to Tags)

class Posting: #Handles Posting - Create new Posts
    def __init__(self, TaggingContent, CommentingContent):
        self.content = [] #Content of the post
        self.initialPost = ""
        self.compact = TaggingContent + CommentingContent #Post that contains the Post, Comments, and Tags
        #How do I do this?

    def doPost(self):
        self.initialPost = raw_input("Post: ")
        self.content.append(self.initialPost)

if __name__ == "__main__":
    T = Tagging()
    C = Commenting()
    ##Do stuff here with tagging and commenting....
    P = Posting(T.content, C.content)
    #Do stuff with posting

rawDescription: Transferring value of variable from one unrelated class to another


code:
import numpy as np
#import time
#import matplotlib.pyplot as plt
import scipy.io as c
import pylab as pl                     #added

datafile = c.loadmat('data.mat') # loading data
img = datafile['img'] # extracting the (351:467:300) array
imgShape = np.shape(img)
pl.ion()                               #added
for i in range(imgShape(2)):           #no need for 0
    pl.cla()                           #added
    pl.imshow(img[:,:,i])
#    time.sleep(0.3)
    pl.draw()
    pl.pause(0.3)                      #added
pl.ioff()                              #added
print('Done!')

rawDescription: slicing and plotting 3D array with Python

description: Slicing and plotting 3D array with Python


code:
import moviepy.editor as mp
clip = mp.VideoFileClip("mygif.gif")
clip.write_videofile("myvideo.webm")

rawDescription: How to Convert animated .gif into .webm format in Python?


code:
s = "foo_M_bar_type foo_R_bar_type foo_L_bar_type"
import re
re.sub("_[LR]_", lambda m: {'_L_':'_R_','_R_':'_L_'}[m.group()], s)

rawDescription: Swapping token values in a string through regex


code:
num = 5
cur.execute("SELECT Name, Number FROM Ads WHERE Number = ?", (num,))

rawDescription: Python variable in a sqlite query

description: Python variable in a sqlite query


code:
ave = pd.stats.moments.rolling_mean(data,length)
ave = ave.dropna()

sd = pd.stats.moments.rolling_std(data,length)
sd = sd.dropna()

rawDescription: BollingerBand - rolling_mean - length number


rawDescription: Numpy vectorization of 2D array differences


code: if isinstance(myvar, primitiveTypes): ...

rawDescription: Determine if Python variable is an instance of a built-in type


code:
for item in soup.find_all('div',class_="ad_item"):
     if len(item["class"]) != 1:
         continue;

rawDescription: How to Beautiful Soup (bs4) match just one, and only one, css class


code:
from PySide.QtCore import QObject, QUrl, Slot
from PySide.QtGui import QApplication
from PySide.QtWebKit import QWebPage, QWebSettings

qapp = QApplication([])

def load_source(url):
    page = QWebPage()
    page.settings().setAttribute(QWebSettings.AutoLoadImages, False)
    page.mainFrame().setUrl(QUrl(url))

    class State(QObject):
        src = None
        finished = False

        @Slot()
        def loaded(self, success=True):
            self.finished = True
            if self.src is None:
                self.src = page.mainFrame().toHtml()
    state = State()

    # Optional; reacts to DOM ready, which happens before a full load
    def js():
        page.mainFrame().addToJavaScriptWindowObject('qstate$', state)
        page.mainFrame().evaluateJavaScript('''
            document.addEventListener('DOMContentLoaded', qstate$.loaded);
        ''')
    page.mainFrame().javaScriptWindowObjectCleared.connect(js)

    page.mainFrame().loadFinished.connect(state.loaded)

    while not state.finished:
        qapp.processEvents()

    return state.src

rawDescription: Load a web page

description: Load a web page


code:
lst = ['first', 'third', 'second']
dcts = [{'color':'yellow', 'section':'third'}, {'color':'red', 'section':'first'}, {'color': 'blue', 'section':'second'}]
sorted(dcts, key=lambda dct: lst.index(dct['section']))

rawDescription: Python: Sorting a list using another list as an order


code:
cumulative = 0
for item in queryset:
    cumulative += item.minutes
    item.cumulative = cumulative

rawDescription: What is the best way to have a cumulative variable in a django template?


code:
def rotate(tf, points, theta):
    rotation_matrix = tf.pack([tf.cos(theta),
                              -tf.sin(theta),
                               tf.sin(theta),
                               tf.cos(theta)])
    rotation_matrix = tf.reshape(rotation_matrix, (2,2))
    return tf.matmul(points, rotation_matrix)

rawDescription: Create a Rotation Matrix Tensoflow

description: Create a Rotation Matrix Tensoflow


code:
# extract ID column from CSV file 2 into a set
Ids = { row[1] for row in smartee }

# pick only rows whose ID is in Ids
filtered_rows = [item for item in aeries if item[1] in Ids]

rawDescription: How do I delete rows in one CSV based on rows in another CSV using specific columns to compare

description: Delete rows in one CSV based on rows in another CSV using specific columns to compare


rawDescription: String substitution using dictionary

description: String substitution using dictionary


code:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")

s = i = 0         #declare counter: i = 0

x = raw_input ('please enter the number')

while (x != 'f'):
    x = eval (x)
    s = s + x
    i+=1          #increment counter: i=i+1 or i+=1 (these 2 options are equivalent)
    x = raw_input ('please enter the number')

print (' the average is'), s/i    #divide the sum by counter

rawDescription: How to calculate average / mean on python 2.7

description: Calculate average / mean on python 2.7


code: mergeArrays = list.__add__

rawDescription: How do I return a value without using the return statement?

description: Return a value without using the return statement


code:
N = 15
# make an empty data set
data = np.ones((N, N)) * np.nan
# fill in some fake data
for j in range(3)[::-1]:
    data[N//2 - j : N//2 + j +1, N//2 - j : N//2 + j +1] = j
# make a figure + axes
fig, ax = plt.subplots(1, 1, tight_layout=True)
# make color map
my_cmap = matplotlib.colors.ListedColormap(['r', 'g', 'b'])
# set the 'bad' values (nan) to be white and transparent
my_cmap.set_bad(color='w', alpha=0)
# draw the grid
for x in range(N + 1):
    ax.axhline(x, lw=2, color='k', zorder=5)
    ax.axvline(x, lw=2, color='k', zorder=5)
# draw the boxes
ax.imshow(data, interpolation='none', cmap=my_cmap, extent=[0, N, 0, N], zorder=0)
# turn off the axis labels
ax.axis('off')

rawDescription: Drawing grid pattern in matplotlib

description: Drawing grid pattern in matplotlib


code:
if Value(params['json_key']) == "True":
    kw = {
        'target': 'out.txt',
        'source': 'in.txt',
        'action': 'function $SOURCE $TARGET',
    }
else:
    kw = {}
env.Command(**kw)

rawDescription: SCons if/then statement

description: SCons if/then statement


code:
a = [2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 34, 40, 45, 46, 50, 55]
# zip() creates tuples of two consecutive values
# (it zips lists of different length by truncating longer list(s))
# then tuples with first value and difference are placed in 'diff' list
diff = [(x, y-x) for x, y in zip(a, a[1:])]
# now pick only elements with changed difference
result = []
for pair in diff:
    if not len(result) or result[-1][1]!=pair[1]: # -1 to take last element
        result.append(pair)

rawDescription: Running average / frequency of time series data?


code:
import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break
cv2.destroyWindow("preview")

rawDescription: How do I access my webcam in Python?

description: Access my webcam in Python


rawDescription: correct and efficient way to flatten array in numpy in python?

description: Correct and efficient way to flatten array in numpy in python


code:
command = [
        '/usr/bin/ssh',
        '{0}@{1}'.format(username, hostname),
        '-L', '{0}:localhost:{1}'.format(local_port, foreign_port),
        '-o', 'NumberOfPasswordPrompts=1',
        'sleep {0}'.format(SLEEP_TIME),
]

# PID = 0 for child, and the PID of the child for the parent
self.pid, child_fd = pty.fork()

if not self.pid: # Child process
    # Replace child process with our SSH process
    os.execv(command[0], command)

while True:
    output = os.read(child_fd, 1024).strip()
    lower = output.lower()
    # Write the password
    if lower.endswith('password:'):
        os.write(child_fd, self.password_var.get() + '\n')
        break
    elif 'are you sure you want to continue connecting' in lower:
        # Adding key to known_hosts
        os.write(child_fd, 'yes\n')
    elif 'company privacy warning' in lower:
        pass # This is an understood message
    else:
        tkMessageBox.showerror("SSH Connection Failed",
            "Encountered unrecognized message when spawning "
            "the SSH tunnel: '{0}'".format(output))
        self.disconnect()

rawDescription: SSH Password through Python Subprocess

description: SSH Password through Python Subprocess


code:
import multiprocessing

POISON_PILL = "STOP"

def process_odds(in_queue, shared_list):

    while True:

        # block until something is placed on the queue
        new_value = in_queue.get()

        # check to see if we just got the poison pill
        if new_value == POISON_PILL:
            break

        # we didn't, so do the processing and put the result in the
        # shared data structure
        shared_list.append(new_value/2)

    return

def process_evens(in_queue, shared_list):

    while True:
        new_value = in_queue.get()
        if new_value == POISON_PILL:
            break

        shared_list.append(new_value/-2)

    return

def main():

    # create a manager - it lets us share native Python object types like
    # lists and dictionaries without worrying about synchronization -
    # the manager will take care of it
    manager = multiprocessing.Manager()

    # now using the manager, create our shared data structures
    odd_queue = manager.Queue()
    even_queue = manager.Queue()
    shared_list = manager.list()

    # lastly, create our pool of workers - this spawns the processes,
    # but they don't start actually doing anything yet
    pool = multiprocessing.Pool()

    # now we'll assign two functions to the pool for them to run -
    # one to handle even numbers, one to handle odd numbers
    odd_result = pool.apply_async(process_odds, (odd_queue, shared_list))
    even_result = pool.apply_async(process_evens, (even_queue, shared_list))
    # this code doesn't do anything with the odd_result and even_result
    # variables, but you have the flexibility to check exit codes
    # and other such things if you want - see docs for AsyncResult objects

    # now that the processes are running and waiting for their queues
    # to have something, lets give them some work to do by iterating
    # over our data, deciding who should process it, and putting it in
    # their queue
    for i in range(6):

        if (i % 2) == 0: # use mod operator to see if "i" is even
            even_queue.put(i)

        else:
            odd_queue.put(i)

    # now we've finished giving the processes their work, so send the
    # poison pill to tell them to exit
    even_queue.put(POISON_PILL)
    odd_queue.put(POISON_PILL)

    # wait for them to exit
    pool.close()
    pool.join()

    # now we can check the results
    print(shared_list)

    # ...and exit!
    return

if __name__ == "__main__":
    main()

rawDescription: Basic multiprocessing with while loop

description: Basic multiprocessing with while loop


code:
s_id=11
[i for i in d['school'] if i['s_id'] == str(s_id)]

rawDescription: Filter the paricular dictionary

description: Filter the paricular dictionary


rawDescription: How does Sage's "var" work?

description: How does Sage's "var" work


code:
etalone = "String to find"
etalone_length = len(etalone)
counter = 0
for symbol in your_line:
    if symbol == etalone[counter]:
        counter += 1
        if counter == etalone_length:
            print("String matches")
            break
    elif symbol != " " and sybmol != "#":
        # Bad char found
        print("Does not match!")
else:  # exited 'for' before full etalone matched
    print("Does not match!")

rawDescription: Python regex catastrophic backtracking

description: Python regex catastrophic backtracking


code:
def days_hours_minutes(td):
    return td.days, td.seconds//3600, (td.seconds//60)%60

rawDescription: Convert a timedelta to days, hours and minutes


code:
import time, threading
def foo():
    print(time.ctime())
    threading.Timer(10, foo).start()

foo()

#output:
#Thu Dec 22 14:46:08 2011
#Thu Dec 22 14:46:18 2011
#Thu Dec 22 14:46:28 2011
#Thu Dec 22 14:46:38 2011

rawDescription: Executing periodic actions in Python

description: Executing periodic actions in Python


code:
import math
def dot(vA, vB):
    return vA[0]*vB[0]+vA[1]*vB[1]
def ang(lineA, lineB):
    # Get nicer vector form
    vA = [(lineA[0][0]-lineA[1][0]), (lineA[0][1]-lineA[1][1])]
    vB = [(lineB[0][0]-lineB[1][0]), (lineB[0][1]-lineB[1][1])]
    # Get dot prod
    dot_prod = dot(vA, vB)
    # Get magnitudes
    magA = dot(vA, vA)**0.5
    magB = dot(vB, vB)**0.5
    # Get cosine value
    cos_ = dot_prod/magA/magB
    # Get angle in radians and then convert to degrees
    angle = math.acos(dot_prod/magB/magA)
    # Basically doing angle <- angle mod 360
    ang_deg = math.degrees(angle)%360

    if ang_deg-180>=0:
        # As in if statement
        return 360 - ang_deg
    else:

        return ang_deg

rawDescription: Calculating angles between line segments (Python) with math.atan2


code:
def before_feature(context, feature):
    is_software_installed = some_foo_magic()

    if not is_software_installed:
        for scenario in feature.scenarios:
            if depends_on_software(scenario):
                scenario.mark_skipped()

rawDescription: Skip a behave step in the step implementation


code:
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.spiders import CrawlSpider

from scrapy.item import Item, Field

class EscraperItem(Item):
    image_urls = Field()
    productURL = Field()
    productDesc = Field()
    image_paths = Field()
    productSite = Field()
    productTitle = Field()
    productPrice = Field()
    productImage = Field()

class ESpider(CrawlSpider):
    name = "ashikamallSpider"

    allowed_domains = ["ashikamall.com"]
    start_urls = ['http://ashikamall.com/products.aspx?id=222&page=%s' % n for n in range(1, 51)]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//div[@class="product_list"]')
        items = []

        for site in sites:
            item = EscraperItem()
            item['productDesc'] = ""
            item['productSite'] = "http://1click1call.com/"
            item['productTitle'] = site.select('.//div[@class="product_list_name"]/h3/text()').extract()
            item['productPrice'] = site.select('.//div[@class="product_list_offerprice"]/text()').extract()
            item['productURL'] = "http://ashikamall.com/" + site.select('.//div[@class="product_list_image"]/a/@href').extract()[0].encode('utf-8')
            item['productImage'] = "http://ashikamall.com/" + site.select('.//div[@class="product_list_image"]/a/img/@src').extract()[0].encode('utf-8')
            items.append(item)
        return items

rawDescription: Scrapy parse method not working

description: Scrapy parse method not working


code:
x = np.arange(100)
delta = np.random.uniform(-10,10, size=(100,))
y = .4 * x +3 + delta

rawDescription: numpy generate data from linear function

description: Numpy generate data from linear function


code:
# Append with `-1s` at either ends and get the differentiation
dfa = np.diff(np.hstack((-1,a,-1)))

# Get the positions of starts and stops of 1s in `a`
starts = np.where(dfa==2)[0]
stops = np.where(dfa==-2)[0]

# Get valid mask for pairs from starts and stops being of at least 3 in length
valid_mask = (stops - starts) >= 3

# Finally collect the valid pairs as the output
out = np.column_stack((starts,stops))[valid_mask].tolist()

rawDescription: getting ranges of sequences of identical entries with minimum length in a numpy array

description: Getting ranges of sequences of identical entries with minimum length in a numpy array


code:
from tkinter import *

def up(event):
    # warning, exceptions can happen
    old = int(event.widget.get()) # this gives back the actual object!
    event.widget.delete(0, END) # delete existing text
    event.widget.insert(10, old + 1) # put new text in

def down(event):
    # warning, exceptions can happen
    old = int(event.widget.get()) # this gives back the actual object!
    event.widget.delete(0, END) # delete existing text
    event.widget.insert(10, old - 1) # put new text in

window2 = Tk()

eyear1 = Entry(window2, width=4, font=("Helvetica", 16)) #  Entry for year
eyear1.insert(10, 2015)
eyear1.grid(row=1, column=1)

emonth1 = Entry(window2, width=4, font=("Helvetica", 16)) #  Entry for Month
emonth1.insert(10, 1)
emonth1.grid(row=1, column=2)

eday1 = Entry(window2, width=4, font=("Helvetica", 16)) #  Entry for day
eday1.insert(10, 10)
eday1.grid(row=1, column=3)

# bind both keys to corresponding event handlers
window2.bind('<Up>', up)
window2.bind('<Down>', down)
mainloop()

rawDescription: Python get focused entry name

description: Python get focused entry name


code:
cmd = subprocess.Popen("python GetAlexRanking.py " + row ,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       shell=True)
(output, err) = cmd.communicate()

rawDescription: Getting output of external python program in Windows Terminal


code:
def next_color(self):
    return next(self._get_lines.color_cycle)
plt.Axes.next_color = next_color

rawDescription: Cycle colors when plotting in matplotlib: Tracking state on a per-instance basis


rawDescription: How can I get the name of a python class?

description: Get the name of a python class


code:
# bot.py
class BotStreamListener(StreamListener):
    def __init__(api, bot):
        super(self.__class__, self).__init__(api)
        # Do your stuff
        self.bot = bot
        # Do more of your stuff

mybot = bot.bot(api)
bsl = BotStreamListener(api, mybot)

rawDescription: Appending args and code to an inherited method in python2?


rawDescription: python paste multilines to raw_input in a while loop

description: Python paste multilines to raw_input in a while loop


code:
import unittest

class Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._connection = createExpensiveConnectionObject()

    @classmethod
    def tearDownClass(cls):
        cls._connection.destroy()

rawDescription: Python unit test, run some methods only once


code:
MY_DATE_FORMATS = ['%d/%m/%Y',]

class MyModelForm(forms.ModelForm):
    date = forms.DateField(input_formats=MY_DATE_FORMATS)
    class Meta:
        model = MyModel

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

rawDescription: How to accept localized date format (e.g dd/mm/yy) in a DateField on an admin form?

description: Accept localized date format (e.g dd/mm/yy) in a DateField on an admin form


code:
letter_3 = raw_input("What is the third letter that you know?").lower
letter_3
letter_3 = raw_input("What is the third letter that you know?").lower()
letter_3

rawDescription: Crossword Solving Companion

description: Crossword Solving Companion


code:
from lxml.html import document_fromstring
from lxml.html import tostring
doc = document_fromstring(YOUR_HTML_STRING)
h1 = tostring(doc.xpath("//h1")[0])

rawDescription: Parsing a whole tag by lxml.html

description: Parsing a whole tag by lxml.html


code:
from werkzeug.routing import BaseConverter
from werkzeug.routing import ValidationError

class ListOfIntConverter(BaseConverter):
    def __init__(self, url_map):
        super(ListOfIntConverter, self).__init__(url_map)

    def validate(self, value):
        if not isinstance(value, list):
            return False

        for i in value:
            if not isinstance(i, int):
                return False

        return True

    def to_python(self, value):
        try:
            return [int(i) for i in value.split(',')]
        except (TypeError, ValueError) as e:
            raise ValidationError()

    def to_url(self, value):
        if not self.validate(value):
            # Or your specific exception because this should be from the
            # program.
            raise ValueError
        return ','.join(unicode(v) for v in value)

app.url_map.converters['listofint'] = ListOfIntConverter

@app.route('/years/<listofint:years>')
def years(years):
    return '%d, %s' % (len(years), years)

rawDescription: Flask redirect url_for changing type of parameter


code:
with open(filepath1, 'rb') as fin, open(filepath2, 'wb') as fout:
    reader = csv.reader(fin)
    writer = csv.writer(fout, quoting=csv.QUOTE_NONNUMERIC)
    for _ in xrange(4):  # copy first 4 header rows
        writer.writerow(next(reader))
    for row in reader:  # process data lines
        row[0] = row[0][:19] # strip fractional seconds from first column
        writer.writerow([row[0], int(row[1])] + map(float, row[2:]))

rawDescription: Replace column in csv with modified column


code:
def open_new_figure(event):
    if event.inaxes is not None:
        ax = event.inaxes
        # you now have the axes object for that the user clicked on
        # you can use ax.children() to figure out which img artist is in this
        # axes and extract the data from it

cid = fig.canvas.mpl_connect('button_press_event', open_new_figure)

rawDescription: Event Connections and subplots in matplotlib


code:
from stem import Signal
from stem.control import Controller

with Controller.from_port(port = 9051) as controller:
  controller.authenticate()
  controller.signal(Signal.HUP)

rawDescription: Choose specific exit node in TOR (with Python code)


code:
h = plt.hist2d(x, y)
mn, mx = h[-1].get_clim()
mn = 60 * np.floor(mn / 60.)
mx = 60 * np.ceil(mx / 60.)
h[-1].set_clim(mn, mx)
cbar = plt.colorbar(h[-1], ticks=np.arange(mn, mx + 1, 60), )

rawDescription: Make plt.colorbar extend to the steps immediately before and after vmin/vmax


rawDescription: How to add required attribute to a Django form field

description: Add required attribute to a Django form field


code:
tiles = ['/one.bmp', '/two.bmp', '/three.bmp']
tilelist = [pygame.img.load(tile) for tile in tiles]

rawDescription: Python for x in list basic question

description: Python for x in list basic question


code:
def func(lst, lo=0, hi=None):
    if hi is None:
        hi = len(lst)

rawDescription: How to get part of a list in Python without creating a new list?

description: Get part of a list in Python without creating a new list


code:
class HomePageTest(TestCase):

    urls = 'fhqna.urls'

    def test_root_url_resolves_to_list_view(self):
        found = resolve('/testme/')
        self.assertEqual(found.func.func_name, ListView.__name__)

rawDescription: How to unit test urls.py when included by project?

description: Unit test urls.py when included by project


code:
from Tkinter import *

class ImageTest(object):
    def __init__(self):

        self.window = Tk()
        self.window.geometry('300x300')

        self.init_test_screen()

        self.window.mainloop()

    def init_test_screen(self):

        self.testImg = PhotoImage(file='test.gif')
        label1 = Label(self.window, image=self.testImg )
        label1.pack()
        label2 = Label(self.window, image=self.testImg )
        label2.pack()

imagetest = ImageTest()

rawDescription: tkinter: label not displayed when pack() is called outside of a class' init function

description: Tkinter: label not displayed when pack() is called outside of a class' init function


code:
myvars = {}

# iterate through all the lines
for line in open('SampleText.txt').readlines():
    # skip this line if it doesn't look like an assignment
    if not '=' in line: continue

    # split it into left and right pieces
    left, right = line.split('=', 1)

    # keep it around in a dictionary
    myvars[left.strip()] = right.strip()

# now you can query it to get stuff:
myvars['efgh']   # returns /home/user/targetfile1.txt

rawDescription: Python: Get file path from a text file

description: Python: Get file path from a text file


rawDescription: Variable method name in python

description: Variable method name in python


code:
colnames=['TIME', 'X', 'Y', 'Z']
user1 = pd.read_csv('dataset/1.csv', names=colnames, header=None)

rawDescription: Give column name when read csv file pandas


code: ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes)

rawDescription: Place text label in 3D coordinates that are not data-dependent


code:
AnyFile = getSaveFileName
ExistingFile = getOpenFileName
Directory = getExistingDirectory
ExistingFiles = getOpenFileNames

rawDescription: How to use options in QFileDialog.getOpenFileName?

description: Use options in QFileDialog.getOpenFileName


code:
def insert(tree, List):
    for node in List:
        tree = tree[node]

users = tree()
insert(users, ['harold', 'username', 'hrldcpr'])

rawDescription: Python One-Line Tree using defaultdict. How to reduce the number of arguments required?


code:
count = {}
while True:
    color = input('Car: ')
    color = color.lower()
    if not color:
        break
    count.setdefault(color, 0)
    count[color] += 1
for color, n in count.items():
    print('Cars that are %s: %s' % (color, n))

rawDescription: Grok help - dictionaries

description: Grok help - dictionaries


code:
import yourmodule

def isEnumType(o):
    return isinstance(o, type) and issubclass(o,int) and not (o is int)

def _tuple2enum(enum, value):
    enum = getattr(yourmodule, enum)
    e = enum.values.get(value,None)
    if e is None:
        e = enum(value)
    return e

def _registerEnumPicklers():
    from copy_reg import constructor, pickle
    def reduce_enum(e):
        enum = type(e).__name__.split('.')[-1]
        return ( _tuple2enum, ( enum, int(e) ) )
    constructor( _tuple2enum)
    for e in [ e for e in vars(yourmodule).itervalues() if isEnumType(e) ]:
        pickle(e, reduce_enum)

_registerEnumPicklers()

rawDescription: Pickling an enum exposed by Boost.Python


code:
class Value(object):
    def __init__(self,
                 number=None,
                 text=None,
                 url=None):
        self.number = number
        self.text = text
        self.url = url

class Specification(object):
    def __init__(self, propertyName):
        self.propertyName = propertyName
        self.values = []

spec1 = Specification("Spec1")
spec1.values = [Value(number=3,
                      url="http://www.google.com"),
                Value(text="Hello, World!",
                      url="http://www.jasonfruit.com")]

spec2 = Specification("Spec2")
spec2.values = [Value(number=27,
                      text="I can haz cheezburger?",
                      url="http://stackoverflow.com"),
                Value(text="Running out of ideas.",
                      url="http://news.google.com")]

rawDescription: Best way to represent this using Python data structures

description: Represent this using Python data structures


code:
with open('Path/to/file', 'r') as content_file:
    content = content_file.read()
    data = json.loads(content)

rawDescription: Read A Multidimesion String Array From File


code: return flask.jsonify(**Dict)

rawDescription: Send JSON data to the front end in Flask


code:
for root, dirs, files in os.walk('/path/to/test_log_data'):
    if 'EXCEL' not in root:
        continue
    for fname in files:
        if fname.endswith('.xlsx'):
            os.remove(os.path.join(root, fname))

rawDescription: Iterating through directories and removing files based off extensions in Python


code:
from multiprocessing import Pool, Queue

pool = Pool(6)
result_queue = Queue()
graphs=[graph]
intermediary_graphs[graph]

def work(graphs):
    if g.is_column():
        #append data from graph to another list
        map_columns.append(g.lengths)
        return
    l, r = g.split()
    intermediary_graphs.append(l)
    intermediary_graphs.append(r)
    result_queue.put(l, r)

while graphs:
    pool.map(work, graphs)
    graphs = []
    while not result_queue.empty():
        graphs.append(result_queue.get())

rawDescription: Python: Using multiprocessing to partition a graph


code:
import random
import struct
str1 = struct.pack('<Q', random.randint(1, 1000))
str1.encode('hex')

rawDescription: Remove \x in string in python

description: Remove \x in string in python


code:
import scipy.optimize
import numpy as np

def yA(x):
    # whatever calculations here you do for curve A
    return(1.0) # return whatever yA is at x
def yB(x):
    # whatever calculations here you do for curve B
    return(1.0) # return whatever yB is at x
def yC(x):
    # whatever calculations here you do for curve C
    return(1.0) # return whatever yC is at x

def func(x,data):
    A,B,C = data # unpack tuple
    devA = np.abs((yA(x)-A)/yA(x)) # normalize the deviations
    devB = np.abs((yB(x)-B)/yB(x)) # to account for the order
    devC = np.abs((yC(x)-C)/yC(x)) # of magnitude variations
    return(devA+devB+devC) # you want to minimize the sum of the deviations

A = 1.0E-10 # these are your data points (rough guess from plot)
B = 1.0E-11
C = 1.0E-8
x0 = 1000.0 # an initial guess

result = scipy.optimize.minimize(func,x0,args=(A,B,C))

print(result.x)

rawDescription: Comparing model and data using scipy.optimize


code:
from twisted.conch.ssh import keys as Keys
import base64

public_key = """\
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20101003"
AAAAB3NzaC1yc2EAAAABJQAAAgEAi+91fFsxZ7k1UuudSe5gZoavwARUyZScCtdf
WQ0ROoJC+XIqW5vVJfgmr+A1jLS5m4wNsrCqeyoX2B22T6iEwqVXrXt3QcbccKMu
WkLKFK1h67q6Coc+3eOTmKrOuZbWc19YQgybdkR/GxF7XAbq4NCGNaCDtMOqX8Q2
L/a9fAYqVdTwg9trpcz3whNmdLk/B0edOABKuVX51UdLV+ZggK503+uAb1JiIIj0
mARwR/HNo4oRLMLf2PjuZsGVYYjJDdVJBU6AN4PUQSRRRPL4+YmsrLJb/TpfJeXA
vj4KZMNJv15YXz7/iMZMKznDtr2RJX5wbSpuTUBNZveA7YiIHxvvvis38b/lX9SJ
SYPfZ9CeQY6MvQgG2zwDTOOvKgOIB4sTGMXfcoxB8AF/QXOcxWFJkZoj36rvMd9n
Po6szLjHXwcEUOUvvQfG4VvdQA0H5gGLHqYL1EehRsgi5qcCoFPaZW2K09ErKcS0
MbrLFjBkQ9KmqAM38bvM8UhCWAMA9VXOGHMxUHBV4Bir9alGS4VX0B8Y0b3dZ+7I
MKkHMCwdEUJf7QVdGxGuSQtVsq8RZbIpk3g7wtv8f6I/iEC58ekdrH35tq5+1ilW
dkk9+rrhUy4qrZ+HFi7AeemybpiumbSnebvnkMaIPAOo23V8C9BQ0iuxx4gIZf10
o+TPSK8=
---- END SSH2 PUBLIC KEY ----"""

key_data = ''.join(public_key.splitlines()[2:-1])# remove begin, end tags and comment
blob = base64.decodestring(key_data)
key = Keys.Key._fromString_BLOB(blob)

rawDescription: Python Asymmetric Encryption: Using pre-generated prv/pub keys


code:
keys = ['key1', 'key2', 'key3', 'key4', 'key5'] # and so forth..

dictionaries = [my_dict, my_dict2] # Just an example, you probably build this list while you stream the tweets.

with open('mycsvfile.csv', 'wb') as f:
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    for d in [x for x in dictionaries if x.keys() == keys]: # only matching keys.
       w.writerow(d)

rawDescription: Writing multiple dictionaries to CSV with one header with Python


code:
import pyttsx
engine = pyttsx.init()
engine.say('Sally sells seashells by the seashore.')
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

rawDescription: Pyttsx not saying all text when using non default voice


code: closest = min(P, key=lambda p: sum((p - A)**2))

rawDescription: Find nearest neighbour in a more pythonic way


code: text = line.split(": ", 1)[1]

rawDescription: Python regular expression (is it possible to shorten it?)


code:
import matplotlib.colors as mcol

lvTmp = np.linspace(0.1,1.0,len(levels)-1)
cmTmp = mlp.cm.Paired(lvTmp)
newCmap = mcol.ListedColormap(cmTmp)

rawDescription: Select starting color in matplotlib colormap


code:
#!/usr/bin/python
import glob
from sys import argv

g=open(argv[2],'w')
g.write("Status,Job Number,Coder Machine Name,Machine type, Operator Id,Job Start time,Job end time\n")
for fname in glob.glob(argv[1]):
    with open(fname) as f:
        status=f.readline().strip().strip(',')
        f.readline()#extended report not needed
        f.readline()#job spec numerical control not needed
        s=f.readline()
        job_no=s.split('Job Number,')[1].split(',')[0]
        op_id=s.split('Operator Id,')[1].strip().strip(',')
        s=f.readline()
        machine_name=s.split('Coder Machine Name,')[1].split(',')[0]
        start_t=s.split('Job Start time,')[1].strip().strip(',')
        s=f.readline()
        machine_type=s.split('Machine type,')[1].split(',')[0]
        end_t=s.split('Job end time,')[1].strip().strip(',')
    g.write(",".join([status,job_no,machine_name,machine_type,op_id,start_t,end_t])+"\n")
g.close()

rawDescription: Extracting oddly arranged data from csv and converting to another csv file using python


code:
import yt
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

fns = ['enzo_tiny_cosmology/DD0005/DD0005', 'enzo_tiny_cosmology/DD0040/DD0040']

fig = plt.figure()

# See http://matplotlib.org/mpl_toolkits/axes_grid/api/axes_grid_api.html
# These choices of keyword arguments produce a four panel plot with a single
# shared narrow colorbar on the right hand side of the multipanel plot. Axes
# labels are drawn for all plots since we're slicing along different directions
# for each plot.
grid = AxesGrid(fig, (0.075,0.075,0.85,0.85),
                nrows_ncols = (2, 1),
                axes_pad = 0.05,
                label_mode = "L",
                share_all = True,
                cbar_location="right",
                cbar_mode="single",
                cbar_size="3%",
                cbar_pad="0%")

for i, fn in enumerate(fns):
    # Load the data and create a single plot
    ds = yt.load(fn) # load data

    # Make a ProjectionPlot with a width of 34 comoving megaparsecs
    p = yt.ProjectionPlot(ds, 'z', 'density', width=(34, 'Mpccm'))

    # Ensure the colorbar limits match for all plots
    p.set_zlim('density', 1e-4, 1e-2)

    # This forces the ProjectionPlot to redraw itself on the AxesGrid axes.
    plot = p.plots['density']
    plot.figure = fig
    plot.axes = grid[i].axes
    plot.cax = grid.cbar_axes[i]

    # Finally, this actually redraws the plot.
    p._setup_plots()

plt.savefig('multiplot_1x2_time_series.png', bbox_inches='tight')

rawDescription: Adding subplots within yt-Project plot

description: Adding subplots within yt-Project plot


code:
try:
    # python 3.x
    import tkinter as tk
except ImportError:
    # python 2.x
    import Tkinter as tk

class CustomWidget(tk.Frame):
    def __init__(self, parent, label, default=""):
        tk.Frame.__init__(self, parent)

        self.label = tk.Label(self, text=label, anchor="w")
        self.entry = tk.Entry(self)
        self.entry.insert(0, default)

        self.label.pack(side="top", fill="x")
        self.entry.pack(side="bottom", fill="x", padx=4)

    def get(self):
        return self.entry.get()

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.label = tk.Label(self)
        self.e1 = CustomWidget(self, "First Name:", "Inigo")
        self.e2 = CustomWidget(self, "Last Name:", "Montoya")
        self.submitButton = tk.Button(self, text="Submit", command=self.submit)

        self.e1.grid(row=0, column=0, sticky="ew")
        self.e2.grid(row=1, column=0, sticky="ew")
        self.label.grid(row=2, column=0, sticky="ew")
        self.submitButton.grid(row=4, column=0)

        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(2, weight=1)

    def submit(self):
        first = self.e1.get()
        last = self.e2.get()
        self.label.configure(text="Hello, %s %s" % (first, last))

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).place(x=0, y=0, relwidth=1, relheight=1)
    root.mainloop()

rawDescription: creating a custom widget in tkinter

description: Creating a custom widget in tkinter


rawDescription: App Engine NDB alternative for db.StringListProperty


code:
df = pd.read_csv('brainweight.csv')
w = list(df['Weight'])
s = list(df['Sex'])
def list_by_gender():
    females = []
    males = []
    for sex, weight in zip (s, w):
        if sex == 'f':
            females.append(weight)
        else:
            males.append(weight)
    return males,females

male_list,female_list=list_by_gender()

rawDescription: Splitting list according to criteria (gender)


code:
format_string = "{last}, {first}"
name = {'first': 'John', 'last':''}
format_string.format(**name).strip(', ')
'John'

rawDescription: Conditionally including additional characters using python string formatting


code:
s = 'THESE_VALUES = ["Value1", "vAlue2", "VaLUE4"]'
eval(s.split('=', 1)[1])

rawDescription: Execute file rather than parse it

description: Execute file rather than parse it


code:
t = threading.Thread(target=some_function, args=[argument])
t.setDaemon(False)
t.start()

rawDescription: Perform Task Directly After Returning JSON


code:
#only for testing
a = ([2,7],[1,4],[2,3],[6,4],[9,2])
b = [1,4]

def findindex(matrix, row):
    for index in range(0,len(matrix)):
        if matrix[index] == row:
            return index
    return -9

if __name__ == '__main__':
    print(findindex(a, b))

rawDescription: Python toe find the row index

description: Python toe find the row index


code:
urls = [j.url for j in a.followers]
db.graph.update_one({"user_id": a.url}, {"$addToSet": {"following": {"$each": urls}}})

rawDescription: Avoid a duplicate value when I update array using $push on MongoDB


code:
f1 = csv.reader(open('file1.csv', 'rb'))
writer = csv.writer(open("file2.csv", "wb"))
phone_numbers = set()
for row in f1:
    if row[1] not in phone_numbers:
        writer.writerow(row)
        phone_numbers.add( row[1] )

rawDescription: Python: Removing duplicate CSV entries

description: Python: Removing duplicate CSV entries


code: c = C.objects.filter(todays_treatment=medication, patient__in=b)

rawDescription: Field lookup with a queryset

description: Field lookup with a queryset


code:
def getData(i, value):
    global dataList
    if condition:
        return list(suffixList)
    #do something
    return getData(i, value)

rawDescription: python functions returning noneType

description: Python functions returning noneType


code:
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import pandas as pd
from datetime import datetime

def get_datetime(string):
    "Converts string '2008-05-04' to datetime"
    return datetime.strptime(string, "%Y-%m-%d")

# Generate datarame
df = pd.DataFrame(dict(
             starbucks=["2008-09-18", "2007-06-12"],
             cafe_cool=["2010-05-04", "2011-02-17"],
             barista=["2007-02-21"]),
             index=["dist1", "dist2"])

ax = plt.subplot(111)

label_list = []
label_ticks = []
yval = 1 # numbering system

# Iterate through coffee shops
for coffee_shop, dates in df.iteritems():

    # Convert strings into datetime list
    datetimes = [get_datetime(date) for date in dates]

    # Create list of yvals [yval, yval, ...] to plot against
    yval_list = np.zeros(len(dates))+yval

    ax.plot_date(datetimes, yval_list)

    # Record the number and label of the coffee shop
    label_ticks.append(yval)
    label_list.append(coffee_shop)

    yval+=1 # Change the number so they don't all sit at the same y position

# Now set the yticks appropriately
ax.set_yticks(label_ticks)
ax.set_yticklabels(label_list)

# Set the limits so we can see everything
ax.set_ylim(ax.get_ylim()[0]-1,
            ax.get_ylim()[1]+1)

rawDescription: Scatter plot for non numeric data

description: Scatter plot for non numeric data


code:
try:
    import readline
except:
    pass #readline not available

rawDescription: command line in python with history

description: Command line in python with history


code:
import os

directory = os.path.join("c:\\","path")
for root,dirs,files in os.walk(directory):
    for file in files:
       if file.endswith(".csv"):
           f=open(file, 'r')
           #  perform calculation
           f.close()

rawDescription: Read in all csv files from a directory using Python


code:
import re

r = re.compile(r'(<my id="1">.*)(</my>)')

with open(infilename, 'r') as infile, open(newfile, 'w+') as outfile:
    for line in infile:
        match = r.search(line)
        if match:
            f.write(match.group(1) + '(1)' + match.group(2))
        else:
            f.write(line)

rawDescription: Edit an xml file using python regular expression


code:
class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.id'))
    child = relationship("Child", backref="parents")

rawDescription: How do I access the related ForeignKey object from a object in SQLAlchemy?

description: Access the related ForeignKey object from a object in SQLAlchemy


code:
import random
def nouns():

    nounPersons = ["cow","crowd","hound","clown"];
    nounPlace = ["town","pound","battleground","playground"];
    rhymes = ["crowned","round","gowned","found","drowned"];

    nounPersons2 = ["dog","frog","hog"];
    nounPlace2 = ["fog","Prague","smog"];
    rhymes2 = ["log","eggnog","hotdog"];

    nounList1 = [nounPersons,nounPlace,rhymes]
    nounList2 = [nounPersons2,nounPlace2,rhymes2]
    nounsList = [nounList1, nounList2]
    randomPick = random.choice(nounsList)

    return randomPick

verbs = ["walked","ran","rolled","biked","crawled"]

# this is change 1.
chosen_list = nouns()

# select single words from lists - this is change 2.

noun_subj = random.choice(chosen_list[0])
noun_obj = random.choice(chosen_list[1])
rhyme_word = random.choice(chosen_list[2])
verb_word = random.choice(verbs)

# insert words in to text line - this is change 3.

print ("The {} {} to the {}. But then it was {}.".format(noun_subj, verb_word, noun_obj, rhyme_word))

rawDescription: Python: How to print my simple poem

description: Python: How to print my simple poem


code:
class MyUserAdmin(UserAdmin):
    def is_superuser_text(self, obj):
        return 'True' if obj.is_superuser else 'False'
    is_superuser_text.short_description = 'Is Superuser'
    is_superuser_text.admin_order_field = 'is_superuser'

    list_display = ('username', 'first_name', 'email', 'date_joined', 'is_superuser_text',)

rawDescription: Django Admin, how to replace the user status sign


code:
with open(argv[1]) as f:
    print(f.readlines())

rawDescription: input string in bio python via sys.argv

description: Input string in bio python via sys.argv


rawDescription: Return IPv6 address Python from domain name


code: my_value = self.kwargs.get('key', 'default_value')

rawDescription: django 1.3 - Correct way to define optional parameters for a class based view

description: Django 1.3 - Correct way to define optional parameters for a class based view


code:
class MyRegistrationForm(UserCreationForm):
    ...
    class Meta:
        model = UserProfile
        fields = ('username', 'address', 'password1', 'password2', 'status')

rawDescription: how to change the order of the fields?

description: Change the order of the fields


code:
class User(Base):
    __tablename__ = 'users'
    id = Column(BigInteger, id_seq, primary=True)
    name = Column(Unicode(256))

class Article(Base):
    __tablename__ = 'articles'
    __bind_key__ = 'another_engine'

    id = Column(BigInteger, id_seq, primary=True)
    author_id = Column(BigInteger, nullable=False, index=True)
    body = Column(UnicodeText, nullable=False)

    author = relationship("User",
                primaryjoin="foreign(Article.author_id) == User.id")

rawDescription: How can I make property comparison able to be compiled to SQL expression in SQLAlchemy?

description: Make property comparison able to be compiled to SQL expression in SQLAlchemy


code:
values = {
    'oauth_token': request_token,
    'username': beatport_login,
    'password': beatport_pass,
    'submit' : 'Login',
}

r = requests.post('https://oauth-api.beatport.com/identity/1/oauth/authorize-submit', data=values)

verifier = r.url.split("oauth_verifier=",1)[1]

tokens = beatport.get_raw_access_token(request_token, request_token_secret, method='POST', data={
    'oauth_verifier': verifier})

rawDescription: How do I get the oauth_verifier for a session in Rauth

description: Get the oauth_verifier for a session in Rauth


code:
import time

old_time = time.strptime('01:00', '%H:%M')
new_time = time.strptime('06:00', '%H:%M')

print(old_time)
print(new_time)

if old_time > new_time:
    print('old time is old')
else:
    print('new is cool')

rawDescription: How to check if the current time is in range in python using time strings?

description: Check if the current time is in range in python using time strings


rawDescription: How to use variable number arguments to pyplot.plot?

description: Use variable number arguments to pyplot.plot


code:
def power(f, n):
    def wrapped(x):
        for i in range(n):
            x = f(x)
        return x
    return wrapped

rawDescription: How to construct such a functional-programming tool in Python?

description: Construct such a functional-programming tool in Python


code:
from time import sleep
from threading import Thread
from Queue import Queue

class DispatcherThread(Thread):

   def __init__(self, *args, **kwargs):
       super(DispatcherThread, self).__init__(*args, **kwargs)
       self.interested_threads = []

   def run(self):
       while 1:
           if some_condition:
               self.dispatch_message(some_message)
           else:
               sleep(0.1)

   def register_interest(self, thread):
       self.interested_threads.append(thread)

   def dispatch_message(self, message):
       for thread in self.interested_threads:
           thread.put_message(message)

class WorkerThread(Thread):

   def __init__(self, *args, **kwargs):
       super(WorkerThread, self).__init__(*args, **kwargs)
       self.queue = Queue()

   def run(self):

       # Tell the dispatcher thread we want messages
       dispatcher_thread.register_interest(self)

       while 1:
           # Wait for next message
           message = self.queue.get()

           # Process message
           # ...

   def put_message(self, message):
       self.queue.put(message)

dispatcher_thread = DispatcherThread()
dispatcher_thread.start()

worker_threads = []
for i in range(10):
    worker_thread = WorkerThread()
    worker_thread.start()
    worker_threads.append(worker_thread)

dispatcher_thread.join()

rawDescription: Need a thread-safe asynchronous message queue