code: tdic = dict((name, max(weeks) - min(weeks) + 1) for name, weeks in tdic.iteritems())

rawDescription: How can I create dictionary within dictionary

description: Create dictionary within dictionary


code:
def foldersLoad(self):
    folders = QtCore.QStringList()
    folders = self.tunSettings.value('musicfolders', None).toStringList()
    if folders.count():
        foldersnum = folders.count()
        for i in range(foldersnum):
            self.configDialog.FolderLIST.addItem(folders.takeFirst())

rawDescription: How to save and load QListWidjet contents to/from QSetting with PyQt4?

description: Save and load QListWidjet contents to/from QSetting with PyQt4


code:
import os
os.environ['PYTHONPATH'] = '/path/to/site-packages'

import nose
nose.run()

rawDescription: Running unit tests with Nose inside a Python environment such as Autodesk Maya?


code:
neg = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date < 0].sum()
pos = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date >= 0].sum()

In [51]: pos
Out[51]: 2.6268029999999998

In [52]: neg
Out[52]: -1.077127

rawDescription: Separating positive and negative values of pandas DataFrame


code:
from datetime import datetime, timedelta, date
import calendar
from random import random

def makeseries(startdate):
    datesA = [startdate] # collect the dates in this list
    valsA = [random()]   # and the randomly generated 'data' in this one
    date = startdate

    # add days
    step = timedelta(1)
    while date - startdate <= timedelta(91):
        date += step
        datesA += [date]
        valsA += [random()]

    # add months
    step = timedelta(30)
    while date - startdate <= timedelta(2*365):
        if date.month in [1,3,5,7,8,10,12]:
            date += timedelta(1)
        elif date.month == 2:
            date -= timedelta(2)
        date += step
        datesA += [date]
        valsA += [random()]

    # add quarters
    step = timedelta(91)
    while date - startdate <= timedelta(int(365*10)):
        date += step
        if date.year % 4 == 0:
            date += timedelta(1)
        datesA += [date]
        valsA += [random()]

    # add years
    step = timedelta(365)
    while date - startdate <= timedelta(int(365*50)):
        date += step
        if date.year % 4 == 0:
            date += timedelta(1)
        datesA += [date]
        valsA += [random()]

    return datesA, valsA

rawDescription: Linear interpolation on fixed dates using Python


code:
true_k = 4
vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(documents)
model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1)
model.fit(X)

rawDescription: Adding feature to k-means

description: Adding feature to k-means


code:
def create_space_buttons():
    while space_buttons: #same as while len(space_buttons)>0:
        space_buttons.pop().destroy() #remove existing buttons

    for txt,val in space:
        space_button=Radiobutton(root, text = txt, font=fnt, indicatoron=0, width=8, variable=v, command=ShowChoice,value=val)
        space_button.grid(row=8, column=val-1)
        #add it to the list of space buttons
        space_buttons.append(space_button)

rawDescription: disable buttons in Python and Tk

description: Disable buttons in Python and Tk


code: df['year_str'] = df['Date'].apply(lambda x: str(x)[-4:])

rawDescription: Python - Retrieve and replace based on a regex


code:
Region = ["Marrakech","London"]
Spider = 20

def trade_spider(max_pages):

    partner_ID = 2
    location_ID = 25
    already_printed = set()
    for reg in Region:
        page = -1
        while page <= max_pages:
            page += 1
            response = urllib.request.urlopen("http://www.jsox.com/s/search.json?q=" + str(reg) +"&page=" + str(page))
            jsondata = json.loads(response.read().decode("utf-8"))
            format = (jsondata['activities'])
            g_data = format.strip("'<>()[]\"` ").replace('\'', '\"')
            soup = BeautifulSoup(g_data)

            hallo = soup.find_all("article", {"class": "activity-card"})

            for item in hallo:
                headers = item.find_all("h3", {"class": "activity-card"})
                for header in headers:
                    header_final = header.text.strip()
                    if header_final not in already_printed:
                        already_printed.add(header_final)

                deeplinks = item.find_all("a", {"class": "activity"})
                for t in set(t.get("href") for t in deeplinks):
                    deeplink_final = t
                    if deeplink_final not in already_printed:
                        already_printed.add(deeplink_final)

                end_final = "Header: " + header_final + " | " + "Deeplink: " + deeplink_final
                print(end_final)
trade_spider(int(Spider))

rawDescription: How to Crawl Multiple pages/cities from a website (BeautifulSoup,Requests,Python3)


rawDescription: Indexing the unique rows of an array

description: Indexing the unique rows of an array


code: d = datetime(1970, 1, 1, tzinfo=utc) + timedelta(seconds=1440498131.372625)

rawDescription: fractions of seconds and pytz: do you have a cleaner solution?

description: Fractions of seconds and pytz: do you have a cleaner solution


code:
from numba import jit
@jit(nopython=True)
def xor(X,Y):
    result=np.zeros((4,4),np.uint64)
    for i in range(len(X)):
    # iterate through columns of Y
      for j in range(Y.shape[1]):
        # iterate through rows of Y
        for k in range(len(Y)):
            result[i,j] = result[i,j] ^ (X[i,k] * Y[k,j])
    return result

rawDescription: xor matrix multiplication for AES mix column stage

description: Xor matrix multiplication for AES mix column stage


code: namesGroup = re.findall(r'name="([^"]*)"', sourceCode, re.IGNORECASE)

rawDescription: Python re.findall

description: Python re.findall


code:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm

# data loading
df = pd.read_csv("file.csv", index_col=0)

# plotting
fig,ax = plt.subplots()
ax.matshow(df.mask(df.isin(df.att1)!=True), cmap=cm.Reds) # You can change the colormap here
ax.matshow(df.mask(df.isin(df.att2)!=True), cmap=cm.Greens)
ax.matshow(df.mask(df.isin(df.att3)!=True), cmap=cm.Blues)
plt.xticks(range(3), df.columns)
plt.yticks(range(4), df.index)
plt.show()

rawDescription: Plotting of 2D data : heatmap with different colormaps


code:
def concatenate(*lists):
    new_list = []
    for i in lists:
        new_list.extend(i)
    return new_list

rawDescription: concatenate an arbitrary number of lists in a function in Python

description: Concatenate an arbitrary number of lists in a function in Python


code:
import mechanize
mechanize.__file__

rawDescription: query about installing Python package

description: Query about installing Python package


code:
change = map(int, raw_input("What number do you want to change in the list? And what number should it be? Separate both numbers with a space ").split())
for indx, _ in enumerate(a):
    if change[0] == 2:
        a[indx] = change[1]

rawDescription: Manually replace elements in a list

description: Manually replace elements in a list


code:
import email
m = email.message_from_string(text)
m.get_all('to')
email.utils.getaddresses(m.get_all('to'))

rawDescription: Ignore strings which do not completely match regex?


code:
def _mapkey(self, key):
    return ','.join(map(str, key))
def _unmapkey(self, key):
    return tuple(map(int, key.split(',')))
def __getitem__(self, key):
    return self.shelf[self._mapkey(key)]
def __iter__(self):
    return map(self._unmapkey, self.shelf)
# etc.

rawDescription: Python dictionary with two keys with shelve


rawDescription: django return foreign key object from queryset?

description: Django return foreign key object from queryset


code:
def max_bits(b):
    return (2 ** b) - 1

rawDescription: calculate maximum value possible from a given number of bits

description: Calculate maximum value possible from a given number of bits


code: data = numpy.loadtxt(..., usecols=xrange(1, numcols, 2))

rawDescription: Numpy loadtxt load every other column

description: Numpy loadtxt load every other column


code:
class A(object):
    a = 'z'
    b = 'b'
    c = 'c'

    @property
    def all(self):
        return (self.a, self.b, self.c)

rawDescription: How can I set a variable within a class to include another variable and update when the other value changes?

description: Set a variable within a class to include another variable and update when the other value changes


code:
if 'cookie_name' in request.COOKIES:
    cookie_value = request.COOKIES['cookie_name']

rawDescription: Why I can not get cookies from requests.get


code:
df["value"] /= df.groupby("type")["value"].transform(sum)
df

rawDescription: normalize column in pandas dataframe based on value in another column

description: Normalize column in pandas dataframe based on value in another column


code:
txt='''\
Line 1
Line 2
Line 3
Line 4
Line 5 April'''

rawDescription: Regular expressions from a list previously specified


code:
i
j

rawDescription: How to extract a list of elements given by their indices from a numpy array efficiently?

description: Extract a list of elements given by their indices from a numpy array efficiently


code: print("hello!")

rawDescription: Create Python object from different .py file


rawDescription: Modifying diagonals in multidimensional numpy arrays


code: np.vstack((loaded_data, loaded_data)).T

rawDescription: What is the best way to reshape and/or slice this array to create the desired pairs of items using NumPy?


code:
def binary(n):
  if n < 2:
    return [n]
  else:
    return binary(n / 2) + [n % 2]

binary(0)
binary(1)
binary(3)
binary(9)
binary(10)

rawDescription: Recursive function that prints the binary representation of the integer


code: subprocess.Popen("/path/to/dd.py", arg)

rawDescription: How to link PyQt4 script button to activate another script?

description: Link PyQt4 script button to activate another script


code:
M = np.dot(X,A) + np.dot(W,B)[:,None] + np.dot(Zij, G)
M

rawDescription: Compute each element of matrix

description: Compute each element of matrix


code: soup.find_all(lambda e: e.name == 'td' and 'Black' in e.text)

rawDescription: Why does bs4 return tags and then an empty list to this find_all() method?


code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

from contextlib import contextmanager

@contextmanager
def wait_for_new_window(driver, timeout=10):
    handles_before = driver.window_handles
    yield
    WebDriverWait(driver, timeout).until(
        lambda driver: len(handles_before) != len(driver.window_handles))

driver = webdriver.Chrome()

driver.get("http://www.google.com")

with wait_for_new_window(driver):
    driver.execute_script("""
    window.open("http://www.google.com", "_blank");
    """)

with wait_for_new_window(driver, 2):
    pass # This will obviously hit the timeout.

driver.quit()

rawDescription: Python. Selenium. How to wait for new window opens?


code:
try:
    new_accountadmin_form.save()
except IntegrityError:
    new_accountadmin_form._errors["account"] = ["some message"]
    new_accountadmin_form._errors["is_master"] = ["some message"]

    del new_accountadmin_form.cleaned_data["account"]
    del new_accountadmin_form.cleaned_data["is_master"]

rawDescription: Django: How do I validate unique_together from within the model


code:
offsets = [-15, -12, -5, -1, 1, 10, 20, 32]
A = {2, 8, 12, 15, 22, ...} # a set of length ~ 1000
N = range(min(A)+min(offsets),max(A)+max(offsets)+1)
THRESHOLD = 3

NN = [num for num in N if sum((1 for offset in offsets if num+offset in A)) >= THRESHOLD]

rawDescription: Find offset sequence in an array of integers


code:
from collections import defaultdict
import bisect

ranges = defaultdict(list)
for info in list_b:
    bisect.insort(ranges[info['Ch']], (info['start'], info['end'], info['name']))

rawDescription: Is there a way to get next value for the same key in the next dictionary in the list of dictionaries?


code:
params = {'action':'query',
        'titles': name,
        'prop':'revisions',
        'rvprop':'ids|flags|timestamp|userid|user|size|comment|tags',
        'rvlimit':'100',
        'rvstart':'2009-01-01T12:00:00Z',
        'rvend':'2014-12-31T23:59:00Z',
        'rvdir':'newer'
    }

rawDescription: Wikipedia API: Get revisions by timeframe


code: dict(((x[0], x[1]), x) for x in L).values()

rawDescription: Removing Duplicates from Nested List Based on First 2 Elements


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as mgrid
import pandas as pd

