code:
sender = soup.find("td", text="SENDER:")
print(sender.find_next_sibling("td").get_text(strip=True))

rawDescription: Python Beautifulsoup4:

description: Python Beautifulsoup4:


code:
#!/usr/bin/env python3
import shlex
from io import TextIOWrapper
from subprocess import Popen, PIPE

output = []
with Popen(shlex.split("apt-get --quiet=0 download firefox"),
           stdout=PIPE, bufsize=1) as p:
    # recognize '\r' as newline but don't convert it to '\n'
    for line in TextIOWrapper(p.stdout, newline=''):
        print(line, end='', flush=True) # print to terminal
        output.append(line) # save for later
print(p.returncode)

rawDescription: Last unbuffered line can't be read

description: Last unbuffered line can't be read


code:
s = "detected dot knight track"

allowed = ({"t","d"},{"k","c"})
forbidden = {"s","z","n", "m"}

for word in s.split():
    letter_set = set(word)
    if all(letter_set & a for a in allowed) and letter_set - forbidden == letter_set:
        print(word)

rawDescription: regex: find all words with certain letters but not other

description: Regex: find all words with certain letters but not other


rawDescription: How do I check if a network is contained in another network in Python?

description: Check if a network is contained in another network in Python


code:
i1 = iter(['a', 'b', 'c'])
i2 = iter(['d', 'e'])
# Select the iterator to advance: `i2` if `x` == 1, `i1` otherwise
print([next(i2 if x else i1) for x in [0, 1, 0, 0, 1]]) # ['a', 'd', 'b', 'c', 'e']

rawDescription: Merge two or more lists with given order of merging


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

wait = WebDriverWait(driver, 10)
try:
    next_page_elem = self.browser.find_element_by_xpath("//a[text()='%d']" % pageno)

except noSuchElementException:
    break
print('page ', pageno)
next_page_elem.click()

# wait for the page to load
wait.until(
    EC.presence_of_element_located((By.XPATH, "//a[@class = 'on' and . = '%d']" % pageno))
)

rawDescription: How to wait a page is loaded in Python Selenium

description: Wait a page is loaded in Python Selenium


