code:
import re
spl = "TO"
strs = "TO YOUDate : 06/12/2013 09:52:55 AMHi can u pls pick up some bread from the store. TO :   Contact NameDate : 06/12/2013 10:00:10 AMI can in about 15 minutes. I'm still in a meeting."
lis = re.split(r'\bTO\b',strs)[1:]

rawDescription: Edit a text file by starting each line with TO


rawDescription: How to mock a method and see if it was called at all?

description: Mock a method and see if it was called at all


code:
for counter, file in ((i + 1, f) for i, f in enumerate(files)):
    ...

rawDescription: How to enumerate through list with the first "index" reported as 1? (Python 2.4)

description: Enumerate through list with the first "index" reported as 1? (Python 2.4)


code:
not False
not True
not "".isalpha()
not "abc".isalpha()

rawDescription: Is there any way to enter a "while" loop while a boolean value is false


code:
for dirname, dirnames, filenames in os.walk(path):
    print()
    print(dirname + ":")
    for filename in filenames:
        print(os.path.join(dirname, filename))

rawDescription: Python Recursing Through A Directory

description: Python Recursing Through A Directory


code:
for link in soup.findAll('a'):
    if link['href'].startswith('/'):
        link['href']= 'http://www.foobarinc.com'+link['href']

rawDescription: Is it possible to edit the inline code in with BeautifulSoup?


code:
with open("article.text" , "w") as f:
    for sentence in soup2.select("#articleText p"):
        block_text = sentence.get_text()
        f.write(block_text)

rawDescription: How to write an object into a text file in python

description: Write an object into a text file in python


rawDescription: Why does 'key in d.keys()' finish in O(n) time while 'key in d' finishes in O(1)?


code:
import wx

class Win(wx.Frame):
    def __init__(self):
        super(Win, self).__init__(None, wx.ID_ANY)
        self.p = wx.Panel(self, wx.ID_ANY)
        self.p.SetSizer(wx.BoxSizer())
        # set the minimum size when creating the custom window so that the sizer doesn't "squash" it to 0,0
        self.rt = RotatedText(self.p, wx.ID_ANY, 'hello', 90,size=(60,60))
        self.p.GetSizer().Add(self.rt)

class RotatedText(wx.Window):
    def __init__(self, parent, id, text, angle, font=None, *args, **kwargs):
        super(RotatedText, self).__init__(parent, id, *args, **kwargs)
        self.text = text
        self.font = font
        self.angle = angle
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)

        # set our minimum size based on the text with
        dc = wx.MemoryDC()
        self.text_width, self.text_height= dc.GetTextExtent(self.text)
        # height and width are reversed since we are drawing text vertically
        self.SetMinSize((self.text_height,self.text_width))

    def repaint(self, dc):
        if self.font:
            dc.SetFont(self.font)
        text_width, text_height = dc.GetTextExtent(self.text)
        dc.SetTextForeground(wx.BLACK)
        #dc.DrawText(self.text, 0, 0) # change this line to start drawing from bottom to top beginning 60 units from top
        dc.DrawRotatedText(self.text, 0, self.text_width, self.angle)

    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        self.repaint(dc)
        event.Skip()

    def OnSize(self, event):
        dc = wx.ClientDC(self)
        self.repaint(dc)
        event.Skip()

app = wx.App()
win = Win()
win.Show()
app.MainLoop()

rawDescription: Drawing on a Panel within a Sizer

description: Drawing on a Panel within a Sizer


code: sorts = sorted(data, key= lambda x: x.get('name') or x.get('full_name'))

rawDescription: python: sorting list of dicts by one key OR another

description: Python: sorting list of dicts by one key OR another


code:
def length(x, y):
    return (x ** 2 + y ** 2) ** .5

def norm(x, y):
    _len    = length(x, y)
    return x / _len, y / _len

class ZombieController(object):

    def __init__(self, zombie_view_range):
        self._zombs = []
        self.append = self._zombs.append
        self._range = zombie_view_range

    def NextFrame(self, player_pos):
        px, py      = player_pos
        _range      = self._range
        for zombie in self._zombs:
            x, y    = zombie.position
            dx, dy  = px - x, py - y
            _len    = length(dx, dy)
            if _len <= _range:
                speed       = zombie.speed
                direction   = norm(dx, dy)
                zombie.positon  = x + direction[0] * speed, y + direction[1] * speed

rawDescription: Python/Pygame Making An Object Follow Another Object


code:
def worker(cmd):
    p = subprocess.Popen(cmd, stderr=outputfile, stdout=outputfile);
    p.wait()

rawDescription: Control the number of subprocesses using to call external commands in python


code:
from selenium  import webdriver
from selenium.webdriver.chrome.options import Options
chromeOptions = Options()

chromeOptions.add_argument("--cache-path=C:\\CEF\\c_path")
chromeOptions.binary_location = r"C:\cef_binary_client\Release\cefclient.exe"

driver = webdriver.Chrome(executable_path=r"C:\Driver\chromedriver_220.exe", chrome_options=chromeOptions)

driver.get("https://google.com")
s = "test"
driver.find_element_by_name("q").send_keys(s)

rawDescription: How do I set user data directory in chromium-embedded with chromedriver?

description: Set user data directory in chromium-embedded with chromedriver


code:
class MyClass:

    def __init__(self, name):
        self.cuname = name

    @property
    def av(self):
        return "Core/" + self.cuname + ">> "

obj = MyClass("thefourtheye")
print(obj.av)
# Core/thefourtheye>>
obj.cuname = "awesome"
print(obj.av)
# Core/awesome>>

rawDescription: How to reinitialize a variable in Python?

description: Reinitialize a variable in Python


code: df1.loc[:, df2.stock]  # equivalent to df1[df2.stock]

rawDescription: Python: Select multiple columns in a dataframe from another dataframe without loop


code:
L = [{'id':44}, {'name':'alexa'},{'color':'blue'}]
newd = {}
for d in L:
   newd.update(d)
newd['id']

rawDescription: How do I do this with Python list? (itemgetter?)

description: Do this with Python list? (itemgetter?)


code:
with Model() as sw_model:

    sigma = HalfCauchy('sigma', beta=10, testval=1.)

    switchpoint = DiscreteUniform('switchpoint', lower=0, upper=90, testval=45)

    # Priors for pre- and post-switch intercepts and slopes
    intercept_u1 = Uniform('Intercept_u1', lower=-10, upper=10, testval = 0)
    intercept_u2 = Uniform('Intercept_u2', lower=-10, upper=10, testval = 0)
    x_coeff_u1 = Normal('x_u1', 0, sd=20)
    x_coeff_u2 = Normal('x_u2', 0, sd=20)

    intercept = switch(switchpoint < x, intercept_u1, intercept_u2)
    x_coeff = switch(switchpoint < x, x_coeff_u1, x_coeff_u2)

    likelihood = Normal('y', mu=intercept + x_coeff * x, sd=sigma, observed=y)

    start = find_MAP()

    step1 = NUTS([intercept_u1, intercept_u2, x_coeff_u1, x_coeff_u2])
    step2 = Metropolis([switchpoint])

    trace = sample(20000, step=[step1, step2], start=start, njobs=4,progressbar=True)

rawDescription: PyMC3 regression with change point

description: PyMC3 regression with change point


code:
someElements = [3, 8, 6, 4, 2]
allElements = [[4, 3, 7], [2, 8, 6], [5, 4, 2]]
finalList = [[] for _ in allElements]

i = j = k = 0

while i < len(someElements) and j < len(allElements):
    sub = allElements[j]
    if k >= len(sub):
        j += 1
        k = 0
        continue
    if someElements[i] == sub[k]:
        finalList[j].append(sub[k])
        i += 1
    k += 1

rawDescription: Creating a list of lists with only certain elements of another list


code:
s = "11 (1)"
import re

re.escape(s)

rawDescription: How to escape all special character for regex in python

description: Escape all special character for regex in python


code:
def bisect(sortedlist,targetvalue,firstindex=0,lastindex=None):

    if(len(sortedlist)==0):
        return None
    if(len(sortedlist)==1):
        if(sortedlist[0]==targetvalue):
            return firstindex
        else:
            return None
    center = int(round(len(sortedlist)/2))

    if(sortedlist[center]==targetvalue):
        return firstindex+center
    if(targetvalue>sortedlist[center]):
        return bisect(sortedlist[center+1:lastindex],targetvalue,center+1,lastindex)
    else:
        return bisect(sortedlist[0:center],targetvalue,firstindex,center-1)

rawDescription: Python bisecting a list

description: Python bisecting a list


code: from A.foo import fooFun1, fooFun2

rawDescription: Python import works when running module but breaks when this module is imported


code:
import csv
with open("your/file.csv", ...) as source:
    reader = csv.reader(source, delimiter='\t')
    selection = [row for row in reader if row[2] == 'a']

rawDescription: python reading specific lines from CSV using list comprehension

description: Python reading specific lines from CSV using list comprehension


code:
out, err = subprocess.Popen(
    ["pdftotext", '-layout', "-", "-"], stdin = tf, stdout=subprocess.PIPE ).communicate()

rawDescription: using subprocess.popen in python with os.tmp file while passing in optional parameters

description: Using subprocess.popen in python with os.tmp file while passing in optional parameters


code:
# returns True only if player has all data, otherwise returns False
def has_data(player):
    return (player["h_inches"] != 'NULL' and
            player["h_feet"]   != 'NULL' and
            player["weight"]   != 'NULL' and
            player["h_inches"] is not None and
            player["h_feet"]   is not None and
            player["weight"]   is not None)

obese_count = 0
total_count = 0

for player in players:
    if has_data(player):
        if is_obese(player):
            print ('player', player["lastname"], 'is obese')
            obese_count += 1
        total_count += 1

rawDescription: How to count rows in a csv file and ignore the rows not in use (using python)

description: Count rows in a csv file and ignore the rows not in use (using python)


code:
for step in xrange(steps):
    e = self.model - np.dot(self.p, self.q.T)
    p_temp = learning_rate * np.dot(e, self.q)
    self.q *= (1-regularization)
    self.q += learning_rate*(np.dot(e.T, self.p))
    self.p *= (1-regularization)
    self.p += p_temp

rawDescription: Scipy - how to further optimize sparse matrix code for stochastic gradient descent


code:
key = 'name2'
found = next(d for d in (a, b, c)
             if key in d)

rawDescription: Get the name of the dictionary that contains the given key in python


code: c[k] = p[k]*count

rawDescription: python, weighted linspace

description: Python, weighted linspace


code:
def factor(n, factors=None):
    factors = [] if factors is None else factors
    for i in range(2, n + 1):
        if n%i==0 and i not in factors: #checks for duplicates as well
            factors.append(i)
            factor(int(n / i),factors) #pass the factors list in the recurive call
            break
    return factors

factor(20) #returns [2, 5]

rawDescription: Python - clear a list in a function each time it's run


code:
from app.models import Json, Dweet
a = Json(data="asdf")
a.save()
b = Dweet(name="Test", data=a)
b.save()
c = Dweet(name="Test2", data=a)
c.save()

rawDescription: Adding Models to Django Foreign Key

description: Adding Models to Django Foreign Key


code:
import datetime
datetime.date.today().strftime("%B %d, %Y")
datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")

rawDescription: How do I get a string format of the current date time, in python?

description: Get a string format of the current date time, in python


code:
from collections import defaultdict as defd
dic = defd(dict)

def create_dict(astr):
    keys, val = astr.split(' ')
    keys = keys.split('.')
    val = int(val)
    prevdic = dic
    for j, k in enumerate(keys):
        if j == len(keys)-1:
            prevdic[k] = val
        elif k not in prevdic:
            prevdic[k] = defd(dict)
        prevdic = prevdic[k]

