code:
from myapp import Injection

inj = Injection() # create an instance

inj.gather_path() # to set self.object to a value other than None

inj.parse_param_paths() # call method with instance

rawDescription: Print results in console of class

description: Print results in console of class


code:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
import numpy as np

r = [(datetime.datetime(2015, 12, 22), 6), (datetime.datetime(2015, 12, 23), 5), (datetime.datetime(2015, 12, 23), 4), (datetime.datetime(2015, 12, 24), 12), (datetime.datetime(2015, 12, 25), 14)]

x, v = zip(*[(d[0], d[1]) for d in r])  # same as #x , v = [d[0] for d in r], [d[1] for d in r]
v = np.array(v).cumsum()  # cumulative sum of y values

# now plot the results
fig, ax = plt.subplots(1)
ax.plot(x, v, '-o')
fig.autofmt_xdate()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
ax.xaxis.set_major_locator(mdates.DayLocator())
plt.show()

rawDescription: Plot sum over time

description: Plot sum over time


code:
entities = len(a)

for data in range(entities):
    ID = []
    ID.append(a[data][0])
    ID.extend(a[data][1].split(' '))
    print("ID[0] = {0}\nID[1] = {1}\nID[2] = {2}\n".format(ID[0], ID[1], ID[2]))

rawDescription: how to use split and strip in python for lines with multiple delimiters on linux

description: Use split and strip in python for lines with multiple delimiters on linux


rawDescription: Python - creating a delay that takes in account the execution time


code:
def getIsland(request):
    if hasattr(request, "_cached_island"):
        return request._cached_island
    try:
        island = Island.objects.get(user=request.user) # Retrieve
    except Island.DoesNotExist:
        island = Island(user=request.user) # Doesn't exist, create default one
        island.save()
    island.update() # Run scheduled tasks
    request._cached_island = island
    return island # Return

rawDescription: Django querysets - make sure results are retrieved only once


code:
def hasmethod(obj, name):
    return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType

rawDescription: How to test if a class attribute is an instance method

description: Test if a class attribute is an instance method


rawDescription: How to mock.patch a class imported in another module

description: Mock.patch a class imported in another module


code: url = c.fetchone()[0]

rawDescription: Remove unwanted characters from SQL retreival


code:
# when write action log
# 1. decide the prefix based on the data
prefix = decide_prefix(action)

# 2. random pick up a bulk for this data
index = random.choice(range(100))

# 3. write action into a queue
action_list = memceche.get("%s_%s"%(prefix, index))
action_list.append(action)
memcache.set("%s_%s"%(prefix,index), action_list)

# when read action log
action_lists = memcache.get_multi(["%s_%s"%(prefix, k) for k in range(100)])

# merge all action list together.
all_action_list = merge_action_list(action_lists)

rawDescription: App Engine: Memcache design to ensure fast read and high write throughput


rawDescription: Python parsing numbers

description: Python parsing numbers


code:
@api.onchange('fieldx')
def do_stuff(self):
   if self.fieldx == x:
       self.fieldy = 'toto'

rawDescription: onchange functions on boolean fields in odoo 8

description: Onchange functions on boolean fields in odoo 8


code:
def blit_mask(source, dest, destpos, mask, maskrect):
    """
    Blit an source image to the dest surface, at destpos, with a mask, using
    only the maskrect part of the mask.
    """
    tmp = source.copy()
    tmp.blit(mask, maskrect.topleft, maskrect, special_flags=pygame.BLEND_RGBA_MULT)
    dest.blit(tmp, destpos, dest.get_rect().clip(maskrect))

rawDescription: Pygame: How to draw in non rectangle clipping area


rawDescription: How do I verify if every list contains a common number?

description: Verify if every list contains a common number


code:
from math import pi

pianswer = input ("What is pi?")
if str(pi).startswith(pianswer):
    print ("That is correct")

rawDescription: Python: How do I check if something in a string is right


code:
class A(object):
    def __init__(self, foo, bar=3):
        self.foo = foo
        self.bar = bar

class B(A):
    def __init__(self, quux=6, **kwargs):
        super(B, self).__init__(**kwargs)

        self.quux = quux

B(foo=1, quux=4)

rawDescription: Can I pass python **kwargs to parent class from sub?

description: Pass python **kwargs to parent class from sub


code:
def isnamedtupleinstance(x):
    t = type(x)
    b = t.__bases__
    if len(b) != 1 or b[0] != tuple: return False
    f = getattr(t, '_fields', None)
    if not isinstance(f, tuple): return False
    return all(type(n)==str for n in f)

rawDescription: Python: how to check if an object is an instance of a namedtuple?


code:
for i in range(len(ts0)):
    tM = ts0[i] # time in minutes
    tH = tM/60.0 # time in hours

    tHs[i] = int(tH) # now this is the data within hour tH

tHs0 = tHs[:] # keep a record of the original hourly times, there are repeats here
tHs = list(set(tHs0)) # now we have a list of the hours with no repeats

for i in range(len(ts0)):
    y0 = ys0[i]
    t0 = ts0[i]
    tH = int(t0/60.0)
    ys[tHs.index(tH)] += R0
    Cs[tHs.index(tH)] += 1 # keep a record of how many times this was seen

for i in range(len(ys)):
    ys[i] = ys[i]/Cs[i]

rawDescription: Smoothing in Python

description: Smoothing in Python


code:
import re
match_literal_hyphen = "[ab-]"
re.findall(match_literal_hyphen, "abc - def")
match_literal_caret = "[a^b]"
re.findall(match_literal_caret, "abc ^ def")

rawDescription: Difference between character sets in Python and re2c regular expressions


code:
s, bins = pd.cut(pd.Series(np.arange(11)), bins = 5, retbins=True)
mid = [(a + b) /2 for a,b in zip(bins[:-1], bins[1:])]
s.cat.rename_categories(mid)

rawDescription: python bin data and return bin midpoint (maybe using pandas.cut and qcut)

description: Python bin data and return bin midpoint (maybe using pandas.cut and qcut)


rawDescription: Convert array of int to array of chars - Python


code: response.menu = [(T('Index'), False, 'http://www.google.com')]

rawDescription: Web2py: how to config menu.py to add link to an external link


code: newstr = oldstr[:4] + oldst[5:]

rawDescription: Remove char at specific index - python

description: Remove char at specific index - python


code:
dictionary = {}
cur.execute('select idcustomer,idfactory,distance from distance')
result = cur.fetchall()
for idcustomer, idfactory, distance in result:
   dictionary[distance] = "{}:{}".format(idcustomer, idfactory)

rawDescription: Populate Python dictionary from sqlite database


code:
import logging
logging.getLevelName(10)
logging.getLevelName('DEBUG')
logging.addLevelName(15, 'DEBUGGISH')
logging.getLevelName(15)
logging.getLevelName('DEBUGGISH')

rawDescription: Python logging - determine level number from name


code:
for d in response:
    d['highlighted_string'] = response.highlighting[d['id']]
results_list = response

rawDescription: Solr highlighting through Scorched in Django


code:
import networkx as nx
import matplotlib.pyplot as plt

G=nx.DiGraph()
R=[('S0','S1'),('S1','S2'),('S1','S7'),('S0','S7')]

G.add_edges_from(R)

# Calculate layout and get all positions
pos = nx.circular_layout(G)

# Draw everything
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edge_labels(G, pos,
    {
        ('S0', 'S1'): 'edge1',
        ('S1', 'S2'): 'edge2',
        ('S1', 'S7'): 'edge3',
        ('S0', 'S7'): 'edge4'
    }
)

plt.axis('off')
plt.savefig("path.png");
plt.show()

rawDescription: python build graph with notes

description: Python build graph with notes


code:
class MyUser(AbstractUser):
    pass
    class Meta:
        app_label = 'auth'

rawDescription: Keep User and Group in same section in Django admin panel


code:
db = pyodbc.connect('DSN=northwind')
isolation = db.getinfo(pyodbc.SQL_DEFAULT_TXN_ISOLATION)
print('isolation=%s' % isolation)

rawDescription: Python pyodbc settings

description: Python pyodbc settings


code:
with open('data.csv') as data:
    lines = [re.split(r'\s+|,', i.strip()) for i in data]

rawDescription: Reading in data with different delimiters in Python


code:
zmin = 0.0
zmax = 0.4
zi[(zi<zmin) | (zi>zmax)] = None
CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow,
                  vmax=zmax, vmin=zmin)

rawDescription: putting limits to x,y,z interpolated heatmap in matplotlib

description: Putting limits to x,y,z interpolated heatmap in matplotlib


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://www.indeed.com/viewjob?jk=2e3d019aa34a2801&q=bartender&tk=1a9g51n08a3iof6h&from=web&advn=5333586156877432&sjdu=UvkB_mgi5f7NyMagFcTHP0E6zA3mclLGHWb8Kte-0FV3cY2ZuZvj3LUvh8wnnxrqeYWG3HpvTXBK3G4htWfwgfQeMa0N1Tds6VxYb4V3Vlg&pub=4a1b367933fd867b19b072952f68dceb")

driver.find_element_by_class_name('indeed-apply-button').click()

wait = WebDriverWait(driver, 10)
frame = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "iframe[name$=modal-iframe]")))

driver.switch_to.frame(frame)
driver.switch_to.frame(0)

print(driver.find_element_by_css_selector("h1.jobtitle").text)

rawDescription: Selecting nested iframes with Selenium in Python


code:
array1 = np.array([[1,2,3],[4,5,6]])
array1
add = np.zeros((2,1), dtype=int64)
add
np.append(array1, add, axis=1)
b=np.array([[6],[8]])
np.append(array1,b,axis=1)

rawDescription: Is there an easy way to append a column to 2-d numpy array in Python?


code:
def simple_func(dirpath):
    paths = os.listdir(dirpath)
    # create absolute paths
    abs_paths = [os.path.join(dirpath, p) for p in paths]
    # filter for paths that are files
    file_list = [p for p in paths if os.path.isfile(p)]
    return file_list

rawDescription: How to stop os.walk from walking all sub-directories down?

description: Stop os.walk from walking all sub-directories down


code:
import os
data = [(int(p), c) for p, c in [x.rstrip('\n').split(' ', 1) \
       for x in os.popen('ps h -eo pid:1,command')]]

rawDescription: how do I get the process list in Python?

description: Get the process list in Python


code:
def rlinput(prompt, prefill=''):
   readline.set_startup_hook(lambda: readline.insert_text(prefill))
   try:
      return raw_input(prompt)
   finally:
      readline.set_startup_hook()

rawDescription: Show default value for editing on Python input possible?


code:
from threading import Thread

threads = [Thread(target=f1), Thread(target=f2), Thread(target=f3)]

for thread in threads:
    thread.start()

# Wait for all of them
for thread in threads:
    thread.join()

# Do stuff afterwards

rawDescription: Simultaneus threads

description: Simultaneus threads


code:
def update_user_social_data(strategy, *args, **kwargs):
    if not kwargs['is_new']:
        return

    user = kwargs['user']

    fbuid = kwargs['response']['id']
    access_token = kwargs['response']['access_token']

    url = u'https://graph.facebook.com/{0}/' \
          u'?fields=email' \
          u'&access_token={1}'.format(
        fbuid,
        access_token,
    )

    request = urllib2.Request(url)
    email = json.loads(urllib2.urlopen(request).read()).get('email')

    user.email = email
    user.save()

rawDescription: Facebook Doesn't Return Email Python Social Auth


code:
l = [
    HeadObj(1),
    HeadObj(2),
    BodyObj(1),
    BodyObj(2),
    BodyObj(3),
    FooterObj(1)
]
if USE_SEPARATORS:
    l.insert(2, Separator())
    l.insert(6, Separator())

rawDescription: Conditionally add items to a list when defining the list?