code:
cmds.rowColumnLayout( numberOfColumns = 5 )
with neat_indent():
    cmds.text( label="", width = 1 )
    cmds.text( label="Column 1", enable = False, width = 250 )
    cmds.text( label="", width = 1 )
    cmds.text( label="Column 2", enable = False, width = 250 )
    cmds.text( label="", width = 1 )

    cmds.text( label="" )

    cmds.rowColumnLayout( numberOfColumns = 4 )
    with neat_indent():
        cmds.text( label="   Input data:", align="left" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.textField( text = "Text here" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.setParent( ".." )

    cmds.text( label="" )
    cmds.rowColumnLayout( numberOfColumns = 4 )
    with neat_indent():
        cmds.rowColumnLayout( numberOfColumns = 5 )
        with neat_indent():
            cmds.radioButton( label = "Read file from path", width = 100 )
            cmds.text( label="" )
            cmds.button( label = "Browse" )
            cmds.text( label="" )
            cmds.button( label = "Validate" )
            cmds.setParent( ".." )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.setParent( ".." )
    cmds.setParent( ".." )

rawDescription: Is there a way to indent Python without affecting the code


code:
class ImageField(models.ImageField):

    def save_form_data(self, instance, data):
        if data is not None:
            file = getattr(instance, self.attname)
            if file != data:
                file.delete(save=False)
        super(ImageField, self).save_form_data(instance, data)

rawDescription: Django: how to automatically also delete file from storage when Clear Checkbox ticked?


code: hwnd = win32gui.GetForegroundWindow()

rawDescription: How do I get the URL of the active Google Chrome tab in Windows?

description: Get the URL of the active Google Chrome tab in Windows


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

x = np.linspace(0, 2*np.pi, 100)

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

ax.plot(x, np.sin(x))

ax.grid(True)
ax.set_xticklabels([])

plt.show()

rawDescription: Remove the x-axis ticks while keeping the grids (matplotlib)


rawDescription: What does Django Date filter mean by 'Naive'?


code: self.card = choice(self.rank) + choice(self.suit)

rawDescription: Python 2.7.x - trying to get the hang of OOP and classes


code:
def replace_char(word, replacewith=replacewith):
    for w in replacewith:
            word = word.replace(w,replacewith[w])
    return word

rawDescription: Replacing characters in a string and returning in python


rawDescription: Python's 2.7 socket.timeout behavior

description: Python's 2.7 socket.timeout behavior


code: indNZ

rawDescription: How to minimize chi squared for 3 linear fits

description: Minimize chi squared for 3 linear fits


rawDescription: difference between two dates python

description: Difference between two dates python


rawDescription: limit how much data is read with numpy.genfromtxt for matplotlib

description: Limit how much data is read with numpy.genfromtxt for matplotlib


code:
#Update the status with the filename
status_string = 'Status: Working on file: ' + str(filename)
status.set(status_string)
root.update_idletasks()

rawDescription: Python / Tkinter status bar not updating correctly


code: cities = db.ListProperty(db.Key)

rawDescription: How to model a one-to-many?

description: Model a one-to-many


code:
cat
meoooow
mouse

rawDescription: how to remove all non english characters and words using NLTK >

description: Remove all non english characters and words using NLTK >


rawDescription: finding streaks in pandas dataframe

description: Finding streaks in pandas dataframe


code:
desired_fig, desired_axes = plt.subplots(2)
dummy_fig, dummy_ax = plot_something(desired_fig, desired_axes[0]) # or desired_axes[1] depending on where you need to plot

rawDescription: Matplotlib: Copy one axes to another

description: Matplotlib: Copy one axes to another


code:
my_list_of_parm = ['I want this in',
                   yellow, 'yellow',
                   ' and this is ',
                   green, 'green']

rawDescription: python - create a dynamic list of parameter for a method

description: Python - create a dynamic list of parameter for a method


code:
import cv2
import numpy
img = cv2.imread("zebra.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA) #convert to 4-channel image
triangle = numpy.array([[300, 0], [399, 0], [399, 100]])
color = [255, 255, 255, 0] #white with zero alpha
cv2.fillConvexPoly(img, triangle, color)
cv2.imwrite("with_triangle.png", img) #save to PNG for transparency support

rawDescription: Removing the upper corner part of the image


code:
T3 = [[int(letter) for letter in x] for x in T1]
T3

rawDescription: Convert string to integer using map()

description: Convert string to integer using map()


rawDescription: "IndexError: string index out of range" with a Python Program


code:
from itertools import permutations

def non_repeating_permutations(seq):
    seen = set()
    for permutation in permutations(seq):
        hperm = hash(permutation)
        if hperm in seen:
            continue
        seen.add(hperm)
        yield permutation

rawDescription: How to generate permutations of a list without “moving” zeros. in Python

description: Generate permutations of a list without “moving” zeros. in Python


code:
monster_image = pyglet.image.load('./roar.png')
for i in range(100): # We'll create 100 test monsters
    self.blocks['monster'+str(i)] = pyglet.sprite.Sprite(imgage=monster_image, x=0, y=0, batch=main_batch, group=background)

rawDescription: Pyglet Image Rendering

description: Pyglet Image Rendering


rawDescription: Gathering every other string from list / line from file


code:
import struct

def u2s(v, width=32):
    fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
    return struct.unpack(fmt.lower(), struct.pack(fmt, v))[0]

def s2u(v, width=32):
    fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
    return struct.unpack(fmt, struct.pack(fmt.lower(), v))[0]

rawDescription: Sneaking unsigned values from Jython, through Java, to C and back again


code: sorted(m, key= lambda x: -y.get(x))

rawDescription: Python: Sorting list based on the values of dictionary


code:
while True:
    gap = 21 - sum(compCards)
    if gap > 0 and random.random() < (1 / (40 / float(gap))):
        compCards.append(random.choice(availableCards))
    else:
        break

rawDescription: Python Blackjack Game how to carry a variable in a while loop


code:
f = open("126logs.txt",'r')
IPs = [line.split()[3] for line in f if line.split()[3].startswith('192.168.')]

rawDescription: python working with files as they are written

description: Python working with files as they are written


code:
set1 = set(list1)
newlist = [key for key, value in dict_a.iteritems() if value.viewkeys() & set1]

rawDescription: Check if items in a list exist in dictionary


code:
class ModelName(models.Model):

    data = models.CharField()

    def save(self):
        """ Extension of parent save method """

        for name in ModelName._meta.get_all_field_names():
            field = getattr(name, ModelName, None)
            field = translate(field)

        super(ModelName, self).save()

rawDescription: Django translate data on model save

description: Django translate data on model save


code:
cache_key = 'view/{}'.format(url_for('this_view'))
cache.delete(cache_key)

rawDescription: control flask-cache'ing from a view

description: Control flask-cache'ing from a view


code: "letter~ stamp~ mail~"

rawDescription: python fuzzy text search

description: Python fuzzy text search


code: from functools import reduce

rawDescription: Is there a built-in product() in Python?

description: Is there a built-in product() in Python


code:
def __new__(cls, *args, **kwargs):
    obj = object.__new__(cls, *args, **kwargs)
    obj.__init__(*args, **kwargs)
    return obj

rawDescription: Ensuring __init__ is only called once when class instance is created by constructor or __new__


code: print([s["data-pages"] for s in soup.select("select.catalogPagination_dropdown") if s.has_attr("data-pages")])

rawDescription: python - web scraping - return attributes from inside a class

description: Python - web scraping - return attributes from inside a class


code: mse = np.sum(np.power((step_matrix - total_displacement), 2), axis=1).reshape(num_walkers,1)/num_steps

rawDescription: General Random Walk generator questions

description: General Random Walk generator questions


rawDescription: How to loop through a percentage investment?

description: Loop through a percentage investment


code: counts, binEdges=np.histogram(A, bins=nbins, weights=B)

rawDescription: Which elements of list go into which histogram bins?


rawDescription: Python urlparse urljoin

description: Python urlparse urljoin


code: lambda event, i=i: self.click_poligono(event,'%s' % i)

rawDescription: select a line and process its tags on mouse click (python tkinter)

description: Select a line and process its tags on mouse click (python tkinter)


code:
class Test(BaseHandler):
    @tornado.web.authenticated
    def post(self):
        user = self.get_secure_cookie("name_of_your_cookie")
        # the rest of the code...

rawDescription: WebService with Tornado.web and Authentication. Do you have Example?


code:
def Cake():
    print("The", get_noun(), "is a", get_noun())

def XistheNew():
    print(get_noun(), "is the new", get_noun())

def get_Sentence():
    num = random.randrange(1, 3)
    if num == 1:
        Cake()
    elif num == 2:
        XistheNew()

rawDescription: Using a loop to make a random sentence generator


rawDescription: Transpose of a Matrix

description: Transpose of a Matrix


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(range(10), color='red', lw=3, zorder=5000)
# Placing the text in figure coordinates
fig.text(0.5, 0.5, 'Test', color='white', fontsize=45,
        bbox={'facecolor':'black', 'pad':12})

plt.show()

rawDescription: How to put pylab.plot line over pylab.figtext?

description: Put pylab.plot line over pylab.figtext


rawDescription: In Python, how can I randomly chose an element of one list that's NOT in a second list?


code:
#views.py --note ignore file system it is a test output
def get_miniondetail(request, minion_id):

    detail = minion_id
    context = {'minion_detail': detail}

    html_string = '<html>' + detail + '</html>'

    f = open('test.html', 'w+')
    f.write(html_string)
    f.close()

    return HttpResponse(html_string, mimetype='text/plain')

rawDescription: Trying to post data to same page

description: Trying to post data to same page


rawDescription: Python: how to make a function visible throughout a program


code:
numRows = len(l)
numCols = len(l[0])

for i in range(numRows):
    for j in range(numCols):
        celula = l[i][j]

rawDescription: Sum of specific elements in a list, if they are consecutive (python)


rawDescription: Create dictionary from 2-D list

description: Create dictionary from 2-D list


rawDescription: Split based by a-z character in an alphanumeric string in python


code:
def f(x):
    return x**2

map(f, range(5))

rawDescription: Difference between map and dict

description: Difference between map and dict


code:
import numpy as np
arr=np.array([1, 2, 3, 4, 5])
(arr>2)&(arr<5)

rawDescription: How to get a boolean array from applying criteria to an array in Python?

description: Get a boolean array from applying criteria to an array in Python


code:
root = Tkinter.Tk()
...
changeImage()
root.mainloop()

rawDescription: Randomly displaying images with one window with Tkinter


code:
list_of_nonstrings = [1.83, some_object, 4, 'abc'] # given a list of mixed types

# construct new list of strings for join function
list_of_strings = [str(thing) for thing in list_of_nonstrings]

new_string = "".join(list_0f_strings) # join into new string, just like before

rawDescription: Python - Combine all items in a list into a string


code:
import scrapy
response = scrapy.Selector(text="""

 Name

 Age

 Description:

 Line 1

 Line 2

Line 3

""", type="html")
response.xpath("""//div/p[contains(., 'Description:')]
     /following-sibling::node()
        /descendant-or-self::text()""").extract()

rawDescription: Using Xpath in Scrapy to select any text below paragraph


code:
np.random.seed(1234)
df = pd.DataFrame(data=randint(-10, high=20, size=(len(idx),2)), index=idx)

rawDescription: Find row corresponding to timestamp in pandas DataFrame


code:
@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
    ...

rawDescription: Using python's mock patch.object to change the return value of a method called within another method


code: critics[int(i)] = sales_dict

rawDescription: re reading a csv file in python without loading it again

description: Re reading a csv file in python without loading it again


code:
import inspect
inspect.isfunction(add)

rawDescription: How to check the type of an object against the type "function"

description: Check the type of an object against the type "function"


rawDescription: Regex - Replacing a matching subgroup

description: Regex - Replacing a matching subgroup


code:
allmytext = """
(CLAUSE (NP Jack/NNP) (VP loved/VBD) (NP Peter/NNP))
(CLAUSE (NP Jack/NNP) (VP stayed/VBD) (NP in/IN London/NNP))
(CLAUSE (NP Tom/NNP) (VP is/VBZ) (NP in/IN Kolkata/NNP))
"""
wrapped = "(ROOT "+ allmytext + " )"  # Add a "root" node at the top
trees = nltk.Tree.fromstring(wrapped, read_leaf=lambda x: x.split("/")[0])
for tree in trees:
    print(tree.leaves())

rawDescription: How can I remove POS tags before slashes in nltk?

description: Remove POS tags before slashes in nltk


code:
def main():
    scores = []
    with open('scores.txt') as f:
        for line in f:
            scores.append(int(line.strip()))
    print(scores)

rawDescription: Removing \n from file being read by while loop


code:
def listFunc(lst):
    if len(lst) == 0: return ''      #no elements? empty string
    if len(lst) == 1: return lst[0]  #one element? no joining/separating to do, just give it back
    firstPart = lst[:-1]             #firstPart is now everything except the last element
    retFirst = ", ".join(firstPart)  #retFirst is now the first elements joined by a comma and a space.
    retSecond = ", and " + lst[-1]   #retSecond is now ", and [last element]"
    return retFirst + retSecond;

rawDescription: Is there a better way to accomplish this python excercise? (Beginner)


code:
match = re.search("(\d?\d?):(\d\d)", "12:30")
match.groups()
match = re.search("(\d?\d?):(\d\d)", ":30")
match.groups()
match = re.search("(\d?\d?):(\d\d)", "no time here... 1234")
print(match)

rawDescription: How do I extract numbers from a string into multiple variables?

description: Extract numbers from a string into multiple variables


rawDescription: Unable to scrape the text from a certain LI element


code:
visited = set()

def disableControls(control):
    visited.add(control)

    for childNumber in xrange(VisualTreeHelper.GetChildrenCount(control)):
        child = VisualTreeHelper.GetChild(control, childNumber)

        # save the old state
        if type(child) in [Button, ComboBox, CheckBox] and child.IsEnabled:
            child.IsEnabled = False
            self.disabledControls.add(child)
        elif type(child) == TextBox and not child.IsReadOnly:
            child.IsReadOnly = True
            self.disabledControls.add(child)
        elif child not in visited:
            disableControls(child)
disableControls(self.windowOwner)

rawDescription: Set style for certain controls within window from contained usercontrol


code:
df1
df1.index.names=['sex','name']
df2.index.name = 'name'

rawDescription: Joining/Merging two Pandas dataframes. Match the levels of one to the index of the other


code:
def OnOver(event):
   if len(ax.lines) > 1 :
      ax.lines[-1].remove()
      ax.lines[-1].remove()
   ax.axhline(event.ydata)
   ax.axvline(event.xdata)
   plt.draw()

rawDescription: How can I delete plot lines that are created with Mouse Over Event in Matplolib?

description: Delete plot lines that are created with Mouse Over Event in Matplolib


code:
if callable(value):
    value = value()

rawDescription: Python getattr() member or function?

description: Python getattr() member or function


code:
x = list()
x.append({'name':'bob', 'roll': 5}) # or x.append(dict())
x[0]['name'] = 'giul'
x[0]['roll'] = 4

rawDescription: How use structures with arrays in python


code:
class Doer: #Naturally, give it a real name based on it's purpose.
    def __init__(self):
        self.exit = False
        while not self.exit:
            option = raw_input("What would you like to do?")
            if option == "exit":
                self.exit()

    def exit(self):
        self.exit = True

rawDescription: How do you define a variable in one function and change it in another with the first function recognizing it

description: Define a variable in one function and change it in another with the first function recognizing it


code: line1, = ax[1].plot([],[], lw=2, color='green', label="green")

rawDescription: Dynamically change y limit

description: Dynamically change y limit


code:
@has_a_boy_child.expression
def has_a_boy_child(cls):
    return (
        select([
            case([(exists().where(and_(
                Child.parent_id == cls.id,
                Child.is_boy == True,
            )).correlate(cls), True)],
                else_=False,
            ).label("has_boys")
        ])
        .label("number_of_boy_children")
    )

rawDescription: How do I write a Hybrid Property that depends on a column in children relationship?

description: Write a Hybrid Property that depends on a column in children relationship


code:
import itertools
combinations = (''.join((first, second)) for first, second in itertools.product(a, b))
any('HelloWorld' == combination for combination in combinations)

rawDescription: If string equals item from list a, followed by item from list b


code:
code = fib.func_code.co_code
code
import opcode
op = code[0]
op
op = ord(op)
op
opcode.opname[op]

description: Python Compilation/Interpretation Process


rawDescription: Python : text replacemnt in two files using a keyword?


code:
from pprint import pprint
numbers = {1: 5.01, 11: 7.02, 21: 9.03, 31: 11.04, 41: 15.0, 51: 71.08, 61: 19.15}
numbers = {k: v for start, v in numbers.items() for k in range(start, start + 10)}
pprint(numbers)

rawDescription: Python - Assigning Multiple Keys for a Single Value


code:
df.update(df_view.apply(lambda x: x/2))
df

rawDescription: How to df.groupby(cols).apply(my_func) for some columns, while leave a few columns not tackled?

description: Df.groupby(cols).apply(my_func) for some columns, while leave a few columns not tackled


code:
rem_spaces = str.maketrans({' ':None})

from binascii import unhexlify

unhexlify(u.translate(rem_spaces))
Out[13]: b'\x01\xa02\x00\x00\x00\x00\xfe\x12o\x04'

rawDescription: Transform string in a list with elements separated on Python


code:
xCoords = [[]*n for x in xrange(n)]
yCoords = [[]*n for x in xrange(n)]
zCoords = [[]*n for x in xrange(n)]

rawDescription: Question about Arrays in Python and Perl?


rawDescription: Repeatedly execute python script over files in folder arranged in order of date


code:
import itertools

def minimum_letter_set(words, n):
    attempts = itertools.combinations(string.ascii_lowercase, n)
    return min(attempts, key=lambda attempt: ncont(words, attempt))

rawDescription: Is there a better algorithm for exercise 9.3 in 《Think Python: How to Think Like a Computer Scientist》


code: ignore_indices = { index for index in list1 if 0 < index < len(list2) }

rawDescription: Remove elements from a list according to indexes list efficiently


code:
def parse(filename):
    servicesset = set(services)
    with open(filename, 'r', encoding='koi8-r') as f:
        for log_line in f:
            words = set(log_line.split())
            servicesset -= words

    services[:] = list(servicesset)

rawDescription: More pythonic way to write this function


code:
def e_cf_expansion():
    yield 1
    k = 0
    while True:
        yield k
        k += 2
        yield 1
        yield 1

rawDescription: Code to Generate e one Digit at a Time

description: Code to Generate e one Digit at a Time


code:
class Getdata(models.Model):
    title = models.CharField(max_length=255)
    state = models.CharField(max_length=2, choices=STATE, default="0")
    name = models.ForeignKey(School)
    created_by = models.ForeignKey(profile)
    class Meta:
        unique_together = ["title", "state", "name"]

rawDescription: Django models avoid duplicates

description: Django models avoid duplicates


code:
[
    {"categoryName":"AAAS","categoryId":"63007512","categoryIdentifier":"670_1_A14_4","title":"AAAS"},
    {"categoryName":"ACCT","categoryId":"63007490","categoryIdentifier":"670_1_A14_5","title":"ACCT"},
    ...
]

rawDescription: Get all combinations from selenium drop down list without options or select tag


rawDescription: Add an object associating two existing objects


code:
course_details = CourseDetail.objects.filter(course__name='Django 101')
cc_attendance = CourseDetailAttendance.objects.filter(course_details__in=course_details).count()

rawDescription: Queryset across fours models

description: Queryset across fours models


code:
class Node(models.Model):
    title = models.CharField(max_length=200)
    text = models.TextField(max_length=max_post_length)
    created = models.DateField()
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    up_votes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='%(class)s_upvotes')
    down_votes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='%(class)s_downvotes')

    class Meta:
        abstract = True

    def __str__(self):
        return self.title

class Thread(Node):
    pass

class Comment(Node, MPTTModel):
    thread = models.ForeignKey(Thread)
    parent = TreeForeignKey('self', related_name='children', blank=True, null=True)
    vote_count = models.IntegerField(default=0)

    class MPTTMeta(Node.Meta):
        order_insertion_by = ['created']

rawDescription: How to check if some post was voted for by the current user in a list

description: Check if some post was voted for by the current user in a list


code:
from __future__ import division
from pyparsing import (Literal,CaselessLiteral,Word,Combine,Group,Optional,
                       ZeroOrMore,Forward,nums,alphas,oneOf)
import math
import operator

__author__='Paul McGuire'
__version__ = '$Revision: 0.0 $'
__date__ = '$Date: 2009-03-20 $'
__source__='''http://pyparsing.wikispaces.com/file/view/fourFn.py
http://pyparsing.wikispaces.com/message/view/home/15549426
'''
__note__='''
All I've done is rewrap Paul McGuire's fourFn.py as a class, so I can use it
more easily in other places.
'''

class NumericStringParser(object):
    '''
    Most of this code comes from the fourFn.py pyparsing example

    '''
    def pushFirst(self, strg, loc, toks ):
        self.exprStack.append( toks[0] )
    def pushUMinus(self, strg, loc, toks ):
        if toks and toks[0]=='-':
            self.exprStack.append( 'unary -' )
    def __init__(self):
        """
        expop   :: '^'
        multop  :: '*' | '/'
        addop   :: '+' | '-'
        integer :: ['+' | '-'] '0'..'9'+
        atom    :: PI | E | real | fn '(' expr ')' | '(' expr ')'
        factor  :: atom [ expop factor ]*
        term    :: factor [ multop factor ]*
        expr    :: term [ addop term ]*
        """
        point = Literal( "." )
        e     = CaselessLiteral( "E" )
        fnumber = Combine( Word( "+-"+nums, nums ) +
                           Optional( point + Optional( Word( nums ) ) ) +
                           Optional( e + Word( "+-"+nums, nums ) ) )
        ident = Word(alphas, alphas+nums+"_$")
        plus  = Literal( "+" )
        minus = Literal( "-" )
        mult  = Literal( "*" )
        div   = Literal( "/" )
        lpar  = Literal( "(" ).suppress()
        rpar  = Literal( ")" ).suppress()
        addop  = plus | minus
        multop = mult | div
        expop = Literal( "^" )
        pi    = CaselessLiteral( "PI" )
        expr = Forward()
        atom = ((Optional(oneOf("- +")) +
                 (pi|e|fnumber|ident+lpar+expr+rpar).setParseAction(self.pushFirst))
                | Optional(oneOf("- +")) + Group(lpar+expr+rpar)
                ).setParseAction(self.pushUMinus)
        # by defining exponentiation as "atom [ ^ factor ]..." instead of
        # "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right
        # that is, 2^3^2 = 2^(3^2), not (2^3)^2.
        factor = Forward()
        factor << atom + ZeroOrMore( ( expop + factor ).setParseAction( self.pushFirst ) )
        term = factor + ZeroOrMore( ( multop + factor ).setParseAction( self.pushFirst ) )
        expr << term + ZeroOrMore( ( addop + term ).setParseAction( self.pushFirst ) )
        # addop_term = ( addop + term ).setParseAction( self.pushFirst )
        # general_term = term + ZeroOrMore( addop_term ) | OneOrMore( addop_term)
        # expr <<  general_term
        self.bnf = expr
        # map operator symbols to corresponding arithmetic operations
        epsilon = 1e-12
        self.opn = { "+" : operator.add,
                "-" : operator.sub,
                "*" : operator.mul,
                "/" : operator.truediv,
                "^" : operator.pow }
        self.fn  = { "sin" : math.sin,
                "cos" : math.cos,
                "tan" : math.tan,
                "abs" : abs,
                "trunc" : lambda a: int(a),
                "round" : round,
                "sgn" : lambda a: abs(a)>epsilon and cmp(a,0) or 0}
    def evaluateStack(self, s ):
        op = s.pop()
        if op == 'unary -':
            return -self.evaluateStack( s )
        if op in "+-*/^":
            op2 = self.evaluateStack( s )
            op1 = self.evaluateStack( s )
            return self.opn[op]( op1, op2 )
        elif op == "PI":
            return math.pi # 3.1415926535
        elif op == "E":
            return math.e  # 2.718281828
        elif op in self.fn:
            return self.fn[op]( self.evaluateStack( s ) )
        elif op[0].isalpha():
            return 0
        else:
            return float( op )
    def eval(self,num_string,parseAll=True):
        self.exprStack=[]
        results=self.bnf.parseString(num_string,parseAll)
        val=self.evaluateStack( self.exprStack[:] )
        return val

rawDescription: Evaluating a mathematical expression in a string


code:
import pprint
pprint.pprint(jdata)

rawDescription: Decoding JSON with Python and storing nested object


code: 'two quotes: \'\"'

rawDescription: double quotes in string representation

description: Double quotes in string representation


code:
import os
def abspath(file):
    return os.path.join(os.path.dirname(__file__), file).replace('\\','/')

rawDescription: Any potential gotchas or things to be aware of for a newcomer to Django?


rawDescription: Ajax Autocomplete for Jquery : OnSelect Function redirect to url


code: wclf = svm.SVC(kernel='linear', class_weight={1: 10})

rawDescription: class_weigths in claserization in lib scikit, python

description: Class_weigths in claserization in lib scikit, python


code:
from splinter import Browser

with Browser() as b:
    b.visit('http://example.com/')
    image_url = b.find_by_css('img.my_image_class')['src']

rawDescription: how to grab a web image which has a dynamic src ID in python

description: Grab a web image which has a dynamic src ID in python


code:
outerdict = {}
outerdict[name] = {type_: [v1, v2, v3]}

rawDescription: Python idiom for creating dict of dict of list


rawDescription: How to copy a matrix to a larger matrix in Python?

description: Copy a matrix to a larger matrix in Python


rawDescription: Find out indices of an array elements

description: Find out indices of an array elements


code:
dfs={ i : pd.DataFrame.from_csv('file'+str(i)+'.csv',sep=',',\
header=None,index_col=None) for i in range(n)} # n files.
panel=pd.Panel(dfs)
dfs_sum=panel.sum(axis=0)

rawDescription: Sum data from multiple csv files using pandas


code:
a = np.array([1, 2, 6, 4, 2, 3, 2])
sort_idx = np.argsort(a)
a_sorted = a[idx]
unq_first = np.concatenate(([True], a_sorted[1:] != a_sorted[:-1]))
unq_items = a_sorted[unq_first]
unq_count = np.diff(np.nonzero(unq_first)[0])

rawDescription: Grouping indices of unique elements in numpy


code:
import numpy as np

x = np.linspace(0, 1, 20)
y = np.linspace(0, 1, 20)
X, Y = np.meshgrid(x, y, copy=False)
Z = X**2 + Y**2 + np.random.rand(*X.shape)*0.01

X = X.flatten()
Y = Y.flatten()

A = np.array([X*0+1, X, Y, X**2, X**2*Y, X**2*Y**2, Y**2, X*Y**2, X*Y]).T
B = Z.flatten()

coeff, r, rank, s = np.linalg.lstsq(A, B)

rawDescription: Equivalent of `polyfit` for a 2D polynomial in Python


rawDescription: put installed app model in selected database

description: Put installed app model in selected database


code:
numpy.where(M == 0)
row, col = numpy.where(M == 0)
M[row, col]
M[numpy.where(M == 0)] = 1000
M

rawDescription: How to get a value from every column in a Numpy matrix

description: Get a value from every column in a Numpy matrix


code:
# get current cursor position
curr_y, curr_x = window.getyx()

# save position for later use
start_y = curr_y; start_x = curr_x

# loop until 'v' is pressed again
while highlight_state:
    # change the attribute of the current character, for 1 character only, to reverse
    window.chgat(curr_y,curr_x, 1, curses.A_REVERSE)
    curr_y, curr_x = get_next_direction()

# save end state, this is buggy obviously, but you get the point
end_y = curr_y; end_x = curr_X

rawDescription: Highlighting and Selecting text with Python curses


code:
alphabetical_names = get_scores('Test Scores Class1.txt')
highest_averages = sorted(alphabetical_names, key=lambda data: sum(data[1])/float(len(data[1])), reverse=True)
highest_scores = sorted(alphabetical_names, key=lambda data: max(data[1]), reverse=True)

rawDescription: How do I order a file of scores in Python?

description: Order a file of scores in Python


code:
def unique_with_order(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if x not in seen and not seen_add(x)]

def ordered_op(*sequences):
    return product(*map(unique_with_order, zip(*sequences)))

rawDescription: all combinations of differences of two lists

description: All combinations of differences of two lists


rawDescription: seaborn FacetGrid , ranked barplot separated on row and col

description: Seaborn FacetGrid , ranked barplot separated on row and col


code:
l4 = [', '.join(str(s) for s in l) for l in l4]
l4

rawDescription: Calculate range between list elements (int/str)


code:
for x in range(dimX):
    data[x] = [np.frombuffer(stream.readBytes(8*dimZ), dtype=np.dtype('complex64')) for y in range(dimY)]

rawDescription: Python: unpacking string of floats to complex numbers


code:
import re

str_ = '  d     A7    g7'

for m in re.finditer(r'\S+', str_):
    index, item = m.start(), m.group()
    # now do something with index, item

rawDescription: Python: split string and get position

description: Python: split string and get position


code: ['%3d' % getPentagonalNumber(n) for n in range(1, 1 +10)]

rawDescription: Printing multiple strings on same line in a loop


code:
for i, val in enumerate(gen()):
    if i > N: break

rawDescription: opposite of itertools.dropwhile (how to stop generators after N iteration)

description: Opposite of itertools.dropwhile (how to stop generators after N iteration)


code:
dudes = []
for dude in soup.find_all('div', 'well well-small'):
    dude_info = {}
    dude_info['Name'] = dude.parent['id']
    dude_info['Age'] = dude.find('div', 'age meta').contents[1]
    dude_info['Race'] = dude.find('div', 'race meta').contents[1]
    dude_info['Cause'] = dude.find('div', 'cause meta').contents[1]
    dude_info['Neighborhood'] = dude.find('div', 'neighborhood meta').contents[1]
    dude_info['Time'] = dude.find('div', 'time meta').contents[-1].next_element

    dudes.append(dude_info)

rawDescription: Trying to retrieve data from a template in a website using urllib2 and BeautifulSoup


rawDescription: How to loop through subfolders showing jpg in Tkinter?

description: Loop through subfolders showing jpg in Tkinter


code:
F = Deferred(A,B) >> C >> D >> E
F = Deferred(A,B,C) >> D >> E
F = Deferred(A,B,C,D) >> E
F = Deferred(A,B,C,D,E)

rawDescription: Python operator overloading and operator associativity


code:
mylist = list(graph.degree().values())

unique_elements_list = list()

# iterates all elements in mylist
for element in mylist:
    # adds to unique elements list only current
    # element is not included.
    if element not in unique_elements_list:
        unique_elements_list.append(element)

rawDescription: Python get degrees within nodes

description: Python get degrees within nodes


code: dep_list = [opcodes[i] for i,dest in enumerate(dests) for src in srcs if dest in src]

rawDescription: Python: Script to detect data Hazards

description: Python: Script to detect data Hazards


code:
def register(myMethod,t):
    pqueue.add(myMethod,time_now+t)

def tick():
    clock.tick()
    if(time_now > pqueue[0]):
        pqueue.pop()[0]()

rawDescription: How would I set a timer with Pygame and Livewires?


code:
import re
from bs4 import BeautifulSoup
from opengraph import OpenGraph

def parser(self, html):
    """
    """
    if not isinstance(html,BeautifulSoup):
        doc = BeautifulSoup(html, from_encoding='utf-8')
    else:
        doc = html
    ogs = doc.html.head.findAll(property=re.compile(r'^og'))
    for og in ogs:
        self[og[u'property'][3:]]=og[u'content']

    # Couldn't fetch all attrs from og tags, try scraping body
    if not self.is_valid() and self.scrape:
        for attr in self.required_attrs:
            if not hasattr(self, attr):
                try:
                    self[attr] = getattr(self, 'scrape_%s' % attr)(doc)
                except AttributeError:
                    pass

OpenGraph.parser = parser
OpenGraph.scrape = True   # workaround for some subtle bug in opengraph

rawDescription: Fetching the first image from a website that belongs to the post


code:
from twisted.python.reflect import namedAny
namedAny(fullyQualifiedName(namedAny)) is namedAny

rawDescription: Send method to subprocess

description: Send method to subprocess


code:
import rpy2.robjects as ro

output = ro.r['write.table'](x=xmldf, file=save_path, sep=",", row_names=False)

rawDescription: How to export DataFrame to csv without index using rpy2?

description: Export DataFrame to csv without index using rpy2


rawDescription: New to Python, replacing characters in a string


code:
import shlex

include_words, exclude_words = [], []
for word in shlex.split('+world -tigers "how are" -"bye bye"'):
    (exclude_words if word.startswith('-') else include_words).append(word.lstrip('-+'))

print(include_words, exclude_words)
# -> (['world', 'how are'], ['tigers', 'bye bye'])

rawDescription: Python text search library

description: Python text search library


code:
from string import Template, uppercase, _multimap
import collections

rawDescription: Python String Templating with Case Sensitivity


code:
i = 0
while i < 7:
    if someCondition(i):
        i = 5
    i += 1

rawDescription: How do I use a C-style for loop in Python?

description: Use a C-style for loop in Python


code:
class MyClass:
    def my_func(self):
        pass
my_obj = MyClass()

rawDescription: Inheritance. (A function calling something in a class)


code: current_salary *= 1 + amount_of_raise

rawDescription: Should I do anything to make my code more pythonic?


code:
from operator import itemgetter

{k: max(v, key=itemgetter(-1)) for k, v in somedic.iteritems()}

rawDescription: Finding the max value of list in dictionary


code:
def loop(start, eind, step, ei):
    for a in range (start, eind, step):
        for b in range(a):
            yield " "
        for c in range(ei+1, a, -1):
            yield a
        for d in range(a, ei):
            yield a
        yield '\n'
def main():
    print("Welcome!  :) ")
    y = 5
    for x in loop(y,0,-1,y):
        print(x,end="")
    for x in loop(2,y+1,1,y):
        print(x,end="")
main()

rawDescription: Returning in for loops python

description: Returning in for loops python


code:
from collections import defaultdict
import csv

def test_results(filename):
    with open(filename, "rU") as f:
        reader = csv.reader(f, delimiter="\t")
        result = defaultdict(list)
        # Skip header row
        next(reader)
        for row in reader:
            result[row[0]].append(row[1:])

rawDescription: Appending input from csv file to a dictionary including duplicate values for a unique key


code:
# based on info from http://stackoverflow.com/questions/1057431/loading-all-modules-in-a-folder-in-python
# more info in my own question: http://stackoverflow.com/questions/24718759/how-do-i-dynamically-reload-a-module-in-a-custom-package
import os
import sys
import imp

# based off of https://github.com/myano/jenni/blob/master/modules/reload.py#L40
def reload(moduleName):
    name = '{0}.{1}'.format(os.path.dirname(__file__).split('/')[-1:][0], moduleName)
    if name in sys.modules.keys():
        filePath = sys.modules[name].__file__
        if filePath.endswith('.pyc') or filePath.endswith('.pyo'):
            filePath = filePath[:-1]
        module = imp.load_source(name, filePath)
        sys.modules[name] = module
    else:
        pass

for module in os.listdir(os.path.dirname(__file__)):
    if module[0:8] != '__init__' and module[-3:] == '.py':
        name = '{0}.{1}'.format(os.path.dirname(__file__).split('/')[-1:][0], module[:-3])
        __import__(module[:-3], locals(), globals())

rawDescription: How do I dynamically reload a module in a custom package?

description: Dynamically reload a module in a custom package


rawDescription: 2D binary list python

description: 2D binary list python


code:
with open('letter.txt') as l:
    for lines in l:
        if not lines.startswith("WOOF"):
            with open('fixed.txt', 'a') as f:
                print(lines.strip(), file=f)

rawDescription: writing specific lines from one file to another file

description: Writing specific lines from one file to another file


code:
class bob:
    def __init__(self, n):
        self.n=n
        self.i=0

bob1=bob(2)

print(id(i))
print(id(bob1.i))
bob1.i += 1
print(id(bob1.i))
print(id(i))
print(id(1))
28426608
28426608
28426584
28426608

rawDescription: Instance attribute mutability (very basic)


code:
from distutils.core import setup

setup(
    name='tk',
    version='1.0',
    description='Graphics package that supplements native Tkinter',
    packages=['tk', 'tk.latex'],
)

rawDescription: Python Distutils Package Distribution

description: Python Distutils Package Distribution


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

def animate(frameno):
    x = mu + sigma * np.random.randn(10000)
    n, _ = np.histogram(x, bins, normed=True)
    for rect, h in zip(patches, n):
        rect.set_height(h)

mu, sigma = 100, 15
fig, ax = plt.subplots()
x = mu + sigma * np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)