fig, tsax = plt.subplots(figsize=(12,5))
barax = tsax.twinx()

data = pd.DataFrame(np.random.randn(10,3), columns=list('ABC'), index=pd.DatetimeIndex(freq='1M', start='2012-01-01', periods=10))
data['A'] **= 2

# the `width` is specified in days -- adjust for your data
barax.bar(data.index, data['A'], width=5, facecolor='indianred')

barax.set_ylabel('Miles')
tsax.set_ylabel('Miles/Gallon')

barax.xaxis.tick_top()

fig.tight_layout()

tsax.plot(data.index, data['B'])
tsax.plot(data.index, data['C'])

rawDescription: Plot bar graph and timeseries plot on different axis using pandas


code: x, y = read_xy()

rawDescription: why can't I change the variables using kwargs inside a function?

description: Why can't I change the variables using kwargs inside a function


rawDescription: Best way of adding two lists?

description: Best way of adding two lists


code:
L = [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}]
L.sort(key= lambda x:x['country'])
L

rawDescription: sorting list of dictionnaries in python

description: Sorting list of dictionnaries in python


rawDescription: Why doesn't the Python 2D array index order matter when used with colon ( : )


code:
with open('file.json') as f:
    data = json.load(f)

rawDescription: Creating a dictionary using information from JSON file


code:
def remove_diacritics(text):
    """
    Returns a string with all diacritics (aka non-spacing marks) removed.
    For example "Héllô" will become "Hello".
    Useful for comparing strings in an accent-insensitive fashion.
    """
    normalized = unicodedata.normalize("NFKD", text)
    return "".join(c for c in normalized if unicodedata.category(c) != "Mn")

rawDescription: Regex - match a character and all its diacritic variations (aka accent-insensitive)


code:
import contextlib

@contextlib.contextmanager
def doing_xy():
    print('statement_x')
    yield
    print('statement_y')

rawDescription: Run some common code before and after a block


code:
# Create an empty list
indices = []
# Step through your target list, pulling out the tuples you mention above
for index, value in enumerate(my_list):
    # If the current value matches something, append the index to the list
    if value == 'whatever':
        indices.append(index)

rawDescription: How to find all occurrences of an element in a list?

description: Find all occurrences of an element in a list


code:
from nltk import word_tokenize, pos_tag
from nltk.stem import WordNetLemmatizer
wnl = WordNetLemmatizer()
txt = """Resumption of the session I declare resumed the session of the European Parliament adjourned on Friday 17 December 1999 , and I would like once again to wish you a happy new year in the hope that you enjoyed a pleasant festive period ."""
[wnl.lemmatize(i,j[0].lower()) if j[0].lower() in ['a','n','v'] else wnl.lemmatize(i) for i,j in pos_tag(word_tokenize(txt))]

rawDescription: Python NLTK: how to lemmatize text include verb in english?


rawDescription: Reads a word and prints all substrings, sorted by length in Python


code: re.match(pattern, str, re.MULTILINE | re.IGNORECASE)

rawDescription: Python: passing flags to functions

description: Python: passing flags to functions


code: [pair[0] for pair in sorted(d.items(), key=lambda item: item[1])]

rawDescription: Sorted Word frequency count using python


code: data = '01AF23'.decode('hex')

rawDescription: How can I send anything other than strings through Python sock.send()

description: Send anything other than strings through Python sock.send()


rawDescription: Is there a way to export data from a Counter object to a CSV file?


code: b = make_b(a)

rawDescription: how to rewrite this loop in a more efficient way in python

description: Rewrite this loop in a more efficient way in python


code:
for i in range(4):
    val = a.instances["name_"+str(i)]
    my_list.append(val)

rawDescription: Python: List to tuple without "

description: Python: List to tuple without "


code:
name, zipcode = zip(*params)[1]
name
zipcode

rawDescription: Get string inbetween text Python

description: Get string inbetween text Python


code:
def multi_intersect(*args):
    if len(args) == 1:
        try:
            return multi_intersect(*args)
        except TypeError:
            pass
    inters = [item for sublist in args for item in sublist]
    for arg in args:
        inters = intersect(inters, arg)
    return inters

rawDescription: How can I form a list of matching elements in two lists, including duplicates?

description: Form a list of matching elements in two lists, including duplicates


code:
import nltk
g = nltk.data.load('grammars/large_grammars/atis.cfg')
dir(g)

rawDescription: NLTK: can I add terminal to grammar that is already generated


code:
id(surfaceXY[0])
id(surfaceXY[1])

rawDescription: Iterating in a area contained in a multidimensional array in python, why it doesn't work?


code: m = {k: float(d) / len(cs) for k, d in sum(cs).iteritems()}

rawDescription: Pythonic way to calculate the mean and variance of values in Counters


code:
# put this inside the main loop
# this will throw an IndexError when the connection is closed,
# an empty line does not contain any spaces
line = ircRecv()
if line.split()[0].find('!') != -1:
    # the first character must be a colon because <command> can't include
    # an exclamation mark
    someOneElsesNick = line[1:line.find('!')]
    command = line.split()[1]

rawDescription: Python IRC Bot won't join channels on some servers, and I don't know how to make it respond to user input


code:
import functools

@singledispatch
def div(x, y:int): # default implementation
    raise NotImplementedError('for type: {}'.format(type(x)))

@div.register(Divisible) # anything with __truediv__ method
def _(x, y):
    return x / y

@singledispatch
def add(a, b):
    raise NotImplementedError('for type: {}'.format(type(a)))

@add.register(Addable) # anything with __add__ method
def _(a, b):
    return a + b

rawDescription: Make my_average(a, b) work with any a and b for which f_add and d_div are defined. As well as builtins


code:
import cairo

surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 600, 400)
ctx = cairo.Context(surface)

points = [(100,100), (200,100), (200,200), (100,200), (100,400), (300,400)]
spline = CubicBSpline(points).clamped()

ctx.set_source_rgb(0., 0., 1.)
ctx.set_line_width(5)
BSplineDrawer(ctx).draw(spline)

rawDescription: Drawing a clamped uniform cubic B-spline using Cairo


code:
for i in Showtime.objects.filter(movie_id=movieid,theater_id=theaterid,movietime__gte=get_today()):
    if i.mvtype not in movietimes:
        movietimes[i.mvtype] = {}
    dt = i.movietime.strftime('%Y-%m-%d')
    if dt not in movietimes[i.mvtype]:
        movietimes[i.mvtype][dt] = []
    movietimes[i.mvtype][dt].append(i.movietime.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))

rawDescription: django serialize make a custom display format

description: Django serialize make a custom display format


rawDescription: List comprehension to create list of strings from two lists


code: super(Child, self).fieldname

rawDescription: accessing value of a python @property

description: Accessing value of a python @property


code:
xc = x-c
b_out = ((xc.dot(A))*xc).sum(1) <= 1

rawDescription: Dot product vectorization - NumPy

description: Dot product vectorization - NumPy


rawDescription: How to populate a QListView with value and display data?

description: Populate a QListView with value and display data


code:
def format_datetime(value, format='medium'):
    if format == 'full':
        format="EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'medium':
        format="EE dd.MM.y HH:mm"
    return babel.dates.format_datetime(value, format)

jinja_env.filters['datetime'] = format_datetime

rawDescription: Python: How do I format a date in Jinja2?


rawDescription: Readline into Tuples

description: Readline into Tuples


code:
try:
    title = soup.find("h1", "article-title").string
except AttributeError:
    title = "none"

rawDescription: Python - safe & elegant way to set a variable from function that may return None


code:
import lxml
some_data = "<b>hello BREAK world</b>"
root = lxml.etree.fromstring(some_data)
root
root.text

rawDescription: Replace text with HTML tag in LXML text element


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

pause = False
def simData():
    t_max = 10.0
    dt = 0.05
    x = 0.0
    t = 0.0
    while t < t_max:
        if not pause:
            x = np.sin(np.pi*t)
            t = t + dt
        yield x, t

def onClick(event):
    global pause
    pause ^= True

def simPoints(simData):
    x, t = simData[0], simData[1]
    time_text.set_text(time_template%(t))
    line.set_data(t, x)
    return line, time_text

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([], [], 'bo', ms=10) # I'm still not clear on this stucture...
ax.set_ylim(-1, 1)
ax.set_xlim(0, 10)

time_template = 'Time = %.1f s'    # prints running simulation time
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
fig.canvas.mpl_connect('button_press_event', onClick)
ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=10,
    repeat=True)
plt.show()

rawDescription: stop / start / pause in python matplotlib animation

description: Stop / start / pause in python matplotlib animation


code:
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
list(calendar.day_name)

rawDescription: Get Day name from Weekday int

description: Get Day name from Weekday int


code:
import random
image = random.choice(self.imageListRegular) #this is your 'Y' variable
times = random.randint(1, 4) #this is your 'X' variable

rawDescription: Add images dynamically based on random number


code: (int.from_bytes(bytes_input, 'big') >> bit_position) & 0b11

rawDescription: In Python how do I parse the 11th and 12th bit of 3 bytes?


code:
df
df.ix[df['data1'].argsort()[-3:]]

rawDescription: How to get top N value in python

description: Get top N value in python


rawDescription: Python counting lines in files using exact locations


code:
for i in xrange(len(entries) - 1):
    diff = entries[i+1] - entries[i]

rawDescription: python for loop, how to find next value(object)?

description: Python for loop, how to find next value(object)


code:
filename = "Daily stats 01092014"
# Get folder name from filename by getting month number from filename
foldername = directory_mapping[filename[-6:-4]]

rawDescription: Copying a file maintaining same folder structure


code:
cluster = []

for line in content:
  list = line.decode('utf-8').strip().split(',')
  cluster[list[0]] = list[1 : len(list) - 1]

rawDescription: Python clustering from .csv file as input


code:
class Meta(type):
    def __new__(mcs, name, bases, attr):
        prefix = attr.get("prefix")
        if prefix:
            attr[prefix+"_var1"] = "hello"
            attr[prefix+"_var2"] = "goodbye"

        return type.__new__(mcs, name, bases, attr)

class myclass(object):
    __metaclass__ = Meta
    prefix = "coffee"

    def mytest(self):
        print(self.coffee_var1)
        print(self.coffee_var2)

rawDescription: How do I get a reference for the current class object?

description: Get a reference for the current class object


code: df

rawDescription: Create new pandas timeseries dataframe from other dataframe


code:
df = pd.DataFrame({'C': range(5)})
df.C.values - np.vstack(df.C.values)

rawDescription: Creating matrix from dataframe

description: Creating matrix from dataframe


code: i0, i1, i2 = np.ix_(*[np.arange(d) for d in a.shape])

rawDescription: Numpy fancy indexing suggestion needed

description: Numpy fancy indexing suggestion needed


code: between(1,3)(subf.ix[(t-60 < subf['Time']) & (subf['Time'] <= t), 'Value'])

rawDescription: Customizing rolling_apply function in Python pandas


code: zip(*np.where(test2D > 5000.))

rawDescription: Getting positions of specific values of 2d array


code:
p1 = sb.Popen(["sed", "1i import matplotlib\nmatplotlib.use('Agg')\n", fl],
              stdout=sb.PIPE)
exit_cond = sb.call(["python"], stdin=p1.stdout)

rawDescription: Suppress matplotlib figures when running .py files via python or ipython terminal


rawDescription: XOR neural network backprop

description: XOR neural network backprop


code:
from multiprocessing import Pool

# all your methods declarations above go here
# (...)

def main():
    pool = Pool(processes=3)
    parsed = pool.apply_async(Process1, [largefile])
    pattern = pool.apply_async(Process2, [bigfile])
    calc_res = pool.apply_async(Process3, [integer])

    pool.close()
    pool.join()

    final = FinalProcess(parsed.get(), pattern.get(), calc_res.get())