code:
has_equal = False

lst = list(map(int, input().split(" ")))

sumleft = 0
total = sum(lst)

for i in range(1, lst_size):
    sumright = 0
    sumleft += lst[i-1]
    sumright = total - sumleft - lst[i]

    if sumleft == sumright:
        has_equal = True
        break

if has_equal or lst_size == 1:
    print("YES")
else:
    print("NO")

rawDescription: HackerRank Sherlock and Array performance


code:
while items:
    foo()

rawDescription: Consuming an iterator in a while loop

description: Consuming an iterator in a while loop


code:
class MultipleKeyDict(dict):
    __slots__ = ["_primary_keys"]
    def __init__(self, arg=None, **kwargs):
        self._primary_keys = {}
        self.update(arg, **kwargs)
    def __setitem__(self, key, value):
        super(MultipleKeyDict, self).__setitem__(key, value)
        self._primary_keys.setdefault(value, key)
    def __delitem__(self, key):
        value = self[key]
        super(MultipleKeyDict, self).__delitem__(key)
        if self._primary_keys[value] == key:
            del self._primary_keys[value]
            for k, v in super(MultipleKeyDict, self).iteritems():
                if v == value:
                    self._primary_keys[value] = k
                    break
    def __iter__(self):
        return self.iterkeys()
    def update(self, arg=None, **kwargs):
        if arg is not None:
            if isinstance(arg, collections.Mapping):
                for k in arg:
                    self[k] = arg[k]
            else:
                for k, v in arg:
                    self[k] = v
        for k in kwargs:
            self[k] = kwargs[k]
    def clear(self):
        super(MultipleKeyDict, self).clear()
        self._primary_keys.clear()
    def iteritems(self):
        for v, k in self._primary_keys.iteritems():
            yield k, v
    def items(self):
        return list(self.iteritems())
    def itervalues(self):
        return self._primary_keys.iterkeys()
    def values(self):
        return self._primary_keys.keys()
    def iterkeys(self):
        return self._primary_keys.itervalues()
    def keys(self):
        return self._primary_keys.values()

rawDescription: Python dict like surjective multiple key → value container


rawDescription: Put data in a particularly shaped list

description: Put data in a particularly shaped list


rawDescription: How can I run a file using Python?

description: Run a file using Python


rawDescription: How do I create a "not" filter in python for pandas

description: Create a "not" filter in python for pandas


code:
from django.db.models import Count

Product.objects.get(pk=1).offer_set.all().values('price').annotate(total=Count('price')).order_by('price')

rawDescription: How to count how many records have minimum value in field? (Django)

description: Count how many records have minimum value in field? (Django)


code:
D = [ (x, Dict[x]) for x in Dict]
ascending = sorted(D, key = lambda x: x[1])
ascending.sort()

rawDescription: Sort a dictionary according to the lists size and then alphabetically by their key in Python?


code:
from interface.modules import Wiki, Search, Web, Default

modules = {'wiki': Wiki, 'search': Search, 'Internet': Web, 'browser': Web}

module_to_load = modules.get(user_input, Default)

view.load(module_to_load)

rawDescription: python application structure, dynamically loading modules

description: Python application structure, dynamically loading modules


rawDescription: Rounding values in a numpy array resulting from matrix calculation


rawDescription: Can I dynamically pass a list of arguments to a python function with predefined arguments?

description: Dynamically pass a list of arguments to a python function with predefined arguments


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar')
parser.add_argument('spam')
parser.add_argument('eggs')
parser._actions

rawDescription: How can I list all registered arguments from an ArgumentParser instance?

description: List all registered arguments from an ArgumentParser instance


rawDescription: How to remove elements from a list

description: Remove elements from a list


code:
lst = ["dog", "cat" ,"boy", "cat", "car", "bus"]
pairs = zip(lst, lst[1:])     # [("dog", "cat"), ("cat", "boy"), ...]
d = {}
for k,v in pairs:
    d.setdefault(k, [])    # Set e.g. d["dog"] to [] if there is no d["dog"] yet
    d[k].append(v)

rawDescription: python: creating a dictionary

description: Python: creating a dictionary


code:
from Tkinter import *
import sys

def write():
    new_player = e1_var.get() + " " + e2_var.get()
    with open('stats', 'a') as file:
        file.write("\n" + new_player + "\n")

    players[new_player] = Label(text=new_player).grid(column=0)
    e1_var.set("")
    e2_var.set("")

root=Tk()
root.title("Basketball Stats")
l1=Label(text="Player").grid(column=0, row=0)
l2=Label(text="Number").grid(column=0, row=1)

e1_var = StringVar()
e1 = Entry(textvariable=e1_var).grid(column=1, row=0)

e2_var = StringVar()
e2 = Entry(textvariable=e2_var).grid(column=1, row=1)

b1=Button(text="Submit", command=write).grid(column=1, row=3)

players = {}
with open("stats", "r") as file:
    for line in file.read().split('\n'):
        players[line] = Label(text=line).grid(column=0)

root.mainloop()

rawDescription: How to update Tkinter labels?

description: Update Tkinter labels


code: regex = re.compile('^\d{8}.NYP.xml$')

rawDescription: How to find an XML file with a particular name

description: Find an XML file with a particular name


rawDescription: Search for sentence that may containing different words in Python


code:
import os

os.environ["DJANGO_SETTINGS_MODULE"] = "settings"  # "settings" will be your django settings file path

rawDescription: Settings Issue when running Managepy Shell in Django


code:
import pandas as pd

Location = r'C:\temp\test.xlsx'
data = pd.read_excel(Location, '4bar', header=0, parse_cols=0)
numpy_data = data.as_matrix()

rawDescription: How to convert the dataframe to array in python?

description: Convert the dataframe to array in python


code:
import sys
import threading

last_line = ''
new_line_event = threading.Event()

def keep_last_line():
    global last_line, new_line_event
    for line in sys.stdin:
        last_line = line
        new_line_event.set()

keep_last_line_thread = threading.Thread(target=keep_last_line)
keep_last_line_thread.daemon = True
keep_last_line_thread.start()

rawDescription: How to read most recent line from stdin in python

description: Read most recent line from stdin in python


code: val = struct.unpack('>I', b'\x00' + reg[34:37])

rawDescription: Creating 16 and 24-bit integers from binary file


code:
class Functions(QObject):

    solveComputationSignal = pyqtSignal(str)
    updateStatusSignal = pyqtSignal(int, str)

    def __init__(self, parent=None):
        super(Functions, self).__init__(parent)
        self.text = ""

    def setResultText(self, text):
        self.text = text

    def solveComputation(self, platform, computation, param=None):
        result = urllib.urlopen(COMPUTATION_URL).read()
        if param is None:
            self.solveComputationSignal.emit(result)
        else:
            self.solveAlternateComputation(platform, computation)

        while not self.text:
            time.sleep(3)

        return self.text if self.text else False

    def updateCurrentStatus(self, platform, statusText):
        self.updateStatusSignal.emit(platform, statusText)

# worker_A
    def run(self):
        ...
        f = Functions()
# worker_B
    def run(self):
        ...
        f = Functions()

rawDescription: A couple of questions about calling methods outside of QThread from within the QThread - is my design flawed?


code:
import wx
from wx.lib.iewin import IEHtmlWindow
a = wx.App(redirect=False)
f = wx.Frame(None,-1,"My Desktop Application")
browser = IEHtmlWindow(f)
browser.Navigate("http://google.com")
f.Show()
a.MainLoop()

rawDescription: Implement web based desktop application with python


code:
import urllib2
import cookielib

cookie_jar = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))

#Get the first page with the cookie, installing it in the cookie jar automatically
opener.open("http://yoursite.com/set-cookie")

#Get the second page, passing on the cookie in the cookiejar.
opener.open("http://yoursite.com/other")

#Alternatively, you can also install this opener as the default urllib2 opener:
urllib2.install_opener(opener)
#Now all urllib2 requests will use cookies:
urllib2.urlopen("http://yoursite.com/other")

rawDescription: Help converting code using httlib2 to use urllib2


code:
my_string = "apple,orange,kiwi,mange"
my_list = ["kiwi", "apple", "mange", "orange"]
set(my_list).issubset(my_string.split(','))

rawDescription: Comparaison of two list in python

description: Comparaison of two list in python


code: ",".join( map(str, record_ids) )

rawDescription: Automagically expanding a Python list with formatted output


code:
condition = []
while not condition:
    ...

self.mock_module['time'].sleep.side_effect = [lambda:condition.append(1)]

rawDescription: Return as a function: return()

description: Return as a function: return()


code:
import itertools

a = [1, 2, 3]
b = [4, 5, 6]
c = list(itertools.product(a, b))

idx = c.index((1,4))

rawDescription: python all possible pairs of 2 list elements, and getting the index of that pair

description: Python all possible pairs of 2 list elements, and getting the index of that pair


code:
from TwitterAPI import TwitterAPI

CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN_KEY = ''
ACCESS_TOKEN_SECRET = ''

api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
file = open('Your_image.png', 'rb')
data = file.read()
r = api.request('statuses/update_with_media', {'status':'Your tweet'}, {'media[]':data})
print(r.status_code)

rawDescription: How To Add An Image To A Tweet With TwitterAPI?


code:
import sys
from PySide import QtCore, QtGui

class MyWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.b = QtGui.QPushButton("exit", self, clicked=self.close)
        self.setWindowOpacity(.8)
        self.setStyleSheet("QMainWindow { background: 'black'}");

        self.dialog = QtGui.QDialog()
        self.dialog.setModal(True)
        self.dialog.show()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyWindow()
    myapp.setGeometry(app.desktop().screenGeometry())
    myapp.show()
    sys.exit(app.exec_())

rawDescription: PyQt - How do I fade the desktop background behind a dialog (similar to Windows UAC)?


code: new_loss = loss.replace('\.fail.?$', '', regex=True)

rawDescription: How to delete specific substrings of a pandas table that has strings

description: Delete specific substrings of a pandas table that has strings


code:
d = 'Mar  5 09:10:11'
import dateutil
dateutil.parser.parse(d)

rawDescription: Parse arbitary date formats in Python (including rfc3164)


code:
from django.db.models import Count
qs = Foo.objects.filter(
           bar__eg_id__in=id_list
      ).annotate(
           bar_count=Count('bar')
      ).order_by('bar_count')

rawDescription: Django QuerySet ordering by number of reverse ForeignKey matches


code:
def inputNo( a, b, c ):
    result = {"isComb":[], "notComb":[]}
    for i in range(1,100):
        if ((6*a)+(9*b)+(20*c) == i ):
            result['isComb'].append(i)
        else:
            result['notComb'].append(i)

    return result

rawDescription: combination a of 6a +9b+20c =n when n is range (0, 100)

description: Combination a of 6a +9b+20c =n when n is range (0, 100)


rawDescription: wxpython drag and drop one folder then another to add to list

description: Wxpython drag and drop one folder then another to add to list


code:
p1 = figure(...)
p1.line(...)
p1.circle(...)

p2 = figure(...)
p2.rect(...)

gp = gridplot([p1, p2])
show(gp)

rawDescription: bokeh overlay multiple plot objects in a GridPlot

description: Bokeh overlay multiple plot objects in a GridPlot


code: open('out.csv', 'w').write('\n'.join(map(' '.join, __import__('csv').reader(open('in.csv')))))

rawDescription: Is there a way to convert a csv file to a space sperated file in python


code:
import re
next_page_data = response.xpath('//div[@class="sabai-pull-right sabai-pagination"]/ul/li/a[contains(text(), "Next")]/@onclick').extract()
next_page_data
url = re.findall(r'url\:\'(.*)\'\}', next_page_data[0])
url
nex_page_url = url[0] + '&__ajax=%23sabai-directory-listings&_='
nex_page_url