ani = animation.FuncAnimation(fig, animate, blit=False, interval=10,
                              repeat=True)
plt.show()

rawDescription: How do I display real-time graphs in a simple UI for a python program?

description: Display real-time graphs in a simple UI for a python program


rawDescription: how do I make a list of tuples from a string?

description: Make a list of tuples from a string


rawDescription: Remove minimise and maximise Button

description: Remove minimise and maximise Button


code:
class AddCountryForm(forms.ModelForm):
     class Meta:
         model = Country
         fields ('name_of_team',)

def add_country(request):
    form = AddCountryForm(request.POST or None)
    if form.is_valid():
       obj = form.save(commit=False)
       obj.country = 'RUS'
       obj.save()
       return redirect('/thanks')
    return render(request, 'form.html', {'form': form})

rawDescription: How to limit the choice in django

description: Limit the choice in django


code:
def my_key_function(original_name):
    ## do something to extract the last name, for example:
    try:
        return original_name.split(',')[1].strip()
    except IndexError:
        return original_name

my_sorted_values = sorted(my_original_values, key=my_key_function)

rawDescription: Alphabetize a List of Multiline Values in Python?


code:
import ast
lst = ast.literal_eval(s)

rawDescription: What is the fastest way to convert string to array in python?


rawDescription: turn a number in an element of a string into a coefficient python