# your __main__ handler goes here
# (...)

rawDescription: Run separate processes in parallel - Python


code: pv.reindex( batch.BatchNo ).fillna( 0 )

rawDescription: Collating timestamped events into date ranges with pandas


code:
aString = "Hello, my name is Dave"
aString[7:9]
aString[7:9] = "MY"

rawDescription: Change the value of a list's element

description: Change the value of a list's element


rawDescription: Converting 3D matrix to cascaded 2D Matrices


rawDescription: Print a Pretty Tree

description: Print a Pretty Tree


code: m = [[[[] for x in range(2)] for x in range(4)] for x in range(4)]

rawDescription: Editing multi-dimensional arrays in Python


rawDescription: Unordered collection - sets in python

description: Unordered collection - sets in python


code: cities_to_countries = dict(zip(cities, countries))

rawDescription: How to index a user input list in Python 2.x?

description: Index a user input list in Python 2.x


code:
import csv
from scrapy.item import Item, Field

from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.http import FormRequest
from scrapy.selector import HtmlXPathSelector

class BtwItem(Item):
    fttcAvailable = Field()
    phoneNumber = Field()

class BtwSpider(BaseSpider):
    name = "btw"
    allowed_domains = ["samknows.com"]

    def start_requests(self):
        yield Request("http://www.samknows.com/broadband/broadband_checker", self.parse_main_page)

    def parse_main_page(self, response):
        with open('phones.csv', 'r') as f:
            reader = csv.reader(f)
            for row in reader:
                phone_number = row[0]
                yield FormRequest.from_response(response,
                                                formdata={'broadband_checker[phone]': phone_number},
                                                callback=self.after_post,
                                                meta={'phone_number': phone_number})

    def after_post(self, response):
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//div[@id="results"]')

        phone_number = response.meta['phone_number']
        for site in sites:
            item = BtwItem()

            fttc = site.select("div[@class='content']/div[@id='btfttc']/ul/li/text()").extract()
            item['phoneNumber'] = phone_number
            item['fttcAvailable'] = 'not' in fttc[0]

            yield item

rawDescription: Scrape using multiple POST data from the same URL


code: lst

rawDescription: Reading a file to a dictionary and trying to rank


code:
patterns = collections.defaultdict(list)
for f in image_files:
    p = re.sub("\d+", "XXX", f)
    patterns[p].append(f)

rawDescription: How to identify files that have increasing numbers and a similar form of filename?

description: Identify files that have increasing numbers and a similar form of filename


code:
def egcd(a, b):
    x,y, u,v = 0,1, 1,0
    while a != 0:
        q, r = b//a, b%a
        m, n = x-u*q, y-v*q
        b,a, x,y, u,v = a,r, u,v, m,n
    return b, x, y

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        return None  # modular inverse does not exist
    else:
        return x % m

rawDescription: Modular inverse calculation stuck

description: Modular inverse calculation stuck


code:
#!/usr/bin/env python

import csv
from pprint import pprint
from operator import itemgetter

INPUT = """\
name, id, date, score
chris, 55, 5/22/2014, 70
pete, 56, 5/22/2014, 100
chris, 55, 5/22/2014, 100"""

reader = csv.reader(INPUT.split("\n"))
rows = iter(reader)
next(rows)  # skip header
sort_key = itemgetter(0, 3)
sorted_rows = reversed(sorted(rows, key=sort_key))
unique_rows = dict((row[1], row) for row in sorted_rows)

pprint(unique_rows)

rawDescription: Python 2.7 CSV: How to remove duplicate rows based on a value


code:
def __eq__(self, other, *attributes):
    if not isinstance(other, type(self)):
        return NotImplemented

    if attributes:
        d = float('NaN')  # default that won't compare equal, even with itself
        return all(self.__dict__.get(a, d) == other.__dict__.get(a, d) for a in attributes)

    return self.__dict__ == other.__dict__

rawDescription: Most efficient way of comparing the contents of two class instances in python


code:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', 'project_name.views.index'),
    url(r'^addbook/$', 'project_name.views.addbook'),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

rawDescription: How to configure HTML form to work with django models?

description: Configure HTML form to work with django models


code:
def convert_and_free_char_p(char_p):
    try:
        return char_p.value
    finally:
        libc.free(char_p)
libc.strdup.restype = convert_and_free_char_p

s = libc.strdup(mybuf)
# now use s

rawDescription: Memory leaks in Python when using an external C DLL


code:
class ClassB:
    def __call__(self,obj):
        print('ClassB object %d is called because obj %d '
              'is being destroyed' % (id(self), id(obj)))

rawDescription: using python WeakSet to enable a callback functionality

description: Using python WeakSet to enable a callback functionality


rawDescription: How do I index the 3 highest values in a list?

description: Index the 3 highest values in a list


rawDescription: Find and replace in CSV files with Python


code:
class TaskCreate(CreateView):
    ...
    def get_form(self, form_class):
        form = super(TaskCreate, self).get_form(form_class)
        form.fields['project'].queryset = Project.objects.filter(
                                               type=self.request.GET['type'])
        return form

rawDescription: CreateView use parameters

description: CreateView use parameters


code:
import inspect
from abc import *
inspect.getfile(ABCMeta)

rawDescription: How to know the location of the library that I load in Python?

description: Know the location of the library that I load in Python


code: r = [v for a in A for b in B]

rawDescription: Different results from yield vs return

description: Different results from yield vs return


code: df = df.abs()

rawDescription: Multiple negative numbers with -1 (Dataframe)


code:
from pandas import *
df = DataFrame([[0, 1, 1], [1, 1, 0], [1, 0, 1],], columns=['a','b','c'])

foo = []
for i in df.index:
    foo.append( df.columns[df.ix[i] == 1])
DataFrame(foo, index = df.index)

rawDescription: pandas dataframe - change values based on column heading

description: Pandas dataframe - change values based on column heading


code:
from operator import itemgetter
d2 = {}
for volume,data_list in d.items():
    d2[volume] = sorted(data_list,key=itemgetter("created_at"),reverse=True)[:5]

rawDescription: keep n retention and delete old one

description: Keep n retention and delete old one


code:
def extractYear(s):
    if len(s) >= 6 and s[-6] == '(' and s[-5:-1].isdigit() and s[-1] == ')':
        return s[:-6], s[-6:]
    return s, None

rawDescription: Splitting string with optional year

description: Splitting string with optional year


code:
from sqlalchemy.orm import mapper
mapper(Player, players_table)

rawDescription: Dynamic Table Creation and ORM mapping in SqlAlchemy


code:
inds = B.searchsorted(A)
inds[inds == len(B)] = 0
mask = B[inds] == A

rawDescription: Numpy.array indexing question

description: Numpy.array indexing question


code: network.wfsc_ip() # no print

rawDescription: Python - List and Loop in one def

description: Python - List and Loop in one def


code:
import tempfile
import webbrowser
import time

def open_in_browser(html):
    """like lxml.html.open_in_browser() but `html` is a bytestring."""
    with tempfile.NamedTemporaryFile("wb", 0, suffix='.html') as file:
        file.write(html)
        webbrowser.open(file.name)
        time.sleep(60) # give the browser a minute to open before
                       # deleting the file

open_in_browser((u'''<!doctype html>
    <meta charset="utf-8">
    <title>Fill textarea</title>
''' + textarea_html).encode('utf-8'))

rawDescription: How to store multiline text in html textarea from python?

description: Store multiline text in html textarea from python


code: bravo_value = data.setdefault("bravo", [])  # Initializes bravo with an empty list if it is missing

rawDescription: Manipulating JSON data, when keys may be missing, in Python


code:
objs = TestModel.objects.all()
result = []
for obj in objs:
   if obj.prop_a == 'a':
      result.append(obj)

rawDescription: Accessing Johnny Cache Data

description: Accessing Johnny Cache Data


code:
J = array(I) # copy image
J[30:70, 30:70] = gaussian_filter(I[30:70, 30:70], sigma=1) # apply filter to subregion
figure(2)
imshow(2)

rawDescription: "painting" one array onto another using python / numpy


code: soup.select("span > a")

rawDescription: Python BeautifulSoupe4: How to get link from anchor tag without duplicate


code:
with open("file.csv","w") as f:
    f.write(','.join(str.split()))

rawDescription: Python: Write output in a csv-file

description: Python: Write output in a csv-file


code:
sqlContext.sql(sqlStr).explain()

## == Physical Plan ==
## Window [City#0,Person#1,year#2L,data#3], [HiveWindowFunction#org.apache.hadoop.hive.ql.udf.generic.GenericUDAFRowNumber() windowspecdefinition(Person#1,year#2L DESC,ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS ranking#5], [Person#1], [year#2L DESC]
## +- Sort [Person#1 ASC,year#2L DESC], false, 0
##    +- TungstenExchange hashpartitioning(Person#1,200), None <- PARTITION BY
##       +- Project [City#0,Person#1,year#2L,data#3]
##          +- TungstenExchange hashpartitioning(City#0,2), None <- REPARTITION
##             +- ConvertToUnsafe
##                +- Scan ExistingRDD[City#0,Person#1,year#2L,data#3]

rawDescription: Data shuffle for Hive and Spark window function


code: np.cumsum(z < big,axis=1)[:,-1]

rawDescription: Is there a more pythonic way to write

description: Is there a more pythonic way to write


code: d = {(k1,k2):v  for k1,k2,v in List}

rawDescription: Python create nested dictionary from list with nested tuples


code:
def __enter__(self):
    """Context manager that returns a Cursor"""
    return self.cursor()

def __exit__(self, exc, value, traceback):
    """On successful exit, commit. On exception, rollback"""
    if exc:
        self.rollback()
    else:
        self.commit()

rawDescription: Can I use pymysql.connect() with "with" statement?

description: Use pymysql.connect() with "with" statement


code:
first_series[second_series == 'Minus'] *= -1
first_series[second_series.isnull()] = np.nan

rawDescription: pandas: Change one Series by using a second one with the same index

description: Pandas: Change one Series by using a second one with the same index


rawDescription: Equidistant ticks on colorbar using SymLogNorm in matplotlib


code: user = bob

rawDescription: Python Regex: Optional White Space Around Matching Group


code:
matches = [(next(g), len(list(g))+1)
           for k, g in groupby(range(min(len(f1), len(f2))), key=lambda i: f1[i] == f2[i])
               if k]

rawDescription: Diffing Binary Files In Python

description: Diffing Binary Files In Python


code:
def recurse( node,  id, depth = -1, position=-1, max_depth=-1):
   depth=depth+1
   current_depth=depth

   max_depth=max(max_depth,current_depth)

   matchl=False
   matchr=False

   if node.l :
       (depthl,position,max_depth,matchl)=recurse(node.l,id,current_depth,position,max_depth)

   positionl = position
   position = position + 1
   current_position=position

   if node.r:
      (depth,position,max_depth,matchr)=recurse(node.r,id,current_depth,position,max_depth)

   if matchl:
      return (depthl,positionl,max_depth,True)

   if node.x==id:
      return (current_depth,current_position,max_depth,True)

   return (depth,position,max_depth,matchr)

rawDescription: How to find position of nodes in binary tree?

description: Find position of nodes in binary tree


code:
class Car(models.Model):
    ...
    def parts_with_manufacturers(self):
        return self.part_set.select_related('manufacturer')

rawDescription: django select_related in template

description: Django select_related in template


code: peakIndexTuple = numpy.unravel_index(numpy.argmax(myArray), myArray.shape)

rawDescription: Getting index of numpy.ndarray

description: Getting index of numpy.ndarray


rawDescription: Assign variables to the list elements, without knowing it's length


code: expand(b'a-f')