rawDescription: Python, scrapy: Unable to paginate dynamically generated links on website, using the link got from firebug


code:
rows = soup.findAll("table",{"id":"cos"})[0].findAll('tr')
records = []
for tr in rows:
  cols = tr.findAll('td')
  record = ''
  for td in cols:
    if record != '': record = record + ', '
    record = record + td.contents[0]
  records.append(record + "\n")

rawDescription: Insert new line after every record in python and comma between elements of record


code:
#! /usr/bin/env python3

# The following is a database of problem and keywords for those problems.
# Its format should be extended to take into account possible solutions.
PROBLEMS = (('My phone does not turn on.',
             {'power', 'turn', 'on', 'off'}),
            ('My phone is freezing.',
             {'freeze', 'freezing'}),
            ('The screen is cracked.',
             {'cracked', 'crack', 'broke', 'broken', 'screen'}),
            ('I dropped my phone in water.',
             {'water', 'drop', 'dropped'}))

# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', '1')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', '0')))

def main():
    """Find out what problem is being experienced and provide a solution."""
    description = input('Please describe the problem with your phone: ')
    words = {''.join(filter(str.isalpha, word))
             for word in description.lower().split()}
    for problem, keywords in PROBLEMS:
        if words & keywords:
            print('This may be what you are experiencing:')
            print(problem)
            if get_response('Does this match your problem? '):
                print('The solution to your problem is ...')
                # Provide code that shows how to fix the problem.
                break
    else:
        print('Sorry, but I cannot help you.')

def get_response(query):
    """Ask the user yes/no style questions and return the results."""
    while True:
        answer = input(query).casefold()
        if answer:
            if any(option.startswith(answer) for option in POSITIVE):
                return True
            if any(option.startswith(answer) for option in NEGATIVE):
                return False
        print('Please provide a positive or negative answer.')

if __name__ == '__main__':
    main()

rawDescription: How Can I Put Keywords Into My Code?

description: Put Keywords Into My Code


code: repr(a)

rawDescription: outputting data as dictionaries in a new python file

description: Outputting data as dictionaries in a new python file


code:
Connection("morton.local", replicaset='foo')
Connection([u'morton.local:27019', 'morton.local:27017', u'morton.local:27018'])
Connection("morton.local:27018", replicaset='foo')
Connection([u'morton.local:27019', u'morton.local:27017', 'morton.local:27018'])
Connection("morton.local", 27019, replicaset='foo')
Connection(['morton.local:27019', u'morton.local:27017', u'morton.local:27018'])
Connection(["morton.local:27018", "morton.local:27019"])
Connection(['morton.local:27019', u'morton.local:27017', 'morton.local:27018'])
Connection("mongodb://morton.local:27017,morton.local:27018,morton.local:27019")
Connection(['morton.local:27019', 'morton.local:27017', 'morton.local:27018'])

rawDescription: Primary Goes down and Secondary now Primary - How to write to new Primary?


code:
import numpy as np
row, col = 10, 5
matrix = np.random.randint(2, size=(row,col))

rawDescription: NUMPY create, fill with random binary data


code:
import sys
from PyQt4 import QtGui

class QTestWidget (QtGui.QWidget):
    def __init__ (self):
        super(QTestWidget, self).__init__()
        self.myQMenuBar = QtGui.QMenuBar(self)
        exitMenu = self.myQMenuBar.addMenu('File')
        exitAction = QtGui.QAction('Exit', self)
        exitAction.triggered.connect(QtGui.qApp.quit)
        exitMenu.addAction(exitAction)
        self.myQMenuBar.hide()
        self.setMouseTracking(True)

    def mouseMoveEvent (self, eventQMouseEvent):
        self.myQMenuBar.setVisible(True if eventQMouseEvent.y() <= 23 else False)
        QtGui.QWidget.mouseMoveEvent(self, eventQMouseEvent)

myQApplication = QtGui.QApplication(sys.argv)
myQTestWidget = QTestWidget()
myQTestWidget.show()
myQApplication.exec_()

rawDescription: Make toolbar appear when approached by cursor


code:
w = .2
bins = np.linspace(-4, 4, 11, endpoint=True)
fig, ax = plt.subplots()
for j in range(1, 15):
    tt = randn(50)

    nn, _bins = np.histogram(tt, bins)
    #  don't use scatter unless you need to change the size or color of the markers
    ax.plot(j*np.ones_like(tt), tt, 'r.')
    ax.imshow(nn.reshape(-1, 1)[::-1], extent=[j-w, j+w, -4, 4], cmap='Blues', aspect='auto', interpolation='none')

ax.set_xlim([0, 15])
ax.set_ylim([-4, 4])

rawDescription: Overlay columns of histograms with scatter plots


code: target: yourmodule

rawDescription: GAE Python - How to set a cron job to launch a backend task


code:
sorted_list = [item[1] for item in sorted(zip(Y, X), reverse=True)]
sorted_list

rawDescription: Sorting list of strings based on a list of ints (Python)


code:
from multiprocessing import Pool

def pull_down(cursor):
    # get all the data in one query
    count = cursor.execute("""SELECT adam_id FROM title WHERE success=0
                      AND number_of_tries < 5 ORDR BY adam_id LIMIT 1""")
    if count:
        # Step #1
        adam_id_list = [row[0] for row in cursor.fetchall()]

        # Step #2
        pool = Pool(4)
        results = pool.map(do_api_call, adam_id_list)
        pool.close()

        # Step #3
        update_db(results)

def do_api_call(adam_id):
    # do api call
    success = call_api_with_id(adam_id)
    return (adam_id, success)

def update_db(results):
    # loop over results and built batch queries for the success
    # or failed items

    # (obviously this split up could be optimized)
    succeeded = [result[0] for result in results if result[1]]
    failed = [result[0] for result in results if not result[1]]

    submit_success(succeeded)
    submit_failed(failed)

rawDescription: Distributing a workload in python

description: Distributing a workload in python


code:
from datetime import date, timedelta

start_date = date.today()
end_date = date(2014, 4, 9)

if start_date - end_date > timedelta(days=10):
    print('yes')
else:
    print('no')

rawDescription: Detect Conflict Periods in Django Forms

description: Detect Conflict Periods in Django Forms


code:
import matplotlib.pyplot as plt

T = range(M.shape[0])

for i in range(M.shape[1]):
    plt.plot(T, M[:,i])

plt.show()

rawDescription: graph the contents of a matrix in python (using matplotlib)

description: Graph the contents of a matrix in python (using matplotlib)


rawDescription: Identify and replace rows in a ndarray

description: Identify and replace rows in a ndarray


code:
import imaplib

def get_unread_msgs(user, passwd):
    M = imaplib.IMAP4_SSL('imap.gmail.com')
    M.login(user, passwd)
    try:
        M.select()
        try:
            type, data = M.search(None, '(UNSEEN)')
            for num in data[0].split():
                yield M.fetch(num, '(RFC822)')
        finally:
            M.close()
    finally:
        M.logout()

rawDescription: Getting a link from emails using a dedicated account


code:
import sys

app = QtGui.QApplication([])

widget = QtGui.QLabel("My Label")
widget.setText("New Value")
widget.show()

sys.exit(app.exec_())

rawDescription: Print inside widget

description: Print inside widget


code:
def combine(L):
    results = {}
    for item in L:
        key = (item["date"], item["price"])
        if key in results:  # combine them
            results[key] = {"date": item["date"], "price": item["price"], "amount": item["amount"] + results[key]["amount"]}
        else:  # don't need to combine them
            results[key] = item
    return results.values()

rawDescription: How to match two values in dict and merge results

description: Match two values in dict and merge results


code:
def position_and_velocity (x, t, params):
    # x = (S, V) as vectors
    # Ordinary differential equation - velocity of an object in frictionless free-fall.
    G = params
    g = np.array ([0, 0, -G])
    # convert the 6 element vector to 2 3 element vectors of displacement and velocity
    # to use vector formulation of the math
    s,v = x.reshape (2,3)
    acceleration = np.array ([v * t, g])
    # reshape the two vector results back into one for odeint
    return np.reshape (acceleration, 6)

s = np.array ([0, 0, 5])
v = np.array ([40, 10, 0])
SV0 = np.array ([s, v])
# pass reshaped displacement and velocity vector to odeint
soln = odeint (position_and_velocity, np.reshape (SV0, 6), t, args = (G,))

rawDescription: Is it possible to get scipy.integrate.odeint to work with a pair of vectors (or vector of vectors)


code:
from pandas import DataFrame
from matplotlib.pyplot import show, subplots
from itertools import cycle # Useful when you might have lots of Regions

data = DataFrame({'X': [100, 50, 70, 60, 80, 120],
                     'Y': [50, 25, 35, 40, 120, 35],
                     'Type': ['A', 'A', 'B', 'B', 'C', 'C'],
                     'Region': ['US', 'UK'] * 3
                    },
                    columns=['X', 'Y', 'Type', 'Region']
       )

cs = {'A':'red',
      'B':'blue',
      'C':'green'}

markers = ('+','o','>')
fig, ax = subplots()

for region, marker in zip(set(data.Region),cycle(markers)):
    reg_data = data[data.Region==region]
    reg_data.plot(x='X', y='Y',
          kind='scatter',
          ax=ax,
          c=[cs[x] for x in reg_data.Type],
          marker=marker,
          label=region)
ax.legend()
show()

rawDescription: How to plot multiple groups in different colors and shapes with matplotlib?

description: Plot multiple groups in different colors and shapes with matplotlib


code:
from flask import request

@app.route('/note/<int:id>', methods=['POST'])
def note(id):
    form = PostForm(request.form)
    # or, if you are using Flask-WTF
    # you can do
    # form = PostForm()
    # and Flask-WTF will automatically pull from request.form

rawDescription: How to pass a "WTF object" in Flask

description: Pass a "WTF object" in Flask


code:
import re
import numpy

def read_pgm(filename, byteorder='>'):
    """Return image data from a raw PGM file as numpy array.

    Format specification: http://netpbm.sourceforge.net/doc/pgm.html

    """
    with open(filename, 'rb') as f:
        buffer = f.read()
    try:
        header, width, height, maxval = re.search(
            b"(^P5\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n]\s)*)", buffer).groups()
    except AttributeError:
        raise ValueError("Not a raw PGM file: '%s'" % filename)
    return numpy.frombuffer(buffer,
                            dtype='u1' if int(maxval) < 256 else byteorder+'u2',
                            count=int(width)*int(height),
                            offset=len(header)
                            ).reshape((int(height), int(width)))

if __name__ == "__main__":
    from matplotlib import pyplot
    image = read_pgm("foo.pgm", byteorder='<')
    pyplot.imshow(image, pyplot.cm.gray)
    pyplot.show()

rawDescription: Numpy and 16-bit PGM

description: Numpy and 16-bit PGM


rawDescription: Python Tkinter grid-geometry sticky setting not effective(?)


code:
import collections

all_dict = {"pos": collections.defaultdict(int),
            "neg": collections.defaultdict(int)}

result = {}

for psl in self.readPSL():
    parsed = pls.split()
    strand = "pos" if parsed[9][-1]=='1' else "neg"
    name, contig = parsed[9][:-2], parsed[13]
    all_dict[strand][(name,contig)] += 1
# pre-process all the psl's into all_dict['pos'] or all_dict['neg']
#   this is basically just a `collections.Counter` of what you're doing already!

for info, posqty in all_dict['pos'].items():
    negqty = all_dict['neg'][info]  # (defaults to zero)
    result[info] = qty * other_qty
# process all the 'pos' psl's. For every match with a 'neg', set
#   result[(name, contig)] to the total (posqty * negqty)

rawDescription: Improving a nested loop for efficiency