description: Turn a number in an element of a string into a coefficient python


code:
class Blog(SQLObject):
    class sqlmeta:
        table = 'blogtable'

    author = StringCol()
    keyword = StringCol()

Blog.select(Blog.q.keyword=='dust', distinct=True)

rawDescription: How to translate this to SQLObject: SELECT DISTINCT columnname WHERE

description: Translate this to SQLObject: SELECT DISTINCT columnname WHERE


rawDescription: How to precize that a pattern should start with a letter

description: Precize that a pattern should start with a letter


code:
times = []
timestamps = []
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
for t in timestmp:
    parsed_time = datetime.datetime.strptime(t, TIME_FORMAT)
    times.append(parsed_time)
    timestamps.append(time.mktime(parsed_time.timetuple()))

rawDescription: Fastest way to read comma separated files (including datetimes) in python


code:
url(r'^messstellen/monatlicher_verbrauch/(?P<pk>[0-9]+)/update/$',
    MonatlicherVerbrauchUpdateView.as_view()),

rawDescription: Sucess_url based on pk in GenericView from urls.py


code:
ddd2=list(dd2[1][0])
ddd2
ddd2[2]=(10,)    # change the list
ddd2

rawDescription: Best Way to Resize Numpy Dtype for Structured data


code:
mult_dict = {'lvl0': {0: {'lvl1': {0: {'lvl2': '123'},
                       1: {'lvl2': '456'}}},
          1: {'lvl1': {0: {'lvl2': '789'},
                       1: {'lvl2': '444'}}}}}
[v for lvl0 in mult_dict.itervalues()
   for lvl1 in lvl0.itervalues()
   for lvl2 in lvl1.itervalues()
   for lvl3 in lvl2.itervalues()
   for v in lvl3.itervalues()]
list(flatten_dicts(mult_dict))

rawDescription: extract multidimensional dictionary to list

description: Extract multidimensional dictionary to list


code: np.where(np.allclose(a, a.min()))

rawDescription: How to get array's col and row for specific values in python numpy?

description: Get array's col and row for specific values in python numpy


code:
from lxml import etree

etree.tostring(doc, pretty_print=True, standalone=False)

rawDescription: Use Python to edit XML header

description: Use Python to edit XML header


code:
list1 = ["1","10","3","22","23","4","2","200"]
# call int(x) on each element before comparing it
list1.sort(key=int)

rawDescription: Numeric Sort in Python

description: Numeric Sort in Python


code:
def displayFreeNodes(self, event):

    [...]

    index = self.notebook.GetPageCount() - 1 #get the index of the final page.
    self.notebook.SetSelection(index) #set the selection to the final page

rawDescription: wxpython: How to make a tab active once it is opened via an event handler?

description: Wxpython: How to make a tab active once it is opened via an event handler


rawDescription: Quickest way to make a get_dummies type dataframe from a column with a multiple of strings


code:
class BreakAllTheLoops(BaseException): pass
try:
   for i in range(1,100):
       for j in range(1,100):
           raise BreakAllTheLoops()
except BreakAllTheLoops:
    pass

rawDescription: break two for loops

description: Break two for loops


code:
import shelve
import functools

def _check_cache(cache_, key, func, args, kwargs):
    if key in cache_:
        print("Using cached results")
        return cache_[key]
    else:
        print("No cached results, calling function")
        result = func(*args, **kwargs)
        cache_[key] = result
        return result

def cache(filename):
    def decorating_function(user_function):
        def wrapper(*args, **kwds):
            args_key = str(hash(functools._make_key(args, kwds, typed=False)))
            func_key = '.'.join([user_function.__module__, user_function.__name__])
            key = func_key + args_key
            handle_name = "{}_handle".format(filename)
            if (hasattr(cache, handle_name) and
                not hasattr(getattr(cache, handle_name).dict, "closed")
               ):
                print("Using open handle")
                return _check_cache(getattr(cache, handle_name), key,
                                    user_function, args, kwds)
            else:
                print("Opening handle")
                with shelve.open(filename, writeback=True) as c:
                    setattr(cache, handle_name, c)  # Save a reference to the open handle
                    return _check_cache(c, key, user_function, args, kwds)

        return functools.update_wrapper(wrapper, user_function)
    return decorating_function

@cache(filename='cache')
def expensive_calculation():
    print('inside function')
    return

@cache(filename='cache')
def other_expensive_calculation():
    print('outside function')
    return expensive_calculation()

other_expensive_calculation()
print("Again")
other_expensive_calculation()

rawDescription: Can Python's shelve.open be called in a nested fashion?


code:
import re
X = ['abc(class_1)', 'cde_(class_1)', 'def_(class_2)']
just_classes = [re.findall(r'\((.*)\)', thing)[0] for thing in X]
# ['class_1', 'class_1', 'class_2']

rawDescription: Extract integers from strings

description: Extract integers from strings


code:
import vlc
i = vlc.Instance('--verbose 2'.split())
p = i.media_player_new()
p.set_mrl('rtp://@224.1.1.1')
p.play()

rawDescription: Stream record program VLC

description: Stream record program VLC


code: [(i, c[i]) for i in c if c[i]<(0.1*len(l))]

rawDescription: How do you tally the amount of times a item in appears from a randomly list?

description: Tally the amount of times a item in appears from a randomly list


code:
# Ensure b1 equals b2
print(b1 == b2)  # True

rawDescription: Python dynamic bit manipulation example

description: Python dynamic bit manipulation example


code:
import re, requests
from bs4 import BeautifulSoup

url = 'https://finance.yahoo.com/q/is?s=AAPL&annual'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
pattern = re.compile('Net Income')

title = soup.find('strong', text=pattern)
row = title.parent.parent # yes, yes, I know it's not the prettiest
cells = row.find_all('td')[1:] #exclude the <td> with 'Net Income'

values = [ c.text.strip() for c in cells ]

rawDescription: Scrape Yahoo Finance Income Statement with Python


code:
import time
import sys
toolbar_width = 40
numbers = [1,2,4,5,6,7,8,9,10]
for number in numbers:
    #print number

    for i in xrange(toolbar_width):
                time.sleep(0.1) # do real work here
                # update the bar
                sys.stdout.write("-")
                sys.stdout.flush()

    sys.stdout.write("\r")
    # ^^^^^^^^^^^^^^^^^^^^ <--- here!

rawDescription: progress bar is making new line, would like for it to reset to begining

description: Progress bar is making new line, would like for it to reset to begining


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