rawDescription: converting a C function into Python3 form?

description: Converting a C function into Python3 form


rawDescription: Convert decimal int to little endian string ('\x##\x##...')


code:
class Operation(Enum):
    START_SERVER = (0, "start", ServersDictionary)
    STOP_SERVER = (1, "stop", ServersDictionary)
    START_APP = (1, "start", AppsDictionary)

rawDescription: Refactoring if statements in python

description: Refactoring if statements in python


code:
data = list(tuple(pixel) for pixel in pix)
pic.putdata(data)

rawDescription: PIL and numpy

description: PIL and numpy


code: df[((df.A - some_float).abs() < abs_tol) & (df.B == 0)]

rawDescription: Using python/pandas to search dataframe rows containing both a user-specified integer and approximated float value


code:
code = '''class MyClass:
    pass
'''

the_locals = {}
exec(code, globals(), the_locals)
MyClass = the_locals['MyClass']
MyClass._code = code

rawDescription: Generate python code of a class from an python instance of this class


code:
def reverse(word):
    index = len(word)-1
    result = []
    while index >= 0:
        result.append(word[index])
        index -= 1
    return "".join(result)

rawDescription: Reverse String Function in Python (Primitive Steps)


code:
words = ['a','la','los','shrimp']
sentence = 'They eat shrimp in Mexico, and more these days'
a = map(lambda word: word in words if word in sentence else None, words)
print(a.__next__())
True

rawDescription: Best performance method for evaluating presence of substrings within strings in python?


code:
import difflib
difflib.SequenceMatcher(None, file1.read(), file2.read())

rawDescription: Does python have any direct appoach to compare two .txt files?


rawDescription: Create an import statement using variable "interpolation"


code:
bdict = {k:v for v,k in reversed(blist)}
cdict = {}
for v,k in alist:
   if k not in cdict:
      b = bdict.get(k, None)
      if b is not None:
        cdict[k] = v * b
print(list((k,v) for v,k in cdict.items()))

rawDescription: How to optimize the combination of 2 lists of tuples and remove their duplicates?

description: Optimize the combination of 2 lists of tuples and remove their duplicates


code:
import itertools
import operator

class Item(object):
    def __init__(self,name,price):
        self.name=name
        self.price=price
    def __str__(self):
        return '{0} {1}'.format(self.name,self.price)

class Person(object):
    def __init__(self,id,name,*items):
        self.id=id
        self.name=name
        self.items=set(items)
    def __str__(self):
        return '{0} {1}: {2}'.format(self.id,self.name,map(str,self.items))

list_people = [
    Person('001','jim',Item('pencil',0.99)),
    Person('002','mary',Item('book',15.49)),
    Person('002','mary',Item('tape',7.99)),
    Person('003','john',Item('pen',3.49)),
    Person('003','john',Item('stapler',9.49)),
    Person('003','john',Item('scissors',12.99)),
]

def take_items(person,other):
    '''
    person takes other's items.
    Note however, that although person may be altered, other remains the same --
    other does not lose its items.
    '''
    person.items.update(other.items)
    return person

list_people2 = [reduce(take_items,g)
                for k,g in itertools.groupby(list_people, lambda person: person.id)]
for person in list_people2:
    print(person)

rawDescription: python list of dicts how to merge key:value where values are same?

description: Python list of dicts how to merge key:value where values are same


code: [re.search(r'^\t(.*)\t.*: (.*)$',i).groups() for i in my_list]

rawDescription: Use regex backreferences to create array


code:
lofdicts=[v for k,v in NdocScores.items()]
lofdicts
lofdicts[0]
sum(lofdicts[1].values())

rawDescription: Accessing values in a list of nested dictionaries


code:
"\"hello\" '(world)'".translate(None, r"()\"'")
"a'b c\"d e(f g)h i\\j".translate(None, r"()\"'")

rawDescription: Strip Specific Punctuation in Python 2.x


code: data=np.array(sorted(d, key=lambda  l:l[1]))

rawDescription: sorting a two dimensional array based on one column

description: Sorting a two dimensional array based on one column


rawDescription: Equal strings auto updating (List object reference)


code:
startingPosition = float(data_dict["Starting position"][0])
data_list_of_floats = map(float, data_dict["Data"])

rawDescription: Read Block Data in Python?

description: Read Block Data in Python


code:
hog[Y, X, angle].shape
magnitude = np.sqrt(sobel_X ** 2 + sobel_Y ** 2)
magnitude.shape

rawDescription: numpy 2d array (coordinates) need to assign into 3D array, to some particular bin

description: Numpy 2d array (coordinates) need to assign into 3D array, to some particular bin


code: st=  input("Enter string:").split(',')

rawDescription: string slicing python in lists

description: String slicing python in lists


rawDescription: Add values for different years

description: Add values for different years


code: cProfile.run('C = A + B')

rawDescription: Iterating with Python

description: Iterating with Python


code: unicode(content)

rawDescription: How to render contents of a tag in unicode in BeautifulSoup?

description: Render contents of a tag in unicode in BeautifulSoup


rawDescription: How to delete every nth row of an if one contains a zero?

description: Delete every nth row of an if one contains a zero


code:
extract_groups('Jimmy threw his ball through the window.')
extract_groups('Jimmy |threw his ball| through the window.')
extract_groups('Jimmy |threw his| ball -|through the| window.')

rawDescription: Splitting a python string

description: Splitting a python string


code:
't.com'.count('.')
'x.t.com'.count('.')

rawDescription: How to differentiate lines with one dot and two dot?

description: Differentiate lines with one dot and two dot


code:
rules = input ("Would you like to read the instructions? ")
rulesa = "yes"
if rules.lower() == rulesa:
    print  ("No cheating")
else:
    print ("Have fun!")

rawDescription: Python - Ignore letter case

description: Python - Ignore letter case


code:
@classmethod
def wrap(cls, key, value):
    sign('VerboseMetaclass')
    if isinstance(value, types.FunctionType):
        return cls.wrap_function(key, value)
    return value

def wrap_function(name, func):
    sign('VerboseMetaclass')
    @functools.wraps(func)
    def verbose_function(*args, **kwargs):
        args_str = tuple(repr(item) for item in args)
        kwargs_str = tuple('{!s}={!r}'.format(*pair)
                           for pair in sorted(kwargs.items()))
        signature = '{}({})'.format(name, ', '.join(args_str + kwargs_str))
        print('[ -> ] {}\n'.format(signature))
        try:
            value = func(*args, **kwargs)
            print('[ <- ] {!s} [return {!r}]\n'.format(signature, value))
            return value
        except:
            value = sys.exc_info()[1]
            print('[ <- ] {!s} [raise {!r}]\n'.format(signature, value))
            raise
    return verbose_function

rawDescription: What causes a method wrapped via a metaclass to forget self when called?


code:
df1['B'] = df1['A'].astype('category')
i = df1['B'].cat.categories
i

rawDescription: pandas and category replacement

description: Pandas and category replacement


code:
twitter_friend_ids = twitter_api.friend_ids() # potentially 5000 values
auth_account_keys = [ndb.Key("AuthAccount", "tw:%s" % id) for id in twitter_friend_ids]
friend_system_ids = filter(None, ndb.get_multi(auth_account_keys))

rawDescription: Optimizing for Social Leaderboards

description: Optimizing for Social Leaderboards


rawDescription: How to scrape table with different xpath on the same level with Scrapy?

description: Scrape table with different xpath on the same level with Scrapy


code:
df.loc[:, ['x_axis', 'y_axis']] = s.cat.codes.unstack()
df

rawDescription: Replacing string elements of a pandas DataFrame with integers


code: dict_a = dict(Counter("".join(map(lambda a: a[0] * a[1], a))))

rawDescription: How to merge value of key when I have a list-tuple object

description: Merge value of key when I have a list-tuple object


code:
def replace_callback(matches):
    full_line = matches.group(0)
    number_text = matches.group(2)
    number_of_interest = int(number_text, base=10)
    if number_of_interest > 2147483647:
        return full_line.replace(number_of_interest, number_text[:3])
    else:
        return full_line

rawDescription: How to substitute specific patterns in python

description: Substitute specific patterns in python


code:
class NewFuncMixin():
    def new_func(): pass

rawDescription: Extending a class hierarchy in Python

description: Extending a class hierarchy in Python


code:
xx, yy = np.meshgrid(x, y)
xygrid=np.array([xx,yy])
xygrid=xygrid.reshape(2,-1).T  # clumsy

rawDescription: Python rounding of random floats to nearest points on a 2D uniform mesh grid


code: json.dump(locals(), f, default=repr)

rawDescription: How to dump all the variables in a file?

description: Dump all the variables in a file


code:
def listify(l):
    res = []
    for j in l:
        d = dict([(0,0),(1,0),(2,0),(3,0),(4,0)])
        d.update(j)
        res.append(list(d.items()))
    return res

rawDescription: Python lists with irregular format

description: Python lists with irregular format


code:
class tags(models.Model):
    """ This is the tag model """
    tag = models.CharField(max_length=15)               # Tag name
    tagDescription = models.TextField()                 # Tag Description
    tagSlug = models.CharField(max_length=400)          # Extra info can be added to the existing tag using this field
    createdAt = models.DateTimeField(auto_now_add=True) # Time at which tag is created
    updatedAt = models.DateTimeField(auto_now=True)     # Time at which tag is updated

    def __unicode__(self):
        """Method to display string correctly"""
        return unicode(self.tag)

    def getAllStoreNames(self):

        for t in tags.objects.filter(tag=self.tag):
            return  ([str(a.storeName) for a in t.stores_set.all()])

    class Meta:
        """Meta class to control display Behavior of the Model name """
        verbose_name_plural = "Tags"

rawDescription: backward many to many Django query

description: Backward many to many Django query


code: points = map(int, raw_input().split())

rawDescription: Accepting an unknown number of variables using input()


type: Program

type: ExpressionStatement

type: CallExpression

foo

type: Identifier

rawDescription: Extracting arguments of JavaScript function from HTML page with BeautifulSoup


rawDescription: What does this parameter in numpy.zeros method mean?


code:
for key in self.bok.iterkeys():
    for subkey in key:
        w.write(self.bok[key])
        w.write(";")
        w.write(subkey)
        w.write(";")
        w.write("\n")
w.close()

rawDescription: Python Tuple save to file

description: Python Tuple save to file


code:
size_count = df.groupby(['level'])['size'].apply(lambda x: x.value_counts())
# level
# 0      1      9
#        2      5
#        7      2
# ...
# 1      1     11
#        2      4
#        3      2
#        5      1
# dtype: int64

rawDescription: How to dynamically update a plot in a loop?

description: Dynamically update a plot in a loop


code:
#load your data back to memory when you need it
with open(newfile, 'rb') as fi:
  WordList = pickle.load(fi)

rawDescription: Keeping the data of a variable between runs of code


code:
def checkparen(inp):
    counter = collections.Counter(inp)
    symbols = {'{':'}','[':']','(':')'}
    for symbol in symbols:
            if counter[symbol] != counter[symbols[symbol]]:
                    return False
    return True

checkparen('{')
checkparen('[ [ { { ( ( ) ) } } ] ]')

rawDescription: compare paranthesis in python

description: Compare paranthesis in python


code:
mask = (D[:,None,:] == A).all(-1)
out = mask.dot(B)/(mask.sum(1)[:,None])

rawDescription: Numpy Vectorization While Indexing Two Arrays


code: A[np.arange(J.shape[0]), J]

rawDescription: How can I select values along an axis of an nD array with an (n-1)D array of indices of that axis?

description: Select values along an axis of an nD array with an (n-1)D array of indices of that axis


rawDescription: how do I .decode('string-escape') in Python3?

description: .decode('string-escape') in Python3