description: Improving a nested loop for efficiency


code:
import cv2

# Read image
src = cv2.imread("threshold.png", cv2.CV_LOAD_IMAGE_GRAYSCALE)

# Set threshold and maxValue
thresh = 127
maxValue = 255

# Basic threshold example
th, dst = cv2.threshold(src, thresh, maxValue, cv2.THRESH_BINARY);

# Find Contours
countours,hierarchy=cv2.findContours(dst,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# Draw Contour
cv2.drawContours(dst,countours,-1,(255,255,255),3)

cv2.imshow("Contour",dst)
cv2.waitKey(0)

rawDescription: draw contour with cv2.threshold() function

description: Draw contour with cv2.threshold() function


code:
criteria = lambda row : row['name'] in row['title']
df['flag'] = df.apply(criteria, axis =1)

rawDescription: check if one string contains another substring in python

description: Check if one string contains another substring in python


rawDescription: Accessing matched substrings when substituting using regular expressions in Python


code:
a, b, c = np.split(orig, np.where(orig[:-1, 2] != orig[1:, 2])[0]+1)
a
b
c

rawDescription: Identify vectors with same value in one column with numpy in python


code:
class MainForm(QMainWindow,Ui_MainWindow):
    # lots of methods

    def closeEvent(self, event):
        # here you can terminate your threads and do other stuff

        # and afterwards call the closeEvent of the super-class
        super(QMainWindow, self).closeEvent(event)

rawDescription: Not runing class destructor when i close app in python and pyqt


code:
from django.core import exceptions

class DocumentWizard(SessionWizardView):
    # ...

    def get_form_initial(self, step):
        # ... determine document_id
        document = Document.objects.get(id=document_id)
        if self.request.user == document.owner:
            document_dict = model_to_dict(document)
            return document_dict
        else:
            raise exceptions.PermissionDenied

rawDescription: Python Django: Use Form Wizard to Edit Model and check if request user is allowed to edit


rawDescription: Python - string format - integral part of decimals


code:
class TestThread(QThread):
    testSignal = QtCore.pyqtSignal(str)
    ...

    def run(self):
        while (not self.stopped):
            ps0 = Process(target=Producer, args=(q, l, 'eth0', q2, l2))
            ps0.start()
            self.testSignal.emit('some text message')

class ChildWid(QWidget):
    ...

    QtCore.pyqtSlot(str)
    def handleTestSignal(self, message):
        print(message)
        self.text.setText(message)

class Ui_MainWindow(QWidget):
    def __init__(self):
        ...
        self.th0.testSignal.connect(self.chilWid.handleTestSignal)

rawDescription: how can i real time update the text without affecting other event(pyqt)

description: Real time update the text without affecting other event(pyqt)


code:
seen = set(item_list)

# [...]

if item not in seen:
    seen.add(item)
    item_list.append(item)

rawDescription: Is there a more Pythonic way to prevent adding a duplicate to a list?


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
import uuid

Base = declarative_base()

class GUID(TypeDecorator):
    impl = String(32)

    def process_bind_param(self, value, dialect):
        if value is not None:
            return "%.32x" % value
        else:
            return MNone

    def process_result_value(self, value, dialect):
        if value is None:
            return value
        else:
            return uuid.UUID(value)

class User(Base):
    __tablename__ = 'users'
    id = Column(GUID(), primary_key=True, default=uuid.uuid4)
    name = Column(String(40), unique=True)

e = create_engine("mysql://scott:tiger@localhost/test", echo=True)
Base.metadata.drop_all(e)  # just for testing here
Base.metadata.create_all(e)

s = Session(e)

s.add_all([User(name='u1'), User(name='u2'), User(name='u3')])
s.commit()

for guid in s.query(User.id):
    print(guid)

rawDescription: Configuring MySQL to allow generation of Primary Key values


code:
import sys
getattr(sys,'exc_info')
getattr(sys,'exc_info')()

rawDescription: Python - passing a function as an argument to another function


code:
from itertools import chain
number_of_chr = 22,'X','Y'
n, *rest = number_of_chr
['chr%s'%i for i in chain(range(1, n+1), rest)]

rawDescription: Generate a list with a for-loop

description: Generate a list with a for-loop


code: f = open(r"C:\Users\David\Python Files\apple juice.txt", "a")

rawDescription: How do I decide where to put the file while creating it in python?

description: Decide where to put the file while creating it in python


code:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randn(100,4), columns = ['x', 'y', 'z', 'w'])

plt.ion()
plt.show()
plt.pause(0.001)

p = sns.JointGrid(
    x = df['x'],
    y = df['y']
    )

p = p.plot_joint(
    plt.scatter
    )

p.ax_marg_x.hist(
    df['x'],
    alpha = 0.5
    )

p.ax_marg_y.hist(
    df['y'],
    orientation = 'horizontal',
    alpha = 0.5
    )

p.ax_marg_x.hist(
    df['z'],
    alpha = 0.5,
    range = (np.min(df['x']), np.max(df['x']))
    )

p.ax_marg_y.hist(
    df['w'],
    orientation = 'horizontal',
    alpha = 0.5,
    range = (np.min(df['y']), np.max(df['y'])),
    )

rawDescription: How to overlay a Seaborn jointplot with a "marginal" (distribution histogram) from a different dataset

description: Overlay a Seaborn jointplot with a "marginal" (distribution histogram) from a different dataset


code:
from math import log
def bytes_needed(n):
    if n == 0:
        return 1
    return int(log(n, 256)) + 1
bytes_needed(0x01)
bytes_needed(0x100)
bytes_needed(0x10000)

rawDescription: Get size of integer in Python

description: Get size of integer in Python


code: set(dict1.keys()) & set(list1)

rawDescription: Python - intersect a dict and list

description: Python - intersect a dict and list


code:
current_time = datetime.datetime.utcnow()

ten_weeks_ago = current_time - datetime.timedelta(weeks=10)

subjects_within_the_last_ten_weeks = session.query(Subject).filter(
    Subject.time > ten_weeks_ago).all()

rawDescription: Doing DateTime Comparisons in Filter SQLAlchemy


code: related_model = getattr(Model, field.name).get_query_set().model

rawDescription: python - exec() line works in shell, but not while call in def

description: Python - exec() line works in shell, but not while call in def


code:
c = conn.cursor()
c.execute("SELECT image_data FROM favicon_bitmaps WHERE index='26'")
data = c.fetchone()
with open('C:\file.png', 'wb') as x:
    x.write(data[0])

rawDescription: What is the most concise way to fetch a blob in Python using sqlite3?


code:
import heapq

return heapq.nlargest(n, l)

rawDescription: n highest values of a list in Python

description: N highest values of a list in Python


rawDescription: Django, query for related field: related field exists which meet conditions


code:
#Locale settings
import locale
# Set to German locale to get comma decimal separater
locale.setlocale(locale.LC_NUMERIC, "de_DE")

import numpy as np
import matplotlib.pyplot as plt
plt.rcdefaults()

# Tell matplotlib to use the locale we set above
plt.rcParams['axes.formatter.use_locale'] = True

# make the figure and axes
fig,ax = plt.subplots(1)

# Some example data
x=np.arange(100)
y=4e-18*x**2

# plot the data
ax.plot(x,y,'b-')

plt.show()

rawDescription: How to change point to comma in matplotlib graphics?

description: Change point to comma in matplotlib graphics


code: nin = bar if nin is None else nin

rawDescription: Pythonic way to map optional parameters to a compulsory one if None


rawDescription: Norm along row in pandas

description: Norm along row in pandas


code:
#!/usr/bin/env python
import sys
import fileinput

for line in fileinput.input(inplace=True):
    if line.strip(): # preserve non-blank lines
        sys.stdout.write(line)

rawDescription: How to completely remove "\n" in text file using python

description: Completely remove "\n" in text file using python


code:
list_iter = iter(item_list)

for item in list_iter:
    if item == "XYZ":
        do_something()
        for _ in range(3):   # skip next 3 items
            next(list_iter, None)

# etc.

rawDescription: How to conditionally skip number of iteration steps in a for loop in python?

description: Conditionally skip number of iteration steps in a for loop in python


code:
n = 200
p = 2
X = np.random.normal(0, 1, (n, p))
y = X[:,0]* X[:, 1] + np.random.normal(0, .1, n)
y.shape = (n, 1)

ds = DenseDesignMatrix(X=X, y=y)

hidden_layer = mlp.Sigmoid(layer_name='hidden', dim=10, irange=.1, init_bias=1.)
output_layer = mlp.Linear(dim=1, layer_name='y', irange=.1)
trainer = sgd.SGD(learning_rate=.05, batch_size=10,
                  termination_criterion=EpochCounter(200))
layers = [hidden_layer, output_layer]
ann = mlp.MLP(layers, nvis=2)
trainer.setup(ann, ds)

while True:
    trainer.train(dataset=ds)
    ann.monitor.report_epoch()
    ann.monitor()
    if not trainer.continue_learning(ann):
        break

inputs = X
y_est = ann.fprop(theano.shared(inputs, name='inputs')).eval()

rawDescription: create a single layer neural network with pylearn2

description: Create a single layer neural network with pylearn2


code:
import gst

pipeline = gst.parse_launch("""
v4l2src ! decodebin ! ffmpegcolorspace ! pngenc ! filesink location="%s"
""" % sys.argv[-1])

pipeline.set_state(gst.STATE_PLAYING)

rawDescription: Options to read webcam using Python/Linux


code: _, FILENAME = os.path.split(infile)

rawDescription: How to skip initializing the 1st returned value from a function? - Python

description: Skip initializing the 1st returned value from a function? - Python


code:
branch = r.head.reference
commit = r.head.commit
branch.commit = commit.parents[0]
# This works because the index is unchanged by the `branch.commit`
# edit, but it won't work if you're trying to change a commit on
# another branch -- you can't really do that
new_commit = repo.index.commit(u"new message")

rawDescription: Edit a commit with gitpython

description: Edit a commit with gitpython


code:
class SkillView(ModelView):

    form_ajax_refs = {
        'users': {
            'fields': (User.username,)
        }
    }

rawDescription: How to do a custom query in Model View on *-to-Many relationship in Flask Admin?

description: Do a custom query in Model View on *-to-Many relationship in Flask Admin


code:
import cx_Oracle
import csv

con = cx_Oracle.connect('temapp/password@temappdb')
cur = con.cursor()
cur.execute("SELECT * FROM emp")

with open("emp.csv", "wb") as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow([i[0] for i in cur.description])  # write headers
    csv_writer.writerows(cur)

rawDescription: How to run sqlplus query in python 3.4

description: Run sqlplus query in python 3.4


code:
def get_gc_across_sections(s):
    sections =  [s[i:i+5] for i in range(0, len(s), 5)]
    return [GCcont(section) for section in sections]

rawDescription: Python 2.7 - Identify Pathogenicity Islands - Calculate GC Content Across Sections of a String


code:
def send_a_frame():
    capture = cv2.VideoCapture(0)
    frame = capture.read()[1]
    cnt = cv2.imencode('.png',frame)[1]
    b64 = base64.encodestring(cnt)
    html = "<html><img src='data:image/png;base64,"+b64 +"'></html"
    send(html)

rawDescription: How can i send cv2.frames to a browser

description: Send cv2.frames to a browser


code:
import matplotlib.cm as cmx
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib
import numpy as np

def scatter3d(x,y,z, cs, colorsMap='jet'):
    cm = plt.get_cmap(colorsMap)
    cNorm = matplotlib.colors.Normalize(vmin=min(cs), vmax=max(cs))
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.scatter(x, y, z, c=scalarMap.to_rgba(cs))
    scalarMap.set_array(cs)
    fig.colorbar(scalarMap,label='Test')
    plt.show()