x = np.linspace(0, 10, 100)
y1 = 2 * np.cos(x)
y2 = 3 * np.sin(x)

xthresh = 2.0
diff = np.abs(y1 - y2)
below = diff < xthresh
above = diff >= xthresh

# Plot lines below threshold as dotted...
plt.plot(np.ma.masked_where(below, x), np.ma.masked_where(below, y1), 'b--')
plt.plot(np.ma.masked_where(below, x), np.ma.masked_where(below, y2), 'g--')

# Plot lines above threshold as solid...
plt.plot(np.ma.masked_where(above, x), np.ma.masked_where(above, y1), 'b-')
plt.plot(np.ma.masked_where(above, x), np.ma.masked_where(above, y2), 'g-')

plt.show()

rawDescription: Change matplotlib line style mid-graph

description: Change matplotlib line style mid-graph


code:
output
"This is a description"
"Info!"
""
"References:"
"book1, book 2, etc"
"blahblah.txt"

rawDescription: How to extract data from a file using python and output to another file

description: Extract data from a file using python and output to another file


code:
shape = list(x.shape)

# First, let's make the strides for an array with an itemsize of 1 in C-order
tmp_strides = shape[::-1]
tmp_strides[1:] = list(np.cumprod(tmp_strides[:-1]))
tmp_strides[0] = 1

# Now adjust it for the real itemsize:
tmp_strides = x.base.itemsize * np.array(tmp_strides)

# And convert it to a tuple, reversing it back for proper C-order
strides = tuple(tmp_strides[::-1])

rawDescription: How do I get the strides from a dtype in numpy?

description: Get the strides from a dtype in numpy


rawDescription: Matrix indexing in Numpy

description: Matrix indexing in Numpy


code:
import datetime
from Tkinter import * # from tkinter import *   # Python 3.x

root = Tk()
root.geometry('500x500')
frame = Frame(root)
frame.pack(side=BOTTOM, fill=BOTH)

entry = Entry(frame)
entry.pack(side=RIGHT)
entry.insert(END, datetime.datetime.now().strftime('%H:%M:%S'))
root.mainloop()

rawDescription: can we code time in text widget?

description: Can we code time in text widget


code:
with open('score.txt') as infile:
    readfile = sorted(infile)

print(readfile)

rawDescription: Python 3.4.3 - Sorting statistical list alphabetically


code:
from itertools import islice
'0.' + ''.join(str(digit) for digit in islice(infinite_divide(1, 7), 50))

rawDescription: python calculate decimal fraction part to arbitrary length

description: Python calculate decimal fraction part to arbitrary length


code:
import json
page = "http://www.zillow.com/search/GetResults.htm?spt=homes&status=110001&lt=001000&ht=111111&pr=,&mp=,&bd=2%2C&ba=0%2C&sf=,&lot=,&yr=,&pho=0&pets=0&parking=0&laundry=0&income-restricted=0&pnd=0&red=0&zso=0&days=any&ds=all&pmf=1&pf=1&zoom=3&rect=-134340820,16594081,-56469727,54952386&p=1&sort=globalrelevanceex&search=maplist&disp=1&listright=true&isMapSearch=true&zoom=3"
response = requests.get(page) # request the json file
json_response =  json.loads(response.text) # parse the json file
soup = Soup(json_response['list']['listHTML'], 'html.parser')

rawDescription: How to use BeautifulSoup Python to scrap a webpage url?

description: Use BeautifulSoup Python to scrap a webpage url


code:
# file <app folder>/management/commands/closepoll.py
from django.core.management.base import BaseCommand, CommandError
from example.polls.models import Poll

class Command(BaseCommand):
    args = '<poll_id poll_id ...>'
    help = 'Closes the specified poll for voting'

    def handle(self, *args, **options):
        for poll_id in args:
            try:
                poll = Poll.objects.get(pk=int(poll_id))
            except Poll.DoesNotExist:
                raise CommandError('Poll "%s" does not exist' % poll_id)

            poll.opened = False
            poll.save()

            self.stdout.write('Successfully closed poll "%s"\n' % poll_id)

rawDescription: Fire Django Signal's from the command line


code:
import numpy as np

while True:
    n2 = np.random.uniform(0.1, 1.5)
    c2 = np.random.uniform(4,14)
    c3 = np.random.uniform(0.1,2.9)
    ic4 = np.random.uniform(0.01,1)
    nc4 = np.random.uniform(0.01,1)
    ic5 = np.random.uniform(0,0.2)
    nc5 = np.random.uniform(0,0.01)

    if (n2/c2 <= 0.11 and
        c3/c2 <= 0.26 and
        ic4/c3 <= 0.27 and
        nc4/ic4 <= 1 and
        ic5/nc4 <= 0.06 and
        nc5/ic5 <= 0.25):

        comp_list = [n2, c2, c3, ic4, nc4, ic5, nc5]
        comp_list.append(100 - sum(comp_list))
        break

rawDescription: Generating a list of numbers based on a constraint-step procedure


code:
l = range(30)
list_range(15,10,l)
list_range(25,10,l) # I'm guessing the 35 in the example was accidental
list_range(-8,10,l)

rawDescription: Python, loop through list within a range


code: list(filter((2).__ne__, x))

rawDescription: Remove all occurrences of a value from a Python list


rawDescription: Adding elements in arrays that fall within a criteria in Python


code:
def nextpos(p,w=4,h=4):
    """
    @param p     Current position tuple (x,y)
    @param w     Width of matrix
    @param h     Height of matrix

    Generate all matrix cells adjacent to the current one
    """
    rel = ((-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1))

    x,y = p
    for dx,dy in rel:
        nx,ny = x+dx, y+dy
        if 0<=nx<w and 0<=ny<h:
            yield (nx,ny)

rawDescription: All possible combinations of numbers of length 5 in a 4X4 matrix


code:
import os
import os.path
import hashlib
import subprocess
from BeautifulSoup import BeautifulSoup

PHANTOM_DIR = os.path.join(os.getcwd(), 'phantom')

try:
    os.stat(PHANTOM_DIR)
except OSError:
    os.mkdir(PHANTOM_DIR)

PHANTOM_TEMPLATE = """var page = require('webpage').create();
page.open('%(url)s', function (status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var p = page.evaluate(function () {
            return document.getElementsByTagName('html')[0].innerHTML
        });
        console.log(p);
    }
    phantom.exit();
});"""

def get_executed_soup(url):
    """ Returns a BeautifulSoup object with the parsed HTML of the url
        passed, after executing all the scripts in it. """
    file_id = hashlib.md5(url).hexdigest()
    PHANTOM_ABS_PATH = os.path.join(PHANTOM_DIR, 'phantom%s.js' % file_id)
    OUTPUT_ABS_PATH = os.path.join(PHANTOM_DIR, 'output%s.html' % file_id)
    phantom = open(PHANTOM_ABS_PATH, 'w')
    phantom.write(PHANTOM_TEMPLATE % {'url': url})
    phantom.close()
    cmd = 'phantomjs ' + PHANTOM_ABS_PATH + ' > ' + OUTPUT_ABS_PATH
    stdout, stderr = subprocess.Popen(cmd, shell=True).communicate()
    output = open(OUTPUT_ABS_PATH, 'r')
    soup = BeautifulSoup(output.read())
    output.close()
    os.remove(PHANTOM_ABS_PATH)
    os.remove(OUTPUT_ABS_PATH)
    return soup

rawDescription: Obtain social networking information from HTML content


code:
from django.http import HttpResponseRedirect
from pygooglechart import PieChart3D

def pytest(request):
    chart = PieChart3D(250, 100)
    chart.add_data([20, 10])
    chart.set_pie_labels(['Hello', 'World'])
    return HttpResponseRedirect(chart.get_url())

rawDescription: How can I display a pygooglechart in a Django view?

description: Display a pygooglechart in a Django view


code:
class MySuperForm(CombinedForm):
    includes = (ImageForm, EntryForm, )

rawDescription: Django multiple form factory

description: Django multiple form factory


code:
import pandas
df = pandas.read_csv('data.csv')

rawDescription: Summing sections of a 2d array python

description: Summing sections of a 2d array python


code:
import builtins
def no_import(*args, **kwargs):
    raise ImportError("I cannot let you do that, Dave.")
builtins.__import__ = no_import
import os

rawDescription: Creating a simple scripting language in Python


code: file = open("Output.txt", "a")

rawDescription: How to read data from Excel and write it to text file line by line?

description: Read data from Excel and write it to text file line by line


code:
[0].extend(nx.algorithms.bfs_successors(G, 0).values())
# Get your first, node, and extend with a list of all successor nodes in BFS order

rawDescription: Using networkx bfs_tree to obtain a list of nodes of a directed graph in BFS order


code:
namesAndTreatments = {"Allocated":("Allocated", None),
                      "Bought":("Bought", boughtColClipper),
                      "Sold":("Bought", None),
                      "Remaining":("Remaining", None)}

col_prefix = "Base (MW) "
for newCol, (oldCol, treatment) in namesToAssign.iteritems():
    df[newCol] = baseMultiply(df, col_prefix + oldCol, preTreat=treatment)

rawDescription: Refactoring a bad 'code smell' in multiplication of columns in a dataframe


code:
from sklearn.feature_extraction import DictVectorizer
dv = DictVectorizer()
dv.fit_transform(flatten_ingredients(d) for d in RecipeData).toarray()
dv.feature_names_

rawDescription: Can sklearn's LabelBinarizer act similarly to DictVectorizer?


code:
@init_args_preprocessor
def flat(operands, kwargs): # No need for asterisks
    head = []
    for o in operands:
        if isinstance(o, cls):
            head += list(o.operands)
        else:
            head.append(o)
    return tuple(head), kwargs

rawDescription: Python: Modifying passed arguments before class instance initialization


code:
for ls in lst:
    ls.insert(2, "Null")

rawDescription: List comprehension expression showing none value insted of sublist


rawDescription: Convert a string into a list with integers including negative numbers


code:
tsg.SecurityGroupIngress = []
for i in mylist:
    tsg.SecurityGroupIngress.extend(mksg(i['cidr'], i['proto'], [i['port']]))

rawDescription: unexpected output while using list(and nested dictionary)

description: Unexpected output while using list(and nested dictionary)


rawDescription: Is there a way to place values onto a preset sentence and replace them if there is a repeated word?


code:
from email import utils
utils.parsedate_tz('Fri, 10 Jun 2011 11:04:17 +0200 (CEST)')
utils.parsedate_tz('Fri, 10 Jun 2011 11:04:17 +0200')
utils.parsedate_tz('Fri, 10 Jun 2011 11:04:17')

rawDescription: Best way to extract datetime from string in python

description: Extract datetime from string in python


code:
from inspect import getcallargs
from types import MethodType
from functools import wraps

class MethodBinder(object):
    def __init__(self, function):
        self.function = function

    def set_defaults(self, args, kwargs):
        kwargs = getcallargs(self.function, *args, **kwargs)
        # This is the self of the method we wish to call
        method_self = kwargs["self"]

        # First we build a list of the functions that are bound to self
        targets = set()
        for attr_name in dir(method_self):
            attr = getattr(method_self, attr_name)
            # For older python versions, replace __func__ with im_func
            if hasattr(attr, "__func__"):
                targets.add(attr.__func__)

        # Now we check whether any of the arguments are identical to the
        # functions we found above. If so, we bind them to self.
        ret = {}
        for kw, val in kwargs.items():
            if val in targets:
                ret[kw] = MethodType(val, method_self)
            else:
                ret[kw] = val

        return ret

rawDescription: Make a membermethod a default parameter

description: Make a membermethod a default parameter


code:
from datetime import datetime, timedelta, timezone
time_string = '1582-10-04T12:34:56.123Z'
timeformat = '%Y-%m-%dT%H:%M:%S.%fZ'
datetime.strptime(time_string, timeformat).replace(tzinfo=(timezone(timedelta(0))))