rawDescription: Bigram function using python

description: Bigram function using python


code: [[n, ws] for n, ws in data if set(ws.split()).isdisjoint(neg_words)]

rawDescription: Removing sublist from nested lists based on element values


code:
now = datetime.datetime.now()
jobs = Job.query(Job.published == "on", Job.expire <= now).fetch()
for job in jobs:
    job.published = "off"
ndb.put_multi(jobs)

rawDescription: Google App Engine: Using cron to expire (or 'unpublish') entities


code:
import matplotlib
import matplotlib.pyplot as plt

x = [0,0,1,1,2,2,3,3]
y = [-1,3,2,-2,0,2,3,1]
values = [2,6,10,8,0,9,3,6]
# Let the colormap extend between:
vmin = min(values)
vmax = max(values)

cmap = matplotlib.cm.viridis
norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)

fig, ax = plt.subplots(4, sharex=True, sharey=True)
# Alternative 1: using plot:
for i in range(len(x)):
    color = cmap(norm(values[i]))
    ax[0].plot(x[i], y[i], linestyle='none', color=color, marker='o')

# Alternative 2: using scatter without specifying norm
ax[1].scatter(x, y, c=values, cmap=cmap)

# Alternative 3: using scatter with normalized values:
ax[2].scatter(x, y, c=cmap(norm(values)))

# Alternative 4: using scatter with vmin, vmax and cmap keyword-arguments
ax[3].scatter(x, y, c=values, vmin=vmin, vmax=vmax, cmap=cmap)

plt.show()

rawDescription: Dynamic marker colour in matplotlib

description: Dynamic marker colour in matplotlib


rawDescription: How to initialize NumPy array with different default value for each column?

description: Initialize NumPy array with different default value for each column


code: d = dict((e, i) for i, e in enumerate(l))

rawDescription: Transforming list to dict with list items as keys and list indices as values in python


rawDescription: Face Recognition - How to return the correct image?


rawDescription: Python - How to make a local variable (inside a function) global


code:
L=[1,1,1,1,1,1,2,3,4,4,5,1,2]
from itertools import groupby
[x[0] for x in groupby(L)]

rawDescription: Removing elements that have consecutive dupes


code:
def complete(text, state):
    return (glob.glob(os.path.expanduser(text)+'*')+[None])[state]

rawDescription: Cmd module '~' completion

description: Cmd module '~' completion


code: import os

rawDescription: Saving files downloaded from Urlretrieve to another folder other


code:
def Intersects(self, point, direction):
    if (point[0] > 0):
        if (direction != [1, 0] and self.WallSpaces[point[0] - 1] & (1 << point[1]) != 0):
            return True
        if (point[1] == 0 or self.WallSpaces[point[0] - 1] & (1 << (point[1] - 1)) != 0):
            return True
        if (point[1] == self.Width or self.WallSpaces[point[0] - 1] & (1 << (point[1] + 1)) != 0):
            return True
    else:
        return True
    if (point[0] < self.Height):
        if (direction != [-1, 0] and self.WallSpaces[point[0] + 1] & (1 << point[1]) != 0):
            return True
        if (point[1] == 0 or self.WallSpaces[point[0] + 1] & (1 << (point[1] - 1)) != 0):
            return True
        if (point[1] == self.Width or self.WallSpaces[point[0] + 1] & (1 << (point[1] + 1)) != 0):
            return True
    else:
        return True
    if (point[1] == 0 or (direction != [0, 1] and self.WallSpaces[ point[0] ] & (1 << (point[1] - 1)) != 0)):
        return True
    if (point[1] == self.Width or (direction != [0, -1] and self.WallSpaces[ point[0] ] & (1 << (point[1] + 1)) != 0)):
        return True
    return False

rawDescription: Find enclosed spaces in array

description: Find enclosed spaces in array


code:
# mysql/gaerdbms.py
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
.. dialect:: mysql+gaerdbms
    :name: Google Cloud SQL
    :dbapi: rdbms
    :connectstring: mysql+gaerdbms:///<dbname>?instance=<instancename>
    :url: https://developers.google.com/appengine/docs/python/cloud-sql/developers-guide

    This dialect is based primarily on the :mod:`.mysql.mysqldb` dialect with minimal
    changes.

    .. versionadded:: 0.7.8

Pooling
-------

Google App Engine connections appear to be randomly recycled,
so the dialect does not pool connections.  The :class:`.NullPool`
implementation is installed within the :class:`.Engine` by
default.