create_dict('aa.bb.cc 6')
create_dict('aa.bb.dd.ee 8')
dic['aa']['bb']['cc'] ## returns 6
dic['aa']['bb']['dd']['ee'] ## returns 8

rawDescription: How to convert coma delimited string into python dictionary?

description: Convert coma delimited string into python dictionary


code:
sys.stdout = redirect
sys.stderr = redirect

rawDescription: Scrolling text "console like" window in wxPython?


code:
E = set(T.edges())  # optimization
[e for e in G.edges() if e in E or reversed(e) in E]

rawDescription: Spanning tree of directed graph with networkx


code:
stokes_list = []
for i in xrange(numrows):
    ...
    stokes_line = ...
    stokes_list.append(stokes_line)

big_stokes = np.vstack(stokes_list)

rawDescription: how to use numpy vstack

description: Use numpy vstack


code:
def myoverridenmeta(name, bases, adict):
    newClass = type(name, bases, adict)
    for field in newClass._meta.fields:
        if field.attname == 'last_login':
            field.column = 'lastlogin'
            field.db_column = 'lastlogin'
    return newClass

class UserProfile(AbstractBaseUser):

    class Meta:
        """
        meta class for user role, defining ordering and db table name
        """
        ordering = ["name"]
        db_table = 'user'

    username = models.CharField(max_length=254, unique=True)
    name = models.CharField(max_length=254, blank=True)
    email = models.EmailField(blank=True, unique=True)
    createdon = models.DateTimeField(auto_now_add=True)
    updatedon = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True, db_column='status')
    is_admin = models.BooleanField(default=False, db_column='isadmin')
    is_staff = models.BooleanField(default=False, db_column='isstaff')
    is_superuser = models.BooleanField(default=False, db_column='issuperuser')

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    objects = CustomUserManager()

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    __metaclass__ = myoverridenmeta

rawDescription: How to change the name of db column last_login created by custom Django user?

description: Change the name of db column last_login created by custom Django user


rawDescription: SQLAlchemy: operator LIKE and custom types


code:
import psutil, os

def kill_proc_tree(pid, including_parent=True):
    parent = psutil.Process(pid)
    for child in parent.get_children(recursive=True):
        child.kill()
    if including_parent:
        parent.kill()

me = os.getpid()
kill_proc_tree(me)

rawDescription: Auto kill process and child process of multiprocessing Pool


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pylab as pl

A = np.random.random(size=(5,5))
fig, ax = plt.subplots(1, 1)

xl, yl, xh, yh=np.array(ax.get_position()).ravel()
w=xh-xl
h=yh-yl
xp=xl+w*0.1 #if replace '0' label, can also be calculated systematically using xlim()
size=0.05

img=mpimg.imread('microblog.png')
ax.matshow(A)
ax1=fig.add_axes([xp-size*0.5, yh, size, size])
ax1.axison = False
imgplot = ax1.imshow(img,transform=ax.transAxes)

plt.savefig('temp.png')

rawDescription: Using an image for tick labels in matplotlib


code:
# Do imports
import re
import pandas as pd

# Define regular expression to pull out root
xpr = re.compile('/([^/?]+)')
# Define initial dataframe, assuming your 3-column example above
df = pd.DataFrame(datas,columns=['Page','Country','Count'])
# Create a column for the root of the page column by applying a regular expression
df['Root'] = df['Page'].apply(lambda v:re.match(xpr,v).groups(0)[0])

# At this point, dataframe looks like:
#                 Page  Country  Count    Root
# 0            /page_1    China      1  page_1
# 1      /page_1?x=123    China      2  page_1
# 2  /page_1/subpage_1       US      1  page_1
# 3            /page_2  Britain     10  page_2

# Sum over the Root & Country groups
results = df.groupby(['Root','Country']).sum()
#                 Count
# Root   Country
# page_1 China        3
#        US           1
# page_2 Britain     10

rawDescription: group on some rules for a dimension in pandas in Python

description: Group on some rules for a dimension in pandas in Python


code:
import unittest

class InputParser:
    def parse(self, input):
        input = input.replace("\n", "").replace(" ", "")
        bits = input.split("=>")
        return bits[:-1]

class InputParserTest ( unittest.TestCase ):
    def test_parse ( self ):
        subject = InputParser()
        self.assertEqual(subject.parse("a =>\nb => "), ["a", "b"])

if __name__ == '__main__':
    unittest.main()

rawDescription: Python - Sequence not equal, but it is what I am expecting


code: mystr = "path: %s curr: %s prev: %s" % (mydict[path], curr, prev)

rawDescription: Python string interpolation using dictionary and strings


code:
def tuple_of_primes_less_than( n ):
    if n <= 2: return ()
    else:
        x, p = set( range(2,n) ), 2
        while p <= max(x):
            for k in range(2,int(2+math.sqrt(p))):
                x.discard(k*p)
            p += 1
        return tuple( sorted( x ) )

rawDescription: Are there any uses of the empty tuple in Python?


rawDescription: finding value from nested dictionary

description: Finding value from nested dictionary


code:
import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style='white')

iris = sns.load_dataset('iris')
g = sns.FacetGrid(iris, row='species', size=4)

def scatter(x, y, c, **kwargs):
    plt.scatter(x, y, c=c, **kwargs)

g.map(scatter, 'sepal_width', 'sepal_length', 'petal_length')

rawDescription: With seaborn.facetgrid, how do I specify the color of a mapped scatter plot to reflect the values of a column in the data frame?


code:
f = open('file.txt','w')
a = input('is python good?')
f.write('answer:'+str(a))
f.close()

rawDescription: Create Text Document (Python)

description: Create Text Document (Python)


code:
class MessageDialog(wx.Dialog):
    def __init__(self, message, title):
        wx.Dialog.__init__(self, None, -1, title,size=(300, 120))
        self.CenterOnScreen(wx.BOTH)

        ok = wx.Button(self, wx.ID_OK, "OK")
        ok.SetDefault()
        text = wx.StaticText(self, -1, message)

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(text, 1, wx.ALIGN_CENTER|wx.TOP, 10)
        vbox.Add(ok, 1, wx.ALIGN_CENTER|wx.BOTTOM, 10)
        self.SetSizer(vbox)

class Frame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(100, 100),style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN)

        host=os.system('hostname')
        if host!='superman':
            dlg = MessageDialog('The host name should be superman. Closing this dialog box in 2s...', 'Info')
            wx.FutureCall(2000, dlg.Destroy)
            dlg.ShowModal()
        else:
            self.Center()
            self.Show()

rawDescription: wxMessageBox with an auto-close timer in wxPython

description: WxMessageBox with an auto-close timer in wxPython


code:
class node:

  def __init__(self, color, location, parent, children):
    self.nodeColor = color
    self.location = location
    self.parentNode = parent
    self.children = children

rawDescription: Storing points for a 3D maze with irregular spacing?


code:
s = "'here is some stuff 'now there are quotes' now there's not'"
print(' '.join(w.strip("'") for w in s.split()).lower())

rawDescription: Removing single quotes if they aren't in the middle of a word


code: OsSpecificClass = MacClass if os.name == 'posix' else WinClass

rawDescription: How to replace dynamic inheritance with a new class to inherit from in Python?

description: Replace dynamic inheritance with a new class to inherit from in Python


code:
# automatically closes file when done
with open('access.txt', 'r') as f:
    for line in f.readlines():
        s = line.split()
        print(s),

rawDescription: Why is my string.split() function producing unexpected results?


code:
url = "file:///your/path/to/downloaded/file.html"
dr.get(url)

rawDescription: How to use the selenium.PhantomJS() on webpage already downloaded by scrapy

description: Use the selenium.PhantomJS() on webpage already downloaded by scrapy


code: z = mydata[[x for x in a.dtype.names if 'z' in x]]

rawDescription: subset structured array based on column names

description: Subset structured array based on column names


code: from MyProj.views import hello, mainpage, current_datetime, hours_ahead, editareapage

rawDescription: NameError at / name 'editareapage' is not defined


code:
# Guess my number game
# User must attempt to guess randomly selected number within a range in fewest possible attempts

from tkinter import *
import random

class Application(Frame):
    """A GUI application which which generates random number and gets user input"""

    def __init__(self, master): #initialize newly created Application object
        """Initialize the frame"""
        Frame.__init__(self, master) # super(Application, self).__init__(master) in python 3
        self.grid()
        self.create_widgets()
        self.number = random.randint(1, 101)

    def create_widgets(self):
        """Get user inputs"""
        # create instruction label
        Label(self, text = "I'm thinking of a number between 1 and 100.").grid(row = 0, column = 0, sticky = W)
        Label(self, text = "Try and guess it in as few attempts as possible!").grid(row = 1, column = 0, sticky = W)

        # create guess input prompt label and entry
        Label(self, text = "Take a guess:").grid(row = 2, column = 0, sticky = W)
        self.guess_ent = Entry(self)
        self.guess_ent.grid(row = 2, column = 1, sticky = W)

        # create start game prompt label and submit button
        Label(self, text = "Press submit to start the game!").grid(row = 3, column = 0, sticky = W)
        Button(self, text = "Submit", command = self.run_game).grid(row = 3, column = 1, sticky = W)

        # create submit button
        #Button(self, text = "Submit", command = )

        # create computer feedback text box
        self.text = Text(self, width = 75, height = 10, wrap = WORD)
        self.text.grid(row = 4, column = 0, columnspan = 4)

    def run_game(self):
        """Generate number and get user input"""
        guess = int(self.guess_ent.get())

        if guess != self.number:
            print_text = "You guessed {0}.".format(guess)

            if guess > self.number:
                print_text += " That's too high. Guess lower..."
            elif guess < self.number:
                print_text += " That's too low. Guess higher..."

            self.text.delete(0.0, END)
            self.text.insert(0.0, print_text)

            self.guess_ent.delete(0, END)
        else:
            print_text = "That's the right number! Well done!"
            self.text.delete(0.0, END)
            self.text.insert(0.0, print_text)

# main
root = Tk()
root.title("Guess my number game!")
app = Application(root)
root.mainloop()

rawDescription: Guess my number game and GUI = stumped :(


code:
def offset_to_synset(offset):
    """
    Look up a synset given offset-pos
    (Thanks for @FBond, see http://moin.delph-in.net/SemCor)
    >>> synset = offset_to_synset('02614387-v')
    >>> print '%08d-%s' % (synset.offset, synset.pos)
    >>> print synset, synset.definition
    02614387-v
    Synset('live.v.02') lead a certain kind of life; live in a certain style
    """
    return wn._synset_from_pos_and_offset(str(offset[-1:]), int(offset[:8]))

rawDescription: Python: Retrieving WordNet hypernyms from offset input


code:
import win32security
import ntsecuritycon as con

FILENAME = "whatever"

userx, domain, type = win32security.LookupAccountName ("", "User X")
usery, domain, type = win32security.LookupAccountName ("", "User Y")

sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION)
dacl = sd.GetSecurityDescriptorDacl()   # instead of dacl = win32security.ACL()

dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, userx)
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, usery)

sd.SetSecurityDescriptorDacl(1, dacl, 0)   # may not be necessary
win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)

rawDescription: Setting folder permissions in Windows using Python


code:
import timeit
start_time = timeit.default_timer()
# code you want to evaluate
elapsed = timeit.default_timer() - start_time

rawDescription: Get time of execution of a block of code in Python 2.7


code:
if currentFC.endswith(".shp"):
    rootName = currentFC[:-4]
    newFC = str(rootName) + "_projected.shp"

rawDescription: Batch Reprojection Tool, creating a variable with no value


code:
import csv

curr = []
with open('file.csv') as infile, open('path/to/output', 'w') as fout:
    outfile = csv.writer(fout)
    for area, pop10, pop20, pop50 in csv.reader(infile):
        if curr and curr[0] != area:
            outfile.writerow(curr)
            curr = [area, pop10, pop20, pop50]
            continue

        if pop10: curr[1] = pop10
        if pop20: curr[2] = pop20
        if pop50: curr[3] = pop50