rawDescription: strptime, format and saving the milliseconds

description: Strptime, format and saving the milliseconds


code:
isinstance(b, Test1)
isinstance(b, Test2)
isinstance(a, Test1)
isinstance(a, Test2)
isinstance([], list)
isinstance({}, dict)

rawDescription: Determine the type of an object?

description: Determine the type of an object


code:
df['dif'] = a1.sub(h, fill_value=0)
g = df.groubpy('date')['dif'].sum()

rawDescription: zip(,) string to float?

description: Zip(,) string to float


rawDescription: Create New Columns in dataFrame using existing columns in Panda


rawDescription: Pandas DataFrame from dictionary with nested lists of dictionaries


code:
x = True
x = not x        # toggle
x
x = not x        # toggle
x
x = not x        # toggle
x

rawDescription: toggle a value in Python

description: Toggle a value in Python


code:
def set_if_not_there(d, fields, default_factory=None):
    if default_factory is None:
        default_factory = lambda: None
    for field in fields:
        if not field in d:
            d[field] = default_factory()

rawDescription: Problems with a shared mutable?

description: Problems with a shared mutable


code:
# Display Menu Bar
root.config(myMenu = menu_Bar)

rawDescription: Python quit unexpectedly

description: Python quit unexpectedly


code: hex_list = ("{:02x}".format(ord(c)) for c in fp.read())

rawDescription: Python: Read hex from file into list?

description: Python: Read hex from file into list


code:
while datetime.datetime.now() < end_time:
    pass # do work

rawDescription: Accessing datetime.now() values in Python


code:
s = boto.manage.cmdshell.SSHClient(hostname, uname='root')
s.run('uptime')

rawDescription: how to verify a reboot occurs?

description: Verify a reboot occurs


rawDescription: How to form a string from 2 values

description: Form a string from 2 values


code:
for model in seen_models:
    for field in model._meta.local_many_to_many:
        if not field.creates_table:
            continue

        table = field.m2m_db_table()
        columns = ['id'] # They always have an id column
        columns.append(field.m2m_column_name())
        columns.append(field.m2m_reverse_name())
        table_info.append((table, columns))

rawDescription: Django: How do I get every table and all of that table's columns in a project?


code: df

rawDescription: Groupby in pandas timeseries dataframe choosing most recent event


code: a = soup.findAll("a", href="whatever")

rawDescription: How do I parse out the following HTML in python beautifulsoup?

description: Parse out the following HTML in python beautifulsoup


code: anyValue in MyList([])

rawDescription: Exists a list where every item is a member?


code:
def matches(s):
    return s.count('.') >= 2

rawDescription: Recognizing valid IP addresses having 2 or 3 components


code:
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^general/$', views.general, name='general'),
]

rawDescription: How to link html files together using Django 1.9?

description: Link html files together using Django 1.9


code:
try:
    obj = Model.objects.get(field=value)
    obj.field = new_value
    obj.save()
except Model.DoesNotExist:
    obj = Model.objects.create(field=new_value)
# do something else with obj if need be

rawDescription: Django: Calling .update() on a single model instance retrieved by .get()?


rawDescription: How to assign values to individual elements of python igraph list attributes?

description: Assign values to individual elements of python igraph list attributes


code: df = pd.concat([df, newdf], axis=1)

rawDescription: Add a calculated result with multiple columns to Pandas DataFrame with MultiIndex columns


code:
import sqlite3

# connect to memory-only database for testing
con = sqlite3.connect('')
cur = con.cursor()

# create the table
cur.execute('''
CREATE TABLE CorpWalletJournal (
    date INT, refID INT, refTypeID INT, ownerName1 TEXT,
    ownerID1 INT, ownerName2 TEXT, ownerID2 INT, argName1 TEXT,
    argID1 ID, amount INT, balance INT, reason TEXT, accountKey INT,
    UNIQUE (ownerID1, ownerID2, accountKey, argID1)
);
''')
con.commit()

insert_sql = '''INSERT INTO CorpWalletJournal
(date, refID, refTypeID, ownerName1, ownerID1, ownerName2, ownerID2,
argName1, argID1, amount, balance, reason, accountKey)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'''

## create 5 rows changing only argID1 - it works:
for argid in xrange(5):
    cur.execute(insert_sql, (1, 1, 1, 'a', 1, 'a', 1, 'a', argid, 1, 1, 'a', 1))
con.commit()

# now try to insert a row that is already there:
cur.execute(insert_sql,  (1, 1, 1, 'a', 1, 'a', 1, 'a', 0, 1, 1, 'a', 1))

rawDescription: Multiple Unique Columns in SQLite

description: Multiple Unique Columns in SQLite


code:
names=[o.name for o in things[:-1]]
last_name = things[-1].name

rawDescription: Add 'and' before the last item in a string list


rawDescription: What is the new approach to get user profile in Django 1.6?


code:
deck = Deck()
deck.shuffle()
dealer_hand = []
player_hand = []
for _ in range(2): # number of rounds to deal
    for hand in (dealer_hand, player_hand): # hands to deal to
         deck.deal(hand)

rawDescription: Deck of cards, dealing alternately

description: Deck of cards, dealing alternately


rawDescription: Using Argparse and Json together

description: Using Argparse and Json together


code: divider = make_axes_locatable(ax2)

rawDescription: Set colorbar resized beside each subplots


rawDescription: Advanced string parsing in python

description: Advanced string parsing in python


rawDescription: Divide Every Other Line Between Two Files


code:
l = ['jj01','gg01',',','yy01','hh01',',','yy04','uu01']
joined = ':'.join(l)
separated = joined.split(':,:')
final = [x.split(':') for x in separated]

rawDescription: splitting comma separated list

description: Splitting comma separated list


code: [{"foo": item, "bar": grouper[item]} for item in grouper]

rawDescription: aggregating an array of objects by attribute

description: Aggregating an array of objects by attribute


code: matches = [ s for s in states if s in postal_addr ]

rawDescription: Python - match a word in a string with a list of strings


code:
coords = []
for element in elements:
    if element['type'] == 'node':
        coords.append((element['lat'], element['lon']))

rawDescription: How to access way coordinates from a large (.json-based) list structure

description: Access way coordinates from a large (.json-based) list structure


code:
colors = ['red', 'blue', 'green']  # Lists

for color in colors:  # For loops
    print(color)

person = {}  # Empty dictionary
person['name'] = 'Symmitchry'  # Add a key / value pair to a dictionary

if 'name' in person:  # Looking for a key in a dictionary
    print('Person has a name:')  # How to print
    print(person['name'])  # How to access a value from a dictionary
else:  # how to write an else statement
    print('Person has no name! Weird.')

import random  # importing a module
x = random.randint()  # Using a function from a module

rawDescription: Count occurrences of array in string

description: Count occurrences of array in string


code:
import pafy
import json

url = input()
video = pafy.new(url)

data = []

allstreams = video.allstreams
for s in allstreams:
    data.append({
        'mediatype': s.mediatype,
        'extension': s.extension,
        'quality': s.quality,
        'filesize': s.get_filesize(),
        'url': s.url
    })

result = json.dumps(data)
print(result)

rawDescription: How to connect node.js app with python script?

description: Connect node.js app with python script


code: ct = pd.crosstab(df.node, df.precedingWord)

rawDescription: Create advanced frequency table with Python


code:
def encode(inString):
    outString = ''
    for char in inString:
        outString += mapInToOut(char, alphabet, keyString)
    return(outString)

def decode(inString):
    outString = ''
    for char in inString:
        outString += mapInToOut(char, keyString, alphabet)
    return(outString)

rawDescription: Generalizing two similar functions into one


code:
outputlist = [] # Better position for outputList
for eqnSet in symEqns:
  for eqn in eqnSet:
    func = sp.lambdify(['R_0', 'R_1'], eqn, 'numpy')
    for row in inputArray:
        results = []
        results.append(func(*row))
    outputList.append(results)

rawDescription: Improving Performance - Symbolic function applied to each row of numpy array


code:
def validate_inp(fun):
    def wrapper(inp):
        return fun(inp) if inp else False
    return wrapper

@validate_inp
def func(inp):
    return int(inp['value']) + 1

print(func(False))
print(func({'value': 1}))

rawDescription: Looking for idiomatic way to evaluate to False if argument is False in Python 3


code:
('2016',
 '03',
 '13',
 'financial-times-china-rebuts-economy-doomsayers-on-debt-and')

rawDescription: compare url with a customized pattern in python

description: Compare url with a customized pattern in python


code:
from pylab import *
from numpy import outer
rc('text', usetex=False)
a=outer(arange(0,1,0.01),ones(10))
figure(figsize=(10,5))
subplots_adjust(top=0.8,bottom=0.05,left=0.01,right=0.99)
maps=[m for m in cm.datad if not m.endswith("_r") ]
maps.sort()
l=len(maps)+1
for i, m in enumerate(maps):
    subplot(1,l,i+1)
    axis("off")
    imshow(a,aspect='auto',cmap=get_cmap(m),origin="lower")
    title(m,rotation=90,fontsize=10)

rawDescription: pyplot.scatter: How does one set color of points from low --> high?

description: Pyplot.scatter: How does one set color of points from low --> high


code:
class RevisionSelectorWidget(QtGui.QComboBox):
    def __init__(self, parent = None):
        QtGui.QComboBox.__init__(self, parent)

        self.log_list = RevisionSelectorLogList(self)
        self.setView(self.log_list)
        self.log_list.installEventFilter(self)
        self.log_list.viewport().installEventFilter(self)

    def eventFilter(self, object, event):
        if event.type() == QtCore.QEvent.MouseButtonRelease:
            if self.log_list.colapse_expand_click:
                return True
        return False

rawDescription: Using PyQT, how do you filter mousePressEvent for a QComboBox with custom list


rawDescription: changing given text to list of lists

description: Changing given text to list of lists


code:
def replace_zeros_w_random_normal(DF,label, mu, sigma):
    truth_1 = DF[label] == 0
    random = np.random.normal(mu, sigma, DF.shape[0])
    filt = DF[DF[label] > 0]
    vector_1 = truth_1 * random
    truth_2 = vector_1 == 0
    vector_2 = truth_2 * DF[label]
    DF[label] = np.maximum(vector_1,vector_2)
    return DF

rawDescription: replace unique values in a pandas dataframe with random numbers

description: Replace unique values in a pandas dataframe with random numbers


code: df = df.reset_index()

rawDescription: Converting a dataframe in pandas to another one


code:
def listing(request,page):
    contact_list = Contacts.objects.all()
    paginator = Paginator(contact_list, 25) # Show 25 contacts per page

    # page = request.GET.get('page') not needed
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)

    return render_to_response('list.html', {"contacts": contacts})

rawDescription: How to make Django pagination search engine friendly?

description: Make Django pagination search engine friendly


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

def graph(formula, x_range):
    x = np.array(x_range)
    y = eval(formula)
    plt.plot(x, y, 'r--')   # `r--` for dashed red line
    plt.show()

graph('((x-3) * (x-2))', range(-3,3))  # <----

rawDescription: Graphs in python using matplotlib

description: Graphs in python using matplotlib


code:
import numpy as np
import pandas as pd

string = 'A B C D E F G H I J K L'

list1 = [char for char in string.split(' ') if char != '']
df = pd.DataFrame(np.reshape(list1,[3,4]))

rawDescription: Convert a string with whitespaces to a dataframe with desired dimensions in Python


code:
df
df.iloc[:, 0]
df.eq(df.iloc[:, 0], axis=0)

rawDescription: Pandas Dataframe Find Rows Where all Columns Equal


code:
ios = fbx.FbxIOSettings.Create(manager, fbx.IOSROOT)
manager.SetIOSettings(ios)