x = np.random.uniform(0,1,50)
y = np.random.uniform(0,1,50)
z = np.random.uniform(0,1,50)

rawDescription: A right way to represent 4 dimension points using colors in a matplotlib scatter


code:
lines = file.readlines()
lines = lines[:-1]

rawDescription: Delete final line in file via python

description: Delete final line in file via python


code:
from subprocess import Popen, PIPE

process = Popen('mysql %s -u%s' % (db, "root"), stdout=PIPE, stdin=PIPE, shell=True)
output = process.communicate('source' + file)[0]

rawDescription: Automated database restore from *.sql files


code:
from numpy import array
a = array(['java database servlets derby', 'java graphics groovy awt basic',
           'java lucene', 'javascript android',
           'iphone ios ipad file uiimage',
           'javascript jquery transition effect'])
list_of_lists = [x.split() for x in a]
list_of_lists

rawDescription: Converting a 1D numpy array to a list of lists


rawDescription: How can I sort a list of dictionaries by a value in the dictionary?

description: Sort a list of dictionaries by a value in the dictionary


code:
import sys
import time
import threading

from PySide.QtCore import *
from PySide.QtGui import *
qt_app = QApplication(sys.argv)
label = QLabel('Hello, loop!')
label.show()

running = True #only set to False when user is done with app in the real code.

def worker():
    global running
    while running:
        #I am handling connections here that MUST be in continual while loop
        print("loop")
        time.sleep(0.5)

thread = threading.Thread(target=worker)
thread.setDaemon(True)
thread.start()

qt_app.exec_()

rawDescription: pyside qapplication exec with while loop

description: Pyside qapplication exec with while loop


code:
contact = ContactInfo(user=target_user)
# other stuff
contact.save()
#or
target_user.contactinfo_set.create(...)#contactinfo_set is the related name of target_user
#Django maintains the foreign key things.

rawDescription: saving a django orm model with a foreign key

description: Saving a django orm model with a foreign key


code:
message = 'Thank you for using our Library! You have decided to borrow {0.title} \
           on {0.start_date}. Please remember to return the book in \
           {0.lend_duration} calendar days on {0.return_date}'

for i in books:
    print(message.format(i))

rawDescription: Conform long lines to fit PEP 8

description: Conform long lines to fit PEP 8


code: [x for l in list for x in l]

rawDescription: Python - unpack list of lists

description: Python - unpack list of lists


code:
it = zip(x, y, z)
xnew, ynew, znew = zip(*(t for t in it if t[-1] > 0))

rawDescription: Simpler Way of Creating Lists from other Lists


rawDescription: Add columns from different dataframes to target dataframe in PySpark


code:
from tests import *
import unittest

if __name__ == '__main__':
    testsuite = unittest.TestLoader().discover('.')
    unittest.TextTestRunner(verbosity=1).run(testsuite)

rawDescription: How to write tests in Python using unittest

description: Write tests in Python using unittest


code:
import random
random.randrange(5, 19+1, 2)

rawDescription: How do I generate a number of random numbers that are all odd

description: Generate a number of random numbers that are all odd


code:
from math import log10, floor

def roundSD(x, sd):
    "Returns x rounded to sd significant places."
    return round(x, -int(floor(log10(abs(x)))) + sd - 1)

def round5(x, sd):
    "Returns x rounded to sd significant places, ending in 5 and 0."
    return round(x * 2, -int(floor(log10(abs(x)))) + sd - 1) / 2

inputData = [-0.1, 0.21, 0.29, 4435.0, 9157, 9858.0, 10758.0, 11490.0, 12111.9]
roundedDict = {}
roundedData = []

for input in inputData:
    if input in roundedDict:
        # The input is already calculated.
        roundedData.append(roundedDict[input])
        continue

    # Now we attempt to round it
    success = False
    places = 1
    while not success:
        rounded = roundSD(input, places)
        if rounded in roundedDict.values():
            # The value already appeared! We use better precision
            places += 1
        else:
            # We rounded to the correct precision!
            roundedDict[input] = rounded
            roundedData.append(rounded)
            success = True

rawDescription: Round Python list with unique values

description: Round Python list with unique values


code:
class YourObjectHere(object):
    ###blahblahblah your code here
    ...
    ...

def main():
    MyObj = YourObjectHere(*args, **kwargs)
    OtherObj.do_stuff_with_obj(MyObj)
    #etc etc etc
    ...
    ...

if __name__ == '__main__':
    main()

rawDescription: Is it bad practice to use Functions in OOP?


code:
from dateutil.relativedelta import relativedelta
from datetime import datetime

# Where day is the day you want in the following month
dt = datetime.now() + relativedelta(months=1, day=20)

rawDescription: How do I find the nth day of the next month in Python?

description: Find the nth day of the next month in Python


rawDescription: Using boolean opeation between 2 arrays in python


rawDescription: How can I change the folder where a file is created in python?

description: Change the folder where a file is created in python


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')

plt.show()

rawDescription: Changing the color of the axis, ticks and labels for a plot in matplotlib


code:
openFiles = {}
for line in fileinput.input(src):
    parts = line.split('|')
    recType = parts[7]
    if not recType in openFiles:
        openFiles[recType] = open('f_' + recType, 'w')
    openFiles[recType].write(line)
    # ....

rawDescription: Split a file into parts based on the data using Python


code:
def _clean_doc(self, doc, namespace, timestamp):
    """Reformats the given document before insertion into Solr.

    This method reformats the document in the following ways:
      - removes extraneous fields that aren't defined in schema.xml
      - unwinds arrays in order to find and later flatten sub-documents
      - flattens the document so that there are no sub-documents, and every
        value is associated with its dot-separated path of keys
      - inserts namespace and timestamp metadata into the document in order
        to handle rollbacks

    An example:
      {"a": 2,
       "b": {
         "c": {
           "d": 5
         }
       },
       "e": [6, 7, 8]
      }

    becomes:
      {"a": 2, "b.c.d": 5, "e.0": 6, "e.1": 7, "e.2": 8}

    """

    # Translate the _id field to whatever unique key we're using.
    # _id may not exist in the doc, if we retrieved it from Solr
    # as part of update.

    """mf mongo-connector extension"""
    if 'created' in doc:
        if isinstance( doc['created'], int ):
            utc_dt = datetime(1970, 1, 1) + timedelta(seconds=doc['created'])
            doc['created'] = utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    if 'updated' in doc:
        if isinstance( doc['updated'], int ):
            utc_dt = datetime(1970, 1, 1) + timedelta(seconds=doc['updated'])
            doc['updated'] = utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    """end mf mongo-connector extension"""

    if '_id' in doc:
        doc[self.unique_key] = u(doc.pop("_id"))

    # Update namespace and timestamp metadata
    if 'ns' in doc or '_ts' in doc:
        raise errors.OperationFailed(
            'Need to set "ns" and "_ts" fields, but these fields already '
            'exist in the document %r!' % doc)
    doc['ns'] = namespace
    doc['_ts'] = timestamp

    # SOLR cannot index fields within sub-documents, so flatten documents
    # with the dot-separated path to each value as the respective key
    flat_doc = self._formatter.format_document(doc)

    # Only include fields that are explicitly provided in the
    # schema or match one of the dynamic field patterns, if
    # we were able to retrieve the schema
    if len(self.field_list) + len(self._dynamic_field_regexes) > 0:
        def include_field(field):
            return field in self.field_list or any(
                regex.match(field) for regex in self._dynamic_field_regexes
            )
        return dict((k, v) for k, v in flat_doc.items() if include_field(k))
    return flat_doc

rawDescription: Indexing mongoDb date(in unix timestamp) to solr 'date' (YYYY-MM-DDThh:mm:ssZ) in mongo-connector(solr_doc_manager.py)


code:
class Database:

    def __init__(self, config):
        self.CONFIG=config
        sys.path.append(self.CONFIG.cx_oracle_path)
        from cx_Oracle import cx_Oracle
        self.cx_Oracle = cx_Oracle
        self.open()

    def open(self):
        self.CONNECTION = self.cx_Oracle.Connection(self.CONFIG.username,
                                                    self.CONFIG.password,
                                                    self.CONFIG.db_sid)
        self.CURSOR = self.CONNECTION.cursor()

rawDescription: Import module based on path within a config file


code:
def vanish_image(image, screen, background_color):
    image = pygame.image.load(image).convert()
    image.set_colorkey((0,0,0)) #RGB-value for transparent color if needed

    alpha = 255

    while True:
        if alpha < 0: #exit function if alpha is smaller than 0
            return

        alpha -= 1

        screen.fill(background_color) #"clear" last blitted image
        image.set_alpha(alpha)

        pygame.display.update(screen.blit(image,(0,0))) #blit new image onto surface and update only this area

        pygame.time.delay(20) #wait 20 milliseconds

rawDescription: How can I use the alpha channel un Pygame?

description: Use the alpha channel un Pygame


code:
import matplotlib.pyplot as plt
import numpy

x = numpy.arange(10.)
d = dict((i, numpy.sin(x+i)) for i in range(5))

for k in sorted(d):  # sort purely to make deterministic
    plt.plot(x,d[k],label=str(k))

plt.legend(loc=2)
plt.draw()

rawDescription: How does legend() work on a dynamic data set?


code:
def remove_last_odd(numbers):
    rnumbers = numbers[::-1]
    for n in rnumbers:
        if n % 2 != 0:
            rnumbers.remove(n)
            break
    return rnumbers[::-1]

rawDescription: How to remove last odd number in a list

description: Remove last odd number in a list


code: vote_date = models.DateField(_('vote date'), null=False, blank=False, auto_now=True)

rawDescription: Set today date as default value in the model


code:
rand_num = random.random()
entity = MyModel.all().order('rand_num').filter('rand_num >=', rand_num).get()
if entity is None:
  entity = MyModel.all().order('rand_num').get()

rawDescription: How to get something random in datastore (AppEngine)?

description: Get something random in datastore (AppEngine)


code:
def NewCols(x):
    for item, frame in group['Column2'].iteritems():
        Genes = frame.split(',')
        for value in Genes:
            string = value
            x[string] = np.nan
    return x

UngroupedResGenesLineage.groupby('Column1').apply(NewCols)

rawDescription: How to append new columns to a pandas groupby object from a list of values

description: Append new columns to a pandas groupby object from a list of values


code:
import numpy
e = [(Pa, Pb) for Pa in a for Pb in b]
e[numpy.argmin([math.sqrt(math.pow(Pa[0]-Pb[0],2) + math.pow(Pa[1]-Pb[1],2)) for (Pa, Pb) in e])]

rawDescription: python: finding smallest distance between two points in two arrays

description: Python: finding smallest distance between two points in two arrays


code:
s
type(s)
dict(s)
s.to_dict()

rawDescription: convert series returned by pandas.Series.value_counts to a dictionary

description: Convert series returned by pandas.Series.value_counts to a dictionary


code:
def on_done(w, *args):
    gtk.gdk.keyboard_ungrab()
    gtk.gdk.pointer_ungrab()

def show_menu_cb():
    menubar.connect('cancel', on_done)
    menubar.connect('selection-done', on_done)
    menubar.select_item(menuitem)

rawDescription: How to select a MenuItem programatically

description: Select a MenuItem programatically


code:
def start_requests(self):
    for index, url in enumerate(self.start_urls):
        yield  Request(url, dont_filter=True, meta={'index': index})

rawDescription: Scrapy: retain original order of scraped items in the output


code:
from testoob.coverage import Coverage
orig_should_cover = Coverage._should_cover_frame
def my_should_cover_frame(self, frame):
    from os.path import abspath
    filename = abspath(frame.f_code.co_filename)
    if filename.find('my_module') == -1:
        return False
    else:
        return orig_should_cover(self, frame)
Coverage._should_cover_frame = my_should_cover_frame