rawDescription: Reformatting Excel spreadsheet in Python


code:
def __str__(self):
    return __name__ + "." + self.__class__.__name__ + "." +  self._testMethodName

rawDescription: Changing verbose report format for nosetests


code:
file_keys = self.request.get_all('blobKey')
blob_info_list = blobstore.BlobInfo.get(file_keys)
file_info_list = []
for blob in blob_info_list:
    info = {"file_name":blob.filename, "key":blob.key()}
    file_info_list.append(info)

template_dict = { 'file_info_list':file_info_list}

rawDescription: Python 2.7 and blobkeys: how to return the filename instead of the url?


code:
class Example:
    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2
    def __int__(self):
        return self.param1
3 * int(Example(2,1))

rawDescription: Attribute in Python class as default operand for all numerical operations


code:
from csv import writer as csvwriter, reader as cvsreader
from os import rename # add ', remove' on Windows

with open(infilename) as infile:
    csvr = csvreader(infile)
    with open(outfilename, 'wb') as outfile:
        csvw = csvwriter(outfile)
        for row in csvr:
            # do whatever to get the username / password
            # for this row here
            row.append(username)
            row.append(password)
            csvw.writerow(row)
            # or 'csvw.writerow(row + [username, password])' if you want one line

# only on Windows
# remove(infilename)
rename(outfilename, infilename)

rawDescription: Appending to a csv file in Python

description: Appending to a csv file in Python


code:
mystring = ""

for digit in new:
    mystring += str(digit)

rawDescription: Convert array of integers to string in Python


rawDescription: Python: How would one represent this particular for loop using list comprehension?


code:
import win32evtlogutil
win32evtlogutil.ReportEvent(ApplicationName, EventID, EventCategory,
    		    EventType, Inserts, Data, SID)

rawDescription: Writing to the windows logs in Python

description: Writing to the windows logs in Python


code:
x = 4  # this is an int (an integer)
name = "Josh"  # string
y = 3.2  # float (decimal point number)
guess = True  # bool (boolean)
stuff = ["guitar", "bed"]  # list
days = {"Monday":"favourite", "Friday": "least favourite"}  # dictionary (a hashmap, in computational-theory speak)
jay = (3, 9)  # tuple (works like a list, but you can't change the elements)

rawDescription: Types of Variables Python

description: Types of Variables Python


code:
from pyfits import getdata
data = getdata(file_name)

rawDescription: Conversion of a .fits file

description: Conversion of a .fits file


code:
import pandas as pd
a=pd.read_csv('yourfile.txt',delim_whitespace=True)
for x in a.iterrows():
    x[1][4:].plot(label=str(x[1][0])+str(x[1][1])+str(x[1][2])+str(x[1][3]))

plt.ylim(-1,10)
plt.legend()

rawDescription: plotting a timeseries graph in python using matplotlib from a csv file

description: Plotting a timeseries graph in python using matplotlib from a csv file


code:
import time
last_update = time.time()

while 1:
   # the rest of your while loop as usual
   now = time.time()
   if now - last_update > 300:
       # you've waited 300 seconds
       # check feeds or whatever
       last_update = now

rawDescription: IRC bot make loop sleep without interrup the main loop


code:
import httplib2
h = httplib2.Http('.cache')
s = ['one', 'two', 'three']

def getinfo(subpage):
    response, content = h.request(
        'https-www.example.com/{}/info'.format(subpage),
        headers={'Connection': 'keep-alive'}
    )
    print(content)
    print(response)

for subpage in s:
    getinfo(subpage)

rawDescription: Python URL and List of targets

description: Python URL and List of targets


code:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib

server = 'smtp.gmail.com'
port = 587
sender = 'mysender@gmail.com'
recipient = 'myreceiver@gmail.com'

# Create message and set message fields
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)