manager.GetIOSettings().SetBoolProp(fbx.EXP_FBX_SHAPE, False)
manager.GetIOSettings().SetBoolProp(fbx.EXP_FBX_GOBO, False)

exportstat = exporter.Initialize(save_path, -1, manager.GetIOSettings())

rawDescription: Convert *.obj to *.fbx with Python FBX SDK


code: self.c.after(1000, self.move_1, i) #note: no parentheses

rawDescription: self." ". after() does not work properly?

description: Self." ". after() does not work properly


rawDescription: Write to a FIFO from a Python program

description: Write to a FIFO from a Python program


code:
class A(object):
    def __new__(cls, *args, **kw):
        instance = super(A, cls).__new__(cls, *args, **kw)
        if hasattr(cls, '__init__'):
            instance.__init__(*args, **kw)
        return [instance]

rawDescription: (Python) __new__ method returning something other than class instance


code:
import itertools

lines = [[23, 52, 63, 76, 23, 45],
         [39, 52, 83, 33, 35, 23]]

# This set will store the unique elements
# across all lines
uniq = set()

# This list will hold a dict for each line
# These dicts will contain the frequency
# of each unique number in that line

freq = [{} for _ in range(len(lines))]
for index, line in enumerate(lines):
    for j in line:

        freq[index][j] = freq[index].get(j, 0) + 1
        uniq.add(j)

# This will store the frequency of each possible pair
counter = {}

# There will be k * (k - 1) / 2 combinations,
# where k is the number of unique pairs

for i in itertools.combinations(uniq, 2):
    for j in range(len(lines)):

        freq1 = freq[j].get(i[0], 0)
        freq2 = freq[j].get(i[1], 0)

        # Multiplying frequencies gives us the number
        # of pairs with these numbers in this line

        counter[i] = counter.get(i, 0) + (freq1 * freq2)

# Performs a descending sort on all pairs
sol = sorted(counter.items(), key=lambda value: value[1], reverse=True)
print(sol)

rawDescription: Finding the most common pair, trio, etc. in a list of 20 random numbers, played 100 times


code:
import itertools

in_ = 'ABC'
D = {'A':['aaa','aba','aac'],'B':['bbb','bab','bbc'],'C':['ccc','cac','ccb']}

iterables = [D[character] for character in in_]
out_ = [''.join(tup) for tup in itertools.product(*iterables)]

rawDescription: All possible combinations of dictionary values given input string. Python


code:
import random
random_generator = random.Random()
random_generator.random()
#>>> 0.9493959884174072

rawDescription: Generate multiple independent random streams in python


code:
from collections import OrderedDict

sam = {
  'food': 'tortas',
  'country': 'Mexico',
  'song': 'Dream On',
  }
dave = {
  'food': 'spaghetti',
  'country': 'USA',
  'song': 'Sweet Home Alabama',
  }
# The OrderedDict stores each person's name.
people = OrderedDict([('Sam', sam), ('Dave', dave)])

for name, data in people.items():
    # Name is a key in the OrderedDict.
    print('Name: ' + name)
    for key, value in sorted(data.items()):
        print('  {0}: {1}'.format(key.title(), value))

rawDescription: How do I work with a nested dictionary's name?

description: Work with a nested dictionary's name


code: [max(g, key=lambda x:x[-1]) for k, g in groupby(data, key= lambda x:x[:2])]

rawDescription: De-duplicating list of tuples, prefering certain ones


code:
for k_d1 in d1:
    if k_d1 in b1:
        d1[k_d1] = b1[k_d1]

rawDescription: Python: updating a large dictionary using another large dictionary


code: data

rawDescription: how to find avg of column of csv file

description: Find avg of column of csv file


code: x, y = map(list, zip(*sset))

rawDescription: How to get a list of Xth elements from a list of tuples?

description: Get a list of Xth elements from a list of tuples


code:
{'username': 'john', 'hostname': 'server1'}
{'username': 'jonny', 'hostname': 'server2'}
{'username': 'jules', 'hostname': 'server3'}

rawDescription: Remove Dictionary entries based on specific criteria in a List of Dictionaries


code:
with open('numbers2.csv', 'wt') as f:
    writer = csv.writer(f, lineterminator = '\n')
    writer.writerow(('Var1', "Var2", 'Var3', "Var4",))
    for value in exchangeDict2.itervalues():
        writer.writerow(value)

rawDescription: Unpacking list items from a dictionary & writing to a CSV file


rawDescription: Use .join() to manipulate inner dictionary elements of a nested dictionary


code:
import wx
import wx.lib.mixins.listctrl as listmix

class TestListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
    def __init__(self, *args, **kwargs):
        wx.ListCtrl.__init__(self, *args, **kwargs)
        listmix.ListCtrlAutoWidthMixin.__init__(self)

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel = wx.Panel(self)
        self.panel.SetBackgroundColour(wx.GREEN)

        self.list = TestListCtrl(self, style=wx.LC_REPORT, size=(200, -1))
        self.list.InsertColumn(0, 'Name')
        self.list.InsertColumn(1, 'Age')

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.list, proportion=0, flag=wx.EXPAND)
        self.sizer.Add(self.panel, proportion=1, flag=wx.EXPAND)

        self.SetSizerAndFit(self.sizer)
        self.SetSize((600, 400))
        self.Show()

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

rawDescription: Limit the size of wxListCtrl in wxpython


code:
import csv
import itertools

with open('extracted.txt', 'r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line for line in stripped if line)
    grouped = itertools.izip(*[lines] * 3)
    with open('extracted.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro', 'tagline'))
        writer.writerows(grouped)

rawDescription: Parse a plain text file into a CSV file using Python


code:
import wx

class MyForm(wx.Frame):
   def __init__(self):
        wx.Frame.__init__(self, None, size=(400,400))
        self.outer_panel = wx.Panel(self) # <--------------
        self.panel2=wx.Panel(parent=self.outer_panel,
                             size=(200,200),
                             pos=(200,0),
                             style=wx.BORDER)
        self.panel2.SetBackgroundColour(wx.RED)

app = wx.App(False)
MyForm().Show()
app.MainLoop()

rawDescription: Can't put the panel at the specified position on wxpython


code: a_counts = [x * y * 37000.0 for x, y in zip(co_60_activities, co_60_masses)]

rawDescription: Iterating through multiple arrays

description: Iterating through multiple arrays


code:
import sys

if hasattr(sys, 'frozen'):
    print(sys.executable)
else:
    print(sys.argv[0])

rawDescription: How to Get the Path of the executing frozen script


code:
import collections
counts = collections.defaultdict(lambda:collections.defaultdict(lambda:0))

rawDescription: Node frequency using networkx

description: Node frequency using networkx


code:
ranges = [(low, high), (low, high), ...]
cr = ConstrainedRandom(ranges, target)
seq = cr.next();
print(seq)
assert sum(seq)==target

seq = cr.next(); # get then get the next one.

rawDescription: Create constrained random numbers?

description: Create constrained random numbers


code:
f = open('1.txt')
f
next(f)
next(f)

rawDescription: What substitutes xreadlines() in Python 3?


rawDescription: Python converting lists into 2D numpy array


code:
user = User.objects.get(...)
user.following.all() # all users this user is following
user.followed_by.all() # all users who follow this user

rawDescription: django add relationships to user model

description: Django add relationships to user model


code:
from collections import defaultdict
d = defaultdict(int)
for dte, val in zip(dates, values):
    d[dte] += val

rawDescription: Python dictionary from two lists

description: Python dictionary from two lists


code:
class MainPage(webapp.RequestHandler):
  def get(self):
    session = self.request.environ['beaker.session']

    if 'counter' in session:
       counter = session['counter'] + 1
       session['counter'] = counter
    else:
       session['counter'] = 1

    self.response.out.write('counter: %d' % counter)

rawDescription: How to use beaker with GAE

description: Use beaker with GAE


code: week_matrix = [[i,j,0] for i in range(7) for j in range(n_day_cells)]

rawDescription: Replace for-loop across week with list comprehension


code:
adict = {'a':5, 'b':0, 'c':0}
init = [adict['a'],adict['b'],adict['c']]
time = np.linspace(0, 10, 101)
soln  = odeint(decay, init ,time)

rawDescription: using scipy.integrate.odeint with dictionary [Python]

description: Using scipy.integrate.odeint with dictionary [Python]


rawDescription: how to represent a number value as a string in python?

description: Represent a number value as a string in python


code:
for ii in xrange(1,size):
    lst_f.append( lambda x: np.dot(matA[ii], x) )

rawDescription: Why does a lambda function change its behavior from in the function that generates it to the main?


rawDescription: python port comtypes to win32com

description: Python port comtypes to win32com


code:
import cv2
import cv2.cv as cv

rawDescription: No highgui in python

description: No highgui in python


code:
@mock.patch.multiple('lib.mymodule', ClassA=mock.DEFAULT, ClassB=mock.DEFAULT, ClassC=mock.DEFAULT)
def TestHostRecordCreation(self):
    def test_A(self, MockClassA, MockClassB, MockClassC):
        f = MyClass("host", "user", "password")
        self.assertEqual(f, "bogus result")

    def test_B(self, MockClassA, MockClassB, MockClassC):
        f = MyClass("myhost", "myuser", "password")
        self.assertEqual(f, "other bogus result")

rawDescription: Good approach to mocking objects in Python?


rawDescription: Quickly append value to a list

description: Quickly append value to a list


code:
df["new"] = df.groupby("L1", as_index=False).apply(lambda x : pd.expanding_sum(x.sort("L3", ascending=False)["L3"])/x["L3"].sum())
df

rawDescription: New cumulative value col derived from existing col in a Pandas dataframe


code:
import json
import requests

response = requests.post('https://xxxxxxxx',
                         data=json.dumps({'name': 'something'}),
                         headers={'Content-Type': 'application/json'},
                         auth=('username', 'password'))
response_data = response.json()

rawDescription: using testrail api in python script

description: Using testrail api in python script


code:
char_functions = [
    (':', colon_function),
    ('eq', eq_function),
    ('lt', lt_function)
    # ...and so on...
]

def apply_function(particle):
    for char, function in char_functions:
        if char in particle:
            function()
            break # so successive functions are not run

rawDescription: Expressions in a dictionary mapping

description: Expressions in a dictionary mapping


rawDescription: python: id() of mutable object - explanation interesting pattern?

description: Python: id() of mutable object - explanation interesting pattern


rawDescription: how do i test subprocess's stdout, stderr in python on windows

description: Test subprocess's stdout, stderr in python on windows


code:
def parse_irc(line):
    src = None
    parts = line.split(' ')
    if parts[0][0] == ':':
        srcpart = parts.pop(0)[1:]
        src = {'ident': None, 'host': None}
        if '!' not in srcpart:
            # e.g. a message from a server
            src['nick'] = srcpart
        else:
            # nick!ident@host
            tmp = srcpart.split('!', 1)
            src['nick'] = tmp[0]
            src['ident'], src['host'] = tmp[1].split('@', 1)
    cmd = parts.pop(0)
    args = []
    for i, arg in enumerate(parts):
        if arg[0] == ':':
            args.append(' '.join(parts[i:])[1:])
            break
        args.append(arg)
    return src, cmd, args

rawDescription: modifying a string and sending a PM/query to a irc user

description: Modifying a string and sending a PM/query to a irc user


code: m * c[:, np.newaxis]

rawDescription: Multiplying across in a numpy array

description: Multiplying across in a numpy array


code:
class LoginWidget(FloatLayout):
    pass

rawDescription: Kivy GridLayout is At Bottom-Left and Looking Weird


rawDescription: Regular expression to match 3 capital letters followed by a small letter followed by 3 capital letters?


code: data['playerStatSummaries']

rawDescription: Python 3: Iterating over a dictionary

description: Python 3: Iterating over a dictionary


rawDescription: My walk animation in pygame isnt working