rawDescription: Ignoring modules other than own in testoob coverage reporting


code:
lines   = inputString.split('\n')
phone   = lines[-1] if lines[-1].match(REGEX_PHONE_US) else None
address = '\n'.join(lines[:-1]) if phone else inputString

rawDescription: How to Python split by a character yet maintain that character?


code:
with open('file_a','r') as fa:  # open file a --> read the files into lists
    list_a = fa.read().splitlines()
with open('file_b','r') as fb:  # open file b --> read the files into lists
    list_b = fb.read().splitlines()

# get element in list_b if list_a contain the element(only first 24 characters)
match_list = [n for n in list_b if n[:24] in list_a]

with open('file_c','w+') as fc:  # write the matching list to the new file
    fc.write('\n'.join(match_list))

rawDescription: How to match two text files, find matches and replace with original content?

description: Match two text files, find matches and replace with original content


code:
import sys
import hashlib

file_path = sys.argv[0]
with open(file_path, 'rb') as file_handle:
    file_contents = file_handle.read()
    print('MD5 - ' + hashlib.md5(file_contents).hexdigest())

rawDescription: Pythons hashlib producing different hash value than the original hash


code:
import vtk
extents = [[0,0],[620,0],[620,220],[0,220]]

polyPoints = vtk.vtkPoints()

for x, y in extents:
    polyPoints.InsertNextPoint(x, y, 0)

num_corners = len(extents)
polyCells = vtk.vtkCellArray()
polyCells.InsertNextCell(num_corners + 1)

for i in range(0, num_corners):
    polyCells.InsertCellPoint(i)

polyCells.InsertCellPoint(0) ## Rejoin at the end

poly_profile = vtk.vtkPolyData()
poly_profile.SetPoints(polyPoints)
poly_profile.SetPolys(polyCells) ## Goes solid

cut_triangles = vtk.vtkTriangleFilter()
cut_triangles.SetInput(poly_profile)

_poly_mapper = vtk.vtkPolyDataMapper2D()
_poly_mapper.SetInput(poly_profile)
_poly_mapper.SetInputConnection(cut_triangles.GetOutputPort())

_actor = vtk.vtkActor2D()
_actor.SetMapper(_poly_mapper)
_actor.GetProperty().SetColor([0.1,0.1,0.1])
_actor.GetProperty().SetOpacity(0.5)
#Add to renderer as normal

rawDescription: Semi-transparent 2d VTK text background

description: Semi-transparent 2d VTK text background


code:
from django.contrib.messages.api import get_messages

def messages(request):
    """
    Returns a lazy 'messages' context variable.
    """
    return {'your_name_space': get_messages(request)}

rawDescription: Rename reference to Django messages in templates?


code:
def min_abs_diff(L):
    sum1, sum2 = 0, sum(L)
    min_abs_diff = float('inf')  # sentinel value
    for i in L:
        sum1 += i
        sum2 -= i
        abs_diff = abs(sum1 - sum2)
        if min_abs_diff > abs_diff:
            min_abs_diff = abs_diff
    return min_abs_diff

rawDescription: Reduce complexity in list operations

description: Reduce complexity in list operations


code:
import pandas as pd
from pandas import Timestamp
import datetime as dt
import matplotlib.pyplot as plt

s = pd.Series({Timestamp('2014-11-08 00:00:00'): 345,
    Timestamp('2014-11-09 00:00:00'): 678,
    Timestamp('2014-11-10 00:00:00'): 987,
    Timestamp('2014-11-11 00:00:00'): 258})

fig = plt.figure()
ax = fig.gca()
s.plot(ax=ax)

i = 0
ax.text(s.index[i], s.iloc[i], "Hello")
ax.text(dt.date(2014, 11, 9), 500, "World")
ax.text(Timestamp("2014-11-10"), 777, "!!!")

plt.show()

rawDescription: Matplotlib, settng in-plot text with plt.text() with pandas time series data


code:
import re
re.split(r"(\s+)", "This is the string I want to split")

rawDescription: Is there a function in Python to split a string without ignoring the spaces?


code:
class Color(models.Model):
    name = CharField(...)

rawDescription: Assigning value to a random word in Django


code:
#!/usr/bin/env python
"""Run a unit test and return result.

This can be used with `hg bisect`.
It is assumed that this file resides in the same dir as settings.py

"""

import os
from os.path import abspath, dirname
import sys
import unittest

# Set up django
project_dir = abspath(dirname(dirname(__file__)))
sys.path.insert(0, project_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

from django.db import connection
from django.test import TestCase
from django.test.utils import setup_test_environment, teardown_test_environment

from myproject import settings
from myproject.myapp.models import MyModel

class MyTestCase(TestCase):

    def test_something(self):
        # A failed assertion will make unittest.main() return non-zero
        # which if used with `hg bisect` will mark the revision as bad
        self.assertEqual(0, len(MyModel.objects.all())) # and so on

if '__main__' == __name__:
    try:
        setup_test_environment()
        settings.DEBUG = False
        verbosity = 0
        old_database_name = settings.DATABASE_NAME
        connection.creation.create_test_db(verbosity)
        unittest.main()
    finally:
        connection.creation.destroy_test_db(old_database_name, verbosity)
        teardown_test_environment()

rawDescription: How to setup and teardown temporary django db for unit testing?

description: Setup and teardown temporary django db for unit testing


code:
import signal
def handler(signum, frame):
    print('Caught signal %d' % signum)
    # Now do something (clean-up?) ...
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)

input() # Example to keep the program running

rawDescription: what kind of signal have to be caught when shell exits

description: What kind of signal have to be caught when shell exits


code:
import random
import socket
import struct
socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))

rawDescription: Python randomly generated IP address of the string


code:
def isIn(inside, outside):
    if isinstance(inside, dict) and isinstance(outside, dict):
        return all(isIn(v, outside.get(k, object())) for k, v in inside.items())
    return inside == outside

print(isIn(first, second)) # True
print(isIn(second, first)) # False
print(isIn({}, 9999)) # False

rawDescription: Recusively test if dict contained in dict


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)

        self.post_tweet = tk.Text(self)
        bindtags = list(self.post_tweet.bindtags())
        bindtags.insert(2, "custom") # index 1 is where most default bindings live
        self.post_tweet.bindtags(tuple(bindtags))

        self.post_tweet.bind_class("custom", "<Key>", self.count)
        self.post_tweet.grid()

        self.char_count = tk.Label(self)
        self.char_count.grid()

    def count(self, event):
        current = len(self.post_tweet.get("1.0", "end-1c"))
        remaining = 140-current
        self.char_count.configure(text="%s characters remaining" % remaining)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Tkinter: set StringVar after <Key> event, including the key pressed


code:
def __cmp__(gem, other):
    if (gem.value / gem.carot) < (other.value / other.carot):
        return -1
    elif (gem.value / gem.carot) > (other.value / other.carot):
        return 1
    else:
        return 0

rawDescription: Reading in a CSV file AND sorting it in Python


code:
import requests
import re

r = requests.get('https://carrinho.submarino.com.br/CustomerWeb/pages/Login')
m = re.search('id="(.*)\.loginForm\.username', r.content)
id = m.group(1)
payload = {id+':username': email, id+':password': senha}

rawDescription: Trying to login using requests but the fields are dynamic


code: result = results[0] if results else None

rawDescription: Is it possible to check that a list is not empty before grabbing the first element using as few lines as possible in Python?


code:
userInput = raw_input(
    'Enter n to deal a new hand, r to replay the last '
    'hand, or e to end game: ')

rawDescription: coding raw_input prompt into multiple lines...?

description: Coding raw_input prompt into multiple lines...


rawDescription: How to find the same item in multiple lists?

description: Find the same item in multiple lists


code:
from sklearn.datasets import fetch_20newsgroups
data = fetch_20newsgroups(categories=['rec.autos'])
from sklearn.feature_extraction.text import TfidfVectorizer
cv = TfidfVectorizer()
X = cv.fit_transform(data.data)
cv.vocabulary_

rawDescription: Find the tf-idf score of specific words in documents using sklearn


rawDescription: django queryset filter out the objects with same values

description: Django queryset filter out the objects with same values


code:
def pg_dump(*tables, **kwargs):
  file = kwargs['file']
  port = kwargs['port']
  name = kwargs['name']
  ...

pg_dump('stack', 'overflow', file='/tmp/dump.sql', port=5434, name='europe')

rawDescription: Pythonic way to verify parameter is a sequence but not string


code:
s = 'select :param1, :param2 from my_table'

d = {'param1': 'val1', 'param2': 'val2'}

for k, v in d.items():
    s = s.replace(':'+k, v)

rawDescription: Subtitue named variables with semicolon in Python 2.7


code:
list_with_none = [(1,"foo"), (2,"bar"), (3,""), (4,None), (5,"blub")]
col = 1
sorted(list_with_none, key=lambda k: (k[col] is None, k[col] == "", k[col]))

rawDescription: Sort when values are None or empty strings python


rawDescription: Flushing Database Deque

description: Flushing Database Deque


code:
haystack = "abcdefabc. asdli! ndsf acba saa abe?"
needle = "abc"
for i, _ in enumerate(haystack):
    if haystack[i:i + len(needle)] == needle:
        print (i)

rawDescription: Finding a string multiple times in another String - Python


code:
for ndx, value in zip(I,R):
    L[ndx-1] = value

rawDescription: Assigning multiple python list elements in one go


code:
import operator
def insertionSort(L, reverse=False):
    lt = operator.gt if reverse else operator.lt
    for j in xrange(1,len(L)):
        valToInsert = L[j]
        i = j-1
        while 0 <= i and lt(valToInsert, L[i]):
            L[i+1] = L[i]
            i -= 1
        L[i+1] = valToInsert
    return L

rawDescription: What is a typical way to add a reverse feature to an insertion sort?


code:
import numpy as np
from itertools import product
from scipy.spatial import Delaunay

eps = 3.  # choose value, which filters out some points
A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8],[9,2]])

# triangulate points:
pts = np.vstack([A, B])
tri = Delaunay(pts)

# extract all edges:
si_idx = [[0, 1], [0, 2], [1, 2]]  # edge indeces in tri.simplices
edges = [si[i] for si, i in product(tri.simplices, si_idx)]
dist_edges = [np.linalg.norm(tri.points[ii[0]] - tri.points[ii[1]])
              for ii in edges]  # calculate distances

# list points which are closer than eps:
for ee, d in zip(edges, dist_edges):
    if d < eps:
        print("|p[{}] - p[{}]| = {}".format(ee[0], ee[1], d))

rawDescription: Duplicate removal within a certain distance in Python


code:
class ToAdd(object):
    @property
    def foo(self):
        return 'foo!'

class Base(object):
    pass

b = Base()

NewBase = type('NewBase', (Base, ToAdd), {})
b.__class__ = NewBase
print(b.foo)
# foo!

rawDescription: Copy a property-decorated member to a new class


code:
Split(src, src_r, src_g, src_b)
Smooth(src_r, dst_r)
Merge(dst_r, src_g, src_b, dst)

rawDescription: Can I smooth just 1 channel in a 3 channel image?

description: Smooth just 1 channel in a 3 channel image


code:
class DownloadAdmin(admin.ModelAdmin):
    readonly_fields = ('task_added_at',)

    def task_added_at(self, obj):
        return obj.task.added_at

rawDescription: Displaying ForeignKey data in Django admin change/add page


code:
email = EmailMessage(
    'My foobar subject!!',
    body,
    'Darth Vader <notify@foobar.com>',
    [the_user.email])

rawDescription: What is the proper way to set the "From" header in an email using Django EmailMessage class?


code:
import httplib

conn = httplib.HTTPConnection(url)

conn.request('GET', '/foo')
r1 = conn.getresponse()
r1.read()