# Actual message body (with the image in the HTML code)
msgText = MIMEText('Some HTML text and an image.

Nifty!', 'html')
msgAlternative.attach(msgText)

# Open image and read it
fp = open('test.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# Attach image to 'image1' in the e-mail
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

# Send message
session = smtplib.SMTP(server, port)
session.starttls()
session.login(sender, 'mypassword')

session.sendmail(sender, recipient, msgRoot.as_string())
session.quit()

rawDescription: Image not going as a body of email but some random lines are coming


code:
plt.ylabel('horizontal\nmultiline label', ha='right', va='center', ma='left',
           rotation=0)
plt.tight_layout()

rawDescription: Proper alignment of labels in matplotlib


code:
import PythonMagick

img = PythonMagick.Image("infile.pdf")

img.density('400')

bgColour = PythonMagick.ColorRGB(1.0, 1.0, 1.0)
size = "%sx%s" % (img.columns(), img.rows())

flattened = PythonMagick.Image(size, bgColour)
flattened.type = img.type

flattened.composite(img, 0, 0, PythonMagick.CompositeOperator.SrcOverCompositeOp)

flattened.resize('1900x')
flattened.magick('JPG')
flattened.quality(60)

flattened.write("outfile.jpg")

rawDescription: How to make transparent background white instead of black when converting PDF to JPG using PythonMagick

description: Make transparent background white instead of black when converting PDF to JPG using PythonMagick


code: '</%s Name="%s" Password="%s" />' % (method, username, password)

rawDescription: print double quotes around a variable in python

description: Print double quotes around a variable in python


code:
for word in header:
    writer.writerow([word])

rawDescription: writing data from a python list to csv row-wise

description: Writing data from a python list to csv row-wise


code:
with open('script.py') as myFile:
    content = myFile.readlines()

with open('script.py', 'w') as myFile:
    for line in content:
        newLine = line.replace("string1 = 'OriginalValue'", "string1 = 'newValue'")
        myFile.write(newLine)

rawDescription: Replacing string in script from another script


code: sniff(filter = 'dst port 5555')

rawDescription: sniff traffic on a particular port using scapy

description: Sniff traffic on a particular port using scapy


code:
for item in mylist:
    foofunction(*item)

rawDescription: I need help iterating a list of list, To pass through a function


code:
names_to_search = A.objects.all().values_list('name', flat=True)
people = B.objects.filter(name__in=names_to_search)

rawDescription: Advanced database queries with Django

description: Advanced database queries with Django


code:
import numpy, datetime
a=numpy.array([datetime.datetime.now(),datetime.datetime.now()+datetime.timedelta(days=2)])
a[0].weekday()

rawDescription: Numpy date time conversion

description: Numpy date time conversion


code:
lines = [l.rstrip('\n') for l in open('words.txt')]
print('\n'.join(sorted(lines, key=lambda l:int(l.split()[0]))))

rawDescription: How could I rearrange the lines in this file and print them?


code:
# -*- coding: utf-8 -*-
import re

s = r'#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:17\n#EXT-X-MEDIA-SEQUENCE:1\n#EXTINF:16.667,\nmedia_1.ts?wowzasessionid=184420502\n#EXTINF:16.666,\nmedia_2.ts?wowzasessionid=184420502\n#EXTINF:16.667,\nmedia_3.ts?wowzasessionid=184420502\n#EXTINF:16.667,\nmedia_4.ts?wowzasessionid=184420502\n#EXTINF:16.666,\nmedia_5.ts?wowzasessionid=184420502\n#EXTINF:16.667,\nmedia_6.ts?wowzasessionid=184420502\n#EXTINF:16.667,\nmedia_7.ts?wowzasessionid=184420502\n#EXTINF:16.666,\nmedia_8.ts?wowzasessionid=184420502\n#EXTINF:16.667,\nmedia_9.ts?wowzasessionid=184420502\n#EXTINF:16.667,\nmedia_10.ts?wowzasessionid=184420502\n#EXTINF:16.666,\nmedia_11.ts?wowzasessionid=184420502\n#EXTINF:16.667,\nmedia_12.ts?wowzasessionid=184420502\n#EXTINF:16.667,\nmedia_13.ts?wowzasessionid=184420502\n#EXTINF:16.666,\nmedia_14.ts?wowzasessionid=184420502\n#EXTINF:16.667,\nmedia_15.ts?wowzasessionid=184420502'
pattern = r"""
\\        # Match literal backslash
nmedia_   # Match the text 'nmedia_'
(         # Begin capturing group 1.
\d+       # Match one or more digits.
)         # End capturing group 1.
\.        # Match a literal dot.
ts        # Match the text 'test'
"""
pattern_match = re.compile(pattern, re.VERBOSE)
match = pattern_match.findall(s)
print(match)
#['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']

rawDescription: Extracting multiple matches using Regex in Python


code:
a=[1, 2, 3]
b=list(a)
id(a)
id(b)
id(a) == id(b)   # Equivalent to a is b
a is b

rawDescription: in python , how to make two lists contianing the same elements not equal with each other?

description: In python , how to make two lists contianing the same elements not equal with each other


code: plt.annotate(df.iloc[pqr,0]+', (%.2f, %.2f)' % (x.ix[pqr], y.ix[pqr]), xy=(x.ix[pqr], y.ix[pqr]), xycoords='data', xytext=(x.ix[pqr], y.ix[pqr]+0.3), arrowprops=dict(arrowstyle='-|>'), horizontalalignment='center')

rawDescription: Python anotation arrow direction

description: Python anotation arrow direction


rawDescription: Python parse list and list of tuples into csv


code:
s1 = "abc"
s2 = "bc"
"".join(i if i in s2 else '+' for i in s1)

rawDescription: Conditional replacement in a string

description: Conditional replacement in a string


code:
n = 64
stride = n >> 1
while stride > 0:
    # stuff
    stride >>= 1

rawDescription: Can you use bit shift operations in a 'for-loop'?

description: Use bit shift operations in a 'for-loop'


code: definitions_list = [definition.encode("utf8") for definition in definitions.objects.values_list('title', flat=True)]

rawDescription: Django remove unicode in values_list

description: Django remove unicode in values_list


code:
class myVector():
    def __init__(self, sd=(UNINITIALIZED, UNINITIALIZED)):
       try:
           self.size, self.direction = sd
       except (ValueError, TypeError) as e:
           raise ValueError('two values of size and direction must be specified')

rawDescription: python function use multiple defaults or no defaults at all

description: Python function use multiple defaults or no defaults at all


code:
plt.imshow(im1)
plt.axis('image')
x = plt.ginput(4)

rawDescription: pyplot.ginput() causes axes to change?

description: Pyplot.ginput() causes axes to change


code:
import numpy as np
import scipy.spatial
import matplotlib
import math

import matplotlib.tri as mtri
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# First create the x and y coordinates of the points.
n_angles = 20
n_radii = 10
min_radius = 0.15
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2*math.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += math.pi/n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()

# Create the Delaunay tessalation using scipy.spatial
pts = np.vstack([x, y]).T
tess = scipy.spatial.Delaunay(pts)

# Create the matplotlib Triangulation object
x = tess.points[:, 0]
y = tess.points[:, 1]
tri = tess.vertices # or tess.simplices depending on scipy version
triang = mtri.Triangulation(x=pts[:, 0], y=pts[:, 1], triangles=tri)

# Plotting
z = x*x + y*y
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(triang, z)
plt.show()

rawDescription: Using scipy.spatial.Delaunay in place of matplotlib.tri.Triangulation's built-in version


code:
for dohicky_id in dohicky['dohicky']:
    stuff = dohicky['dohicky'][dohicky_id]['Stuff']

rawDescription: Conditional Python for loop based on YAML data


code:
form = FirstForm(request.POST)
if form.is_valid():
    uni = form.cleaned_data['uni']
    courses = Course.objects.filter(university__name=uni).order_by('name')
    return render_to_response("registration/step3.html", {'courses': courses},  RequestContext(request))

rawDescription: Django pass selected object from form to another form


code:
word = 'hello'
out = []
c_prev = None

for c in word:
    value = ord(c) - ord('a')

    if c == c_prev:  # double if repeated character
        value = value * 2

    out.append(value)
    c_prev = c  # store for next comparison

print(sum(out))

rawDescription: Alphabet to integers

description: Alphabet to integers


rawDescription: Matplotlib: eps-plots lost quality

description: Matplotlib: eps-plots lost quality


code:
names=['Peter', 'Tom',  'Carl', 'Edward', 'Jake', 'Joe',  'Ken']
times=[10.01,    9.89,   9.91,    9.88,    9.91,   9.91,   9.90]
name_time_dict = dict(zip(names,times))
name_time_dict
times.sort()
times.index(name_time_dict['Joe'])+1
4
times.index(name_time_dict['Peter'])+1
7

rawDescription: Python exercise: 100m running with name list


code:
import tkinter as tk

root = tk.Tk()

def update_btn_text():
    btn_text.set("b")

btn_text = tk.StringVar()
btn = tk.Button(root, textvariable=btn_text, command=update_btn_text)
btn_text.set("a")

btn.pack()

root.mainloop()

rawDescription: Python 3, Tkinter, How to update button text


code:
from django.contrib.auth.models import User
from django.db import connection, models, transaction
from django.db.models.signals import post_delete, post_save

class Question(models.Model):
    # ...
    favourite_count = models.PositiveIntegerField(default=0)

class FavouriteQuestion(models.Model):
    question = models.ForeignKey(Question)
    user     = models.ForeignKey(User)

def update_question_favourite_count(instance, **kwargs):
    """
    Updates the favourite count for the Question related to the given
    FavouriteQuestion.
    """
    if kwargs.get('raw', False):
        return
    cursor = connection.cursor()
    cursor.execute(
        'UPDATE soclone_question SET favourite_count = ('
            'SELECT COUNT(*) from soclone_favouritequestion '
            'WHERE soclone_favouritequestion.question_id = soclone_question.id'
        ') '
        'WHERE id = %s', [instance.question_id])
    transaction.commit_unless_managed()

post_save.connect(update_question_favourite_count, sender=FavouriteQuestion)
post_delete.connect(update_question_favourite_count, sender=FavouriteQuestion)

# Very, very naughty
User.add_to_class('favourite_questions',
                  models.ManyToManyField(Question, through=FavouriteQuestion,
                                         related_name='favourited_by'))

rawDescription: post_save signal on m2m field

description: Post_save signal on m2m field


code:
from   fabric.api                                        import output

FAB_SHOW_RUNNING  = True   # Show the command that fabric runs
FAB_SHOW_STDOUT   = False  # Show the stdout of the command run
FAB_SHOW_STDERR   = False  # Show the stderr of the command run
FAB_SHOW_DEBUG    = True   # Increase logging detail for messages
FAB_SHOW_USER     = True
FAB_SHOW_STATUS   = False  # Prevent fabric from using print in some situations (at least in disconnect_all)
FAB_SHOW_WARNINGS = False  # Avoid fabric from showing messages about failed commands

output['running']  = FAB_SHOW_RUNNING
output['stdout']   = FAB_SHOW_STDOUT
output['stderr']   = FAB_SHOW_STDERR
output['debug']    = FAB_SHOW_DEBUG
output['user']     = FAB_SHOW_USER
output['status']   = FAB_SHOW_STATUS
output['warnings'] = FAB_SHOW_WARNINGS

rawDescription: Why is fabric using /bin/sh

description: Why is fabric using /bin/sh


code:
def pretty_date(time=False):
    """
    Get a datetime object or a int() Epoch timestamp and return a
    pretty string like 'an hour ago', 'Yesterday', '3 months ago',
    'just now', etc
    """
    from datetime import datetime
    now = datetime.now()
    if type(time) is int:
        diff = now - datetime.fromtimestamp(time)
    elif isinstance(time,datetime):
        diff = now - time
    elif not time:
        diff = now - now
    second_diff = diff.seconds
    day_diff = diff.days

    if day_diff < 0:
        return ''

    if day_diff == 0:
        if second_diff < 10:
            return "just now"
        if second_diff < 60:
            return str(second_diff) + " seconds ago"
        if second_diff < 120:
            return "a minute ago"
        if second_diff < 3600:
            return str(second_diff / 60) + " minutes ago"
        if second_diff < 7200:
            return "an hour ago"
        if second_diff < 86400:
            return str(second_diff / 3600) + " hours ago"
    if day_diff == 1:
        return "Yesterday"
    if day_diff < 7:
        return str(day_diff) + " days ago"
    if day_diff < 31:
        return str(day_diff / 7) + " weeks ago"
    if day_diff < 365:
        return str(day_diff / 30) + " months ago"
    return str(day_diff / 365) + " years ago"

rawDescription: User-friendly time format in Python?

description: User-friendly time format in Python


code:
# Its a square with the top edge poked in
points = [
    ( 1.0,  1.0),
    ( 0.0,  0.0),
    (-1.0,  1.0),
    (-1.0, -1.0),
    ( 1.0, -1.0)]

def angle(x1, y1, x2, y2):
    # Use dotproduct to find angle between vectors
    # This always returns an angle between 0, pi
    numer = (x1 * x2 + y1 * y2)
    denom = sqrt((x1 ** 2 + y1 ** 2) * (x2 ** 2 + y2 ** 2))
    return acos(numer / denom)

def cross_sign(x1, y1, x2, y2):
    # True if cross is positive
    # False if negative or zero
    return x1 * y2 > x2 * y1

for i in range(len(points)):
    p1 = points[i]
    ref = points[i - 1]
    p2 = points[i - 2]
    x1, y1 = p1[0] - ref[0], p1[1] - ref[1]
    x2, y2 = p2[0] - ref[0], p2[1] - ref[1]

    print('Points', p1, ref, p2)
    print('Angle', angle(x1, y1, x2, y2))
    if cross_sign(x1, y1, x2, y2):
        print('Inner Angle')
    else:
        print('Outer Angle')
    print('')

rawDescription: Best algorithm for detecting interior and exterior angles of an arbitrary shape in python


rawDescription: Sending mail in Django 1.5 with Gmail smtp


code:
def getIndices(number, values):
    '''Return a tuple (n, l) where l is a list of indices in 'values' and the
    following condition holds: n + sum(values[i] for i in l) == number.

    values -- sorted list of numbers
    number -- sum to search for

    >>> values=[10,20,20,50,100,200,200,500,1000,2000,2000,5000]
    >>> getIndices(18000, values)
    (6900, [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
    >>> getIndices(450, values)
    (0, [6, 5, 3])
    >>> getIndices(15, values)
    (5, [0])
    >>> getIndices(10, values)
    (0, [0])
    >>> getIndices(5, values)
    (5, [])
    >>> getIndices(0, values)
    (0, [])

    This simplicist algorithm does not always find a solution with 'n' == 0,
    even if one exists. The following test fails, it returns (10, [2])
    instead.

    >>> getIndices(40, [20, 20, 30])
    (0, [0, 1])

    '''
    n = number
    l = []

    for i in range(len(values) - 1, -1, -1):
        if values[i] <= n:
            l.append(i)
            n -= values[i]

    assert(n + sum(values[i] for i in l) == number)
    return n, l

if __name__ == '__main__':
    import doctest
    doctest.testmod()

rawDescription: Get the indices of a list whose value add up to the given number


code:
from Tkinter import *

def hide_me(event):
    event.widget.pack_forget()

root = Tk()
btn=Button(root, text="Click")
btn.bind('<Button-1>', hide_me)
btn.pack()
btn2=Button(root, text="Click too")
btn2.bind('<Button-1>', hide_me)
btn2.pack()
root.mainloop()

rawDescription: In Tkinter is there any way to make a widget not visible?


code:
import os
os.urandom(10).encode('hex')
os.urandom(20).encode('hex')
os.urandom(30).encode('hex')

rawDescription: python, hash function selection

description: Python, hash function selection


code:
import subprocess
with open('output.txt', 'w') as output_f:
    p = subprocess.Popen('Text/to/execute with-arg',
                         stdout=output_f,
                         stderr=output_f)

rawDescription: How to redirect the output of .exe to a file in python?

description: Redirect the output of .exe to a file in python


code:
import sys
sys.modules['os'] = None
sys.modules['system'] = None

rawDescription: How can I block a Python stdlib module from being imported?

description: Block a Python stdlib module from being imported


code: [mydict[x] for x in mykeys]

rawDescription: Python dictionary: Get list of values for list of keys


code:
EVLO, EVLA, STLO, STLA = np.genfromtxt('ray_temp', unpack = True)

for x,y,z,w in zip(evlo,evla,stlo,stla):
    map.drawgreatcircle(x,y,z,w)

plt.show()

rawDescription: Numpy Array iteration and Call of Matplotlib Function


code:
class X(object):
    def __getattr__(self, name):
        return name
i = X()
from collections import Callable
isinstance(i, Callable)
callable(i)
hasattr(i, '__call__')
i()

rawDescription: Using callable(x) vs. hasattr(x, "__call__")


rawDescription: set_data and autoscale_view matplotlib

description: Set_data and autoscale_view matplotlib


code:
df.groupby('id')['x'].apply(pd.rolling_mean, 2, min_periods=1)
df.groupby('id')['x'].cumsum()

rawDescription: Python - rolling functions for GroupBy object


rawDescription: How do I import from a child directory / subfolder?

description: Import from a child directory / subfolder


code:
import numpy, scipy.signal
taps = numpy.repeat(1.0/9, 9)
smoothed_x = scipy.signal.lfilter(taps, 1.0, x)

rawDescription: NumPy analog of R's `filter`

description: NumPy analog of R's `filter`


code:
import sys
import csv

input_file = csv.DictReader(open(sys.argv[1], "rU")) #has all info

ref_list = csv.DictReader(open(sys.argv[2], "rU")) #reference list

output_file = csv.DictWriter(
open(sys.argv[3], "w"), input_file.fieldnames) #to write output file with headers

output_file.writeheader() #write headers in output file

white_list={} #create empty dictionary
for record in ref_list: #for every line in my reference list
    white_list[record["Sample_ID"]] = None #store into the dictionary the  ID's as keys

for record in input_file: #for every line in my input file
    record_id = record["Sample_ID"] #store ID's into variable record_id
    if (record_id in white_list): #if the ID is in the reference list
        output_file.writerow(record)   #write the entire row into a new file
    else:   #if it is not in my reference list
        continue  #ignore it and continue iterating through the file

rawDescription: extracting data from CSV file using a reference

description: Extracting data from CSV file using a reference


code:
class LazyList(object):
    def __init__(self, it):
        self._cache = []
        self._it = it
    def __iter__(self):
        for item in self._cache:
            yield item
        for item in self._it:
            self._cache.append(item)
            yield item

rawDescription: how can I lazily construct a list?

description: Lazily construct a list


code:
class UserSearch(Resource):
    def get(self, search_term):
        results = User.query.filter(User.name.like('%'+search_term+'%')).all()

        # serialize and return items...

api.add_resource(UserSearch, '/users/search/<search_term>')

rawDescription: Flask Restful search query

description: Flask Restful search query


rawDescription: Consolidating two dictionaries with the same keys and different values


code:
address_pattern = re.compile(
    r'street:\s?(?P<street>.*?)\s*'
    r'city:\s?(?P<city>.*?)\s*'
    r'floor:\s?(?P<floor>.*?)\s*'
)
address_pattern.search(address).groups()

rawDescription: Extracting trimmed data from string using regex in python


code:
import numpy as np
import matplotlib.pyplot as plt
# random data to stand in
x1 = 0.8+0.1*np.random.rand(25)
x2 = 0.3+0.2*np.random.rand(25)
# customise the marker properties
plt.plot(x1, color='g', marker='s', mec='w', mfc='g', mew='3', ms=8)
plt.plot(x2, color='b', marker='s', mec='w', mfc='b', mew='3', ms=8)
plt.show()

rawDescription: Matplotlib: Markers surrounded by white space


code:
import urllib.request

@cherrypy.tools.json_in()
@cherrypy.expose
def index(self):
    httpreq = urllib.request.Request(url="http://somesite/")
    response = urllib.request.urlopen(httpreq)
    jsonobject = response.read()

rawDescription: Make HTTP request with cherrypy

description: Make HTTP request with cherrypy


code: res_list_1 = [item for object in my_list for item in (object*2, object*3)]

rawDescription: flat list as a result of list comprehension

description: Flat list as a result of list comprehension


code:
r = requests.post("https://{Egnyte Domain}.egnyte.com/puboauth/token", params=payload)
token = r.json()['access_token']

users = requests.get(url, headers={'Authorization': 'Bearer %s' % token})

rawDescription: Unclear on making an API call after authentication?


code:
class Foo:
    def __init__(self, bar, bazz):
        self.bar = bar
        self.bazz = bazz

    def __hash__(self):
        return hash((self.bar, self.bazz))

    def __eq__(self, other):
        return (self.bar, self.bazz) == (other.bar, other.bazz)

rawDescription: How to customize 'has_key' or 'in' method of a Python dictionary

description: Customize 'has_key' or 'in' method of a Python dictionary


code:
msgIDs = {}
# get where you left off in the logfile during the last read:
try:
    with open('logfile_placemarker.txt', 'r') as f:
        lastRead = int(f.read())
except IOError:
    print("Can't find/read place marker file!  Starting at 0")
    lastRead = 0

with open('logfile.log', 'r') as f:
    f.seek(lastRead)
    for line in f:
        # ...
        # Pick out msgIDs and response codes
        # ...
        if msgID in msgIDs:
            print("uh oh, found the same msg id twice!!")
        msgIDs[msgID] = responseCode
    lastRead = f.tell()

# Do whatever you need to do with the msgIDs you found:
updateDB(msgIDs)
# Store lastRead (where you left off in the logfile) in a file if you need to so it persists in the next run
with open('logfile_placemarker.txt', 'w') as f:
    f.write(str(lastRead))

rawDescription: Python analyse logfile with regex

description: Python analyse logfile with regex


code:
import re
re.sub(r'\d', '', s) # or re.sub(r',\d', '', s) to remove the commas, too

rawDescription: How can I filter out numbers from this letter-number pairs?

description: Filter out numbers from this letter-number pairs


code:
from collections import Counter
myword = [{'a': 2}, {'b':3}, {'c':4}, {'a':1}]
c = Counter()
for d in myword:
    c.update(d)
[{key: value} for key, value in c.items()]
[{key: value} for key, value in sorted(c.items())]

rawDescription: Python adding dictionary values with same key within a list


code: exec(functions_to_create, globals())

rawDescription: How to run "exec" from the global scope in python

description: Run "exec" from the global scope in python


code:
from itertools import product
def _combinations_for_record(d):
    for tmp, vlt, prs in product(d['Temp'], d['Voltage'], d['Pressure']):
        yield {"Temp": [tmp], "Voltage": [vlt], "Pressure": [prs]}

rawDescription: iterator/generator to produce all possible cases in a control system

description: Iterator/generator to produce all possible cases in a control system


code:
for node in G.nodes():
    edges = G.in_edges(node, data=True)
    if len(edges) > 0: #some nodes have zero edges going into it
        min_weight = min([edge[2]['weight'] for edge in edges])
        for edge in edges:
            if edge[2]['weight'] > min_weight:
                G.remove_edge(edge[0], edge[1])

rawDescription: Find highest weight edge(s) for a given node


code: cur.execute("SELECT * FROM Posts ORDER BY date ASC")

rawDescription: Sqlite python - how to sort by date(newest first)


code:
data = pd.DataFrames({'x': x, 'sin(x)': y}, columns=['x', 'sin(x)'])
data

rawDescription: Read lists into columns of pandas DataFrame


code: datetime.datetime.utcnow().strftime('%B %d %Y - %H:%M:%S')

rawDescription: Format datetime.utcnow() time

description: Format datetime.utcnow() time


code:
from flask import request, abort

def check_auth(instance_id=None, **kw):
    current_user = None
    auth = request.headers.get('Authorization', '').lower()
    try:
        type_, apikey = auth.split(None, 1)
        if type_ != 'your_api_scheme':
            # invalid Authorization scheme
            ProcessingException(message='Not Authorized',
                                status_code=401)
        current_user = user_for_apikey[apikey]
    except (ValueError, KeyError):
        # split failures or API key not valid
        ProcessingException(message='Not Authorized',
                            status_code=401)

rawDescription: Accessing request headers in flask-restless preprocessor


code:
class ToDoList(models.Model):
    name = models.CharField(...)
    validated_at = models.DateTimeField(..., null=True, editable=False)
    rejection_reason = models.TextFiel(..., editable=False)

rawDescription: What is the best way to add temporary information to a Django model? (without creating a new model)


code:
DATABASES = {'default': dj_database_url.config()}
DATABASES['default']['ATOMIC_REQUESTS'] = True

rawDescription: How to configure Django database using Heroku?

description: Configure Django database using Heroku


code:
from django.db.models.query_utils import Q

tag_name_list = xxx # dynamic tag name list based on user input

query_list = [Q(tags__name=tag_name) for tag_name in tag_name_list]
query_set = Entry.objects
for query in query_list:
    query_set = query_set.filter(query)
return query_set

rawDescription: Querying for Multiple ManyToMany Fields

description: Querying for Multiple ManyToMany Fields


rawDescription: Python Adjacency -- the range() function


code:
import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import *

class MyWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.edit = QTextEdit()
        self.edit.setWindowTitle("QTextEdit Standard Output Redirection")
        self.button = QPushButton('Run ldconfig')
        self.button.clicked.connect(self.onClick)
        layout = QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.button)

    @pyqtSlot()
    def readStdOutput(self):
        self.edit.append(QString(self.proc.readAllStandardOutput()))

    def onClick(self):
        self.proc = QProcess()
        self.proc.start("echo hello")
        self.proc.setProcessChannelMode(QProcess.MergedChannels);
        QObject.connect(self.proc, SIGNAL("readyReadStandardOutput()"), self, SLOT("readStdOutput()"));

def main():
    app = QApplication(sys.argv)
    win = MyWindow()
    win.show()
    return app.exec_()

if __name__ == '__main__':
    main()

rawDescription: Adding Button and Separate Window to Python QProcess Example


code:
for line in open("words/text.txt", 'r').readlines():
    split_lines = line.strip('{}').split('|')
    if word == split_lines[0]: #Or word in line would look for word anywhere in the line
        return split_lines[1]

rawDescription: Find word in file, return definition

description: Find word in file, return definition


code:
from PIL import Image
import numpy as np

im = Image.open(sample_path.bmp)
p = np.array(im)

rawDescription: How to convert image into numerical array(numpy)?

description: Convert image into numerical array(numpy)


rawDescription: Iterate and compare within lambda in Python


code:
headers = {
    "User-Agent": "jpostma1's crawler"
}

url = "http://manybooks.net/_scripts/send.php?tid=lovecrafthother06At_the_Mountains_of_Madness&book=1:text:.txt:text"
req = urllib2.Request(url, headers=headers)
testfile = urllib2.urlopen(req)
with open("book 001.txt",'w') as w:
    w.write(testfile.read())

rawDescription: Download .txt with Python that is accessed through an php request


code: pos_tagger = nltk.data.load("http://<your S3 bucket with the nltk data>.s3.amazonaws.com/nltk_data/taggers/maxent_treebank_pos_tagger/english.pickle")

rawDescription: Heroku Django app using NLTK: How do I use the NLTK corpora in the app?


rawDescription: Replace multiple objects conditionally

description: Replace multiple objects conditionally


code:
import tkinter as tk
import tkinter.ttk as ttk

class MyButton(tk.Frame):

    def __init__(self, master, bg_hover='red', bg_normal=None, **options):
        tk.Frame.__init__(self, master, **options)

        self.bg_normal = bg_normal
        self.bg_hover = bg_hover

        # use default color if bg_normal is `None`
        if not self.bg_normal:
            self.bg_normal = self['bg']

        # add first label
        self.left_label = tk.Label(self, text="Left")
        self.left_label.pack(side=tk.LEFT, padx=16, pady=4)

        # add second label
        self.right_label = tk.Label(self, text="Right")
        self.right_label.pack(side=tk.RIGHT, padx=16, pady=4)

        # bind events
        self.bind('<Enter>', self.on_enter)
        self.bind('<Leave>', self.on_leave)

    def on_enter(self, event=None):
        # change all backgrounds on mouse enter
        self['bg'] = self.bg_hover
        self.left_label['bg'] = self.bg_hover
        self.right_label['bg'] = self.bg_hover

    def on_leave(self, event=None):
        # change all backgrounds on mouse leave
        self['bg'] = self.bg_normal
        self.left_label['bg'] = self.bg_normal
        self.right_label['bg'] = self.bg_normal

root = tk.Tk()

normal_button = ttk.Button(root, text="Normal Button")
normal_button.pack(fill=tk.X)

my_button = MyButton(root)
my_button.pack()

root.mainloop()

rawDescription: How to put widgets inside a ttk.Button

description: Put widgets inside a ttk.Button


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

data  = np.random.randint(8, size=(100,100))
cmap = plt.cm.get_cmap('PiYG', 8)
plt.pcolormesh(data,cmap = cmap,alpha = 0.75)
# Set borders in the interval [0, 1]
bound = np.linspace(0, 1, 9)
# Preparing borders for the legend
bound_prep = np.round(bound * 7, 2)
# Creating 8 Patch instances
plt.legend([mpatches.Patch(color=cmap(b)) for b in bound[:-1]],
           ['{} - {}'.format(bound_prep[i], bound_prep[i+1] - 0.01) for i in range(8)])

rawDescription: Plotting discrete colorbar in legend style using Matplotlib


code:
query = Q()
for search in (prefs.address1, prefs.address2):
    if search:
        query |= Q(title__icontains=search)
results = Stores.objects.filter(query)

rawDescription: How to deal with "None" DB values in Django queries

description: Deal with "None" DB values in Django queries


code:
try: paraview.simple
except: from paraview.simple import *
paraview.simple._DisableFirstRenderCameraReset()

my_foam = FindSource("case.foam")
SetActiveSource(my_foam)

tsteps = my_foam.TimestepValues
PlotOverLine1 = PlotOverLine( Source="High Resolution Line Source" )
DataRepresentation7 = Show()

PlotOverLine1.Source.Point1 = [-0.052, 0.0, 0.0]
PlotOverLine1.Source.Point2 = [0.0, 0.0, 0.0]

source = PlotOverLine1

for TimeStepNum in range(0,len(tsteps)):
    view = GetActiveView()
    view.ViewTime = tsteps[TimeStepNum]
    Render()
    writer = CreateWriter("file_%d.csv" %(TimeStepNum), source)
    writer.FieldAssociation = "Points"
    writer.UpdatePipeline()
    Render()
    del writer

rawDescription: writing plotOverline csv data from paraview for all time steps with python script

description: Writing plotOverline csv data from paraview for all time steps with python script


code:
from django.db.models import Count

B.objects.annotate(a_count=Count('a')).filter(a_count__lt=5)

rawDescription: Query set of number of related objects

description: Query set of number of related objects


code:
def key_at_depth(dct, dpt):
     if dpt > 0:
         return [ key for subdct in dct.itervalues() for key in key_at_depth(subdct, dpt-1)  ]
     else:
         return dct.keys()

dict_o_dicts = {'a': {1:'bob', 2: 'fred', 3: 'henry'}, 'b': {2:'fred',3: 'henry', 4: 'pascale'} }

key_at_depth(dict_o_dicts, 0)

Out[69]: ['a', 'b']

key_at_depth(dict_o_dicts, 1)

Out[70]: [1, 2, 3, 2, 3, 4]

rawDescription: Python: How do I get a list of all keys in a dictionary of dictionaries, at a given depth


code:
class Pool(object):
    '''
    Class which supports an async version of applying functions to arguments.
    '''
    Process = Process

    def __init__(self, processes=None, initializer=None, initargs=(),
                 maxtasksperchild=None):
        self._setup_queues()
        self._taskqueue = queue.Queue()
        self._cache = {}
        self._state = RUN
        self._maxtasksperchild = maxtasksperchild
        self._initializer = initializer
        self._initargs = initargs

        if processes is None:
            try:
                processes = cpu_count()
            except NotImplementedError:
                processes = 1
        if processes < 1:
            raise ValueError("Number of processes must be at least 1")

        if initializer is not None and not callable(initializer):
            raise TypeError('initializer must be a callable')

        self._processes = processes
        self._pool = []
        self._repopulate_pool()

        self._worker_handler = threading.Thread(
            target=Pool._handle_workers,
            args=(self, )
            )
        self._worker_handler.daemon = True
        self._worker_handler._state = RUN
        self._worker_handler.start()

        self._task_handler = threading.Thread(
            target=Pool._handle_tasks,
            args=(self._taskqueue, self._quick_put, self._outqueue, self._pool)
            )
        self._task_handler.daemon = True
        self._task_handler._state = RUN
        self._task_handler.start()

        self._result_handler = threading.Thread(
            target=Pool._handle_results,
            args=(self._outqueue, self._quick_get, self._cache)
            )
        self._result_handler.daemon = True
        self._result_handler._state = RUN
        self._result_handler.start()

        self._terminate = Finalize(
            self, self._terminate_pool,
            args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
                  self._worker_handler, self._task_handler,
                  self._result_handler, self._cache),
            exitpriority=15
            )