code:
#a.py
import sys
sys._getframe(1).f_globals['lol'] = 1

rawDescription: What are all the ways to add an object to the local scope in Python?


rawDescription: check that a list contains only elements from a given "permissible" list

description: Check that a list contains only elements from a given "permissible" list


code:
from itertools import izip
d = dict(izip(array_of_strings, array_of_samples))

rawDescription: convert two different arrays to a dictionary

description: Convert two different arrays to a dictionary


code: my_bytes = value.tobytes()

rawDescription: Convert string of 0s and 1s to byte in Python


code: result

rawDescription: Use Python/Pandas to Match Sample Pairs Yearly Data


code:
pfd = subprocess.Popen(['ls'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)

out, err_output = pfd.communicate()

rawDescription: detecting end of tty output

description: Detecting end of tty output


rawDescription: how to Pass variable in link to the django view


code:
c = np.einsum('i,j,k->ijk', a, a, b)
c.shape

rawDescription: Creating 3rd order tensors with python and numpy


code:
import test
test.pow2(3)   #only need to pass intent(in) parameters :-)

rawDescription: making python and fortran friends

description: Making python and fortran friends


code:
from PySide.QtGui import *
import sys
import types

class MainFrame(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        tree = {'root': {
                    "1": ["A", "B", "C"],
                    "2": {
                        "2-1": ["G", "H", "I"],
                        "2-2": ["J", "K", "L"]},
                    "3": ["D", "E", "F"]}
        }

        self.tree = QTreeView(self)
        layout = QHBoxLayout(self)
        layout.addWidget(self.tree)

        root_model = QStandardItemModel()
        self.tree.setModel(root_model)
        self._populateTree(tree, root_model.invisibleRootItem())

    def _populateTree(self, children, parent):
        for child in sorted(children):
            child_item = QStandardItem(child)
            parent.appendRow(child_item)
            if isinstance(children, types.DictType):
                self._populateTree(children[child], child_item)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MainFrame()
    main.show()
    sys.exit(app.exec_())

rawDescription: Multi-level QTreeView

description: Multi-level QTreeView


code:
def mergeleft(lst, fieldnums):
    fieldnums.reverse()
    for pos in fieldnums:
        # Merge this field left
        lst[pos-2] = str(lst[pos-2]) + str(lst[pos-1])
        lst = lst[:pos-1] + lst[pos:]

    return lst

print(mergeleft(fields,[2,4,5]))

rawDescription: Is there a better way to combine multiple items in a python list


rawDescription: Issue with using the chr() method to add \x to characters in a list


code:
['DEFAULT_CHUNK_SIZE', 'chunks', 'close', 'closed', 'encoding', 'file',
'fileno', 'flush', 'isatty', 'mode', 'multiple_chunks', 'name', 'newlines', 'open',
'read', 'readinto', 'readline', 'readlines', 'seek', 'size', 'softspace', 'tell',
'truncate', 'write', 'writelines', 'xreadlines']

rawDescription: django - How to insert the content of uploaded file in template?

description: Django - How to insert the content of uploaded file in template


code:
def make_counter():
    next_value = 0
    def return_next_value():
        nonlocal next_value
        val = next_value
        next_value += 1
        return val
    return return_next_value

my_first_counter = make_counter()
my_second_counter = make_counter()
print(my_first_counter())
print(my_second_counter())
print(my_first_counter())
print(my_second_counter())
print(my_first_counter())
print(my_second_counter())

rawDescription: Python Closures Example Code

description: Python Closures Example Code


code:
def carriage_return():
    sys.stdout.write('\r')
    sys.stdout.flush()

rawDescription: Problems refreshing stdout line using print with python


code:
for i in xrange(10):
    '{0:04}'.format(i)

rawDescription: how to loop from 0000 to 9999 and convert the number to the relative string?

description: Loop from 0000 to 9999 and convert the number to the relative string


code:
import string, random
def pick(num):
    for j in range(num):
        print("".join([random.choice(string.ascii_uppercase) for i in range(3)])+"-"+"".join([random.choice(string.digits) for i in range(3)]))

rawDescription: Generate two random strings with dash in between


code: df1.groupby('Location Code').apply(lambda x: pd.concat([x['Trait ID'].str.split(',', expand=True).stack(), x['Effective Date'].str.split(',', expand=True).stack()], axis=1)).reset_index([1, 2], drop=True)

rawDescription: Creating a single dataframe out of two columns each containing lists


code: print ('AAA' if True else 'BBB') + ('CCC' if True else 'DDD')

rawDescription: A issue of concatenating two strings with if...else statement


code:
pv = df.pivot_table( cols='name',
                     rows='date',
                     values='tag',
                     aggfunc=len ).shift( 1 ).fillna( 0 ).cumsum( )

rawDescription: Calculating previous chance figure for use in chi square test


code:
# Click a link that opens a new tab ...

# You'll see there's a new window handle!
print(driver.window_handles)

# Switch to the new window handle in the window_handles list
driver.switch_to.window(driver.window_handles[1])

# Switch back to the original window
driver.switch_to.window(driver.window_handles[0])

rawDescription: python selenium phantomJS new tab not working

description: Python selenium phantomJS new tab not working


code:
it = iter(map(str, bits))
[int("".join(sli), 2) for sli in zip(*iter([it] * 8))]

rawDescription: Python bit list to byte list

description: Python bit list to byte list


code:
import people
rootObject = people.parse('people.xml')

rawDescription: read XSD and create corresponding XML

description: Read XSD and create corresponding XML


rawDescription: Dynamically assign values - python

description: Dynamically assign values - python


rawDescription: Converting binary timestamp to string

description: Converting binary timestamp to string


code:
df.yyyymmdd = pd.to_datetime(df.yyyymmdd)
df.yyyymmdd = df.apply(lambda x: x.yyyymmdd + pd.DateOffset(hours = x.hr), axis=1)
df.set_index('yyyymmdd', inplace=True)
df = df.resample('H')

rawDescription: How to fill the indexs of dataframe & make the subplots?

description: Fill the indexs of dataframe & make the subplots


rawDescription: Python: Converting Unicode code point filenames to strings


code:
def clicked_(self, notification):
    self.menuItem.setTitle_("Clicked!")

rawDescription: NSMenuItem + Python + Dynamic Variables

description: NSMenuItem + Python + Dynamic Variables


code:
y = [(1, 2), (2, 3), (1, 2), (5, 6),(2, 1),(6,5)]
from collections import Counter

print(Counter(map(frozenset, y)))

rawDescription: Multiprocessing module for updating a shared dictionary in Python


code: str = type("")

rawDescription: Overloaded or rewritten str() function in Python


code:
def codons_pair(pairs, codonsA, codonsB):
    codonsB = set(codonsB)
    for codon in codonsA:
        complement = ''.join([pairs[base] for base in codon])
        if complement in codonsB:
            yield (codon, complement)

rawDescription: Using Dictionary to match codons

description: Using Dictionary to match codons


rawDescription: Python stdout logging: terminal vs bash file


code:
with open("outfile", "w") as outfile:
    for row in matrix:
        outfile.write(" ".join(map(str, row)) + "\n")

rawDescription: Python from matrix to simple text file

description: Python from matrix to simple text file


code:
import webapp2

form = '''

something

'''

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write(form)
    def post(self):
        self.response.write("RESPONSE")

app = webapp2.WSGIApplication([
    ('/', MainHandler),
], debug=True)

rawDescription: How to get jQuery and Python to send data back and forth in a GAE app

description: Get jQuery and Python to send data back and forth in a GAE app


code:
from itertools import permutations, repeat
a = [1, 2, 3]
b = [4, 5, 6]
list(list(zip(r, p)) for (r, p) in zip(repeat(a), permutations(b)))

rawDescription: Python merging two lists with all possible permutations


code: np.sum(L, axis=0)

rawDescription: Numpy - summing up a list of vectors

description: Numpy - summing up a list of vectors


code:
import numpy as np
from scipy.sparse import csr_matrix

x = np.arange(5)+1

y = [1, 0, 0, 1, 2]
y = csr_matrix(y)

x2 = 1.0 / np.matrix(x)

z = y.multiply(x2)

rawDescription: How to do operations with two vectors of different format in python

description: Do operations with two vectors of different format in python


code: [v for specie in spices for v in spices[specie].values()]

rawDescription: How to get a simple list from a list comprehension that returns a list of lists

description: Get a simple list from a list comprehension that returns a list of lists


code:
class myParent( object ):
    def customInit( self, customParam ):
        self.parentNumber = 5
        self.customParam = customParam

class Child( myParent ):
    def __init__( self, customParam ):
        self.childNumber = 4

p = Child()
p.customInit(10)
p.multiplyNumbers()

rawDescription: Python: Getting baseclass values from derived class


code:
from matplotlib import pyplot as PLT

with open('name_of_your_file.csv') as f:
  v = NP.loadtxt(f, delimiter=",", dtype='float', comments="#", skiprows=1, usecols=None)

rawDescription: Histogram in Matplotlib with input file

description: Histogram in Matplotlib with input file


code:
x = "spam"
z = {x: "eggs"}
z["spam"]

rawDescription: How do I do variable variables in Python?

description: Do variable variables in Python


code:
from collections import defaultdict
d = defaultdict(list)
d['1'].append('x')
d['1'].append('y')
d['1'].append('z')
d

rawDescription: python dictionary adding to an existing key

description: Python dictionary adding to an existing key


code: new_list = old_list[:]

rawDescription: Pythonic way to append multiple values to a list


code:
whitespace = u' \t\n\r\x0a'  # extend as needed

for p in soup.find_all('p'):
    for string in list(p.strings):  # copy so we can replace some
        left = string[:1] in whitespace
        right = string[-1:] in whitespace
        if not left and not right:
            continue  # leave be
        new = string
        if left:
            new = ' ' + new.lstrip()
        if right:
            new = new.rstrip() + ' '
        string.replace_with(new)

rawDescription: Remove empty spaces inside <p> tags using BeautifulSoup


code:
grouped.apply(lambda x: x.quantile(0.5))
grouped.agg(lambda x: x.quantile(0.5))

rawDescription: Pandas TimeGrouper: .median() behaves differently to .quantile(0.5)


code:
new_names = set(name.lower() for name in names)
[ t for t in target if any(map(new_names.__contains__,t.lower().split())) ]

rawDescription: What's a more efficient way of looping with regex?


code:
# Here's the original function
def foo():
  def bar():
    print("    In bar orig")
  def baz():
    print("  Calling bar from baz")
    bar()
  print("Foo calling bar:")
  bar()
  print("Foo calling baz:")
  baz()

# Here's using it
foo()

# Now lets override the bar function

import types

# This is our replacement function
def my_bar():
  print("   Woo hoo I'm the bar override")

# This creates a new code object used by our new foo function
# based on the old foo functions code object.
foocode = types.CodeType(
    foo.func_code.co_argcount,
    foo.func_code.co_nlocals,
    foo.func_code.co_stacksize,
    foo.func_code.co_flags,
    foo.func_code.co_code,
    # This tuple is a new version of foo.func_code.co_consts
    # NOTE: Don't get this wrong or you will crash python.
    (
       foo.func_code.co_consts[0],
       my_bar.func_code,
       foo.func_code.co_consts[2],
       foo.func_code.co_consts[3],
       foo.func_code.co_consts[4]
    ),
    foo.func_code.co_names,
    foo.func_code.co_varnames,
    foo.func_code.co_filename,
    foo.func_code.co_name,
    foo.func_code.co_firstlineno,
    foo.func_code.co_lnotab,
    foo.func_code.co_freevars,
    foo.func_code.co_cellvars )

# This is the new function we're replacing foo with
# using our new code.
foo = types.FunctionType( foocode , {})

# Now use it
foo()

rawDescription: Does an equivalent of override exist for nested functions?