conn.request('GET', '/bar')
r2 = conn.getresponse()
r2.read()

conn.close()

rawDescription: How to Speed Up Python's urllib2 when doing multiple requests


code:
def get_hops(url):
    redirect_re = re.compile('<meta[^>]*?url=(.*?)["\']', re.IGNORECASE)
    hops = []
    while url:
            if url not in hops:
                hops.insert(0, url)
            response = urllib2.urlopen(url)
            if response.geturl() != url:
                hops.insert(0, response.geturl())
                # check for redirect meta tag
            match = redirect_re.search(response.read())
            if match:
                url = urlparse.urljoin(url, match.groups()[0].strip())
            else:
                url = None
    return hops

rawDescription: urllib2 Request issue

description: Urllib2 Request issue


code:
starting_line = int(starting_line_string)
lines_to_search = file_lines[starting_line:]

rawDescription: How can I assign a variable to a list item in Python?

description: Assign a variable to a list item in Python


code:
import cv2

image = cv2.imread("some_image.jpg")
image[x, y, z]

rawDescription: Reading and Compressing a picture with RLE


rawDescription: Exercise 14.5, "Think Python" (Allen Downey)


code:
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
              help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
              action="store_false", dest="verbose", default=True,
              help="don't print status messages to stdout")

(options, args) = parser.parse_args()

rawDescription: Instruction manual to a python script

description: Instruction manual to a python script


code:
import sys
sys.path.append("C:\\Users\\dhiw\\workspace\\basics\\")

import Login

rawDescription: Importing Python Modules

description: Importing Python Modules


code:
s = "title='bah' name='john' purple='haze' none=None i=1"
d = eval("dict(%s)"% ",".join(s))

rawDescription: string of kwargs to kwargs

description: String of kwargs to kwargs


rawDescription: How do I use my own loop with pyhook instead of pumpMessages()?

description: Use my own loop with pyhook instead of pumpMessages()


code:
from PyQt4 import QtGui, QtCore

class MyWidget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)

        ...
        self.txt_list = QtGui.QTextEdit(self)
        self.txt_list.resize(580,400)
        self.txt_list.move(50, 50)
        self.txt_list.setReadOnly(1)
        self.txt_list.setFont(font_consolas)
        ...
        self.monitor = Monitor()
        self.monitor.updateText.connect(self._handleTextUpdate)
        self.monitor.update_list()

    def _handleTextUpdate(self, txt):
        self.txt_list.clear()
        self.txt_list.setText(txt)

class Monitor(QtCore.QObject):

    updateText = QtCore.pyqtSignal(str)

    def update_list(self):
        t_monitor = Thread(self.monitor_vector, parent=self)
        t_monitor.daemon = True
        t_monitor.setName('monitor')
        t_monitor.start()

    def monitor_vector(self):
        ...
        self.updateText.emit('updated list')

class Thread(QtCore.QThread):

    def __init__(self, fn, args, kwargs, parent=None):
        super(Thread, self).__init__(parent)
        self._fn = fn
        self._args = args
        self._kwargs = kwargs

    def run(self):
        self._fn(*self._args, **self._kwargs)

rawDescription: how to clear QTextEdit in different thread in pyQt4

description: Clear QTextEdit in different thread in pyQt4


code:
from itertools import permutations
permutations([1,2,3])

rawDescription: permutating on list

description: Permutating on list


code:
user = User.objects.create_user(
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password1'],
            email=form.cleaned_data['email'],
        )
user.is_active = False
user.save()

rawDescription: Give access from admin panel to users that registered in django


rawDescription: Get toDebugString from DecisionTreeClassifier in PySpark ML


code:
def to_base_8(n):
    digits = []
    while n > 0:
        digits.append(str(n % 8))
        n = n // 8
    return ''.join(reversed(digits))

SQUARE = dict([(c, int(c)**2) for c in "01234567"])
def is_happy(n):
 s = set()
 while (n > 1) and (n not in s):
   s.add(n)
   n = sum(SQUARE[d] for d in to_base_8(n))
 return n == 1

a=is_happy(28)

rawDescription: Happy numbers using python base 8

description: Happy numbers using python base 8


code:
class MyClass(object):
  def get(self): return 10
  def setprop(self, val): raise ValueError("hax%s"%str(val))
  prop = property(get, setprop)
i = MyClass()
i.prop =4
i.prop
setattr(i, 'prop', 12)

rawDescription: Setting Property via a String

description: Setting Property via a String


code:
d = {'x': 'bar'}
getattr(f, d['x']) # gives the value of f.bar
setattr(f, d['x'], 2) # sets f.bar = 2

rawDescription: Setter of a property used in a dictionary


code:
from xml.etree import ElementTree as ET

tree = ET.parse(r'D:\Squish\squish results\Results-On-2013-01-18_0241 PM.xml')

with open("Result_Summary.txt", "w") as output:
    output.write(' {} \n\n'.format('-' * 101))
    output.write('\tTest Name \t\t No Of PASS\t\t No Of FAIL\t\t\t Description\t\t \n')
    output.write(' {} \n\n'.format('-' * 101))

    # Find all <test> elements with a <verification> child:
    for test in tree.findall('.//test[verification]'):
        # Collect passed and failed counts
        passed = len(test.findall(".//result[@type='PASS']"))
        failed = len(test.findall(".//result[@type='FAIL']"))
        # Collect all the *last* <description> elements of type DETAILED
        descriptions = test.findall(".//result/description[@type='DETAILED'][last()]")
        # write a line of information to the file, including first desc
        output.write('{0}\t\t\t{1}\t\t\t{2}\t\t\t{3}\n'.format(
            test.attrib['name'], passed, failed, descriptions[0].text))
        # write remaining descriptions
        for desc in descriptions[1:]:
            output.write('\t\t\t\t\t\t\t\t\t{0}\n'.format(desc.text))

rawDescription: XML parsing to get description using python using minidom


code:
import time
import signal
import threading
import sys
if sys.version_info > (3,0):
    from socketserver import TCPServer, BaseRequestHandler
else:
    from SocketServer import TCPServer, BaseRequestHandler

def shutdown(signum, frame):
    print("Shutting down server thread")
    server.running = False
    server.shutdown()

server = TCPServer(
    ('127.0.0.1', 7654),
    BaseRequestHandler
)
signal.signal(signal.SIGTERM, shutdown)
signal.signal(signal.SIGINT, shutdown)
server_thread = threading.Thread(target=server.serve_forever)
print("Starting server thread")
server_thread.start()
server.running = True
print("Waiting for server thread to shut down")

while server.running:
    time.sleep(1)

server_thread.join()
print("Server thread terminated")

rawDescription: Python 2 does not handle signals if TCPServer is running in another thread


code:
class ModelWithRevisions(models.Model):
    creationname = models.CharField(max_length=64)
    creationdate = models.DateTimeField('creation date', auto_now_add=False)
    revisionname = models.CharField(max_length=64)
    revisiondate = models.DateTimeField('revision date', auto_now=False)

    class Meta:
        abstract = True

class OtherModel(ModelWithRevisions):
    column1 = models.CharField(max_length=64)
    column2 = models.CharField(max_length=64)

rawDescription: how to automatically add default columns to all django model tables

description: Automatically add default columns to all django model tables


code:
def streamInYAML(stream):
	y = stream.readline()
	cont = 1
	while cont:
		l = stream.readline()
		if len(l) == 0:
			cont = 0
		else:
			if l.startswith(' '):
				y = y + l
			else:
				yield yaml.load(y)
				y = l

rawDescription: How to process a YAML stream in Python

description: Process a YAML stream in Python


code:
filter(lambda a: 'find' in a, dir(re))
[a for a in dir(re) if 'find' in a]

rawDescription: Stuck at LearnPython.org Tutorial(Regarding Modules)


code:
from math import ceil

def takespread(sequence, num):
    length = float(len(sequence))
    for i in range(num):
        yield sequence[int(ceil(i * length / num))]

rawDescription: Choose m evenly spaced elements from a sequence of length n


code:
import itertools

def main():

    ip = "10.1.1."
    port = 23
    to_check = 10
    counter = itertools.count().next
    from twisted.internet import reactor
    def connected(whathappened):
        print >>sys.stdout, "Successfully connected to %s %s" % (whathappened[0],whathappened[1])
        return counter()

    def failed(reason):
        print >>sys.stderr, "Connection to failed : %s" % reason
        return counter()

    def checked(count):
        print >>sys.stdout, "%d connections left to check" % (to_check - count,)
        if count == to_check:
            reactor.stop()

    for i in range(0,total):
        d = check_conn(ip + str(i),port)
        d.addCallbacks(connected,failed)
        d.addBoth(checked)

    reactor.run()

rawDescription: weird behaviour in twisted defer callback

description: Weird behaviour in twisted defer callback


code: figure.scene.interactor.interactor_style =  tvtk.InteractorStyleImage()

rawDescription: Is it possible to prohibit axes rotation with the mouse in Mayavi?


code:
from collections import defaultdict
d = defaultdict(list)
for i in a:
  for j in range(int(i), int(i) + 2):
    d[j].append(i)
d
d.items()

rawDescription: Python creating a dictionary of lists

description: Python creating a dictionary of lists


code:
import numpy as np

def F(c,D,x):
    """Assume c and x are numpy arrays of equal size and D is a scalar"""
    # differencing of the concentration field
    deltac = np.diff(c)
    deltax = np.diff(x)

    return -D * deltac / deltax

rawDescription: Trying to implement Fick's first law of diffusion in a simulation of water movement across cell membrane


code:
#!/usr/bin/python
import wx

class SpinStepCtrl(wx.SpinCtrl):
    def __init__(self, *args, **kwargs):
        wx.SpinCtrl.__init__(self, *args, **kwargs)
        self.step = 99
        self.last_value = 0
        self.Bind(wx.EVT_SPINCTRL, self.OnSpin)

    def OnSpin(self, event):
        delta = self.GetValue() - self.last_value
        if delta == 0:
            return
        elif delta > 0:
            self.last_value = self.GetValue() + self.step
        else:
            self.last_value = self.GetValue() - self.step
        self.SetValue(self.last_value)

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel = wx.Panel(self)
        self.spin = SpinStepCtrl(self.panel, min=0, max=1000)
        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: SpinCtrl with step increment value

description: SpinCtrl with step increment value


code:
zip_ref = zipfile.ZipFile(path_to_zip_file, 'r')
zip_ref.extractall(directory_to_extract_to)
zip_ref.close()

rawDescription: Unzipping files in python

description: Unzipping files in python


code:
def initiate_values(directory):
    for file in glob.glob(os.path.join(directory, '*.[xX][lL][sS]')):
        title = os.path.basename(file).lower()
        if title == 'etc.xls':
            wb = xlrd.open_workbook(file)
            wb = wb.sheet_by_name(u'Sheet1')
            return get_values(file, wb)  # added `return'
    return {} # or some other value

rawDescription: Passing a dictionary to another function


code: assigns = ast.literal_eval(open(r'D:\Dropbox\Dev\Output\dict', 'r').read())

rawDescription: Read lists and dicts from file without exec


code:
from django.forms import ModelForm
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=128)
    author = models.CharField(max_length=128)
    pub_date = models.DateTimeField(auto_now_add=True)
    # ...

# The form class.
class BookForm(ModelForm):
     class Meta:
         model = Book
         fields = ('title', 'author', )

# Use your form in a template and then in the view:
f = BookForm(request.POST)
if f.is_valid():
    new_book = f.save()

rawDescription: How to take user input and create an object with it?

description: Take user input and create an object with it