rawDescription: When does python's Pool fork?

description: When does python's Pool fork


code:
filter(lambda seq: get_long(seq, 3),
       dna_list)

rawDescription: Passing a function with two arguments to filter() in python


code: ab = [any(x) for x in zip(cd, ca, cp)]

rawDescription: Python OR'ing arrays together

description: Python OR'ing arrays together


code: open('//HOST/share/path/to/file')

rawDescription: Using Python, how can I access a shared folder on windows network?


code:
from itertools import chain, repeat

class OuterZipStopIteration(Exception):
    pass

def outer_zip(*args):
    count = len(args) - 1

    def sentinel(default):
        nonlocal count
        if not count:
            raise OuterZipStopIteration
        count -= 1
        yield default

    iters = [chain(p, sentinel(default), repeat(default)) for p, default in args]
    try:
        while iters:
            yield tuple(map(next, iters))
    except OuterZipStopIteration:
        pass

print(list(outer_zip( ("abcd", '!'),
                      ("ef", '@'),
                      (map(int, '345'), '$') )))

rawDescription: Outerzip / zip longest function (with multiple fill values)


code:
import csv #imports module csv

filea = "fileA.csv"
fileb = "fileB.csv"
output = "fileC.csv"

delim = ";" #set your own delimiter

source1 = csv.reader(open(filea,"r"),delimiter=delim)
source2 = csv.reader(open(fileb,"r"),delimiter=delim)
#open csv readers