"""

import os
import re

from sqlalchemy.dialects.mysql.mysqldb import MySQLDialect_mysqldb
from sqlalchemy.pool import NullPool

class MySQLDialect_gaerdbms(MySQLDialect_mysqldb):

    @classmethod
    def dbapi(cls):
        # from django:
        # http://code.google.com/p/googleappengine/source/
        #     browse/trunk/python/google/storage/speckle/
        #     python/django/backend/base.py#118
        # see also [ticket:2649]
        # see also http://stackoverflow.com/q/14224679/34549
        if is_production():
            # Production mode.
            from google.storage.speckle.python.api import rdbms_apiproxy
            return rdbms_apiproxy
        elif is_remote_mode():
            # Development mode with remote database.
            from google.storage.speckle.python.api import rdbms_googleapi
            return rdbms_googleapi
        else:
            # Development mode with local database.
            from google.appengine.api import rdbms_mysqldb
            return rdbms_mysqldb

    @classmethod
    def get_pool_class(cls, url):
        # Cloud SQL connections die at any moment
        return NullPool

    def create_connect_args(self, url):
        opts = url.translate_connect_args()
        if is_production() or is_remote_mode():
            # 'dsn' and 'instance' are because we are skipping
            # the traditional google.api.rdbms wrapper.
            # they are not needed in local mode; 'dns' even causes an error.
            opts['dsn'] = ''
            opts['instance'] = url.query['instance']
        return [], opts

    def _extract_error_code(self, exception):
        match = re.compile(r"^(\d+):|^\((\d+),").match(str(exception))
        # The rdbms api will wrap then re-raise some types of errors
        # making this regex return no matches.
        code = match.group(1) or match.group(2) if match else None
        if code:
            return int(code)

dialect = MySQLDialect_gaerdbms

def is_production():
  return os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine')

def is_remote_mode():
  return os.getenv('SETTINGS_MODE') == 'prod'

rawDescription: Using SQLAlchemy on App Engine development server


code:
@admin.site.register(ModelOne)
class AdminModel(admin.ModelAdmin):

    def get_actions(self, request):
        actions = super(AdminModel, self).get_actions(request)
        if not request.user.is_superuser:
            if 'delete_selected' in actions:
                del actions['delete_selected']
        else:
            self.actions.append(make_published)
            self.actions.append(make_unpublished)
        return actions

@admin.site.register(ModelTwo)
class NoActionsModel(admin.ModelAdmin):
    pass

rawDescription: Django: Admin action choices

description: Django: Admin action choices


code:
from xml.etree.ElementTree import parse
doc = parse('data.xml')
root = doc.getroot()
for t in root.iterfind('pubgroup/member'):
    t.attrib['objlocation'] = "spam"

doc.write('output.xml', xml_declaration=True)

rawDescription: Edit XML with python

description: Edit XML with python


code: a[r_[:len(b)], b] = vals

rawDescription: Numpy: placing values into an 1-of-n array based on indices in another array


rawDescription: How to get the desktop resolution in Mac via Python?

description: Get the desktop resolution in Mac via Python


code:
keyword_dictionary = {
    'Animal' : {'animal', 'dog', 'cat'},
    'Art' : {'art', 'sculpture', 'fearns'},
    'Buildings' : {'building', 'architecture', 'gothic', 'skyscraper'},
    'Vehicle' : {'car','formula','f-1','f1','f 1','f one','f-one','moped','mo ped','mo-ped','scooter'},
    'Person' : {'person','dress','shirt','woman','man','attractive','adult','smiling','sleeveless','halter','spectacles','button','bodycon'},
    'People' : {'people','women','men','attractive','adults','smiling','group','two','three','four','five','six','seven','eight','nine','ten','2','3','4','5','6','7','8','9','10'},
    'Food' : {'food','plate','chicken','steak','pizza','pasta','meal','asian','beef','cake','candy','food pyramid','spaghetti','curry','lamb','sushi','meatballs','biscuit','apples','meat','mushroom','jelly', 'sorbet','nacho','burrito','taco','cheese'},
    'Glass' : {'glass','drink','container','glasses','cup'},
    'Bottle' : {'bottle','drink'},
    'Signage' : {'sign','martini','ad','advert','card','bottles','logo','mat','chalkboard','blackboard'},
    'Slogan' : {'Luck is overrated'},
    'DJ' : {'dj','disc','jockey','mixer','instrument','turntable'},
    'Party' : {'party'}
 }

def matcher(keywords, searcher):
     for key, words in keywords.items():
        if not words.isdisjoint(searcher):
            print(key)

with open("test.txt") as termsdesk:
    for line in termsdesk:
        matcher(keyword_dictionary, line.split())

rawDescription: Python - reading complex lines of text into dictionary


code:
message = "I like %s a lot!" % spam
# do whatever
print(message)

rawDescription: How to set the global value of % in python

description: Set the global value of % in python


code:
from collections import defaultdict
with open('test.dat') as f:
    data = defaultdict( lambda:([],[]))
    header = f.readline()
    for line in f:
        col1,col2,col3,col4 = line.split()
        col3_data,col4_data = data[(col1,col2)]  #data[frozenset((col1,col2))] if order doesn't matter
        col3_data.append(col3)
        col4_data.append(col4)

rawDescription: Based on the values in two columns merge values in other columns


code:
class AnswerFormSet(forms.models.BaseInlineFormSet):
     def clean(self):
        correct_count = sum([form.cleaned_data['is_correct'] for form in self.forms])
        if correct_count != 1:
            raise forms.ValidationError('Exactly one answer must be marked as correct')

rawDescription: django multiple ModelForms with the same model and ForeignKeys

description: Django multiple ModelForms with the same model and ForeignKeys


code: help(enumerate)

rawDescription: Pythonic way of maintaining counter variables?


rawDescription: Is this a "pythonic" method of executing functions as a python switch statement for tuple values?


rawDescription: Passing functions which have multiple return values as arguments in Python


rawDescription: How to display continuous data in a py-gtk window?

description: Display continuous data in a py-gtk window


code:
result = df.groupby("c3")[["c1", "c2"]].apply(lambda x: dict(x.values))
result
result.to_dict()

rawDescription: Pandas: Most efficient way to make dictionary of dictionaries from DataFrame columns


rawDescription: Turning a list into a string or a word

description: Turning a list into a string or a word


code:
from flask import Flask
from route import mod

app = Flask(__name__)
app.register_blueprint(mod, url_prefix='/')

rawDescription: Error while a Flask project turning into a package


code: sorted_probabilities = sorted(probabilities, key=lambda x: abs(x[0][0]-x[0][1]))

rawDescription: Sorting a complex datastructure

description: Sorting a complex datastructure


rawDescription: How to find the maximum number of times that the most common item in a list appears?

description: Find the maximum number of times that the most common item in a list appears


rawDescription: pandas get all columms without one

description: Pandas get all columms without one


code:
from datetime import datetime
from pprint import pprint

L = [('28.10.11/D/text1/' , {'key':'value1'}),
     ('27.01.11/D/text2/' , {'key':'value2'}),
     ('07.11.12/D/text3/' , {'key':'value3'})]

L.sort(key=lambda k: datetime.strptime(k[0][:8],"%d.%m.%y"))
pprint(L)

rawDescription: Python: sorting multilevel dictionary by part of key


code: edited = [factors[i] if i%2 else -factors[i] for i in range(len(factors))]

rawDescription: add a character in front of every element in a list

description: Add a character in front of every element in a list


code:
def swept_range(start, stop, step=1, sweep=1):
    for i in range(start, stop):
        if not 0 < i % sweep < step:
            yield i

rawDescription: Python: Create a range of ordered numbers skipping the inverse of every Nth through Nth+D number


rawDescription: Numpy: How to resize an random array using another array as template


code:
from numba import autojit
def pysumeq(a, b):
    tot = 0
    for i in xrange(a.shape[0]):
        for j in xrange(a.shape[1]):
            if a[i,j] == b[i,j]:
                tot += 1
    return tot
# make numba version
nbsumeq = autojit(pysumeq)
A = (rand(10,10)<.5)
B = (rand(10,10)<.5)
# do a simple dry run to get it to compile
# for this specific use case
nbsumeq(A, B)

rawDescription: Numpy sum of operator results without allocating an unnecessary array


code:
ids = []
for sublist in li:
  subnums = map(lambda x: d[x], sublist)
  ids.append(sublist[subnums.index(max(subnums))])

rawDescription: Python - a clean approach to this problem?


code:
while i > 0:
    print("do something")
    n /= 2.0

rawDescription: Python: How to create a C type for loop for a geometrical progression?


code:
from pyparsing import *
integer = Word(nums)
patt = Word(alphas) + OneOrMore(Group(integer*4 + Suppress(',')))

rawDescription: How can I build a regular expression which has options part

description: Build a regular expression which has options part


code: im = im.resize(maxsize)

rawDescription: how to fit image to label in Python

description: Fit image to label in Python


code:
ax = plt.gca()
ax.set_xticks([1, 2.5, 4])
ax.set_xticklabels(["a", "b", "c"])

rawDescription: How to label certain x values

description: Label certain x values


rawDescription: Way of using sorted function in a different manner?


rawDescription: Sub matrix of a list of lists (without numpy)


code: a = '2{}'.format(b64encode(plain))

rawDescription: Understanding a custom encryption method in python


code:
def shift(data, amount):
    data = data[:-amount]
    pad = (amount, 0)
    return np.pad(data, pad, mode='constant', constant_values=(np.nan,))

rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code: print("The value of {0} is {1}".format("foo", 5))

rawDescription: Please provide an example of the .format() function where the index field is left blank


code: Button = namedtuple("Button", ['name','action'])

rawDescription: Pyqt4 accessing objects when creating a dynamic form


code: return [q.get() for _ in xrange(len(job_list[:50]))]

rawDescription: Thread/Queue hanging issue

description: Thread/Queue hanging issue


code: self.st = [ Node( 0 ) ] * N * 4;

rawDescription: Simple code in python causing unexpected behaviour


code:
from unittest import TestCase
from mock import patch
import twitter
from my_module import get_tweets

class MyTestCase(TestCase):
    def test_ok(self):
        with patch.object(twitter.Api, 'GetSearch') as search_method:
            search_method.return_value = [{'tweet1', 'tweet2'}]

            self.assertEqual(get_tweets('blabla'), [{'tweet1', 'tweet2'}])

rawDescription: Programming a web API with test driven development


code:
from nltk import bigrams
import collections

a= """When the defendant and his lawyer walked into the court, some of the victim supporters turned their backs on him.  if we have more data then it will be more interesting because we have more chance to repeat bigrams. After some of the victim supporters turned their backs then a subset of the victim supporters turned around and left the court."""

a1=a.split()
a2=collections.Counter(a1)

a3=collections.Counter(bigrams(a1))
a4=sum([a2[x]for x in a2])
a5=sum([a3[x]for x in a3])
a6={x:float(a2[x])/a4 for x in a2} # word probabilities(w1 and w2)
a7={x:float(a3[x])/a5 for x in a3} # joint probabilites (w1&w2)
u = {}
v = {}
for x in a6:
  k={x:round(math.log((a7[b]/(a6[x] * a6[y])),2),4) for b in a7 for y in a6 if x and y in b}
  u[x] = k[x]
  k={x:round(math.log((a7[b]/(a6[x] * a6[y])),2),4) for b in a7 for y in a6 if x in b and y in b}
  v[x] = k[x]

u['the']
v['the']

rawDescription: Computing Pointwise Mutual Information of a text document using python


code:
def __getattr__(self, attr):
    if attr in self.backend.get_allowed_attr():
        return getattr(self.backend, attr)
    else:
        raise AttributeError('No attribute named ' + attr)

rawDescription: Pythonic Way to set Multiple Properties Based on another class


code: s = map(float, s)

rawDescription: Tab separated data python

description: Tab separated data python


code:
c = df.groupby(["A","C"]).cumcount()
c = c.replace(0, '').astype(str)
df["A"] += c
df

rawDescription: pandas change a specific column value of duplicate rows

description: Pandas change a specific column value of duplicate rows


code:
for x, y, prop in ((Item1, Item2, 'a'), (Item1, Item2, 'b')):
    yprop = getattr(y, prop)
    if getattr(x, prop) != yprop:
        setattr(x, prop, yprop)

rawDescription: How to change object variables in for loop in python

description: Change object variables in for loop in python


code:
class TopicLabel(models.Model):
    ...
    topics = models.ManyToManyField(Topic, through=TopicLabelConnection)

rawDescription: How to display elements of a Many-To-Many relation in Django?

description: Display elements of a Many-To-Many relation in Django


code: y = (name[count], i)

rawDescription: enumerate is iterating of letters of strings in a list instead of elements

description: Enumerate is iterating of letters of strings in a list instead of elements


code: b = module1.Button(command=lambda: do_whatever(some, arguments))

rawDescription: Call a function from main script in an imported file


code:
def make_eigenpaws(paw_data):
    """Creates a set of eigenpaws based on paw_data.
    paw_data is a numdata by numdimensions matrix of all of the observations."""
    average_paw = paw_data.mean(axis=0)
    paw_data -= average_paw

    # Determine the eigenvectors of the covariance matrix of the data
    cov = np.cov(paw_data.T)
    eigvals, eigvecs = np.linalg.eig(cov)

    # Sort the eigenvectors by ascending eigenvalue (largest is last)
    eig_idx = np.argsort(eigvals)
    sorted_eigvecs = eigvecs[:,eig_idx]
    sorted_eigvals = eigvals[:,eig_idx]

    # Now choose a cutoff number of eigenvectors to use
    # (50 seems to work well, but it's arbirtrary...
    num_basis_vecs = 50
    basis_vecs = sorted_eigvecs[:,-num_basis_vecs:]

    return basis_vecs

rawDescription: How to sort my paws?

description: Sort my paws


code: filter(lambda pic: pic.endswith('jpg'), pictures)

rawDescription: Python - FOR loop to remove list items by file extension


code: os.path.splitext('Zipped Party Food Invoice 22.09.2011.xlsx.zip')

rawDescription: Renaming files according to a set of rules


code: import thread, time, itertools

rawDescription: How to make an action happen every minute in Python

description: Make an action happen every minute in Python


code:
s = "Pizza"
for c in s:
    c = c.upper() # to fold lowercase into upper case
    if c in Characters:
        Characters[c](width)

rawDescription: How to write a python program that read the input and convert it to pre-defined 14-segments characters with turtle graphics?

description: Write a python program that read the input and convert it to pre-defined 14-segments characters with turtle graphics


rawDescription: What representation should I use in Pandas for data valid throughout an interval?


code:
...
gameisplaying = False
while True:
    thesurface.fill(overlay)
    thesurface.blit(menu1, (400,400))
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP:
            pos = pygame.mouse.get_pos()

            gameisplaying = True
    break
# run the game loop
while gameisplaying:
   ...

rawDescription: Pygame: Initial menu leading up to game loop


code:
Y
X
Z

rawDescription: Iterate over unknown object attributes in Python


code:
iPhone = 'Original 3G 3GS 4 4S 5 5C 5S 6 6Plus'.split()
len(iPhone)
iPhone[0]  # Python indexes start at 0
iPhone[9]  # So the max index is 9, not 10
iPhone[10]

rawDescription: List index out of range and random number to choose an item in list


code:
@memo
def id(x): return x
id(1)
id(2)
id.memo

rawDescription: Why is a line in this python function necessary? (memoized recursion)


rawDescription: How to delete duplicate values in a list?

description: Delete duplicate values in a list


code:
# makes a new inner list for every m
b = [[0.0]*len(a[0]) for m in xrange(len(a))]

rawDescription: Assigning values to a list, identity

description: Assigning values to a list, identity


code:
import ipaddr
mask = ipaddr.IPv4Network('192.192.45.1/25')
mask.netmask

rawDescription: Get IP Mask from IP Address and Mask Length in Python


code: translation = myDict['fast car']

rawDescription: Scanning for two word phrase in Python dictionary


code: [a - int(a) for a in l]  # works with negatives too

rawDescription: From a list of floats, how to keep only mantissa in Python?


code:
for link in soup.findAll('a', {'class': 'hoverbuy a-color'}):
    href.append(link.get('href'))

for title in soup.findAll('span', {'class': 'title ellipsis'}):
    name.append(title.string)

for price in soup.find_all('div', {'class': 'itm-price'}):
    fprice= price.get_text()
    newprice.append(fprice.replace("৳", ""))

rawDescription: Python MySQL data insert

description: Python MySQL data insert


code:
class ClassMethod(object):
    "Emulate PyClassMethod_Type() in Objects/funcobject.c"

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

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        def newfunc(*args):
            return self.f(klass, *args)
        return newfunc

rawDescription: Can the staticmethod and classmethod decoraters be implemented in pure Python?


code: os.system("C:\\FIOCheck\\xutil.exe  -i get phy" +HBEA + ">C:\\FIOCheck\\HBEAResult.txt")

rawDescription: os.system commands

description: Os.system commands


code:
import datetime
dt = datetime.date(2013,12,30)
w = datetime.timedelta(weeks=1)
dt - w
dt + w
dt + 10 * w

rawDescription: How to get week start dates and week number of each week in a year considering start day of the week is Monday in python?

description: Get week start dates and week number of each week in a year considering start day of the week is Monday in python


code:
import sys
import random
import pygame

pygame.init()
screen = pygame.display.set_mode((1000,400))
colour = (0, 255, 0)
array = [random.randint(100, 400) for c in range(5)]

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    linewidth = 40
    for i, b in enumerate(array):
        x = i*linewidth*2 + linewidth//2
        pygame.draw.line(screen, colour, (x, 400), (x, (400-b)), linewidth)

    pygame.display.update()

rawDescription: pygame draw function

description: Pygame draw function


code:
from collections import OrderedDict
d = {'Gears of war 3': 6, 'Batman': 5, 'gears of war 3': 4, 'Rocksmith': 5, 'Madden': 3}
od = OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True))
od
od.keys()
od.values()
od['Batman']

rawDescription: convert a dict to sorted dict in python

description: Convert a dict to sorted dict in python


rawDescription: How to randomly extract FASTA sequences using Python?

description: Randomly extract FASTA sequences using Python


code:
test = raw_input("answer ")
type(test)
test = int(raw_input("answer "))
type(test)

rawDescription: Python maths does not multiply, it uses string instead?


code:
import inspect

allowed_vars = set(["min_", "max_", "path", ...])
def update_globals(dic):
    caller_frame = inspect.currentframe(1)
    globals = caller_frame.f_globals
    # here, you _could_ simply do globals.update(dic)
    # but it is  evil
    for key, value in dic.items():
        #here you shuld carefullyt verify each key, and value for not
        #not dangerous pairs, with stuff like:
        #if key not in allowed_vars:
        #    sys.stderr.write("Warning: invalid variable in configuration update\n")
        #     continue
        #if type(value) not in (string, int, float):
        #    #(issue error)
        #    continue
        globals[key] = value

rawDescription: How can I load all keys from a dict as local variables, a better aproach?

description: Load all keys from a dict as local variables, a better aproach


code:
import android

droid = android.Android()

title=("Your Tittle")
content=("Your content")

droid.dialogCreateAlert(title, content)
droid.dialogShow()

rawDescription: Show data on android desktop with SL4A Python (example)


rawDescription: Copying some data of a file and pasting it to another file in python


code:
def pre_save(self, obj):
    obj.user = self.request.user
    super(ToDoResponder, self).pre_save(obj)

rawDescription: Use request.user for model deserialization in django rest framework


rawDescription: Reimplementing function using regular expression


code: yourdomain/admin

rawDescription: Unable to find course mode in edx as superuser


code:
#Problem 2
P2 = 0
fib= 0
f1 = 1
f2 = 0
debugP2 = []
while fib < 4000000:
    fib = f1 + f2
    f2 = f1
    f1 = fib
    if fib % 2 == 0:
        P2 += fib
        debugP2.append(fib)
print(P2) # Its not fib

rawDescription: Why does this not work for project euler part 2? (Python) project euler instructions included


rawDescription: Initialising a large dict with unknown keys? Is there a better way than this?


rawDescription: Matching filenames containing a particular string in delimited format


code:
class MyButtonGroup(QtCore.QObject):
    trigger = QtCore.pyqtSignal(bool)

    def addButton(self, button):
        button.clicked.connect(self.trigger.emit)

    def removeButton(self, button):
        button.clicked.disconnect(self.trigger.emit)

group = MyButtonGroup()
button1 = QtGui.QPushButton("button1")
button2 = QtGui.QPushButton("button2")
group.addButton(button1)
group.addButton(button2)
group.trigger.connect(do_something)

rawDescription: How to group buttons in pyQT

description: Group buttons in pyQT


code:
# viewsets.py
class UserViewSet(ListCreateAPIView):
    queryset = User_Data.objects.all()
    serializer_class = User_Data_Serializers

# urls.py
router = DefaultRouter()
router.register(r'users', UserViewSet, 'users')
urlpatterns = router.urls

rawDescription: Not getting forms to post data in Django REST framework


code:
from itertools import product, izip, tee

n = 3
[("{}"*n).format(*p)  for p in product(range(3), repeat=n) if check(p)]
n = 4
[("{}"*n).format(*p)  for p in product(range(3), repeat=n) if check(p)]

rawDescription: Equality in Python's list-comprehension

description: Equality in Python's list-comprehension


code:
class A:
    def __init__(self):
        self.odd = 7
class B:
    def __init__(self):
        self.number = A()
value = B()
value.number.odd
x = 'number.odd'
reduce(getattr, x.split('.'), value)

rawDescription: How can I use getattr to access an attribute within an attribute?

description: Use getattr to access an attribute within an attribute


code:
threads = Thread.tree.all()
data = {
    'nodes':threads
}
return render_to_response("show.html",data )

rawDescription: django-mptt not linking data together correctly

description: Django-mptt not linking data together correctly


code:
a = np.random.rand(3, 5, 4)
b = np.random.rand(6, 5)
out_ein = np.einsum('ijk,lj->ilk', a, b)
out_dot = np.transpose(np.dot(np.transpose(a, (0, 2, 1)),
                              np.transpose(b, (1, 0))),
                       (0, 2, 1))
np.allclose(out_ein, out_dot)

rawDescription: Convert einsum computation to dot product to be used in Theano


code:
a = np.ascontiguousarray(A).view(np.dtype((np.void, A.shape[1]*min(A.strides))))
b = np.ascontiguousarray(B).view(np.dtype((np.void, B.shape[1]*min(B.strides))))

check = np.in1d(a, b)
C = np.where(check)[0]
D = A[check]

check = np.in1d(b, a)
E = np.where(check)[0]

rawDescription: 'Remove' command for ND arrays in Python


rawDescription: What is a cell in the context of an interpreter or compiler?


code:
def foo():
    if conditional():
        logger.info("<Conditional's meaning> happened, so we're not " +
                    "setting up the interface.")

dis.dis(foo)

rawDescription: How to cleanly keep below 80-char width with long strings?

description: Cleanly keep below 80-char width with long strings


code: anAckTxSOCKET.send( topicfilter )                        # ACK with an "identity"-proxy

rawDescription: Python and ZeroMQ subscriber acknowledgement to publisher


rawDescription: Python Regular Expression with optional but greedy groups


code:
bar_tops(np.arange(10), np.sort(np.random.rand(10)), lw=2)
plt.show()

rawDescription: Matplotlib Bar Customization

description: Matplotlib Bar Customization


code:
def rangesOverlap(x1, x2, y1, y2):
    return (x1 <= y2) and (y1 <= x2)

fileSetToRangesMap = {}
for i, r in enumerate(allRanges):
    fileSet = set([r[3]])
    x1 = r[1]
    x2 = r[2]
    for j, r2 in enumerate(allRanges):
        y1 = r2[1]
        y2 = r2[2]
        if (r[0] == r2[0]) and rangesOverlap(x1, x2, y1, y2):
            fileSet.add(r2[3])
    fileSetToRangesMap.setdefault(frozenset(fileSet), []).append(r)

rawDescription: Python Compare overlap of multiple dictionaries of ranges


code:
logging.config.fileConfig('logging.config',
                          defaults={'logfilename': '/path/to/log/file'})

rawDescription: Python change logfile location at runtime


code:
def parse(self, response):
    # Loop all the product elements, those div elements with a "listing-item" class
    for product in response.xpath('//div[@class="listing-item"]'):
        # Create an empty item container
        item = ArcherItemGeorges()
        # Scrape the primary product name and keep in a variable for later use
        product_name = product.xpath('.//*[@class="product-shop"]/h5/a/text()').extract()[0].strip()
        # Fill the 'product' field with the product name
        item['product'] = product_name
        # Fill the 'price' field with the scraped primary product price
        item['price'] = product.xpath('.//*[@class="price-box"]/span/span[@class="price"]/text()').extract()[0].strip()
        # Yield the primary product item. That with the primary name and price
        yield item
        # Now, for each product, we need to loop through all the subproducts
        for subproduct in product.xpath('.//*[@class="more-views"]/following-sibling::div'):
            # Let's prepare a new item with the subproduct appended to the previous
            # stored product_name, that is, product + subproduct.
            item['product'] = product_name + ' ' + subproduct.xpath('a/text()').extract()[0].strip()
            # And set the item price field with the subproduct price
            item['price'] = subproduct.xpath('text()[2]').extract()[0].strip()
            # Now yield the composed product + subproduct item.
            yield item

rawDescription: SOLVED: How do I create a "Nested Loop" that returns an item to the original list in Python and Scrapy


code:
class Profile(models.Model):
    ...
    medias = models.ManyToManyField(Media, related_name='profiles')
    roles = models.ManyToManyField(Role, related_name='profiles')

rawDescription: How to describe m2m triple-join table in model (Django)

description: Describe m2m triple-join table in model (Django)


code:
class Settings(object):
    def __init__(self, foo=None, bar=None):
        self.foo = foo if foo is not None else True
        self.bar = bar if bar is not None else False

rawDescription: how to override default values needed by function in module?

description: Override default values needed by function in module


rawDescription: How to customize sklearn cross validation iterator by indices?

description: Customize sklearn cross validation iterator by indices


rawDescription: Filter DataFrame based on Max value in Column - Pandas


code:
mask3 = listed_array[:, 3:]
A3 = A[:, 3:]   # This slice is a *view* of A, so changing A3 changes A.
A3[mask3] = 0

rawDescription: How to index numpy array on subset of array of bools that is smaller than numpy array's dimensions?

description: Index numpy array on subset of array of bools that is smaller than numpy array's dimensions


code:
def dir_change_callback(dwErrorCode,dwNumberOfBytesTransfered,p):
     print("dir_change_callback! PID:" + str(os.getpid()))
     print("CALLBACK THREAD: " + str(threading.currentThread()))

rawDescription: Watchdog compatibility: A workaround for "CancelIoEx"


code: m.function = decorator(m.function)

rawDescription: How to retrieve arguments from a "fluid" decorated function

description: Retrieve arguments from a "fluid" decorated function


code:
import pandas as pd
import numpy as np
mySeries = pd.Series(np.arange(start=1, stop=5, step=1))

def myFun(val):
    return pd.Series([val ** 2, val ** 3], index=['square', 'cube'])

myResult = mySeries.apply(myFun)
print(myResult)

rawDescription: Take a Pandas Series where each element is a DataFrame and combine them to one big DataFrame


code:
data = {
    "people" : {
        "Alice" : {
            "position" : "Manager",
            "company" : "Company1"
        },
        "Bob" : {
            "position" : "CEO",
            "company" : "Company1"
        },
        "Charlie" : {
            "position" : "CEO",
            "company" : "Company2"
        }
    },
    "companies" : [
        { "name" : "Company1" },
        { "name" : "Company2" }
    ]
}

rawDescription: Efficiently find objects satisfying relationship


code:
from itertools import repeat

def nest(func, x, times):
     result = [x]
     result_append = result.append
     for _ in repeat(None, times):
         x = func(x)
         result_append(x)
     return result

rawDescription: Iterated function in Python

description: Iterated function in Python


code:
import time
from garden import Garden
from threading import Thread

def main():
    garden = Garden()
    thr = Thread(target=garden.grow)
    thr.start()
    water(garden, 20)
    time.sleep(5)
    water(garden, 30)
    time.sleep(5)
    water(garden, 10)
    thr.join()

def water(garden, amount):
    garden.water += amount
    print("Watered with {0}!".format(amount))

main()

rawDescription: How to increment class field within a Thread in python?

description: Increment class field within a Thread in python


code:
for i in textfile1:
    row = [int(j) for j in i.split()]
    num += row

rawDescription: Recreating a sentence using two text files (Python)


code:
def seq_pow2(N):
    shp = 2*np.ones(np.log2(N),dtype=int)
    return np.arange(N).reshape(shp).ravel('F')

rawDescription: Iterate through a dynamic number of for loops (Python)


code:
{(i, j): {} for i in range(4) for j in range(4)}
from itertools import product
{(i, j): {} for i, j in product(range(4), repeat=2)}

rawDescription: Dictionary assignment to tuple-keys in other dictionary with map() function


code:
from tkinter import *
from tkinter import filedialog
from tkinter import ttk

def folderDiag():
    scanfolder.set(filedialog.askdirectory())

root = Tk()

c = (N, W, S, E)
scanfolder = StringVar()

root.title("Testing")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

frame = ttk.Frame(root, padding="3")
frame.grid(column=0, row=0, sticky=c)
frame.columnconfigure(0, weight=0)
frame.columnconfigure(1, weight=1)
frame.columnconfigure(2, weight=0)
frame.rowconfigure(0, weight=1)
frame.rowconfigure(1, weight=1)
frame.rowconfigure(2, weight=1)
ttk.Label(frame, text="Welcome!",
          font="TkDefaultFont 24 bold").grid(column=0, row=0, columnspan=3,
                                             sticky=c)
ttk.Label(frame, text="Select folder to scan:").grid(column=0, row=1, sticky=E)
ttk.Label(frame, textvariable=scanfolder, justify=LEFT).grid(column=0, columnspan=3, row=2, sticky=W)

scan_folder_entry = ttk.Entry(frame, textvariable=scanfolder)
scan_folder_entry.grid(column=1, row=1, sticky=EW)
browse_button = ttk.Button(frame, text="Browse...",
                           command=folderDiag)
browse_button.grid(column=2, row=1)

root.mainloop()

rawDescription: Prevent Label to be re-aligned after askdirectory() is closed


rawDescription: Write each list as a column in csv table


rawDescription: Python's regex module: repeating 'backreferences' does not appear to work correctly


code:
from datetime import datetime
def parsedate(s):
    return datetime.strptime(s, '%M-%d-%Y')
keys = [parsedate(x[0]) for x in A]

rawDescription: Get Elements between two dates from a list


rawDescription: Python - nmap scan without looking for specific ports


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

rawDescription: Conventions for 'import ... as'

description: Conventions for 'import ... as'


code: replace("banana", "a", "e")

rawDescription: Replacing a character in a stringin Python


code: pdf = distr.pdf(abscissas, *param)

rawDescription: Getting a pdf from scipy.stats in a generic way


code:
Foo() # calls Foo()
Foo(True) # calls Foo(bool)
Foo(1) # calls Foo(int)
Foo(4.2) # calls Foo(double)

rawDescription: boost.python confused about similar constructor

description: Boost.python confused about similar constructor


rawDescription: SymPy express variable in terms of another


code: player_list = [Player() for _ in xrange(players)]

rawDescription: Generating Multiple Duplicate Objects

description: Generating Multiple Duplicate Objects


code: ['اقترح', 'احداث', 'موسس', 'راد', 'تسيس', 'احداث']

rawDescription: Python storing Arabic in an Array?

description: Python storing Arabic in an Array


rawDescription: Python new style class can not use __dict__ to update property attribute


code:
import datetime
from google.appengine.ext import db
from google.appengine.tools import bulkloader

class PostalCode(db.Model):
  id = db.IntegerProperty()
  postal_code = db.PostalAddressProperty()
  city = db.StringProperty()
  province = db.StringProperty()
  province_code = db.StringProperty()
  city_type = db.StringProperty()
  geo_pt = db.GeoPtProperty()

class PostalCodeLoader(bulkloader.Loader):
  def __init__(self):
    bulkloader.Loader.__init__(self, 'PostalCode',
                               [('id', int),
                                ('postal_code', str),
                                ('city', str),
                                ('province', str),
                                ('province_code', str),
                                ('city_type', str),
                                ('geo_pt', str)
                               ])

loaders = [PostalCodeLoader]

rawDescription: AppEngine GeoPt Data Upload

description: AppEngine GeoPt Data Upload


code:
def even_factorial(X):
    x = 1
    for position in range(2, X + 1, 2):
        x = factorial_recurrence(factorial_recurrence(x, position - 1), position)
    return x

rawDescription: Issues with Recursion using Python 3

description: Issues with Recursion using Python 3


code:
from operator import itemgetter

best = (0, [])
maxes = [max(c) for c in zip(*a.values())]
for k, v in a.iteritems():
    v = a[k] = [c/m for c, m in zip(v, maxes)]
    best = max([best, (sum(v), v)], key=itemgetter(0))

rawDescription: normalise list data in range (0.0, 1.0)

description: Normalise list data in range (0.0, 1.0)


code:
models.py
from django.db import models
from django.contrib.auth.models import User

class Speaker(models.Model):
    user = models.OneToOneField(User)

    @property
    def user__username(self):
        return self.user.username

    def __unicode__(self):
        return self.user.username

rawDescription: django rest framework lookup_field through OneToOneField

description: Django rest framework lookup_field through OneToOneField


code:
#!/usr/bin/env python

import sys
# other imports...

INDEX = sys.argv[1]
CROSS = sys.argv[2]
TRACE = sys.argv[3]

...

if INDEX == 'blit': # instead if os.environ.get('INDEX')
  RangeIndex = BlitRangeIndex

...

rawDescription: Confusion about environmental variables in python


code:
from numpy.lib.stride_tricks import as_strided

def stridetrick_einsum(c, rho, out):
    ws = len(c)
    nx, nz = rho.shape

    shape = (nx-ws+1, ws, nz)
    strides = (rho.strides[0],) + rho.strides
    rho_windowed = as_strided(rho, shape, strides)

    np.einsum('j,ijk->ik', c, rho_windowed, out=out)

a = np.zeros((nx, nz))
stridetrick_einsum(c, rho[1:-1,2:-3], a[2:-3,2:-3])
b = np.zeros((nx, nz))
stridetrick_einsum(c, rho[0:-2,2:-3], b[2:-3,2:-3])

rawDescription: Optimize Double loop in python

description: Optimize Double loop in python


code:
for dirpath, dirnames, filenames in os.walk(path):
    print(dirpath, dirnames, filenames)

rawDescription: Using os.walk inside a Tkinter mainloop

description: Using os.walk inside a Tkinter mainloop


code:
def save(self, *args, **kwargs):
    super(YourModelName, self).save(*args, **kwargs)
    remote = OtherModel(
        id = self.id,
        some_field = self.some_field,
        another_field = self.another_field,
    )
    remote.save(using='orcl')

rawDescription: Push table data from django postgres model to remote oracle database


code: data = {k: [] for k in range(2)}

rawDescription: How do I initialize a dictionary of empty lists in Python?

description: Initialize a dictionary of empty lists in Python


code: del dct[key]

rawDescription: Delete a key and value from an OrderedDict


code:
import cython

@cython.locals(
    chars=unicode,
    i=cython.Py_ssize_t,
    L=cython.Py_ssize_t[0x10000])
def countchars_cython(chars):
    for i in range(0x10000): # unicode code points > 0xffff are not supported
        L[i] = 0

    for c in chars:
        L[c] += 1

    return {unichr(i): L[i] for i in range(0x10000) if L[i]}

rawDescription: Python - Is a dictionary slow to find frequency of each character?


code:
def enumerate_nested(nested, indices):
    for i, item in enumerate(nested):
        if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
            for new_indices in enumerate_nested(item, indices + (i,)):
                yield new_indices
        else:
            yield indices + (i,)

rawDescription: Navigate manually with a cursor through nested lists by only providing "left()" and "right()" as commands?


rawDescription: Indexing by multiple fields with pandas in python


rawDescription: Python Recursive Spiral List Printing

description: Python Recursive Spiral List Printing


code:
template = Template(report.markup)
template.render(report=report)

rawDescription: If jinja markup is in string format, how do I use it in django and jinja2?


code:
class UploadFileForm(ModelForm):
    def save(self, commit=True):
        instance = ModelForm.save(self, commit=False)
        instance.filename = self.files['theFile'].name

        if commit:
            instance.save()

        return instance

    class Meta:
        model = UploadFile
        fields = ('title', 'theFile', 'date_uploaded',) # Don't prompt for filename

rawDescription: Django file upload: filename not sticking


code:
def g():
    ...
g = update_wrapper(g, f)

rawDescription: what is the difference between functools.wraps and update_wrapper

description: What is the difference between functools.wraps and update_wrapper


code: help(function)

rawDescription: How do I find information about a function in python?

description: Find information about a function in python


code: dict([(1, None), ("1foo", None), ("foo2bar3", None)])

rawDescription: How to construct a dictionary which contain keys which are invalid keyword arguments, not using {}

description: Construct a dictionary which contain keys which are invalid keyword arguments, not using {}


code: #!/usr/bin/python

rawDescription: How do I make a custom system command out of my Python program?

description: Make a custom system command out of my Python program


code:
your_data = b'\x00\x12abc'
b = bytearray(your_data)
b[0]
b[1]

rawDescription: Unpack BinaryString sent from JavaScript FileReader API to Python


rawDescription: Is there a Python idiom for creating dot folders in home directory?


code:
def generer(self):
    with open(self.fichier) as fichier:
        self.structure = [ligne.split() for ligne in fichier]

rawDescription: How to correctly parse a tiled map in a text file?

description: Correctly parse a tiled map in a text file


code: key=lambda x: x != 2

rawDescription: Make a new sublist of preceding characters every time there's a zero in a list, excluding the zero


code:
['object1' , 'object2' , 'object3'] == ['object1' , 'object2' , 'object3']
['object1' , 'object2' , 'object3'] == ['object3', 'object1' , 'object2' ]
[['object1' , 'object2'] , ['object3']] == [['object1' , 'object2'] ,['object3']]
[['object1' , 'object2'] , ['object3']] == [['object1' , 'object2'] , 'object3']

rawDescription: How to check if two lists have the same objects in the same order?

description: Check if two lists have the same objects in the same order


rawDescription: Can some one explain me what does np.log do?


code: np.where(ibound & (abs(h - nodata) <= eps), L1TopOld, h)

rawDescription: Efficient way to do conditional checks on Numpy Arrays


code: c=[element.split(':') for element in b]

rawDescription: Slicing a python string with intervals?

description: Slicing a python string with intervals


code:
uppercase_len1 = CharacterRange(string.uppercase, 1)
len(uppercase_len1)
uppercase_len5[0]
uppercase_len5[-1]
uppercase_len1[10]
uppercase_len1[24]
uppercase_len5 = CharacterRange(string.uppercase, 5)
len(uppercase_len5)
uppercase_len5[0]
uppercase_len5[-1]
uppercase_len5[1024]
uppercase_len5[1355453]

rawDescription: Generate 2 Unique but random Elements in a List


code:
[
    'bg.APDS.UnitTests.vbproj'
    'bg.DatabaseAPI.UnitTests.vbproj'
    'bg.DataManagement.UnitTests.vbproj'
    'bg.FormControls.UnitTests.vbproj'
]

rawDescription: Getting rid of empty strings in a tuple

description: Getting rid of empty strings in a tuple


code: c = a[1::2]  # Start at second element, then every other.

rawDescription: split list into 2 lists corresponding to every other element

description: Split list into 2 lists corresponding to every other element


code:
def step_mask2(x,limit=+1):
    b = np.broadcast(x, limit)
    out=np.zeros(b.shape)

    out[np.where(x>0)]=1

    zeroindices=np.where(x==0)
    check=out[zeroindices]

    check=np.where(limit>0,1,check)
    check=np.where(limit==0,.5,check)
    check=np.where(limit<0,0,check)
    out[zeroindices]=check

    return out

rawDescription: Numpy zero rank array indexing/broadcasting


code: df = pd.read_csv('sample.csv', dtype={'uid':str}, index_col='uid')

rawDescription: How to read index data as string with Python pandas?

description: Read index data as string with Python pandas


code:
print_lattice_edges([[0, 1], [0, 1]])  # your example
print_lattice_edges([[0, 1], [3, 4, 5]])  # 2x3 points, 7 edges
print_lattice_edges([[0, 1], [0, 1], [0, 1]])  # cube, 12 edges

rawDescription: Transforming lattice into graph?

description: Transforming lattice into graph


code:
a, b, c = multi_return()
a
b
c

rawDescription: Returning multiple values in a python function


code: f['Adj Close'].iloc[:8, :2]

rawDescription: how to pick out individual columns of numerical values from Datareader pandas?

description: Pick out individual columns of numerical values from Datareader pandas


code:
parse_number('1337')
parse_number('8.1k')
parse_number('8.1M')
parse_number('64.367G')

rawDescription: Formatting "Kilo", "Mega", "Gig" data in numpy record array


code:
if data['character1']['health'] <= 0:
    data['character1']['lives'] -= 1

rawDescription: Overwrite flags in a file python

description: Overwrite flags in a file python


code:
from itertools import groupby
string = 'aabccccaaa'
[list(g) for k, g in groupby(string)]
''.join(['{}{}'.format(k, sum(1 for _ in g)) for k, g in groupby(string)])

rawDescription: Run Length Encoding in Python with List Comprehension


rawDescription: Fastest way to draw a ton of squares?

description: Fastest way to draw a ton of squares


rawDescription: String manipulation in Python (All upper and lower case derivatives of a word)


code:
from django.conf import settings
FOO = getattr(settings, 'FOO', "default_value")

rawDescription: Django default settings convention for pluggable app?