code:
def transformPolyData(actor):
    polyData = vtk.vtkPolyData()
    polyData.DeepCopy(actor.GetMapper().GetInput())
    transform = vtk.vtkTransform()
    transform.SetMatrix(actor.GetMatrix())
    fil = vtk.vtkTransformPolyDataFilter()
    fil.SetTransform(transform)
    fil.SetInputDataObject(polyData)
    fil.Update()
    polyData.DeepCopy(fil.GetOutput())
    return polyData;

rawDescription: Updating vtkPolyData from vtkActor

description: Updating vtkPolyData from vtkActor


code:
import types
import pyPdf
pdf = pyPdf.PdfFileReader(open('file.pdf'))
pages = list(pdf.pages)

def findInDict(needle,haystack):
    for key in haystack.keys():
        try:
            value = haystack[key]
        except:
            continue
        if key == needle:
            return value
        if type(value) == types.DictType or isinstance(value,pyPdf.generic.DictionaryObject):
            x = findInDict(needle,value)
            if x is not None:
                return x

answer = findInDict('/MYOBJECT',pdf.resolvedObjects).getData()

rawDescription: pyPdf for IndirectObject extraction

description: PyPdf for IndirectObject extraction


code:
a = {}
for line in file_a.readlines():
    split_line = line.strip().split('\t')
    a[split_line[0]] = split_line[1:]

rawDescription: python accessing the second to the last element in a list

description: Python accessing the second to the last element in a list


code:
class Ride:
    driver = db.Relationship('User', primaryjoin=driver_id==user.id, back_populates="rides_as_driver")
    rider =  db.Relationship('User', primaryjoin=rider_id==user.id, back_populates="rides_as_rider")
class User:
    rides_as_rider = db.Relationship('Ride', primaryjoin=id==ride.rider_id, back_populates="rider")
    rides_as_driver = db.Relationship('Ride', primaryjoin=id==ride.driver_id, back_populates="driver")

rawDescription: How to design 2 different many-to-many relationships between same 2 tables with backref's / back_populate's

description: Design 2 different many-to-many relationships between same 2 tables with backref's / back_populate's


code:
df
df['one'] *= df['three']
df['two'] *= df['three']
df

rawDescription: Pandas: process cell dependencies

description: Pandas: process cell dependencies


code:
from bokeh.plotting import figure, show, output_file

output_file('image.html')

p = figure(x_range=(0,1), y_range=(0,1))
p.image_url(url=['tree.png'], x=0, y=1)
show(p)

rawDescription: How do I work with images in Bokeh (Python)

description: Work with images in Bokeh (Python)


code:
from Bio import Entrez
Entrez.email = '##############'
handle = Entrez.efetch(db="nucleotide", id="AY851612", rettype="gb", retmode="text")
x = SeqIO.read(handle, 'genbank')
print(x)
x.description

rawDescription: How to get the scientific name given the GenBank accession code to biopython?

description: Get the scientific name given the GenBank accession code to biopython


code:
from scipy.sparse import coo_matrix
from numpy import hstack, ones

def graph_to_sparse_matrix(graph):
    xs, ys = map(array, zip(*graph.get_edgelist()))
    if not graph.is_directed():
        xs, ys = hstack((xs, ys)).T, hstack((ys, xs)).T
    else:
        xs, ys = xs.T, ys.T
    return coo_matrix((ones(xs.shape), (xs, ys)))

rawDescription: Graph.get_adjacency() is slow and the output is strange


code:
with open(PATH,"r+") as f:
    line = f.read()
    f.seek(0)
    f.truncate()

rawDescription: Open file for reading and writing with truncate


code:
import pandas as pd
p1 = {'name': 'willy', 'age': 10}
p2 = {'name': 'willy', 'age': 11}
p3 = {'name': 'zoe', 'age': 10}
df = pd.DataFrame([p1, p2, p3])
df
df.duplicated('name')

rawDescription: How to find duplicate names using pandas?

description: Find duplicate names using pandas


code:
{1: None, 9: None}
{9: None, 1: None}
{1: None, 2: None}
{2: None, 1: None}

rawDescription: Order of keys in a different Python dict()


code:
def capitalize_word_in_crossword(crossword,word):

    if not crossword or not word:
        return None

    word_find_horizontal_at= find_word_horizontal(crossword,word)
    if word_find_horizontal_at:
        for i in range(len(word)):
            crossword[word_find_horizontal_at[0]][word_find_horizontal_at[1]+i]=crossword[word_find_horizontal_at[0]][word_find_horizontal_at[1]+i].upper()
        return crossword

    word_find_vertical_at= find_word_vertical(crossword,word)
    if word_find_vertical_at:
        for j in range(len(word)):
            crossword[word_find_vertical_at[0]+j][word_find_vertical_at[1]]=crossword[word_find_vertical_at[0]+j][word_find_vertical_at[1]].upper()
    return crossword

rawDescription: Capitalization of first instance of matching character in a crosswords puzzle


rawDescription: Django Boolean is "True" after migration and not selected in ModelForm


code:
def new_predict(clf, new_bias, X):
  return np.sign(clf.decision_function(X) + clf.intercept_ - new_bias)

rawDescription: changing the bias parameter b in scikit SVM after training, before prediction

description: Changing the bias parameter b in scikit SVM after training, before prediction


code:
word = Word.objects.get(...)
setattr(word, fieldName, True)

rawDescription: Django: using the URL request as the name of a model's field


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

Y, X = np.mgrid[-5:5:100j, -5:5:100j]
R = np.sqrt(X**2 + Y**2)
U = -1 - X**2 + Y
V = 1 + X - Y**2
U[R<1] = np.nan
V[R<1] = np.nan

plt.streamplot(X, Y, U, V, density=2.5, arrowstyle='-')
plt.axis("image")
plt.savefig("stream.png", dpi=300)
plt.show()

rawDescription: Streamplot that masks a circular region

description: Streamplot that masks a circular region


code:
class StdOutWrapper:
    text = ""
    def write(self,txt):
        self.text += txt
        self.text = '\n'.join(self.text.split('\n')[-30:])
    def get_text(self,beg,end):
        return '\n'.join(self.text.split('\n')[beg:end])

if __name__ == "__main__":
    mystdout = StdOutWrapper()
    sys.stdout = mystdout
    sys.stderr = mystdout

    screen = curses.initscr()
    curses.noecho()
    curses.cbreak()

    # do your stuff here
    # you can also output mystdout.get_text() in a ncurses widget in runtime

    screen.keypad(0)
    curses.nocbreak()
    curses.echo()
    curses.endwin()
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
    sys.stdout.write(mystdout.get_text())

rawDescription: Print to standard console in curses

description: Print to standard console in curses


code:
from pyramid.mako_templating import IMakoLookup
lookup = request.registry.queryUtility(IMakoLookup, name='mako.')
tmpl = lookup.get_template('myapp:templates/foo.mako')

opts = {} # rendering context
result = tmpl.render_unicode(**opts)

rawDescription: Get Mako template from within Pyramid app view


code:
from PyQt4 import QtCore, QtGui

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(371, 113)
        self.gridLayout_2 = QtGui.QGridLayout(Dialog)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.label = QtGui.QLabel(Dialog)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.lineEdit = QtGui.QLineEdit(Dialog)
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
        self.label_2 = QtGui.QLabel(Dialog)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        self.lineEdit_2 = QtGui.QLineEdit(Dialog)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.gridLayout.addWidget(self.lineEdit_2, 1, 1, 1, 1)
        self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
        self.buttonBox = QtGui.QDialogButtonBox(Dialog)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.gridLayout_2.addWidget(self.buttonBox, 1, 0, 1, 1)

        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

rawDescription: How can i validate and exit QInputDialog?

description: Validate and exit QInputDialog


code:
def my_unwrap(phase):
    phase_diffs = [phase[i+1] - phase[i] for i in range(len(phases)-1)]
    unwrapped_phases = [phase[0]]
    previous_phase = phase[0]

    for phase_diff in phase_diffs:
        if abs(phase_diff) > pi:
            phase_diff += 2*pi
        previous_phase += phase_diff
        unwrapped_phases.append(previous_phase)

    return unwrapped

rawDescription: Have phase not equal 0 after 2 pi

description: Have phase not equal 0 after 2 pi


code:
def sort(array=[12,4,5,6,7,3,1,15]):
    less = []
    equal = []
    greater = []

    if len(array) > 1:
        pivot = array[0]
        for x in array:
            if x < pivot:
                less.append(x)
            if x == pivot:
                equal.append(x)
            if x > pivot:
                greater.append(x)
        # Don't forget to return something!
        return sort(less)+equal+sort(greater)  # Just use the + operator to join lists
    # Note that you want equal ^^^^^ not pivot
    else:  # You need to hande the part at the end of the recursion - when you only have one element in your array, just return the array.
        return array

rawDescription: Quick sort with Python

description: Quick sort with Python


rawDescription: Is there a way to pad to an even number of digits?


code:
import fileinput
for line in fileinput.input():
    process(line)

rawDescription: Automatically open files given as command line arguments in Python


code:
from matplotlib import transforms

fig = plt.figure(figsize=(16, 4))

fig.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.04, 0.04)

gs1 = plt.GridSpec(1, 4)
gs2 = plt.GridSpec(4, 4)

for i in range(4):
    bbox = gs1[0, i].get_position(fig)
    t = transforms.BboxTransformTo(bbox)

    fig.add_axes(t.transform_bbox(gs2[:3, :3].get_position(fig)))
    fig.add_axes(t.transform_bbox(gs2[3, :3].get_position(fig)))
    fig.add_axes(t.transform_bbox(gs2[:3, 3].get_position(fig)))

rawDescription: How to make plots in normalized coordinates in python?

description: Make plots in normalized coordinates in python


code:
#!/usr/bin/env python
import pexpect
child = pexpect.spawn("/usr/bin/vim")
child.send('a\n\nThis is another test.')
child.send('\x1b')
child.send(':w! test.txt\n')
child.interact()

rawDescription: Using python subprocess.call() to launch an ncurses process


code:
from rdflib.graph import Graph
g = Graph()
g.parse("demo.nt", format="nt")

rawDescription: Python library/code to parse .nt files from dbpedia


rawDescription: Convert a Datatime into a dd-mm-yyyy String in Python - ParseDateTime


rawDescription: Python: threading.timer not respecting the interval


code:
# I have no idea about convert's command line usage,
# so here's an example using echo.
subprocess.call(["echo", str(1 + 1), "bla"])

rawDescription: eval in template strings

description: Eval in template strings


code:
from ast import literal_eval
literal_eval('[1.23, 2.34]')

rawDescription: Pandas DataFrame stored list as string: How to convert back to list?


code:
def intersect(lists):
    return list(set.intersection(*map(set, lists)))

rawDescription: I am trying to find the set of lists in a tuple


code:
import gmpy2

def matching_bits(x, y):
    '''Returns the number of bits that match between x and y. The
    sign of x and y are ignored. x and y must be of type mpfr.'''

    # Force both values to be positive, and x >= y.
    x = abs(x)
    y = abs(y)
    if x < y:
        x, y = y, x

    if not isinstance(x, type(gmpy2.mpfr(0))) or not isinstance(y, type(gmpy2.mpfr(0))):
        raise TypeError("Arguments must be of type 'mpfr'.")

    x_bits, x_exp, x_prec = x.digits(2)
    y_bits, y_exp, y_prec = y.digits(2)

    # (x_exp - y_exp) is the number of zeros that must be prepended
    # to x to align the mantissas. If that is greater than the precision
    # y, then no bits in common.
    if (x_exp - y_exp) > x_prec:
        return 0

    x_bits = "0" * (x_exp - y_exp) + x_bits

    count = 0
    while count < min(x_prec, y_prec) and x_bits[count] == y_bits[count]:
        count += 1
    return count

rawDescription: gmpy2: How do I track precision of mpc operations?

description: Gmpy2: How do I track precision of mpc operations