source2_dict = {}

# prepare changes from file B
for row in source2:
    source2_dict[row[0]] = row[1]

# write new changed rows
with open(output, "w") as fout:
    csvwriter = csv.writer(fout, delimiter=delim)
    for row in source1:
        # needs to check whether there are any changes prepared
        if row[1] in source2_dict:
            # change the item
            row[3] = source2_dict[row[1]]
        csvwriter.writerow(row)

rawDescription: python update a column value of a csv file according to another csv file

description: Python update a column value of a csv file according to another csv file


code: any(key.startswith(mystr) for key in mydict)

rawDescription: fastest way to search python dict with partial keyword

description: Fastest way to search python dict with partial keyword


code:
from mechanize import Browser
from bs4 import BeautifulSoup

br = Browser()
br.set_handle_robots( False )
br.addheaders = [('User-agent', 'Firefox')]
br.open("http://www.mcxindia.com/sitepages/BhavCopyCommodityWise.aspx")
br.select_form("form1")
#now enter the dates according to your choice
br.form["mTbFromDate"] = "date-From"
br.form["mTbFromDate"] = "date-To"
response = br.submit()
#now read the response with BeautifulSoup and do whatever you want
soup = BeautifulSoup(response.read())

rawDescription: Using Python and Mechanize to submit data in the website's html


code:
def simplistic_plural(word, text):
    word_or_plural = re.escape(word) + 's?'
    return re.match(word_or_plural, text)

rawDescription: Escaping regex string in Python

description: Escaping regex string in Python


code:
import collections
import ruamel.yaml as yaml

from ruamel.yaml.reader import Reader
from ruamel.yaml.scanner import Scanner
from ruamel.yaml.parser_ import Parser
from ruamel.yaml.composer import Composer
from ruamel.yaml.constructor import Constructor
from ruamel.yaml.resolver import Resolver
from ruamel.yaml.nodes import MappingNode
from ruamel.yaml.compat import PY2, PY3

class MyConstructor(Constructor):
    def construct_mapping(self, node, deep=False):
        if not isinstance(node, MappingNode):
            raise ConstructorError(
                None, None,
                "expected a mapping node, but found %s" % node.id,
                node.start_mark)
        mapping = {}
        for key_node, value_node in node.value:
            # keys can be list -> deep
            key = self.construct_object(key_node, deep=True)
            # lists are not hashable, but tuples are
            if not isinstance(key, collections.Hashable):
                if isinstance(key, list):
                    key = tuple(key)
            if PY2:
                try:
                    hash(key)
                except TypeError as exc:
                    raise ConstructorError(
                        "while constructing a mapping", node.start_mark,
                        "found unacceptable key (%s)" %
                        exc, key_node.start_mark)
            else:
                if not isinstance(key, collections.Hashable):
                    raise ConstructorError(
                        "while constructing a mapping", node.start_mark,
                        "found unhashable key", key_node.start_mark)

            value = self.construct_object(value_node, deep=deep)
            # next two lines differ from original
            if key in mapping:
                raise KeyError
            mapping[key] = value
        return mapping

class MyLoader(Reader, Scanner, Parser, Composer, MyConstructor, Resolver):
    def __init__(self, stream):
        Reader.__init__(self, stream)
        Scanner.__init__(self)
        Parser.__init__(self)
        Composer.__init__(self)
        MyConstructor.__init__(self)
        Resolver.__init__(self)

yaml_str = """\
some_key: 0,
another_key: 1,
some_key: 1
"""

data = yaml.load(yaml_str, Loader=MyLoader)
print(data)

rawDescription: How to prevent re-definition of keys in YAML?

description: Prevent re-definition of keys in YAML


code:
import numpy as np
import scipy.ndimage as ndi
import matplotlib.pyplot as plt

# Make a small array for the demonstration.
# The ndimage.label() function treats 0 as the "background".
a = np.zeros((16, 16), dtype=int)
a[:6, :8] = 1
a[9:, :5] = 1
a[8:, 13:] = 2
a[5:13, 6:12] = 3

struct = ndi.generate_binary_structure(2, 2)
lbl, n = ndi.label(a, struct)

# Plot the original array.
plt.figure(figsize=(11, 4))
plt.subplot(1, n + 1, 1)
plt.imshow(a, interpolation='nearest')
plt.title("Original")
plt.axis('off')

# Plot the isolated features found by label().
for i in range(1, n + 1):
    # Make an array of zeros the same shape as `a`.
    feature = np.zeros_like(a, dtype=int)

    # Set the elements that are part of feature i to 1.
    # Feature i consists of elements in `lbl` where the value is i.
    # This statement uses numpy's "fancy indexing" to set the corresponding
    # elements of `feature` to 1.
    feature[lbl == i] = 1

    # Make an image plot of the feature.
    plt.subplot(1, n + 1, i + 1)
    plt.imshow(feature, interpolation='nearest', cmap=plt.cm.copper)
    plt.title("Feature {:d}".format(i))
    plt.axis('off')

plt.show()

rawDescription: Python - Iter through identified component features


code:
import pandas as pd

df=pd.DataFrame({'id':    ['a','a','a','a','a','a','a','b','b','b','b','b','b','b','b','b','b'],
                'min':[10,17,21,22,22,7,58,15,17,19,19,19,19,19,25,26,26],
                'day':[15,15,15,15,15,17,17,41,41,41,41,41,41,41,57,57,57]})

# initialize the catagory to 1 for counter increament
cat =1

# for the first row the catagory will be 1
new_series = [cat]

# loop will start from 1 and not from 0 because we cannot perform operation on iloc -1
for i in range(1,len(df)):
    if df.iloc[i]['day'] == df.iloc[i-1]['day']:
        if df.iloc[i]['min'] - df.iloc[i-1]['min'] > 8:
            cat+=1
    else:
        cat+=1
    new_series.append(cat)

df['catagory']= new_series
print(df)

rawDescription: grouping by id and a condition

description: Grouping by id and a condition


code:
import re
sstr = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)|uniprotkb:HIST1H3B(gene name)|uniprotkb:HIST1H3C(gene name)|uniprotkb:HIST1H3E(gene name)|uniprotkb:HIST1H3F(gene name)|uniprotkb:HIST1H3G(gene name)|uniprotkb:HIST1H3H(gene name)|uniprotkb:HIST1H3I(gene name)|uniprotkb:HIST1H3J(gene name)'
re.findall(r'uniprotkb:([^(]*)\(gene name\)', sstr)

rawDescription: python regular expression. Extract text between patterns

description: Python regular expression. Extract text between patterns


code:
import webapp2
newdomain = 'http://www.mynewdomain.com/'

class RedirectPage(webapp2.RequestHandler):
    def get(self, restofurl):
        return webapp2.redirect(newdomain + restofurl, permanent=True)

app = webapp2.WSGIApplication([webapp2.Route(r'/<restofurl:.*>', handler=RedirectPage, name='redirect_page')])

rawDescription: Page for Page Redirect in Google App Engine


code:
from types import ModuleType

isinstance(obj, ModuleType)

rawDescription: Check if a parameter is a Python module?

description: Check if a parameter is a Python module


code:
xp = '//*[contains(@id, "_p_ctl17_ctl04_ctl01_ctl00_dlProps")]/tr[1]/td[1]/text()'
item["Details_H1"] = hxs.select(xp).extract()

rawDescription: Scrapy - incrementing number in a string


code:
youtubePlayer = document.getElementById("movie_player");
youtubePlayer.getPlayerState();

rawDescription: Youtube + Selenium (Python) - How to know when video ends?


code:
def findAinD(cookies, cream):  # assumes that cookies and cream can be treated as such in the for loop will fail otherwise
    A1 = []
    D1 = []

    for mrow in range(1, Cookies.get_highest_row() + 1):
        A1 += cookies['A' + str(mrow)]
        D1 += cream['D' + str(mrow)]

    A1.sort()  # Alphabetical
    D1.sort()  # ^

    for i, cookie in enumerate(A1): # Enumerate returns the index and the object for each iteration
        A1[i] = D1.index(cookie)    # If cookie IS in D, then A1[i] now contains the index of the first occurence of A[i] in D
                                    # If cookie is not, then the result is -1, which is never an index,
                                    #  and we filter those out before round 2 (not shown)

    return A1

rawDescription: Python: How do I search a string from one XLSX to be in another XLSX file?


code:
regex = re.compile(r'Manually launch test ([0-9]+) stringZ')
while True:
    latestOccurrence = None
    with open(fileName) as tempFile:
        for line in tempFile:
            if "stringZ" in line:
                match = regex.match(line)
                if match:
                    latestOccurrence = int(match.group(1))
    # do something with latestOccurrence here?
    time.sleep(1)

rawDescription: How can I get the last occurence of a text in a file that is automatically updated - python?

description: Get the last occurence of a text in a file that is automatically updated - python


code:
sql_command = """
    INSERT INTO
        some_table(some_text_row)
    VALUES
        (%s)"""
cursor.execute(sql_command, (some_text, ))

rawDescription: Python strings - strange replacing behavior


code:
from sqlalchemy import create_engine, MetaData, Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import pandas as pd
engine = create_engine("mssql+pyodbc://@{SERVER}/{database}?driver=SQL+Server+Native+Client+10.0?trusted_connection=yes")
metadata = MetaData()
Base = declarative_base(metadata=metadata)

class TableA(Base):
    __tablename__ = 'tableA'
    name = Column('name', String, primary_key=True)
    desc = Column('description', String)

Session = sessionmaker()
Session.configure(bind=engine)
session = Session()

q = session.query(TableA)

df = pd.read_sql(q.statement, q.session.bind)

rawDescription: sqlalchemy no specified driver, however driver is specified

description: Sqlalchemy no specified driver, however driver is specified


code:
filename = raw_input("File Name: ")
with open(filename, 'r+') as f:
    text = f.read()
    f.seek(0)
    f.write(text.upper())
    f.truncate()

rawDescription: Python converting text file to all caps

description: Python converting text file to all caps


code:
def get_monthly_totals(year, attr):
    queryset = Widget.objects.filter(**{attr + "__year": year})
    totals = [0] * 12
    for widget in queryset:
            totals[getattr(widget, attr).month -1] += 1
    return totals

totals_manufactured = gtotalset_monthly_totals(year, "manufactured")
totals_sold = get_monthly_totals(year, "sold")

rawDescription: Monthly total function for different object properties


code:
class1 = {}
with open("1.txt", "r+") as f:
    for line in f:
        columns = line.split(":")
        if len(columns) == 2:
            name = columns[0].strip()
            scores = map(int, columns[1].split(','))
            class1[name] = scores

for name, scores in class1.items():
    print('{}: {}'.format(name, max(scores)))

rawDescription: Find Highest Value in a dictionary

description: Find Highest Value in a dictionary


code:
df
pd.to_datetime(df.DATE) + df.HOUR.astype('timedelta64[h]')

rawDescription: python/pandas - converting date and hour integers to datetime

description: Python/pandas - converting date and hour integers to datetime


rawDescription: Hashing a python dictionary

description: Hashing a python dictionary


rawDescription: python: pandas - order of data frame column

description: Python: pandas - order of data frame column


code:
class UpdatableBlockingQueue(object):

  def __init__(self):
    self.queue = {}
    self.cv = threading.Condition()

  def put(self, key, value):
    with self.cv:
      self.queue[key] = value
      self.cv.notify()

  def pop(self):
    with self.cv:
      while not self.queue:
        self.cv.wait()
      return self.queue.popitem()

rawDescription: Blocking dict in Python?

description: Blocking dict in Python


code: somelist = [x for x in somelist if not determine(x)]

rawDescription: Fast way to remove a few items from a list/queue


code:
def send_message(request):
  if request.method == "POST":
    message = MessageForm(request.POST)
    message.save()

    return HttpResponse(simplejson.dumps({'result' : 'success'}), mimetype='application/javascript')

rawDescription: Django + jQuery + Ajax

description: Django + jQuery + Ajax


code:
def meets_criteria(line):
  return line.startswith("ATOM") or line.startswith("HETATM")

with open(large_file) as f:
    for line in f:
        if meets_criteria(line):
            with open(line.split()[6], "a") as of:
                of.write(line)

rawDescription: How to save in a file all rows that have equal value for a column

description: Save in a file all rows that have equal value for a column


code: myCanvas.create_rectangle( x0, y0, x1, y1, outline=myCanvas["background"], fill=myCanvas["background"])

rawDescription: How do I get the background color of a Tkinter Canvas widget

description: Get the background color of a Tkinter Canvas widget


code: r = [rand_foo() for _ in range(10)]

rawDescription: Is local variable necessary in Python comprehensions?


rawDescription: How to split a string containing digits and characters

description: Split a string containing digits and characters


code:
import re
string = "DAY MONTH      YEAR    THIS   HAS RANDOM   SPACES"
[match.start() for match in re.finditer(r'\b\w', string)]

rawDescription: Python 2.7: how to find the index of the first letter of each word in a string


code:
for axis_, angle_, lmnt_id_ in zip(axis, angle, lmnt_id):
    result.append(ElementTransformUtils.RotateElement(doc, lmnt_id_,
                                                      axis_, angle_))

rawDescription: function with list inputs in python

description: Function with list inputs in python


rawDescription: regex text between two string python

description: Regex text between two string python


code:
import numpy as np

def image_histogram_equalization(image, number_bins=256):
    # from http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html

    # get image histogram
    image_histogram, bins = np.histogram(image.flatten(), number_bins, normed=True)
    cdf = image_histogram.cumsum() # cumulative distribution function
    cdf = 255 * cdf / cdf[-1] # normalize

    # use linear interpolation of cdf to find new pixel values
    image_equalized = np.interp(image.flatten(), bins[:-1], cdf)

    return image_equalized.reshape(image.shape), cdf

if __name__ == '__main__':

    # generate some test data with shape 1000, 1, 96, 96
    data = np.random.rand(1000, 1, 96, 96)

    # loop over them
    data_equalized = np.zeros(data.shape)
    for i in range(data.shape[0]):
        image = data[i, 0, :, :]
        data_equalized[i, 0, :, :] = image_histogram_equalization(image)[0]

rawDescription: Histogram equalization of grayscale images with NumPy


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

def sleep_spindle_match(sampling_freq):
    freq = 13 #Hz

    x = np.arange(0,1,1.0/sampling_freq)
    y = np.sin(2 * np.pi * freq * x + (np.pi/2)) * np.cos(np.pi * x + (np.pi/2))

    spindle = {'x':x, 'y':y}

    return spindle

x = sleep_spindle_match(44100)
plt.plot(x['x'], x['y'])
plt.show()

rawDescription: Generate sine wave modulated with a cosine


code:
Example
import random

r = random.SystemRandom()
s = "some string"
print(r.choice(s)) # print random character from the string
print(s[r.randrange(len(s))]) # same

rawDescription: Python 3 os.urandom

description: Python 3 os.urandom


code:
from django import db

db.reset_queries()

rawDescription: Python/Django polling of database has memory leak


code:
def trail(word, lst):
    if word in lst:
        return [lst.index(word)]
    for i, x in enumerate(lst):
        if not isinstance(x, list):
            continue
        ret = trail(word, x)
        if ret is not None:
            return [i] + ret

trail('span 1 2', lis)
lis[0][2][2][1][0]
trail('no such string', lis)

rawDescription: How to find indices of a given value in python multi list?

description: Find indices of a given value in python multi list


rawDescription: Round float to x decimals?

description: Round float to x decimals


rawDescription: How can I count the occurrences of a list item in Python?

description: Count the occurrences of a list item in Python


code:
import subprocess
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'bar.settings'
subprocess.call(['python3', '/tmp/bar/manage.py', 'runserver'])

rawDescription: run Django server by calling subprocess from another Django project

description: Run Django server by calling subprocess from another Django project


code:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
plt.imsave('filename.png', np.array(data).reshape(50,50), cmap=cm.gray)

rawDescription: How can I write a binary array as an image in Python?

description: Write a binary array as an image in Python


code: lineno = s.count("\n",0,m.start())+1

rawDescription: map string position to line number in regex output

description: Map string position to line number in regex output


code:
def increment(self, seconds):
    with self._mutex:
        self._countdownInSec += seconds

rawDescription: Is a mutex really necessary in this piece of code?


code:
...
# ObjectType is not directly accessible, so need to get as QObject's type
ObjectType = type(QtCore.QObject)
class SignallerMeta(ObjectType):

    def __new__(cls, name, parents, dct):
        sig_dct = {}   # also generate the sig_dict class attribute here
        for i in range(10):
            signal = QtCore.Signal(Information)
            sig_dct[i] = signal
            dct['signal_{}'.format(i)] = signal
        dct['sig_dict'] = sig_dct
        return super().__new__(cls, name, parents, dct)

class Signaller(QtCore.QThread, metaclass=SignallerMeta):

    def __init__(self, parent=None):
        super().__init__(parent)
        # no need to copy the signals here

    def run(self):
        for key, sig in self.sig_dict.items():
            print("Emitting Key {}: Signal {}".format(key, sig))
            sig.emit(Information(key, sig))

        self.exec_()
...

rawDescription: PySide: Multithread signal connection connects slot to the wrong signal


code: subset_df = df[pd.Series(df.index).str.contains(regex, case=False).values]

rawDescription: Pandas Python: take a subset of df by row labels while using re.IGNORECASE


code:
from datetime import datetime, timedelta

now = datetime.now()
(timedelta(hours=24) - (now - now.replace(hour=6, minute=30, second=0, microsecond=0))).total_seconds() % (24 * 3600)

rawDescription: Python: calculate seconds from now to specified time today or tomorrow


code:
from datetime import datetime

from pymongo import MongoClient

client = MongoClient()
db = client.test
collection = db.collection
bulkOp = collection.initialize_ordered_bulk_op()
count = 0
for doc in collection.find():
    year = doc['createdDate'].year
    month = doc['createdDate'].month
    day = doc['createdDate'].day
    new_date = datetime(year, month, day)
    bulkOp.find({'_id': doc['_id']}).update({'$set': {'createdDate': new_date}})
    count = count + 1
    if count == 125:
        bulkOp.execute()
        bulkOp = collection.initialize_ordered_bulk_op()

if count % 125 != 0:
   bulkOp.execute()

rawDescription: select based on timestamp and update timestamp with zero

description: Select based on timestamp and update timestamp with zero


code:
# file : service_handler.py
from importlib import import_module

# get parameters from your config file beforehand
def get_backend(backend_name, **kwargs):

    # example : foo.Spam gets backend Spam from module foo
    backend_module, backend_class = backend_name.rsplit('.', 1)

    mdl = import_module(backend_module)
    cls = getattr(mdl, backend_class)

    return cls(**kwargs) # create the object

rawDescription: How do I implement run time objects (different) implementation with using Python

description: Implement run time objects (different) implementation with using Python


code:
import re

cleared_subtitles = [subtitle for subtitle in subtitles if not re.match(r'\d*\r')]

rawDescription: How to match numbers using regex in python in list

description: Match numbers using regex in python in list


code:
def connect(self):
    return getattr(self, "connect_%s" % self.type)()

def connect_aol(self):
    pass # AOL stuff

def connect_yahoo(self):
    pass # Yahoo! stuff

rawDescription: django heterogeneous queryset proxy models

description: Django heterogeneous queryset proxy models


code:
rock_group = set()
if len(rock_group) <= 12:
    rock_group.add(a_rock)

rawDescription: Is there a count type of method that you can use on a Python set?


code:
for i in range(len(a)):
    if a[i] > max:
        max = a[i]
        maxIndex = i

rawDescription: Python Finding Index of Maximum in List

description: Python Finding Index of Maximum in List


code:
def f(o, encoding=None, errors=None):
    if encoding is None and errors is None:
        return o.__str__()

    if isinstance(o, str):
        raise TypeError('decoding str is not supported')

    if not isinstance(o, (bytes, bytesarray)):
        raise TypeError('coercing to str: need bytes, bytearray'
             'or buffer-like object, %s found' % type(o).__name__)
    return o.decode(encoding, errors)

rawDescription: Python 3, multiple str functions

description: Python 3, multiple str functions


code:
class Example(object):
    pass

json_types = [int, float, str, Example]

string_to_type_dict = {t.__name__: t for t in json_types}

assert len(string_to_type_dict) == len(json_types)

def string_to_type(s):
    return string_to_type[s]

def type_to_string(t):
    return t.__name__

rawDescription: Converting a String to Type Object - Python


code:
def main():
    with open('StudentGrades.dat', 'r') as input1, open('StudentsAvg.txt', 'w') as output:
        counter = 0
        student_name = ''
        for nextLine in input1:
            if counter % 2 == 0:
                student_name = nextLine
            else:
                grades = [int(x) for x in nextLine.split()]
                avg = sum(grades) / len(grades)
                print(student_name, file=output)
                print(str(avg), file=output)

            counter += 1

rawDescription: Having trouble with my python program

description: Having trouble with my python program


code:
import tkinter as tk

CORRECT_ANSWER = 'Some answer'

def callback():

    if var.get() != CORRECT_ANSWER:
        for i in range(10, 50):
            canvas.move(text, -i if i% 2 == 0 else i, 0)
            canvas.update()
            canvas.move(text, i if i % 2 == 0 else -i, 0)
            canvas.update()

if __name__ == '__main__':

    root = tk.Tk()
    var = tk.StringVar()
    canvas = tk.Canvas(root, bg="black")
    canvas.pack(fill=tk.BOTH, expand=1)
    text = canvas.create_text(200, 100, text='Enter the answer to this question.',
        fill='white')
    entry = tk.Entry(root, textvariable = var)
    entry.pack(side=tk.LEFT, fill=tk.X, expand=1)
    submit = tk.Button(root, text='Submit', command=callback)
    submit.pack(side=tk.LEFT, fill=tk.X, expand=1)
    root.mainloop()

rawDescription: Text Animation in Tkinter Python?

description: Text Animation in Tkinter Python


code:
from scrapy.utils.response import open_in_browser

open_in_browser(response)

rawDescription: Open scrapy output in browser tab or ipython window


code:
import atexit

from IPython.zmq.ipkernel import IPKernelApp
from IPython.lib.kernel import find_connection_file
from IPython.frontend.qt.kernelmanager import QtKernelManager
from IPython.frontend.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.utils.traitlets import TraitError
from PyQt4 import QtGui, QtCore

def event_loop(kernel):
    kernel.timer = QtCore.QTimer()
    kernel.timer.timeout.connect(kernel.do_one_iteration)
    kernel.timer.start(1000*kernel._poll_interval)

def default_kernel_app():
    app = IPKernelApp.instance()
    app.initialize(['python', '--pylab=qt'])
    app.kernel.eventloop = event_loop
    return app

def default_manager(kernel):
    connection_file = find_connection_file(kernel.connection_file)
    manager = QtKernelManager(connection_file=connection_file)
    manager.load_connection_file()
    manager.start_channels()
    atexit.register(manager.cleanup_connection_file)
    return manager

def console_widget(manager):
    try: # Ipython v0.13
        widget = RichIPythonWidget(gui_completion='droplist')
    except TraitError:  # IPython v0.12
        widget = RichIPythonWidget(gui_completion=True)
    widget.kernel_manager = manager
    return widget

def terminal_widget(**kwargs):
    kernel_app = default_kernel_app()
    manager = default_manager(kernel_app)
    widget = console_widget(manager)

    #update namespace
    kernel_app.shell.user_ns.update(kwargs)

    kernel_app.start()
    return widget

app = QtGui.QApplication([])
widget = terminal_widget(testing=123)
widget.show()
app.exec_()

rawDescription: Embedding IPython Qt console in a PyQt application


code: "{{ STATIC_URL }}boostrap-dropdown.js"

rawDescription: Django development server serving css but not js


code:
items = ['24/2', '24/3', '25/2', '6']
sorted(items, key=lambda s: [int(n) for n in s.split('/')])

rawDescription: Python: Modified sorting order for a list


code:
from flask import render_template_string
render_template_string('hello {{ what }}', what='world')

rawDescription: Python Flask Render Text from Variable like render_template


code: nx.draw(G, edge_color='white', node_color='none', with_labels=True, labels=labels, node_shape=None)

rawDescription: How to remove the contour of nodes in networkx

description: Remove the contour of nodes in networkx


code: res = input('Test result? "(P)ass,(F)ail,(R)etry,(S)ave and Quit,(Q)uit": ')

rawDescription: How to detect user inactivity time in python application (Linux)?

description: Detect user inactivity time in python application (Linux)


code:
import inspect
def master(mandatory_arg, *args):
    args = list(args)
    while args:
        f = args.pop(0)
        n = len(inspect.getargspec(f).args)
        p, args = args[:n], args[n:]
        f(*p)

master(mandatory_arg, f1, f2, 'a1', f3, 'a1', 'a2')

rawDescription: How do I write a function that looks like it takes a list of function names and variable arguments for each function_name

description: Write a function that looks like it takes a list of function names and variable arguments for each function_name


code:
df.groupby(["Group", "Size"]).size()
df.groupby(["Group", "Size"]).size().reset_index(name="Time")

rawDescription: Python: get a frequency count based on two columns (variables) in pandas dataframe


code:
# Use `with` to make sure the file is closed properly
with open('question.txt', 'r') as f:
    questions = json.load(f)

value = inputSomething('Enter Index number: ')
queried_index = int(value)

# Since `questions` is a list, why don't you just *index` it with the input value
if 0 <= queried_index < len(questions):
    question_dict = questions[queried_index]
    # Let `print` take care of the `\n` for you
    print(index, ') ', question_dict['question'])
    print('Correct:', question_dict['answer'])
    print('Incorrect:', question_dict['wrong1'])
    print('Incorrect:', question_dict['wrong2'])
    print('Incorrect:', question_dict['wrong3'])
else:
    print('No index exists')

rawDescription: For loop enumerate. Python

description: For loop enumerate. Python


code:
def fileSplit(name,progs):
    num_lines = sum(1 for line in open("{0}.txt".format(name)))
    extra=num_lines%progs #save the remainder length
    sizes=[num_lines / progs ] * progs
    sizes[-1]=sizes[-1]+extra #add remainder lines to the length for last file
    with open('{0}.txt'.format(name)) as f:
        for i,g in enumerate(sizes):
            with open('ip{0}_{1}'.format(name,(i+1)), 'w') as fout:
               #read g lines from f at a time and add them to your new fout
               fout.writelines([next(f) for x in xrange(g)])

rawDescription: python splitting text file by line reminders

description: Python splitting text file by line reminders


code:
class ChatFactory(Factory):

    def __init__(self):
        self.users = {} # maps user names to Chat instances

        def broadcast_msg():
            for name in self.users:
                self.users[name].sendLine("looping call send to users: {}".format(self.users.keys()))

        self.looping_call = task.LoopingCall(broadcast_msg)
        self.looping_call.start(60)

rawDescription: Twisted Send Data to all Clients from Outside the Factory sessions with task Looping Call


rawDescription: Regex to extract names based on patterns in values from a list of name value pairs


code:
import wx

class PanelOne(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent)
        self.state = [('White', 'Turn ON'), ('Red', 'Turn OFF')]
        self.button = wx.Button(self, label=self.state[0][1], pos=(160, 130))
        self.button.Bind(wx.EVT_BUTTON, self.switch_state)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

    def OnPaint(self, evt):
        dc = wx.PaintDC(self)
        dc.Clear()
        dc.SetBrush(wx.Brush(self.state[0][0]))
        dc.DrawCircle(200, 230, 35)

    def switch_state(self, event):
        self.state.append(self.state.pop(0))
        self.button.SetLabel(label=self.state[0][1])
        self.Refresh()

class MainForm(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "LED")
        self.panel_one = PanelOne(self)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.panel_one, 1, wx.EXPAND)
        self.SetSizer(self.sizer)

if __name__ == "__main__":
    app = wx.App(False)
    frame = MainForm()
    frame.Show()
    app.MainLoop()

rawDescription: wxpython: how to show and hide one shape with button

description: Wxpython: how to show and hide one shape with button


rawDescription: How to properly serialize a python bitarray?

description: Properly serialize a python bitarray


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

fig, ax = plt.subplots()

d1 = np.random.random(100)
d2 = np.random.random(1000)

ax_hist = ax.twinx() # Create the twin axis, only once

ax.plot(d1)
ax_hist.hist(d1)

ax.clear()
ax_hist.clear()

ax.plot(d2)
ax_hist.hist(d2)

rawDescription: matplotlib axes.clear() of twinx axes does not clear second y-axis label

description: Matplotlib axes.clear() of twinx axes does not clear second y-axis label


code: {{ quote|safe }}

rawDescription: How could I make tagged user in the comment a hyperlink to that user's home page? (Django)


rawDescription: Regular expression to get string

description: Regular expression to get string


code:
a = s.split()
a[a.index('code') + 2]

rawDescription: Match second number that follows a given pattern


code:
lengthDF['size'] = 'large'
lengthDF['size'][lengthDF.index < 10] = 'small'

rawDescription: Python Pandas create column based on value of index


code:
from rest_framework import serializers
from conjugations.models import Verb, Past

class PastSerializer(serializers.ModelSerializer):
    class Meta:
        model = Past
        fields = ('first_singular','second_singular','third_singular')

class VerbSerializer(serializers.ModelSerializer):
    past = PastSerializer()

    class Meta:
        model = Verb
        fields = ('verb','verbal_noun','verbal_adjective','past','present',
                'future','habitual_present','conditional','past_habitual',
                'past_subjunctive','present_subjunctive','imperative')

    def create(self, validated_data):
        past_data = validated_data.pop('past')
        verb = Verb.objects.create(**validated_data)
        Past.objects.create(verb=verb, **past_data)
        return verb

rawDescription: Django-Rest nested serialization OneToOne


code:
import numpy as np
import pylab as plt
import itertools

k = 20
X = np.linspace(0, 20, 500)
Y = np.zeros((k,X.size))

# Add some fake data
MU = np.random.random(k)
for n in xrange(k):
    Y[n] += np.exp(-(X-MU[n]*n)**2 / (1+n/3))
Y *= 50

# Add some outliers for show
Y += 2*np.random.random(Y.shape)

displace = Y.max()/4

# Add a cutoff
Y[Y<1.0] = None

face_colors = itertools.cycle(["#D3D820", "#C9CC54",
                               "#D7DA66", "#FDFE42"])

fig = plt.figure()
ax = fig.add_subplot(111, axisbg='black')
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

for n,y in enumerate(Y):
    # Vertically displace each plot
    y0 = np.ones(y.shape) * n * displace
    y1 = y + n*displace

    plt.fill_between(X, y0,y1,lw=1,
                     facecolor=face_colors.next(),
                     zorder=len(Y)-n)
plt.show()

rawDescription: frequency trail in matplotlib

description: Frequency trail in matplotlib


code:
for iframe in iframexx:
    response = urllib2.urlopen(iframe.attrs['src'])
    iframe_soup = BeautifulSoup(response)

rawDescription: python beautifulsoup iframe document html extract

description: Python beautifulsoup iframe document html extract


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

# Read data from file into variables
y, c, x1, x2 = np.loadtxt('data.txt', unpack=True)

# Map value to color
color_mapper = np.vectorize(lambda x: {0: 'red', 1: 'blue'}.get(x))

# Plot a line for every line of data in your file
plt.hlines(y, x1, x2, colors=color_mapper(c))

rawDescription: Create gantt Plot with python matplotlib