code: map(lambda x:int(x,16),a)

rawDescription: How to use map for converting a list of decimals to hex in python

description: Use map for converting a list of decimals to hex in python


code:
db_emails = [ doc['email'] for doc in coll.find({}, projection = {'email':1, '_id':0}) if doc ]
common_emails = set(emails) & set(db_emails)

rawDescription: Filter a list of elements for membership in MongoDB


code:
import re
bolded = bolded = re.sub(r"(?i)(%s)" % query, r"<b>\1</b>", content)

rawDescription: Boldening parts of string ignoring case python,HTML


code:
a = int(ipaddress.ip_address('192.0.43.10'))
a = struct.unpack('!I', socket.inet_pton(socket.AF_INET, '192.0.43.10'))[0]
a = struct.unpack('!I', socket.inet_aton('192.0.43.10'))[0]  # IPv4 only

rawDescription: Python - ip <-> subnet match?

description: Python - ip <-> subnet match


code:
import os

def detect_tasks(project_root):
    tasks = []
    file_path = os.path.join(project_root, 'apps')
    for root, dirs, files in os.walk(file_path):
        for filename in files:
            if os.path.basename(root) == 'tasks':
                if filename != '__init__.py' and filename.endswith('.py'):
                    task = os.path.join(root, filename)\
                        .replace(os.path.dirname(project_root) + '/', '')\
                        .replace('/', '.')\
                        .replace('.py', '')
                    tasks.append(task)
    return tuple(tasks)

rawDescription: Celery discover tasks in files with other filenames


rawDescription: Get entries by values in child model

description: Get entries by values in child model


rawDescription: Converting values of dictionary to the timestamp format


code: [[] for i in range(11)]

rawDescription: What are the difference in these two 2d arrays?


code:
from collections import Counter
from itertools import chain

check_list = [[[('1',), ('2',)]], [[('2',), ('3',)], [('3',), ('4',)]], [[('1',), ('3',)]]]

a_list = [('1',), ('2',), ('3',), ('4',)]

cn = Counter(a_list)

print(" ".join([str(t[0]) for t in cn]))
for chk in check_list:
    _cn = Counter(chain(*chk))
    diff = cn.viewkeys() - _cn
    for k  in cn:
        if k not in diff:
            print(_cn[k], end=" ")
        else:
            print(0, end=" ")
    print()

rawDescription: Python 2.7 creating a matrix from lists

description: Python 2.7 creating a matrix from lists


code:
inloop = True;
while inloop:
    bla
    if(something):
        inloop = false;

rawDescription: How could i repeatedly send messages through server socket in python?


code:
def main():
    inFile = open("data.txt")
    builder = TreeBuilder(inFile)
    pprint.pprint(builder.tree)

rawDescription: Refactoring to eliminate global variable in recursive function


code:
def get_cookie_domain(self, app):
    """Helpful helper method that returns the cookie domain that should
    be used for the session cookie if session cookies are used.
    """
    if app.config['SESSION_COOKIE_DOMAIN'] is not None:
        return app.config['SESSION_COOKIE_DOMAIN']
    if app.config['SERVER_NAME'] is not None:
        # chop of the port which is usually not supported by browsers
        rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]

        # Google chrome does not like cookies set to .localhost, so
        # we just go with no domain then.  Flask documents anyways that
        # cross domain cookies need a fully qualified domain name
        if rv == '.localhost':
            rv = None

        # If we infer the cookie domain from the server name we need
        # to check if we are in a subpath.  In that case we can't
        # set a cross domain cookie.
        if rv is not None:
            path = self.get_cookie_path(app)
            if path != '/':
                rv = rv.lstrip('.')

        return rv

rawDescription: How to configure a single flask application to handle multiple domains?

description: Configure a single flask application to handle multiple domains


code: sprite.rect.center = player.center_pos

rawDescription: Different size sprites in sprite sheet

description: Different size sprites in sprite sheet


code:
from django.template.loader import BaseLoader
from django.template.base import TemplateDoesNotExist

class TestTemplateLoader(BaseLoader):

    def __init__(self, *args, **kwargs):
        super(TestTemplateLoader, self).__init__(*args, **kwargs)
        self.is_usable = True

    def load_template_source(self, template_name, template_dirs=None):
        if template_name == 'test.html':
            return 'test.html', 'test.html'
        raise TemplateDoesNotExist

rawDescription: Django create a template just for testing


rawDescription: Replacing a line on Python

description: Replacing a line on Python


code: sTable = sTable + ('\n%s' % sRow)

rawDescription: Why is variable1 += variable2 much faster than variable1 = variable1 + variable2?


code: incrontab -e

rawDescription: Ensure end of file moving, then copy by other program


code:
def partitions(A):
    if not A:
        yield []
    else:
        a, *R = A
        for partition in partitions(R):
            yield partition + [[a]]
            for i, subset in enumerate(partition):
                yield partition[:i] + [subset + [a]] + partition[i+1:]

rawDescription: how find all groups of subsets of set A? Set partitions in Python

description: How find all groups of subsets of set A? Set partitions in Python


rawDescription: From list to tree representation

description: From list to tree representation


rawDescription: How to use a C# class library from an IronPython app in Visual Studio?

description: Use a C# class library from an IronPython app in Visual Studio


rawDescription: How to check if the keys of two dictionaries are the same

description: Check if the keys of two dictionaries are the same


rawDescription: Obtaining value from an array

description: Obtaining value from an array


rawDescription: How to validate an input to certain numbers?

description: Validate an input to certain numbers


code:
TODAY + three_mon_timedelta * 2
TODAY + three_mon_timedelta * 3
TODAY + three_mon_timedelta * 4

rawDescription: How do you add "3 months" to a datetime.date object in python?

description: Add "3 months" to a datetime.date object in python


rawDescription: Merging a list with a list of lists

description: Merging a list with a list of lists


code:
with open('filename') as f:
    myVar = [line.rstrip().split(':') for line in f]

rawDescription: Generate special list from file in python


code:
i='0'
count = 0
while i.isdigit():
    i = input("Enter a number: ")

rawDescription: python while loop user input

description: Python while loop user input


code:
class Whatever(object):
    def get_new_distance(self, old_distance, delta_time, rate):
        delta_distance = delta_time * rate
        new_distance = old_distance + delta_distance
        return new_distance

    def update(self):
       self.delta_time = time.time() - self.last_time_call
       self.last_time_call = time.time() #for use in the next update

       self.current_distance = \
           self.get_new_distance(self.current_distance, self.delta_time,\
           self.rate)

rawDescription: Calculate a distance in for racing game in python


rawDescription: A more complex version of "How can I tell if a string repeats itself in Python?"


code:
import abc

class Shape(object):
    __metaclass__ = abc.ABCMeta

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

    @abc.abstractmethod
    def number_of_edges(self):
        pass

rawDescription: Python base class that makes abstract methods definition mandatory at instantiation


rawDescription: Dictionary __gt__ and __lt__ implementation


code:
myarray=np.ones((2,3,4,5))
myarray[:,:,3,:].shape
myarray.take(3,axis=2).shape
ind=[slice(None)]*4; ind[2]=3
ind
myarray[tuple(ind)].shape

rawDescription: Indexing ndarray of variable number of dimensions


rawDescription: Django: List field in model?

description: Django: List field in model


code:
import random
L = range(1, 1000000)
random.shuffle(L)  # shuffles in-place

rawDescription: Unordered list generation in python

description: Unordered list generation in python


code:
def build_list(children, top):
    l = [ top ]
    if top['id'] in children:
        for child in children[top['id']]:
            l += build_list(children, child)
    return l

rawDescription: Building a list with a parent-child dependency


code:
import marshal
def foo(x): return x*x
code_string = marshal.dumps(foo.func_code)

rawDescription: Is there an easy way to pickle a python function (or otherwise serialize its code)?


code:
from log import setup_logger

class Communicator(object):

    def __init__(self, logger=None):
        if logger is None:
            logger = setup_logger(__name__)

        self.log = logger

    def send(self, data):
        self.log.info('Sending %s bytes of data' % len(data))

rawDescription: How to structure the Logging in this case (python)

description: Structure the Logging in this case (python)


code:
import subprocess

procs = []

for p in range(3):
        args = ['echo',"A Message from process #%d" % p]
        #Funnel stdout to a file object, using buffering
        fout = open("stdout_%d.txt" % p,'w')
        p = subprocess.Popen(args,stdout=fout,bufsize=-1)
        procs.append(p)

#Wait for all to finish
for p in procs:
    p.communicate()

rawDescription: Python - Capturing stdout of a multiple Popen subprocesses in real time to a file


code:
import invRegex
print(''.join(invRegex.invert('[a-z]')))
# abcdefghijklmnopqrstuvwxyz

rawDescription: Generate random string from regex character set


code:
def stem_and_syns(unformatted_string): #unformatted string is your stem_array
    stem_string = unformatted_string[1:-1] #same as before
    stem, synonyms_string = stem_string.split("|") #split the stem and synonyms
    stem = stem.strip() #clean the stem
    synonyms = [synonym.strip() for synonym in synonym_string.split(",")] #same as before
    return stem, synonyms

rawDescription: arrays using python

description: Arrays using python


code:
command = ["ffmpeg", "-i", "concat:1.ts|2.ts", "-vcodec", "copy",
           "-acodec", "copy", "temp.mp4"]
output,error  = subprocess.Popen(
                    command, universal_newlines=True,
                    stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

rawDescription: Passing double quote shell commands in python to subprocess.Popen()?


rawDescription: Dividing Histograms in Pandas

description: Dividing Histograms in Pandas


code:
ax = plt.subplot(111)
plt.plot(x, y)
plot.axis((0, 10, -5, 5))

rawDescription: matplotlib axis-independent version of set_xlim() and set_ylim()?

description: Matplotlib axis-independent version of set_xlim() and set_ylim()


rawDescription: Set global minimum logging level across all loggers in Python/Django


code: [x for x in dic if dic[x] > 1]

rawDescription: Selecting items in a dictionary using python


code:
import pandas as pd
import numpy as np
import numpy.testing.utils as NTU

nan = np.nan
x = pd.Series([nan, nan, nan, 13.109292, 12.623850, 12.150520])
a = 0.8408964152537145
z = pd.ewma(x, com=a/(1.0-a), adjust=False)

def nanzero(x):
    return 0 if np.isnan(x) else x

x.ffill(inplace=True)
y = [x[0]]
for xt in x[1:]:
    yt1 = y[-1]
    if np.isnan(yt1) and np.isnan(xt):
        yt = nan
    else:
        yt1 = nanzero(yt1)
        xt = nanzero(xt)
        yt = a*yt1 + (1-a)*xt
        # yt = (1-a)*yt1 + a*xt
    y.append(yt)
y = pd.Series(y)

NTU.assert_allclose(y,z)

rawDescription: Pandas EWMA not working as expected

description: Pandas EWMA not working as expected


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

nphi, nz = 70, 2
r = 1  # radius of cylinder
phi = np.linspace(0, 360, nphi) / 180.0 * np.pi
z = np.linspace(0, 1.0, nz)

PHI, Z = np.meshgrid(phi, z)
CP = r * np.cos(PHI)
SP = r * np.sin(PHI)
XYZ = np.dstack([CP, SP, Z])
verts = np.stack(
    [XYZ[:-1, :-1], XYZ[:-1, 1:], XYZ[1:, 1:], XYZ[1:, :-1]], axis=-2).reshape(-1, 4, 3)

cmap = plt.cm.rainbow
cols = cmap(np.random.random())
poly3 = Poly3DCollection(verts, facecolor=cols, edgecolor="none")

poly3.set_alpha(0.8)
ax.add_collection3d(poly3)
ax.set_xlabel('X')
ax.set_xlim3d(-1, 1)
ax.set_ylabel('Y')
ax.set_ylim3d(-1, 1)
ax.set_zlabel('Z')
ax.set_zlim3d(0, 1)
plt.show()

rawDescription: Rounding the edges of a cylinder in matplotlib poly3D


code:
dogFile = open('dogs.txt', 'r')
lines = dogFile.readlines()
dogFile.close()

newDogFile = open('newDogs.txt', 'w')
for line in lines:
    if 'dog:' in line or 'age:' in line or '--------------------' in line:
        newDogFile.write(line)
newDogFile.close()

rawDescription: Read and rewrite specific parts of a text file in python


code: new_index = pd.PeriodIndex([ pd.Period(year=year,month=month,freq='M') for year, month in df.index ]).to_timestamp()

rawDescription: How to change a groupby DF to a monthly datetime series in Python Pandas

description: Change a groupby DF to a monthly datetime series in Python Pandas


code:
def change_graph_representation(graph):
    reverse_graph = {}
    for node, links in graph.items():
        for link in links:
            if link not in reverse_graph:
                reverse_graph[link] = set()
            reverse_graph[link].add(node)

    result = {}
    for node,links in graph.items():
        adj = {}
        for link in links:
            for n in reverse_graph[link]:
                adj[n] = link
        del(adj[node])
        result[node] = adj
    return result

rawDescription: Python: How to find more than one pathway in a recursive loop when multiple child nodes refers back to the parent?


code:
for e in comb:
    if sum(l[1] for l in e) == max_sugar:
        print([l[0] for l in e])

rawDescription: How to select only integers in a list of strings/integers?

description: Select only integers in a list of strings/integers


code: [item.strip() for item in input_text.strip(" ()").split(",")]

rawDescription: Regexp for extracting data in parenthesis and commas


code:
combined = AudioSegment.empty()
for song in playlist_songs:
    combined += song

combined.export("/path/to/output.mp3", format="mp3")

rawDescription: Pydub concatenate mp3 in a directory

description: Pydub concatenate mp3 in a directory


code: word = input("Give me a 5 letter word: ")

rawDescription: Python how to find the number of characters in the user input


code:
import csv

def getTID(file='TID.csv', delim='\n'):
    result = []
    with open(file) as csvTID:
        readCSV = csv.reader(csvTID, delimiter=delim)
        for row in readCSV:
            result.append( row[0] )
    return result

stockList = getTID()
for x in stockList:
    print(x)

rawDescription: Python 3.5, how to remove the brackets and quotes from an element when printing or sending the value to a function?


rawDescription: Add multiple values to python dictionary


code:
serialThread = SerialThread(3)
serialThread.start()

def changeSleep():
    serialThread.setSleep(6)

time.sleep(15)
changeSleep()
time.sleep(15)

rawDescription: Seting parameter in other thread

description: Seting parameter in other thread


code:
import re
regex = re.compile(r'@(\d+):(\d+);(\d+):(\d+)')

def optionA(line):
    _id, info = line.split("@")
    data = {}
    for g_info in info.split(";"):
        k, v = g_info.split(":")
        data[k] = v
    return data

def optionB(line):
    _id, info = line.split("@")
    return dict(map(lambda i: i.split(":"), info.split(";")))

def optionC(line):
    data = regex.search(line).groups()
    return {data[0]:data[1],data[2]:data[3]}

line = 'A@1:100;2:240'

rawDescription: What is the best way to create a python dictionary from a string?


code: rows = [[field[k][i] for k in field.keys()] for i in xrange(2)]

rawDescription: Dictionary As Table In Django Template

description: Dictionary As Table In Django Template


code:
def chooseBest(s):
    if not s:
        return None
    best = chooseBest(s[1:])
    return s[0] if s[0] > best else best

rawDescription: Recursive comparison, can you point out my mistake?


code: mydict[obj.value] = obj

rawDescription: Is there a comparison key for set objects?


code:
from django.db.models import Avg

class ProductFilter(django_filters.FilterSet):
    ...

    @property
    def avg(self):
        qs = super(ProductFilter, self).qs

        return qs.aggregate(Avg('price'))['id__avg']

rawDescription: django-filter and aggregate functions

description: Django-filter and aggregate functions


code:
urlpatterns = patterns('',
  (r'^%s/' % settings.SUB_SITE, include('urls_subsite')),
)

rawDescription: Default redirect url in Django

description: Default redirect url in Django


code:
f = [os.path.splitext(e.name)[0] for e in os.scandir(r'C:\Users\username\Desktop\FOLDER')
     if e.is_file()]

rawDescription: remove extension in list python

description: Remove extension in list python


code:
import csv
class DataFile(object):
    empty = ''  # use this if col does not have value

    def __init__(self, filename):
        f = open(filename, 'r')
        self.reader = csv.reader(f)
        # set first line as header
        self.header = [x.strip() for x in self.reader.next()]

    def get_header(self):
        return self.header

    def with_header(self, headers):
        """ Returns a generator for specified headers"""
        header_dict = dict([(a, i,) for i, a in enumerate(self.header)])

        for line in self.reader:
            li = []
            for h in headers:
                if h in header_dict:
                    li.append(line[header_dict[h]])
                else:
                    li.append(self.empty)
            yield li

rawDescription: Merge multiple csv file based on a template header in python


code:
from mymodule import write_data_to_file
...

write_data_to_file()

rawDescription: Structuring of Python code

description: Structuring of Python code


rawDescription: numpy - Comparing two elements of a matrix and filling in the relative value in a different position

description: Numpy - Comparing two elements of a matrix and filling in the relative value in a different position


code:
def find_all(self, name=None, attrs={}, recursive=True, text=None,
             limit=None, **kwargs):
    generator = self.descendants
    if not recursive:
        generator = self.children
    return self._find_all(name, attrs, text, limit, generator, **kwargs)

findAll = find_all       # BS3

rawDescription: Obtaining column from wikipedia table using beautifulsoup


code:
s=df.index
d=collections.defaultdict(set)
for (k,v) in zip(*where(df==1)):
    if k!=v:
        d[s[k]].add(s[v])

rawDescription: np.where on pd.DataFrame for dictionary of non-zero indicies

description: Np.where on pd.DataFrame for dictionary of non-zero indicies


code:
if 'nogo' in came_from:
    return 1

rawDescription: how to generate custom 403 HTTP responses in Plone (prevent redirect)

description: Generate custom 403 HTTP responses in Plone (prevent redirect)


code:
import multiprocessing as mp

if __name__=="__main__":
   p = mp.Process(target=App.run)
   p.start()
   p.join()
   cleanup()

rawDescription: Python losing control of subprocess?

description: Python losing control of subprocess


code:
import decimal
decimal.Decimal(-1200)
decimal.Decimal(-1200).exp()

rawDescription: Exponential of very small number in python


code:
import os
import numpy as np
import pandas as pd

np.random.seed(2016)
df = pd.DataFrame(np.random.randint(10, size=(100, 2)), columns=list('AB'))
df.to_csv('file_csv.csv')
if os.path.exists('file_csv.hdf'): os.unlink('file_csv.hdf')
for i, df in enumerate(pd.read_csv('file_csv.csv', chunksize=50)):
    print('Saving {} chunk...'.format(i), end='')
    df.to_hdf('file_csv.hdf',
              'file_csv',
              format='table',
              data_columns=True,
              append=True)
    print('Done!')
    print(df.loc[df['A']==1])
print('-'*80)
df_hdf = pd.read_hdf('file_csv.hdf', where="A=1")
print(df_hdf)

rawDescription: Pandas HDF limiting number of rows of CSV file


code:
def time_encode(hours):
    now = timezone.now().replace(second=0, microsecond=0)
    remainder = now.minute % 15
    delta = (15 - remainder)
    timeFrom = now + timedelta(minutes=delta)
    timeTo = timeFrom + timedelta(hours=hours)
    return (timeFrom, timeTo)

rawDescription: Refactoring/cleaningup time function in django view


code:
if email_was_not_sent:
    sys.exit(1)
else:
    sys.exit(0)

rawDescription: How do you verify if an emailing script ran correctly?

description: Verify if an emailing script ran correctly


code:
list4 = []
for t in zip(list1, list2):
    list4.extend(t)

rawDescription: Adding elements to a list in Python 3.3 by extracting consecutive elements from two other lists


code:
try:
    proxyTest = isProxyWorking(proxy)
except TimeoutError:
    proxyTest = None
#proxyTest is guaranteed to be bound here

rawDescription: What is the elegant/Pythonic way to keep variables in scope, yet also catch exceptions?


code:
def answer(L):
    return list(zip(L[:len(L)//2], L[len(L)//2:][::-1]))

rawDescription: Algorithm - Grouping List in unique pairs


rawDescription: How to get the real cube root of a negative number in Python3?

description: Get the real cube root of a negative number in Python3


code:
def dutch_flag(seq, order=('red', 'green', 'blue')):
    return sorted(seq, key= order.index)

#Re-assign the returned value to a variable
new_list = dutch_flag(['red', 'green', 'blue', 'red', 'red', 'blue', 'red', 'green'])

rawDescription: Rearranging list in python

description: Rearranging list in python


code:
import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

rawDescription: How to get a matplotlib Axes instance to plot to?

description: Get a matplotlib Axes instance to plot to


code:
IN_MAP  = "D:/Dropbox/Dropbox/Uni Files/Assesment to do/Introduction to Programming/Assignment 3/images/map.png"
OUT_MAP = "D:/Dropbox/Dropbox/Uni Files/Assesment to do/Introduction to Programming/Assignment 3/images/marked-map.png"

class City:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def distance(self, other):
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
    def half_way(self, other):
        return (self.x + other.x) / 2, (self.y + other.y) / 2

cities = [
    City( 45, 310), City( 95, 147), City(182,  84), City(207, 201),
    City(256, 337), City(312, 375), City(328, 434), City(350, 348),
    City(374, 335), City(400, 265)
]

def mapLevel2(cities=cities, in_map=IN_MAP, out_map=OUT_MAP):
    # show map
    map = makePicture(in_map)
    show(map)
    # get tour length
    num_stops = requestInteger("Enter the number of cities you wish to visit: ")
    # start touring!
    total_dist = 0.
    city_a = cities[requestInteger("Enter the city you are starting from: ")]
    for _ in range(1, num_stops):
        city_b = cities[requestInteger("Enter the city you would like to visit next: ")]
        # get distances
        dist = city_a.distance(city_b)
        total_dist += dist
        # show route on map
        addLine(map, city_a.x, city_a.y, city_b.x, city_b.y)
        hx, hy = city_a.half_way(city_b)
        addText(map, hx, hy, "{:3.1f}".format(dist))  # changed! place distance label at midpoint on route line
        repaint(map)
        # prepare for next leg of the tour
        city_a = city_b
    # show overall distance
    addText(map, 21, 34, "Total: {:3.1f} km".format(total_dist))
    repaint(map)
    # Output File
    if out_map:
        writePictureTo(map, out_map)

rawDescription: combining distance between pixels during while loop

description: Combining distance between pixels during while loop


code:
getter = operator.itemgetter('A', 'B', 'C', 'D')
data = {'items': [getter(dct) for dct in data['items']]}

rawDescription: Remove Keys in Dictionary and Store Values in a Dictionary of Lists


rawDescription: How to iterate over class methods

description: Iterate over class methods


code:
keys = yourdict.keys()
output = [dict(zip(keys, col)) for col in zip(*yourdict.values())]

rawDescription: accessing individual elements from a python dictionary

description: Accessing individual elements from a python dictionary


code:
def xml_documents(fileobj):
    document = []
    for line in fileobj:
        if line.strip().startswith('<?xml') and document:
                yield ''.join(document)
                document = []
        document.append(line)

    if document:
        yield ''.join(document)

rawDescription: Parsing large combined XML document with Python


code:
df1
df1.loc[pd.notnull(df1['orts']), 'outts'] = df1['orts']
df1

rawDescription: Over-ride one TimeSeries with another

description: Over-ride one TimeSeries with another


rawDescription: Python Numpy Loadtxt - Convert unix timestamp


code:
adict = {}
adict['key'] = 'value'
adict['key']
adict['apple'] = 'red'
adict['apple']
adict

rawDescription: What does `features['contains(%s)' % word.lower()] = True` mean in NLTK?


rawDescription: twisted python logging issue / confusion?

description: Twisted python logging issue / confusion


code:
def show_pass():
    Password.configure(show=show_option.get())

show_option= StringVar(master,"*") #could also use Password.cget("show") as initial value

Checkbutton(mainframe,command=show_pass,
            text="show password",
            variable=show_option,
            onvalue ="",
            offvalue="*").grid(column=1, row=3, sticky=N)

rawDescription: Tkinter Widget Attribute Update (using ttk frame)


code:
candidates = (ob for ob in CPIobvs['observations']['observation'] if
    ob['realtime_start'] <= aDate)

rawDescription: Find dictionary with greatest date less than or equal to variable, return value


code: value = struct.unpack(">q", data['cf:id'])[0]

rawDescription: Filtering integers with HBase + Python

description: Filtering integers with HBase + Python


code:
def __init__(self, resources=None):
    if resources is None:
        resources = []
    self._resources = resources

rawDescription: Python object initialization bug. Or am I misunderstanding how objects work?


code: from sklearn.metrics import precision_score

rawDescription: Face recognition in OpenCV Python FAR/FRR


code: start_list = [i ** 2 for i in start_list]

rawDescription: How do I square each item in a list using append?

description: Square each item in a list using append


code:
unq, _ = np.unique(b, return_inverse=True)
cnt = np.bincount(_)
unq = unq.view(my_array.dtype).reshape(-1, my_array.shape[1])
unq
cnt

rawDescription: Count how many times each row is present in numpy.array


code:
import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)

rawDescription: How to prevent termination of a running program using "ctrl+c" in Linux using python?

description: Prevent termination of a running program using "ctrl+c" in Linux using python


code:
def method2_dictionary(request):
    people = Person.objects.all()
    return render_to_response('template.htm', {'people': people})

rawDescription: Python Django: in view is it better to add properties to an object or make a dictionary of the data?


code:
np.triu(df, 1)
s = pd.DataFrame(np.triu(df, 1), df.index, df.columns).stack() > 0.77
s[s]
s[s].index.tolist()

rawDescription: Pandas return index and column name based on the item value


code:
import pygame
import sys
import random

pygame.init()
screen = pygame.display.set_mode((640, 480),0,32)
clock = pygame.time.Clock()

# create font only once
font = pygame.font.Font(None,30)

# it's always a good idea to cache all text surfaces, since calling 'Font.render' is
# an expensive function. You'll start to notice once your game becomes more complex
# and uses more text. Also, use python naming conventions
text_cache = {}
def make_text(title, text):
    key = "{title}: {text}".format(title=title, text=text)
    if not key in text_cache:
        text = font.render(key, 1,(0,0,0))
        text_cache[key] = text
        return text
    else:
        return text_cache[key]

# we use the 'Sprite' class because that makes drawing easy
class Button(pygame.sprite.Sprite):
    def __init__(self, rect, color, on_click):
        pygame.sprite.Sprite.__init__(self)
        self.rect = rect
        self.image = pygame.Surface((rect.w, rect.h))
        self.image.fill(color)
        self.on_click = on_click

# this happens when the first button is pressed
def toggle_score_handler(state):
    state['show_score'] = not state['show_score']

# this happens when the second button is pressed
def toggle_backcolor_handler(state):
    state['backcolor'] = random.choice(pygame.color.THECOLORS.values())
    state['score'] += 100

# here we create the buttons and keep them in a 'Group'
buttons = pygame.sprite.Group(Button(pygame.Rect(30, 30, 32, 32), (55, 155 ,0), toggle_score_handler),
                              Button(pygame.Rect(250, 250, 32, 32), (155, 0, 55), toggle_backcolor_handler))

# here's our game state. In a real
# game you probably have a custom class
state = {'show_score': False,
         'score': 0,
         'backcolor': pygame.color.Color('White')}

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
        # you can check for the first mouse button with 'event.button == 1'
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            # to check if the mouse is inside the button, you
            # can simple use the 'Rect.collidepoint' function
            for button in (b for b in buttons if b.rect.collidepoint(event.pos)):
                button.on_click(state)

    screen.fill(state['backcolor'])
    # draw all buttons by simple calling 'Group.draw'
    buttons.draw(screen)

    if state['show_score']:
        screen.blit(make_text("score", state['score']), (100, 30))

    pygame.display.update()
    clock.tick(60)

rawDescription: text not showing up dynamically, pygame

description: Text not showing up dynamically, pygame


code: pointsToAdd = 30

rawDescription: While loop in python not working

description: While loop in python not working


code: from mypushbutton import MyPushButton

rawDescription: Drag n Drop Button and Drop-down menu PyQt/Qt designer


code:
def home (request):

    # just assigning a constant list for simplicity.
    # Also was lazy and did 10 examples rather than 20.
    objids = [ 1, 5, 15, 23, 48, 52, 55, 58, 59, 60 ]

    # make a bunch of Q objects, one for each object id:
    q_objs = []
    for objid in objids:
        q_objs.append(Q(id__exact = objid))

    # 'or' them together into one big Q object.
    # There's probably a much nicer way to do this.
    big_q = q_objs[0]
    for q_obj in q_objs[1:]:
        big_q |= q_obj

    # Make another queryset that will ask for the Vote objects
    # along with the ObjectDetail objects.
    # Try commenting out this line and uncommenting the one below.
    the_objects = ObjectDetail.objects.filter(big_q).prefetch_related('vote_set')
    # the_objects = ObjectDetail.objects.filter(big_q)

    template = 'home.html'
    context = {
        'the_objects' : the_objects,
        }
    context_instance = RequestContext (request)
    return render_to_response (template, context, context_instance)

rawDescription: optimizing no. of queries being fired in django orm for a given model

description: Optimizing no. of queries being fired in django orm for a given model


code:
#remove column names and index name
df = df.rename_axis(None).rename_axis((None,None), axis=1)

writer = pd.ExcelWriter('test.xlsx')
for i, g in df.groupby(axis=1, level=0):
    #print i
    #remove top level 4,5,6
    g.columns = g.columns.droplevel(0)
    #reset index, change column name
    g = g.reset_index().rename(columns={'index':'aaa'})
    #print g
    #sheet name is 'sheet_' + name of group (4,5,6)
    g.to_excel(writer,'sheet_%s' % i)
writer.save()

rawDescription: Save table to different Excel sheets using python


code:
import pygame, sys
from pygame.locals import *
import math
pygame.init()
mainClock = pygame.time.Clock()
degree = 0
WHITE = 250,250,250
rect2 = pygame.rect = (100,100,50,50)
WINDOWWIDTH = 1200
WINDOWHEIGHT = 750
thing = pygame.image.load('car.png')
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Teh test')
left = False
right = False
position = (100, 100)
while True:
    rect2 = pygame.rect = (100,100,50,50)
    if right == True:
        degree -= 2
    if left == True:
        degree += 2
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == ord('a'):
                left = True
            if event.key == ord('d'):
                right = True
        if event.type == KEYUP:
            if event.key == ord('a'):
                left = False
            if event.key == ord('d'):
                right = False
    pygame.draw.rect(screen,WHITE,rect2)
    screen.fill((40, 40, 40))
    thing2 = pygame.transform.rotate(thing,degree)
    dx = math.cos(math.radians(degree))
    dy = math.sin(math.radians(degree))
    position = (position[0] + dx, position[1] - dy)
    screen.blit(thing2, position)
    pygame.display.update()
    mainClock.tick(60)

rawDescription: How would I make a car move the direction it's pointing (After use of pygame.translation.rotate)


code:
Comment.objects.annotate(year=Q(date__year),
                         month=Q(date__month)
                         ).values('year', 'month').annotate(Count('pk'))

rawDescription: Django count grouping by year/month without extra


code:
from itertools import cycle

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

def foo():
    yield from roundrobin(range(10), range(10, 22))

rawDescription: Is there a way in python to change the order in which yield from get's processed?


code: MemoryError

rawDescription: How many elements may python dictionary hold?


rawDescription: sound way to feed commands to twisted ssh after reactor.run()

description: Sound way to feed commands to twisted ssh after reactor.run()


rawDescription: Python: split bytes with a hexadecimal delimiter


code:
def running_sum(iterable):
    s = 0
    for value in iterable:
        s += value
        yield s
running_sum([1,2,3,4,5])
list(running_sum([1,2,3,4,5]))  # Turn the generator into a list

rawDescription: a function that takes a list of integers as a parameter and returns a list of running totals

description: A function that takes a list of integers as a parameter and returns a list of running totals


code:
data, addr = s.recvfrom(1024)
ip, port = addr

rawDescription: Python: How to convert the address recieved from a recvfrom() function to a string?


code:
from __future__ import print_function  # for Py 2 & 3 compatibility

def template(class_T):
    class Foo(class_T):
        def fun(self):
            print('%s.fun()' % self.__class__.__name__)
    Foo.__name__ += '_' + class_T.__name__  # rename the subclass returned
    return Foo

class Base1:
    def bar(self):
        print('Base1.bar()')

class Base2:
    def bar(self):
        print('Base2.bar()')

Foo_Base1 = template(Base1)
print('Foo_Base1 base classes:', Foo_Base1.__bases__)

Foo_Base2 = template(Base2)
print('Foo_Base2 base classes:', Foo_Base2.__bases__)

d1 = Foo_Base1()
d1.fun()
d1.bar()

d2 = Foo_Base2()
d2.fun()
d2.bar()

rawDescription: Python Metaclass to Parametrize Inheritance


code:
import asyncio

def chain(obj):
    """
    Enables coroutines chain for obj.
    Usage: text = yield from chain(obj).go().click().attr
    Note: Returns not coroutine, but object that can be yield from.
    """
    class Chain:
        _obj = obj
        _queue = []

        # Collect getattr of call to queue:
        def __getattr__(self, name):
            Chain._queue.append({'type': 'getattr', 'name': name})
            return self

        def __call__(self, *args, **kwargs):
            Chain._queue.append({'type': 'call', 'params': [args, kwargs]})
            return self

        # On iter process queue:
        def __iter__(self):
            res = Chain._obj
            while Chain._queue:
                action = Chain._queue.pop(0)
                if action['type'] == 'getattr':
                    res = getattr(res, action['name'])
                elif action['type'] == 'call':
                    args, kwargs = action['params']
                    res = res(*args, **kwargs)
                if asyncio.iscoroutine(res):
                    res = yield from res
            return res
    return Chain()

rawDescription: Method chaining with asyncio coroutines

description: Method chaining with asyncio coroutines


code: class B(make_class(123)): ...

rawDescription: Class (not instance) constructor

description: Class (not instance) constructor


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

def main():
    numpoints = 30
    theta = np.linspace(0, 2*np.pi, numpoints)
    r1 = np.random.random(numpoints)
    r2 = 5 * np.random.random(numpoints)

    params = dict(projection='polar', theta_direction=-1, theta_offset=np.pi/2)
    fig, ax = plt.subplots(subplot_kw=params)
    ax2 = polar_twin(ax)

    ax.fill_between(theta, r2, color='blue', alpha=0.5)
    ax2.fill_between(theta, r1, color='green', alpha=0.5)
    plt.show()

def polar_twin(ax):
    ax2 = ax.figure.add_axes(ax.get_position(), projection='polar',
                             label='twin', frameon=False,
                             theta_direction=ax.get_theta_direction(),
                             theta_offset=ax.get_theta_offset())
    ax2.xaxis.set_visible(False)
    # There should be a method for this, but there isn't... Pull request?
    ax2._r_label_position._t = (22.5 + 180, 0.0)
    ax2._r_label_position.invalidate()
    # Ensure that original axes tick labels are on top of plots in twinned axes
    for label in ax.get_yticklabels():
        ax.figure.texts.append(label)
    return ax2

main()

rawDescription: Add second axis to polar plot

description: Add second axis to polar plot


code:
query = {
    'type': 'salesrule/rule_condition_combine',
    'aggregator': 'all',
    'operator': None,
    'attribute': None,
    'conditions': {
        0: {
            'type': 'salesrule/rule_condition_product_subselect',
            'aggregator': 'all',
            'operator': '>=',
            'attribute': 'qty',
            'conditions': {
                0: {
                    'operator': '{}',
                    'attribute': 'category_ids',
                    'type': 'salesrule/rule_condition_product',
                    'is_value_processed': False,
                    'value': '240'
                    }
                },
            'is_value_processed': None,
            'value': '3'
        }
    },
    'is_value_processed': None,
    'value': '1'
    }

rawDescription: Converting dict to list

description: Converting dict to list


code: jims_index = workers.index("Jim")

rawDescription: Trying to access an index from a list and convert it into a string in python


code:
the_date = None
def split_5_min(data_row):
    global the_date

    row_date = datetime.datetime.strptime(data_row[2], '%Y-%m-%d %H:%M:%S')
    if the_date is None or row_date - the_date > datetime.timedelta(minutes=5):
        the_date = row_date
        return the_date

rawDescription: Elegant data processing in Python

description: Elegant data processing in Python


code:
def tails(items, path=()):
    for item in items:
        if isinstance(item, Tree):
            if item.name in {".", ","}:  # ignore punctuation
                continue
            for result in tails(item.branches, path + (item.name,)):
                yield result
        else:
            yield path[-2:]

rawDescription: Extract parent and child node from python tree representation


code:
string = 'hello: world'
string.split(': ')
a, b = string.split(': ')
a
b

rawDescription: Convert string from external file to Python dictionary


code:
class T( object ):
    def __init__( self ):
        cDict = {}
        cDict['__doc__'] = 'Inner class doc string'
        setattr( self, 'C', type('C', (), cDict ) )

rawDescription: Python Docstrings in Subclasses

description: Python Docstrings in Subclasses


code:
for line in old_file:
    new_file.write(line.replace(pattern, subst))

rawDescription: Python find pattern and replace entire line


code:
import matplotlib

matplotlib.mathtext.SHRINK_FACTOR = 0.5
matplotlib.mathtext.GROW_FACTOR = 1 / 0.5

rawDescription: Matplotlib: set superscript font size

description: Matplotlib: set superscript font size


rawDescription: Python str.format() --- passing in list, outputting list


rawDescription: Permute rows and columns of a matrix

description: Permute rows and columns of a matrix


rawDescription: Set the right two characters (if there are any) to capitals?


code:
def strings(grammar, start):
    queue = [start]
    while len(queue):
        current = queue.pop(0)
        # for each symbol in the current string
        for n, sym in enumerate(current):
            # if this symbol is a non-terminal
            if sym in grammar:
                # for each rule for this symbol...
                for rhs in grammar[sym]:
                    # replace it with the right part
                    new = current[:n] + rhs + current[n+1:]
                    # does the result contain non-terminals
                    if any(s in grammar for s in new):
                        # yes, place it into the queue
                        queue.append(new)
                    else:
                        # no, return it
                        yield new

rawDescription: Figuring out how to expand a grammar (Python)


rawDescription: How to use Google Maps Directions API to get zipcode and addresses passed through in python or R.

description: Use Google Maps Directions API to get zipcode and addresses passed through in python or R.


code:
def __get__(self, obj, objtype=None):
    if obj is None:
        return self
    if self.fget is None:
        raise AttributeError("unreadable attribute")
    return self.fget(obj)

rawDescription: Python descriptor returning itself not value when called from class


code:
import sys
from PySide import QtGui, QtCore

class Test(QtGui.QWidget):

    def __init__(self, rows):
        super(Test, self).__init__()

        self.table = QtGui.QTableWidget()
        self.table.setColumnCount(3)
        # Optional, set the labels that show on top
        self.table.setHorizontalHeaderLabels(("First Name", "Last Name", "Address"))

        self.table.setRowCount(len(rows))
        for row, cols in enumerate(rows):
            for col, text in enumerate(cols):
                table_item = QtGui.QTableWidgetItem(text)
                # Optional, but very useful.
                table_item.setData(QtCore.Qt.UserRole+1, user)
                self.table.setItem(row, col, table_item)

        # Also optional. Will fit the cells to its contents.
        self.table.resizeColumnsToContents()

        # Just display the table here.
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.table)
        self.setLayout(layout)

if __name__ == "__main__":
    # ...
    rows = []
    # Here I have to fill it in an array, because you need to know the number of rows before adding... There might be a better solution though.
    for user in session.query(User).all():
        for addr in user.addresses:
            # These are the columns on each row (firstname, lastname, address)
            rows.append((user.firstname, user.lastname, addr.address))

    app = QtGui.QApplication(sys.argv)
    test = Test(rows)
    test.show()
    app.exec_()

rawDescription: Design of the 'model' for QTableView in PySide + SQLAlchemy.


code: arra_mod = np.roll(arra, arra.shape[2])

rawDescription: Choosing and iterating specific sub-arrays in multidimensional arrays in Python


code:
def dissect(text):
    data = {}
    for name, length in fields:
        data[name] = text[:length].rstrip()
        text = text[length:]
    return data

rawDescription: Dissecting a string with python regex, using named groups and substitution


code: results = pool.map(ImageData.shepard_interpolation, [ImageData()]*3)

rawDescription: Can't pickle static method - Multiprocessing - Python


code: other_list.insert(0, a)

rawDescription: What is the right way to create a list from variable and another list?


code:
@app.route('/')
def home():
    return 'home'

rawDescription: How to centralise routing in Flask using a single file instead of decorators?

description: Centralise routing in Flask using a single file instead of decorators


code:
import networkx as nx, numpy as np
from networkx.algorithms import bipartite
from scipy.sparse import csc_matrix
import matplotlib.pyplot as plt
RB = nx.complete_bipartite_graph(3, 2)
A  = csc_matrix(bipartite.biadjacency_matrix(RB, row_order=bipartite.sets(RB)[0]))
G = nx_graph_from_biadjacency_matrix(A)
nx.draw_circular(G, node_color = "red", with_labels = True)
plt.show()

rawDescription: Plot bipartite graph using networkx in Python


rawDescription: Calculating forward or backwards with pandas dataframes


code:
import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
numpy.random.shuffle(x)
training, test = x[:80,:], x[80:,:]

rawDescription: Numpy: How to split/partition a dataset (array) into training and test datasets for, e.g., cross validation?


code:
def get_leaf_nodes(self):
    leafs = []
    def _get_leaf_nodes( node):
        if node is not None:
            if len(node.children) == 0:
                leafs.append(node)
            for n in node.children:
                _get_leaf_nodes(n)
    _get_leaf_nodes(self.root)
    return leafs

rawDescription: How to get leaf nodes of a tree using Python?

description: Get leaf nodes of a tree using Python


code:
my_list = [{"FIRSTNAME":"barc","EMAIL":"jahg@jh.com","ADDRESS":"gyuyj"},
{"FIRSTNAME":"rth","EMAIL":"tht@thuyj.com","ADDRESS":"ytju"},
{"FIRSTNAME":"trhy","EMAIL":"klo@pyu.com","ADDRESS":"trght"},
{"FIRSTNAME":"ghy","EMAIL":"ytj@uki.com","ADDRESS":"ukyk"}]
my_dict = {}
for x in my_list:
    for key, value in x.items():
        my_dict[key] = my_dict.get(key, []) + [value]

rawDescription: How to dynamically add keys and values in python

description: Dynamically add keys and values in python


code: D

rawDescription: python 2.7 defining a class that will show their attributes if called with no arguments

description: Python 2.7 defining a class that will show their attributes if called with no arguments


code:
fields = ['string0', 'string1', 'string2', None, 'string4']
fields_out = filter(lambda f: f is not None, fields[1:])
template = ' '.join('%s' for field in fields_out)
template % tuple(fields_out)

rawDescription: How do I avoid None as result of a query?

description: Avoid None as result of a query


code:
def main(global_config, **settings):
  config = Configurator(settings=settings)
  # ...
  # Use Mustache renderer
  config.add_renderer(name='.mustache',
    factory='myapp.mustacherenderer.MustacheRendererFactory')
  # ...

rawDescription: How to integrate pystache with pyramid?

description: Integrate pystache with pyramid


code: df['expSum'] = list(exponential_sum(df.A.values, df.weight.values))

rawDescription: Pandas: Exponentially decaying sum with variable weights


code:
class Foo:
    def __init__(self):
        self.a = 0

    def f(self, x):
        self.a += 1
        return x + self.a

foo = Foo()
foo.f(0) # 1
foo.f(0) # 2

rawDescription: change value of parameters of a function within the function python

description: Change value of parameters of a function within the function python


code: bar(**{'a': 'happy', 'g': 'birthday'})  # like selector(**kwargs)

rawDescription: Python - Database query function with non-consistent arguments


rawDescription: how to make a function which tells if two lists are equivalent in python

description: Make a function which tells if two lists are equivalent in python


rawDescription: Convert float to log space in python

description: Convert float to log space in python


code:
from cStringIO import StringIO
from django.core.files.base import ContentFile

f = StringIO()
try:
    pil_image_obj.save(f, format='png')
    s = f.getvalue()
    model_instance.image_field.save(model_instance.image_field.name,
                                    ContentFile(s))
    #model_instance.save()
finally:
    f.close()

rawDescription: how to go form django image field to PIL image and back?

description: Go form django image field to PIL image and back


code:
wortliste = ['Bruch', 'Verwerfung']
print(','.join(['%s'] * len(wortliste)))
print(','.join("'%s'" % w for w in wortliste))

rawDescription: Give a list of strings to a sql-query [Python]


code:
def collectInfoFromXLS():
    workbookPath = config.get('TestCaseFileURL','XLSpath')
    workbook = xlrd.open_workbook(workbookPath)
    SheetPath = config.get('TesCaseSheetName','Sheet1')
    worksheet = workbook.sheet_by_name(SheetPath)
    numOfRows = worksheet.nrows - 1
    curr_row = 0
    row2 = []
    while curr_row < numOfRows:
       curr_row += 1
       row2 = []
       row = worksheet.row(curr_row)
       for value2 in re.findall(r"'(.*?)'", str(row)):
            row2.append(value2)
       yield row2

rawDescription: return Set of lists from out of function: python

description: Return Set of lists from out of function: python


code:
def tt_expand(program):
    '''
    expand string manip symbols

    Example:

    >>> tt_expand('5</')
    '5<5<'
    >>> tt_expand('5<//')
    '5<5<5<'
    >>> tt_expand('5</ /')
    '5<5< 5<5<'
    '''

    seen = ''
    new_program = ''
    prev_token = None
    for i, token in enumerate(program):
        if token == '/':
            if prev_token == ' ':
                new_program += new_program.rstrip()
            else:
                new_program += seen
        else:
            new_program += token
            seen += token
        prev_token = token

    return new_program

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

rawDescription: index out of range even after initialization of var serving as index

description: Index out of range even after initialization of var serving as index


code:
def __init__(self, master):
    ...
    self.maintext = Label(master, fg="blue")
    ...

def _on_return(self, event):
    self.maintext.configure(text="Welcome, %s" % self.e1.get())

rawDescription: How to wait for return to be clicked with the entry widget?

description: Wait for return to be clicked with the entry widget


rawDescription: apply a function on two ndarrays's corresponding rows at once(without for loop)

description: Apply a function on two ndarrays's corresponding rows at once(without for loop)


code:
with open(filename) as infh:
    for line in infh:
        name, _, type_, values = line.split(None, 3)
        outerdict[name][type_] = map(int, values.split())

rawDescription: Python idiom for creating dict of dict of list


code:
from django.core.mail import EmailMultiAlternatives
from email.mime.message import MIMEMessage

new = EmailMultiAlternatives("Re: "+original["Subject"],
                             "reply body text",
                             "me@mysite.com", # from
                             [original["Reply-To"] or original["From"]], # to
                             headers = {'Reply-To': "me@mysite.com",
                                        "In-Reply-To": original["Message-ID"],
                                        "References": original["Message-ID"]})
new.attach_alternative("<html>reply body text</html>", "text/html")
new.attach( MIMEMessage(original) ) # attach original message
new.send()

rawDescription: How do I reply to an email using the Python imaplib and include the original message?

description: Reply to an email using the Python imaplib and include the original message


code:
uniques = {}
with open("yourfile.txt") as infile:
    for line in infile:
        ID, thing, widget = line.strip().split(',')
        uniques[(ID, widget)] = thing

with open("output.txt", "w") as outfile:
    for k, v in uniques.iteritems():
        outfile.write("%s,%s,%s\n" % (k[0], v, k[1]))

rawDescription: Using Python to automate data cleanup, some issues


rawDescription: How can I create a sparse matrix instead of a dense one in this program?

description: Create a sparse matrix instead of a dense one in this program


code:
def func():
    return time.time()
d = {'a': time.time(), 'b': func}

rawDescription: Use of lambda in the following expression


code:
class DisableCSRF(object):
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)

rawDescription: Test post requests on django, csrf_token


code:
df
pd.DatetimeIndex(df.Date).to_period("M")  # old way
per = df.Date.dt.to_period("M")  # new way to get the same
g = df.groupby(per)
g.sum()  # dang not quite what we want (doesn't fill in the gaps)

rawDescription: Pandas groupby month and year

description: Pandas groupby month and year


code:
bool("")
bool("x")

rawDescription: Problem with Python's is None test?

description: Problem with Python's is None test


code:
# works
action = 'something important'
max_q = max(self.getQValue(nextState, action) for action in legal_actions)
assert action == 'something important'

# doesn't work (i.e., provides different results)
max_q = max([self.getQValue(nextState, action) for action in legal_actions])
assert action == 'something important'  # fails!

rawDescription: max([x for x in something]) vs max(x for x in something): why is there a difference and what is it?

description: Max([x for x in something]) vs max(x for x in something): why is there a difference and what is it


code:
def calculate(L, N, X):
    n = min(L//X, N)
    return n, L//n

rawDescription: Split a file with no more than N chunks but with minimal length


code:
...

params = urllib.urlencode([
    ('js_code', sys.argv[1]),
    ('compilation_level', 'WHITESPACE_ONLY'),
    ('output_format', 'text'),
    ('output_info', 'compiled_code'),
  ])

# Always use the following value for the Content-type header.
headers = {"Content-type": "application/x-www-form-urlencoded"}
conn = httplib.HTTPConnection('closure-compiler.appspot.com')
conn.request('POST', '/compile', params, headers)

...

rawDescription: Python library to access the Closure Compiler Service API


code: pattern.sub(repl, target)

rawDescription: How to replace only elements found using a python re.findall rather than entire string?

description: Replace only elements found using a python re.findall rather than entire string


code:
def timeit(exec_s, globals={}, number=10000):
    t = time.time()
    for i in range(number):
        exec(exec_s, globals)
    return time.time() - t

rawDescription: timing two algorithms (python) using timeit or time

description: Timing two algorithms (python) using timeit or time


code:
# saves the current TKinter object in postscript format
win.postscript(file="image.eps", colormode='color')

# Convert from eps format to gif format using PIL
from PIL import Image as NewImage
img = NewImage.open("image.eps")
img.save("blank.gif", "gif")

rawDescription: Working with the Python graphics module: is there any way to save the current window as an image?


rawDescription: how to predict unique list in lists?

description: Predict unique list in lists


code:
from shutil import move

move('C:\\Users\\Test.txt', 'C:\\Users\\Tests.csv')

rawDescription: Force Overwrite in Os.Rename

description: Force Overwrite in Os.Rename


code:
import inspect
import logging

logger=logging.getLogger(__name__)

def debug(msg):
    frame,filename,line_number,function_name,lines,index=inspect.getouterframes(
        inspect.currentframe())[1]
    line=lines[0]
    indentation_level=line.find(line.lstrip())
    logger.debug('{i} [{m}]'.format(
        i='.'*indentation_level,
        m=msg
        ))

def foo():
    debug('Hi Mom')
    for i in range(1):
        debug("Now we're cookin")

if __name__=='__main__':
    logging.basicConfig(level=logging.DEBUG)
    foo()

rawDescription: Python indentation \ context level to log prefix length


code: ((equation(v), k) for k, v in d.items())

rawDescription: How do I get values from a dictionary run them through an equation and return the key with the greatest value

description: Get values from a dictionary run them through an equation and return the key with the greatest value


rawDescription: Python returns 5 digit timestamp, what is this?


code:
abortable_async_result = AsyncBoot.apply_async(args=[name], name=name, connect_timeout=3)
myTaskId = abortable_async_result.task_id

rawDescription: Abort a running task in Celery within django


rawDescription: Writing to a particular cell using csv module in python


code:
s = set([u'http://imdb.com/title/tt0118583/'])
next(iter(s))

rawDescription: How to get item in set

description: Get item in set


code:
def lone_sum(*L):
  d = Counter(L)
  return sum(k for k in d if d[k]==1)

rawDescription: Python sum of non duplicate int

description: Python sum of non duplicate int


code: tuple(numpy.subtract((10, 10), (4, 4)))

rawDescription: Elegant way to perform tuple arithmetic

description: Elegant way to perform tuple arithmetic


code:
class ResendActivationEmailForm(forms.Form):
    email = forms.EmailField(required=True)

rawDescription: Django-registration resend activation Email with new code


code:
hours, minutes = s.split(':')
int(hours) * 60 + int(minutes)

rawDescription: Parsing hh:mm in Python

description: Parsing hh:mm in Python


code: any(e == 'love' for e in list1[j-1:j-3])

rawDescription: Searching in three elements before and after a specific word in list


code:
#!/bin/bash
#/path/to/run-weekly
run-parts /path/to/weekly/jobs

rawDescription: Cronjobs per package

description: Cronjobs per package


code:
import pandas as pd
csvinputlist = ['file1.csv','file2.csv','file3.csv']
csvinput = csvinputlist
headers=['A', 'B', 'C'] # continue for as many column that are in the file
df = pd.DataFrame()
for i, csvinput in enumerate(csvinputlist):
    reader = pd.read_csv(csvinput, header=None, names=headers)
    df['A{}'.format(i+1)]=reader['A']

df.to_csv('constructed.csv')

rawDescription: Writing to specific column from csv file


code:
import random
x = tuple(range(100))
random.choice(x)

rawDescription: What's the fastest way to get a random element from a tuple? (python)


code: df.groupby('B').agg(lambda x: ', '.join(x.values))

rawDescription: Pandas Dataframe groupby Display

description: Pandas Dataframe groupby Display


code: return count >= self.count

rawDescription: PhantomJS acts differently than Firefox webdriver


code:
from functools import wraps

class MyCustomError(Exception):
    def __init__(self):
        print('in MyCustomError')

# Common implementation
def wrap(func,cb=None):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            if cb is not None:
                cb()
            raise MyCustomError()
    return wrapper

def wrap_error(func_or_cb):
    # If the function is tagged as a wrap_error_callback
    # return a decorator that returns the wrapped function
    # with a callback.
    if hasattr(func_or_cb,'cb'):
        def deco(func):
            return wrap(func,func_or_cb)
        return deco
    # Otherwise, return a wrapped function without a callback.
    return wrap(func_or_cb)

# decorator to tag callbacks so wrap_error can distinguish them
# from *regular* functions.
def wrap_error_callback(func):
    func.cb = True
    return func

### Examples of use

@wrap_error
def foo(a,b):
    print('in foo',a,b)
    raise Exception('foo exception')

@wrap_error_callback
def callback():
    print('in callback')

@wrap_error(callback)
def bar(a):
    print('in bar',a)
    raise Exception('bar exception')

rawDescription: Python decorator with optional argument (which is function)


code:
operators = {
    '<': operator.lt,
    '>': operator.gt,
    '>=': operator.ge,
    '<=': operator.le,
}

rawDescription: Evaluation with variable pointing to operator


code:
a
elem = 5

rawDescription: How to get the indexes of column and row in a 2-dimensional matrix(list) that have the most given elements in using numpy in python

description: Get the indexes of column and row in a 2-dimensional matrix(list) that have the most given elements in using numpy in python


code:
from collections import OrderedDict
OrderedDict.fromkeys(l).keys()

rawDescription: Grab unique tuples in python list, irrespective of order


code:
local_path = py._path.local.LocalPath('/usr/bin/ls')
print(local_path.sysexec())
# out: file1\nfile2\nfile3...
print(local_path.sysexec('-l'))
# out likes "ls -l" out

rawDescription: Python - How to use py.path.LocalPath.sysexec()


code: nfs = { tr[k]:fs[k] for k in fs }

rawDescription: Transform Python HTML Inputs

description: Transform Python HTML Inputs


code:
class ContributionAdmin(admin.ModelAdmin):
    readonly_fields = ('subscriber', )

rawDescription: Django admin site : Help needed

description: Django admin site : Help needed


code:
class MyIterator(object):
    def __init__(self, iterable):
        self._iterable = iter(iterable)
        self._exhausted = False
        self._cache_next_item()
    def _cache_next_item(self):
        try:
            self._next_item = next(self._iterable)
        except StopIteration:
            self._exhausted = True
    def __iter__(self):
        return self
    def next(self):
        if self._exhausted:
            raise StopIteration
        next_item = self._next_item
        self._cache_next_item()
        return next_item
    def __nonzero__(self):
        return not self._exhausted

rawDescription: python generator with check for empty condition

description: Python generator with check for empty condition


code:
from setuptools import setup, dist

dist.Distribution(dict(setup_requires='Bread'))

from bread.setup_topping import *

setup(
    name='Jam',
    version='0.2',
    long_description=open('README.md').read(),
    **topping_setup_options
)

# Remove *.egg left by bootstrapping Bread
cleanup_bread_bootstrap()

rawDescription: Using code from a dependency in setup.py


code:
xy = [x, y]
np.dot(arr_pairs, xy)

rawDescription: numpy array partial sums with weights

description: Numpy array partial sums with weights


code:
def iterwords(fh):
    for number, line in enumerate(fh):
        for word in re.split(r'\s+', line.strip()):
            yield number, word

rawDescription: How to search for string in Python by removing line breaks but return the exact line where the string was found?

description: Search for string in Python by removing line breaks but return the exact line where the string was found


rawDescription: Multiply each row of one array with each element of another array in numpy


rawDescription: Grab part of filename with Python

description: Grab part of filename with Python


code:
for c in range(1, 7 + 1):
    print(' '*(7-c), end='')
    for cc in reversed(range(1, c)):
        print(cc, end = '')
    print('')

rawDescription: Triangle number pattern in python

description: Triangle number pattern in python


rawDescription: String of bytes into an int

description: String of bytes into an int


code:
import pylab as p
import networkx as nx

class Node(object):
    nodes = []

    def __init__(self, label):
        self._label = label

    def __str__(self):
        return self._label

nodes = [Node(l) for l in ["A","B","C","C","D","H"]]
edges = [(0,1),(0,5),(5,2),(1,3),(1,4)]

G = nx.Graph()
for i,j in edges:
    G.add_edge(nodes[i], nodes[j])

nx.draw(G)
p.show()

rawDescription: Graph traversal with Networkx (Python)

description: Graph traversal with Networkx (Python)


code:
import xml.etree.ElementTree as ET
from StringIO import StringIO

s = '''
<Description>"This is a description"</Description>

<Process expectFailure="false">
    Import
    <Sources>
        <Source>"Test Data"</Source>
    </Sources>
    <Destination>Buffered</Destination>
    <Properties>
        <Property code="format" value="CC"/>
        <Property code="Input" value="10N"/>
        <Property code="Method" value="BASIC"/>
        <Ppoperty code="Resolution" value="5"/>
        <Property code="Convention" value="LEFT"/>
        <Property code="Bounding" value="BUFFERED"/>
    </Properties>
</Process>

<Process>
    SurfaceCompare
    <Sources>
        <Source>expectedOutput</Source>
        <Source>Buffered</Source>
    </Sources>
    <Properties>
        <Property code="compare_designated" value="true"/>
        <Property code="compare_metadata" value="true"/>
        <Property code="metadata_type" value="OTHER"/>
    </Properties>
</Process>'''

rawDescription: Parsing an XML file using ElementTree

description: Parsing an XML file using ElementTree


code: rows = [x[0] for x in cursor.fetchall()]

rawDescription: How to strip "()," from Python, PyODBC, SQL Returns?

description: Strip "()," from Python, PyODBC, SQL Returns


code:
class Node(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Truck(Node):
    def __init__(self, name="", age=0):
        super(Truck, self).__init__(name=name, age=age)
        self._info = None

    @property
    def info(self):
        return self._info

    @info.setter
    def info(self, value):
        # you likely want to it here
        self._info = value
        print("this is being set")

c = Truck()
c.info = "great"
print(c.info)

rawDescription: Python - class object attribute setter not working


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

def gauplot(centers, radiuses, xr=None, yr=None):
        nx, ny = 1000.,1000.
        xgrid, ygrid = np.mgrid[xr[0]:xr[1]:(xr[1]-xr[0])/nx,yr[0]:yr[1]:(yr[1]-yr[0])/ny]
        im = xgrid*0 + np.nan
        xs = np.array([np.nan])
        ys = np.array([np.nan])
        fis = np.concatenate((np.linspace(-np.pi,np.pi,100), [np.nan]) )
        cmap = plt.cm.gray
        cmap.set_bad('white')
        thresh = 3
        for curcen,currad in zip(centers,radiuses):
                curim=(((xgrid-curcen[0])**2+(ygrid-curcen[1])**2)**.5)/currad*thresh
                im[curim<thresh]=np.exp(-.5*curim**2)[curim<thresh]
                xs = np.append(xs, curcen[0] + currad * np.cos(fis))
                ys = np.append(ys, curcen[1] + currad * np.sin(fis))
        plt.imshow(im.T, cmap=cmap, extent=xr+yr)
        plt.plot(xs, ys, 'r-')

rawDescription: matplotlib color gradient in patches?

description: Matplotlib color gradient in patches


code: result = np.sum(Y.data.reshape(Y.shape[0], -1), axis=0)

rawDescription: Scipy Sparse Matrix special substraction


code:
re.search(r'\S+', 'Bob is at the beginning').group()
re.search(r'\S+', '   Tom after period!').group()
re.sub(r'\S+', 'John', '   Bob and Tom.')
re.sub(r'\S+', 'John', '   Bob and Tom.', count=1)

rawDescription: Possible to match at the start of a textfile without using regex?


code:
valgdata\
    .groupby([valgdata.dato_uden_tid.name, valgdata.news_site.name])\
    .mean()\
    .unstack()\
    .plot()

rawDescription: Plotting multiple time series after a groupby in pandas


code:
# Consider each row as indexing tuple & get linear indexing value
lid = np.ravel_multi_index(x.T,x.max(0)+1)

# Get unique indices and tagged indices for all elements
_,unq_idx,tag_idx = np.unique(lid,return_index=True,return_inverse=True)

# Use the tagged indices to count and look for count==1 and repeat like before
out = x[unq_idx[np.bincount(tag_idx)==1]]

rawDescription: Get non-duplicate rows from numpy array

description: Get non-duplicate rows from numpy array


code:
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import string

G = nx.generators.erdos_renyi_graph(18, 0.2)
nx.draw(G,
        node_color = np.linspace(0,1,len(G.nodes())),
        edge_color = np.linspace(0,1,len(G.edges())),
        width = 3.0,
        labels = {n:l for n,l in zip(G.nodes(),string.ascii_uppercase)}
        )
plt.show()

rawDescription: How to change attributes of a networkx / matplotlib graph drawing?

description: Change attributes of a networkx / matplotlib graph drawing


rawDescription: How to shift a pandas MultiIndex Series?

description: Shift a pandas MultiIndex Series


code:
with open('logfile.txt', 'a') as f:
    while True:
       voltsdiff = adc.readADCDifferential01(4096, 8)
       print >> f, time(), voltsdiff
       sleep(0.25)

rawDescription: Is it possible to create a log file in the terminal in python?


code: reduce(lambda r, d: r + [d['birth_year']], dayList, [])

rawDescription: Using Python's Higher Order Functions on a CSV


rawDescription: Changing binary characters in string

description: Changing binary characters in string


code:
cols = ['PetalLength', 'PetalWidth']
transformed = grouped_iris[cols].transform(sum).sum(axis=1)
iris['SumLengthWidth'] = transformed
iris.head()

rawDescription: how to apply functions to grouped dataframes in Python pandas?

description: Apply functions to grouped dataframes in Python pandas


code:
import numpy as np
import pandas as pd

df1 = pd.DataFrame(np.nan, columns=list('ABCDE'), index=pd.to_datetime(
    ['2009-01-30', '2009-02-02', '2009-02-03', '2009-02-04', '2009-02-05',
    '2009-02-06', '2009-02-09', '2009-02-10']))
ser = pd.Series(list('AE'), index=pd.to_datetime(['2009-02-04', '2009-02-06']))
freqs = pd.get_dummies(ser)
freqs = freqs.where(freqs != 0, np.nan)
result = df1.add(freqs, fill_value=0)

print(result)

rawDescription: How to set the values of a dataframe given a series of indices and corresponding column names?

description: Set the values of a dataframe given a series of indices and corresponding column names


code:
class Indexable(object):
    def __getitem__(self, idx):
        return idx

Indexable()[0, 0, :]

rawDescription: Passing list as slice for a N-dimensional numpy array


code: x = np.linspace(xStart, xStop, num=(xStart-xStop)*100)

rawDescription: Python pylab: Making a plot with adjusted spines, but doesn't plot


code: words = word_reader('/usr/share/dict/words', len(rack))

rawDescription: How can this Python Scrabble word finder be made faster?


code:
def not_very_random():
    random.seed(0)
    return random.choice(range(10))

not_very_random()
not_very_random()
not_very_random()
not_very_random()

rawDescription: Selecting a random list element in python


code:
mylist = ['hell o', 'geg gg']
[part for item in mylist for part in item.split()]

rawDescription: separating multiple words out of the same index

description: Separating multiple words out of the same index


code:
brackets = set("[]()")
words = [word for word in random.choice(headlines).split(" ")[1:-1] if not brackets.intersection(word)]

rawDescription: Trying to make sure certain symbols aren't in a word


code: lst = [Object() for _ in range(100)]

rawDescription: Initialize a list of objects in Python

description: Initialize a list of objects in Python


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

def split_plot(ax, x, y, low, high, inner_style, outer_style):
    """
    Split styling of line based on the x-value

    Parameters
    ----------
    x, y : ndarray
        Data, must be same length

    low, high : float
        The low and high threshold values, points for `low < x < high` are
        styled using `inner_style` and points for `x < low or x > high` are
        styled using `outer_style`

    inner_style, outer_style : dict
        Dictionary of styles that can be passed to `ax.plot`

    Returns
    -------
    lower, mid, upper : Line2D
        The artists for the lower, midddle, and upper ranges

    vline_low, vline_hi : Line2D
        Vertical lines at the thresholds

    hspan : Patch
        Patch over middle region
    """

    low_mask = x < low
    high_mask = x > high
    mid_mask = ~np.logical_or(low_mask, high_mask)

    low_mask[1:] |= low_mask[:-1]
    high_mask[:-1] |= high_mask[1:]

    lower, = ax.plot(x[low_mask], y[low_mask], **outer_style)
    mid, = ax.plot(x[mid_mask], y[mid_mask], **inner_style)
    upper, = ax.plot(x[high_mask], y[high_mask], **outer_style)

    # add vertical lines
    vline_low = ax.axvline(low, color='k', ls='--')
    vline_high = ax.axvline(high,  color='k', ls='--')

    hspan = ax.axvspan(low, high, color='b', alpha=.25)

    return lower, mid, upper, vline_low, vline_high, hspan

rawDescription: Using Python 2.7 and matplotlib, how do I create a 2D Line using two different styles?


rawDescription: Python : Convert time format to unix_timeformat


rawDescription: What's the ufunc to do floor division in numpy with python3.x?


code: soup.findAll(lambda tag: tag.name in ['script', 'form'] or tag['id'] == "footer")

rawDescription: Can I combine two 'findAll' search blocks in beautifulsoup, into one?

description: Combine two 'findAll' search blocks in beautifulsoup, into one


rawDescription: Regex through a string with Python 2.7

description: Regex through a string with Python 2.7


code:
proxies = {
    "http" :"192.168.20.130:8080",
    "https":"192.168.20.130:8080",
}
auth = HTTPProxyDigestAuth("username", "password")

# HTTP
r = requests.get("http://www.google.co.jp/", proxies=proxies, auth=auth)
r.status_code # 200 OK

# HTTPS
r = requests.get("https://www.google.co.jp/", proxies=proxies, auth=auth)
r.status_code # 200 OK

rawDescription: How to pass proxy-authentication (requires digest auth) by using python requests module

description: Pass proxy-authentication (requires digest auth) by using python requests module


code: del questions[0]

rawDescription: Python trivia game

description: Python trivia game


code: next(i for i, elem in enumerate(mylist) if re.match(pattern, elem['rep_main']))

rawDescription: Get index of dictionary item in list by regexp


rawDescription: Python 3 - Associating two lists

description: Python 3 - Associating two lists


code:
import contextlib
import sys

@contextlib.contextmanager
def dumping():
    f = sys._getframe(2)
    fl = f.f_locals.copy()
    try:
        yield None
    finally:
        for name, value in f.f_locals.items():
            if name not in fl:
                print('{} = {}'.format(name, value))

bar = 0
def foo():
    global bar
    bar = 3
    baz = 4
    qux = 5
    with dumping():
        spam = 'eggs'
        eggs = 3
        bar = 4
        baz = 5

foo()

rawDescription: Getting name of local variable at runtime in Python


code:
import json

# input data consists of records stored in lists.
items = [
    ['one', 'two', 'three'],
    ['four', 'five', 'six']
]

# create a JSON string from records
# if you want to write to file instead, see json.dump
data = json.dumps(
    [{'id': k, 'array': [{'item': i}]} for k, i in enumerate(items, 1)],
    indent=4
)
print(data)

rawDescription: Creating a json output out of one item and a second as a dictionary


code: return lst[i][1]

rawDescription: function search in a list

description: Function search in a list


code:
S1 = aliased(Stuff)
S2 = aliased(Stuff)
q = (
    session
    .query(A)
    .join(S1, A.stuff)  # S1 will refer to `A.stuff`
    .join(S2, A.more_stuff)  # S2 will refer to `A.more_stuff`
    .filter(or_(S1.id == X, S2.id == X))
)

rawDescription: SQLAlchemy: how to select if in one list or another list?


code:
from itertools import islice
ilista = iter(lista)
groups = [list(islice(ilista, 0, n)) for n in splitby]

rawDescription: How to group a list by n elements, where n is defined in a list

description: Group a list by n elements, where n is defined in a list


code:
import re
word_re = re.compile('\w+')
words = map(lambda match: match.group(0), word_re.finditer(string))
words.index('my') #Out: 2

rawDescription: Position of query word

description: Position of query word


code:
df = df.set_index('unix')

df.resample('D', how={'volume': 'sum', 'price': 'last'})

rawDescription: Convert tick data to daily

description: Convert tick data to daily


code: your_cursor.execute('insert into your_table values {}'.format(ph), values)

rawDescription: Dynamically creating a placeholder to insert many column values for a row in SQLite table


code:
C = empty_like(A)
logical_and(A, B, C)

rawDescription: How to map numpy arrays to one another?

description: Map numpy arrays to one another


code:
import mock
class MyClass(object):
    @classmethod
    def my_method(cls):
        print('my_method')

def mocked_method(cls):
    print('I want this method to get called')

with mock.patch.object(MyClass, 'my_method', classmethod(mocked_method)):
    MyClass.my_method()

rawDescription: TypeError: unbound method when trying to mock a classmethod


rawDescription: recursion None python

description: Recursion None python


code:
info = np.empty_like(users, dtype=np.intp)
first = dat['id'].searchsorted(users, side='left')
last =  dat['id'].searchsorted(users, side='right')
for idx, (start, stop) in enumerate(zip(first, last)):
    info[idx] = len(np.unique(dat[start:stop]))

rawDescription: Counting number of unique values in subset of sorted array


rawDescription: Looping through a list of strings and tuples and appending unique combinations


code:
def get_ffprofile():
    ff_profile_path = 'C:\\Users\\Kasim\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\my89fce2.default'
    ff_profile = webdriver.FirefoxProfile(ff_profile_path)
    return ff_profile

rawDescription: How can I make Selenium use my firefox (not create a fresh one)

description: Make Selenium use my firefox (not create a fresh one)


code: ['|DRAMA|', '|COMEDY|', '|ACTION|ADVENTURE|SCI-FI|', 'DRAMA'] ['Hindi', 'English'] ['New Delhi', 'Mumbai', 'Bangalore'] ['FESTIVAL', 'WORKSHOP', 'FANTASY', 'KIDS', 'EXHIBITION'] ['EVENT_GENRE', 'EVENT_LANGUAGE']

rawDescription: filter out some items from a list and store in different arrays in python

description: Filter out some items from a list and store in different arrays in python


code:
Output
Asia/Calcutta
Asia/Colombo
Asia/Dacca
Asia/Dhaka
Asia/Karachi
Asia/Kathmandu
Asia/Katmandu
Asia/Kolkata
Asia/Thimbu
Asia/Thimphu

rawDescription: Getting timezone name from UTC offset

description: Getting timezone name from UTC offset


code:
def create_blah(class_type = different_classes.first, x=x1, y=y1, z=z1):
    instance = class_type(x, y, z)

rawDescription: Class as an input in a function

description: Class as an input in a function


rawDescription: Python / networkx: creation of note attributes fails erratically


rawDescription: Asserting with..as clause in Python

description: Asserting with..as clause in Python


code:
xyz_unique
mass_unique

rawDescription: Find indices of unique values of a 3-dim numpy array


code:
def __setitem__(self, key, value):
    if isinstance(key, tuple):
        for k, v in zip(key, value):
            setattr(self, k, v)
    else:
        setattr(self, key, value)

rawDescription: A superfluous but cool dynamic python structure and questions about decorators, comprehensions, syntax


code: if (len(subnames) == 1): return subnames[0]

rawDescription: I need help on creating a name changing program


code:
import functools

def wrapit(func):
    @functools.wraps(func)
    def _(self, *args, **kwargs):
        func(self, *args, **kwargs)
        self.save_to_db()

    return _

rawDescription: How to get a method called (decorator?) after every object method

description: Get a method called (decorator?) after every object method


rawDescription: Sorting a pandas DataFrame by the order of a list


code:
with open('my_file.json', 'r+') as f:
    json_data = json.load(f)
    json_data['b'] = "9"
    f.seek(0)
    f.write(json.dumps(json_data))
    f.truncate()

rawDescription: How to update a JSON file by using Python?

description: Update a JSON file by using Python


code:
@task
def ssh():
    env.forward_agent = True
    run('ssh root@localhost -p 49222')
    with settings(output_prefix=False, forward_agent=True):
        run('ssh root@localhost -p 49222')

rawDescription: How to initiate SSH connection from within a Fabric run command

description: Initiate SSH connection from within a Fabric run command


rawDescription: How do you tell python to get the first 6 numbers from a text file and put them horizontally

description: Tell python to get the first 6 numbers from a text file and put them horizontally


code: for singleitem in mylist: break

rawDescription: Getting only element from a single-element list in Python?


code:
symbols = sorted(
    [
        "pelikan", "palma", "rukavnik", "morskyKon", "mraznicka", "kormidlo",
        "lehatko", "drink", "vedro", "Aloha", "koral", "nanuk", "opalovaciKrem",
        "Splash!", "plutva", "morskaPanna", "meduza", "krab", "stopa", "Wipeout",
        "pistol", "zralociaPlutva", "plachetnica", "raketa", "slnko", "sandala",
        "melon", "harpuna", "stolicka", "zachranneKoleso", "lietajuciTanier", "ryba",
        "hrad", "kalamar", "fotoaparat", "osuska", "naramok", "sarkan", "kotva",
        "fakla", "kamene", "snehoveGule", "motyka", "kosatka", "plavky",
        "odtlacokMusle", "klobuk", "ponorka", "morskyJez", "more", "musla",
        "slnecnik", "potapacskeOkuliare", "slnecneOkuliare", "majak", "vlna", "lopta"
    ],
    key = str.lower
)

cards = [
    [symbol for symbol, use_it in zip(symbols, row) if use_it]
    for row in sorted(sol.incidence_matrix().rows())
]

rawDescription: Python - Spot it! Cards

description: Python - Spot it! Cards


code:
from sys import argv

records = {}
for line in open(argv[1]):
    fields = (field.strip() for field in line.split(','))  # generator expr
    record = dict(pairwise(fields))
    records[record['TSN']] = record

print('Found %d records in the file.' % len(records))

rawDescription: Creating a python dictionary from a line of text


code:
from itertools import *
list(takewhile(lambda x: x > 0, starmap(reduction_pass, repeat((dataset,)))))

rawDescription: How to organize this loop in a more elegant Pythonic way

description: Organize this loop in a more elegant Pythonic way


code:
def flat_for(a, f):
    a = a.reshape(-1)
    for i, v in enumerate(a):
        a[i] = f(v)

a = numpy.arange(25).reshape(5, 5)
flat_for(a, lambda x: x + 5)
a

rawDescription: Mapping a NumPy array in place

description: Mapping a NumPy array in place


code:
values = set()
for entry in long_array:
    value = (entry[1], entry[4])
    if (value in values):
        print("Duplicate " + str(entry))
    else:
        values.add(value)

rawDescription: Python3 search value in this array

description: Python3 search value in this array


code:
def dummy(val):
    onelist = 13500 * [val]
    listolists = 12000 * [onelist]

    for i in findpairs(listolists, 3.0):
      pass

dummy(0)
dummy(1)

rawDescription: Identifying pairs of Python array cells separated by maximum distance in a large array?


code:
line = "Teacher   =  Small   |1-2|   Student"
line = line.split()
line[0] += "Short"
line[-1] += "Short"
line = "  ".join(line)
line

rawDescription: Find and replace a string in Python

description: Find and replace a string in Python


code: Model.objects.filter(x=x, y__isnull = False, z=z)

rawDescription: Query when parameter is none django

description: Query when parameter is none django


code:
from django.utils import timezone

class YourModel(models.Model):
    name = models.CharField(max_length=100)

    def save(self, *args, **kwargs):
        super(YourModel, self).save(*args, **kwargs)
        YourModelUpdateHistory.objects.create(your_model=self, updated=timezone.now())

rawDescription: django multiple update dates in one field

description: Django multiple update dates in one field


code: mytuple = ((7,8),) + mytuple

rawDescription: Adding a tuple to a tuple of tuples

description: Adding a tuple to a tuple of tuples


rawDescription: Sorting contours left to right in Python (OpenCV)


code: ax.imshow(image, extent=[0, 10.4, 0, 4.2], aspect=1)

rawDescription: Matplotlib: force aspect ratio in series of plots


code:
dt2 = np.dtype(dict(names=('t', 'x'), formats=(np.int16, np.int8), offsets=(0, 2), itemsize=4))
y = x.view(dt2)

rawDescription: Python numpy recarray: Can one obtain a view into different fields using pointer arithmetic?


rawDescription: Dihedral/Torsion Angle From Four Points in Cartesian Coordinates in Python


code:
from pyspark.sql.functions import explode, avg, col

(df1.select("person", "type", explode("keywords").alias("keyword"))
    .join(df2, "keyword")
    .groupBy("person", "type")
    .agg(avg("score")))

rawDescription: Pyspark join and operation on values within a list in column


code:
result = df.loc[df['VID'].isin(countdf[countdf['value'] > 3].index)]
result.groupby('VID')['value'].apply(list).tolist()

rawDescription: Keeping rows in Pandas where the same ID appears more than n times and convert to list per ID


code:
from pyspark.mllib.random import RandomRDDs

RandomRDDs.uniformRDD(sc, n)

rawDescription: Pyspark: shuffle RDD

description: Pyspark: shuffle RDD


code:
opts, args = getopt.getopt(sys.argv[1:], "cs:np:hv",
#                                            ^ no colon after this option
    ["cli", "server", "username", "password", "help", "verbose"])

rawDescription: Why does my getopts fail if I specify a username?


code:
import os.path,sys
CURRENT_DIR = os.path.dirname(__file__).replace('\\','/')
PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, os.pardir))

# other codes and stuff

rawDescription: How To add images in Django project

description: How To add images in Django project


code:
def rle(seq):
    return ((k, sum(1 for x in g)) for k, g in groupby(seq))

["{}*{}".format(*x) for x in rle(a)]

rawDescription: Are there any smart print methods in Python?


code:
DATABASES = {
    'default': {
        'NAME': 'new_database',
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'USER': '',
        'PASSWORD': ''
    },
    'old': {
        'NAME': 'old_database',
        'ENGINE': 'django.db.backends.mysql',
        'USER': '',
        'PASSWORD': ''
    }
}

rawDescription: Is there any method in django to use database without creating models.py file?


code:
n=2
' '.join(lh.split()[:n]), p, ' '.join(rh.split()[:n])

rawDescription: Python find n-sized window around phrase within string


code:
def my_range(start, stop, step=1):
    current = start
    while current < stop:
        yield current
        current += step

[num for num in my_range(0, 10)]

rawDescription: Extended conditions in a for loop

description: Extended conditions in a for loop


code:
from werkzeug.routing import BaseConverter, ValidationError

class PathVarArgsConverter(BaseConverter):
    """Convert the remaining path segments to a list"""

    def __init__(self, url_map):
        super(PathVarArgsConverter, self).__init__(url_map)
        self.regex = "(?:.*)"

    def to_python(self, value):
        return value.split(u"/")

    def to_url(self, value):
        return u"/".join(value)

app.url_map.converters['varargs'] = PathVarArgsConverter

rawDescription: Flask: URLs w/ Variable parameters

description: Flask: URLs w/ Variable parameters


code:
def seek_array(search_in, search_for, return_coords = False):
    si_x, si_y = search_in.shape
    sf_x, sf_y = search_for.shape
    for y in xrange(si_y-sf_y+1):
        for x in xrange(si_x-sf_x+1):
            if numpy.array_equal(search_for, search_in[x:x+sf_x, y:y+sf_y]):
                return (x,y) if return_coords else True
    return None if return_coords else False

def skimage_based(field_array,match_array):
    windows = view_as_windows(field_array, match_array.shape)
    return (windows == match_array).all(axis=(2,3)).nonzero()

def im2col_based(field_array,match_array):
    col_match = im2col(field_array,match_array.shape)==match_array.ravel()[:,None]
    out_shape = np.asarray(field_array.shape) - np.asarray(match_array.shape) + 1
    return np.where(col_match.all(0).reshape(out_shape))

def cv2_based(field_array,match_array):
    M = cv2m(field_array.astype('uint8'),match_array.astype('uint8'),cv2.TM_SQDIFF)
    return np.where(M==0)

rawDescription: How can I check if one two-dimensional NumPy array contains a specific pattern of values inside it?

description: Check if one two-dimensional NumPy array contains a specific pattern of values inside it


code:
def find_solution(step):
    for num in xrange(step, 999999999, step):
        for n in check_list:
            if num % n != 0:
                break
        else:
            return num
    return None

rawDescription: Python Efficiency / Optimization Project Euler #5 example


code:
df['count_max'] = df.groupby(['Mt'])['count'].transform(max)
df

rawDescription: Python : Getting the Row which has the max value in groups using groupby


code:
ratings = {}
for team in teams:
    ratings[team] = [1500]

rawDescription: Python: How to have a user reference and access a variable?


code:
def bp():
    import ipdb
    ipdb.set_trace(sys._getframe().f_back)

rawDescription: Convenience function defined for debugging with ipdb in Python


rawDescription: Calculate two dimensional pairwise distance on a large numpy three dimensional array


code:
def setUp(self):

    # setup dev_appserver
    APP_CONFIGS = ['app.yaml']
    python_runtime._RUNTIME_ARGS = [
        sys.executable,
        os.path.join(os.path.dirname(dev_appserver.__file__),
                     '_python_runtime.py')
    ]
    options = devappserver2.PARSER.parse_args([
        '--admin_port', '0',
        '--port', '9080',
        '--datastore_path', ':memory:',
        '--logs_path', ':memory:',
        '--skip_sdk_update_check',
        '--',
    ] + APP_CONFIGS)
    server = devappserver2.DevelopmentServer()
    server.start(options)
    self.server = server

    # setup selenium
    self.browser = webdriver.Firefox()
    self.browser.implicitly_wait(3)

    # setup the testbed
    self.tb = testbed.Testbed()
    self.tb.setup_env(current_version_id='testbed.version')
    self.tb.activate()
    self.tb.init_user_stub()
    self.tb.init_datastore_v3_stub()
    self.tb.init_memcache_stub()

rawDescription: Why can't I import a model from a file containing import of any of the Google App Engine components?


code:
import os
os.stat('array.dat').st_size
len(a) * a.itemsize

rawDescription: Storage size of array.array in a file

description: Storage size of array.array in a file


code:
num1 = int(input("Enter first integer: "))
num2 = int(input("Enter second integer: "))

sumNum1Num2N = 0

print("Let's sum all the integers in this range [%d, %d]" %(num1, num2))

#This shows up the sum being done
for i in range(num1, num2 + 1):
        sumNum1Num2N = sumNum1Num2N + i
        print(sumNum1Num2N, " " , end="")

print()
print("The sum of the numbers between %d and %d is %d" %(num1, num2, sumNum1Num2N))

rawDescription: Need to add all the integers between 2 other integers


code:
def add_attribute_block(toybox = None, key = "" ):
    if toybox is not None:
        if key in AttributeBlock.objects:
            toybox.attributes.append(AttributeBlock.objects[key])

rawDescription: creating a new copy of a python class each time it's called

description: Creating a new copy of a python class each time it's called


code:
first = True
for data in self.json_parse(inf):
  records = len(data['MainKey'])
  columns = len(data['MainKey'][0]['Fields'])
  if first:
    # Initialize output as DictWriter
    ofile, outf, fields = self.init_csv(csvname, data, records, columns)
    first = False
  reccount, errcount = self.parse_records(outf, data, fields, records)

rawDescription: Opening A large JSON file in Python with no newlines for csv conversion Python 2.6.6


code: data['elements'] in selectionsFromTable

rawDescription: How to retreive particular values from a list: python

description: Retreive particular values from a list: python


code:
with open(filename) as source:
    for line in source:
        data.append(int(line))

rawDescription: I'm having trouble with input and output from files


rawDescription: Python: Finding the last index of min element?


code:
def f(row):
    row['CORRELATION'] = row['PREDICTION'].corr(row['SYNERGY_SCORE'], method='spearman')
    return row

df2 = df.groupby('COMBINATION_ID').apply(f)

rawDescription: Apply and group in the Pandas python

description: Apply and group in the Pandas python


code: pd.merge(frame, frame2, left_index=True, right_index=True)

rawDescription: Column recoding based on count of distincts


code: [{'type':k, 'items':v} for k,v in res.items()]

rawDescription: Python group by

description: Python group by


code:
df['date'] = [pd.to_datetime(t, unit='s') for t in df['Timestamp']]
for key, grp in df.groupby('Type'):
    plt.plot(grp['date'], grp['Value'])
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%B'))

rawDescription: Python Panda multi Line graph using time stamp


code:
class test(object):
    def __init__(self, a, next):
        self.a = a
        self.next = next

x = test(21, None)
assert x.a == 21

rawDescription: C struct python equivalent

description: C struct python equivalent


code:
import pandas as pd

filename = 'data.txt'
df = pd.read_table(filename, delimiter='\s+')
print(df)
#    Index ORG1 ORG2 ORG3  AB1 AS101 AS201 AS301    AB2 AS102 AS202 AS302
# 0      1    A  NaN  NaN  pen     S   NaN   NaN  dfluc     S   NaN   NaN
# 1      2    A    B    C  pen     R     S     S  dfluc     S     R     S
# 2      3    B    A    B  pen     S     S     R  dfluc     S     S     R
# 3      4    A  NaN  NaN  pen     R   NaN   NaN  dfluc     S   NaN   NaN
# 4      5    A  NaN  NaN  pen     R   NaN   NaN  dfluc     S   NaN   NaN
# 5      6    C    A    A  pen     S     R     R  dfluc     R     S     R
# 6      7    B  NaN    A  pen     R   NaN     S  dfluc     S   NaN     S
# 7      8    A    B    A  pen     R     R     R  dfluc     R     R     R
# 8      9    A  NaN  NaN  pen     R   NaN   NaN  dfluc     S   NaN   NaN

for i in range(2,4):
    orgi = 'ORG{i}'.format(i=i)
    # mask = (df['ORG1'] != 'A')&(df[orgi] == 'A')
    mask = (df['ORG1'].str.contains('A') == False)&(df[orgi].str.contains('A') == True)
    # Move ORGi --> ORG1
    df['ORG1'][mask] = df[orgi][mask]
    for j in range(1,4):
        # Move ASij --> AS1j
        source_as = 'AS{i}{j:02d}'.format(i=i, j=j)
        target_as = 'AS1{j:02d}'.format(i=i, j=j)
        try:
            df[target_as][mask] = df[source_as][mask]
        except KeyError:
            pass

print(df)

rawDescription: Moving row values between columns based on other column values in a Pandas DataFrame


code:
def func(bla, alba):
    pass
decorator = decorator_func(aaa, bar)
func = decorator(func)

rawDescription: Python decorators theory

description: Python decorators theory


code:
sftp = paramiko.SFTPClient.from_transport(transport)
try:
    sftp.chdir(remote_path)  # Test if remote_path exists
except IOError:
    sftp.mkdir(remote_path)  # Create remote_path
    sftp.chdir(remote_path)
sftp.put(local_path, '.')    # At this point, you are in remote_path in either case
sftp.close()

rawDescription: Upload files using SFTP in Python, but create directories if path doesn't exist


code:
begin, end  = a.find('('), a.find(')')
if begin != -1 and end != -1:
    a = a[:begin] + a[end+1:] + " " + a[begin+1:end]

rawDescription: Extracting part of string in parenthesis using python


code:
fd = pickle.load(open("data/fd.txt", 'rb'))
compute_ave_freq = lambda x: sum(fd.freq(i) for i in x)/len(x)
ave_freq = compute_ave_freq(word_forms) if len(word_forms) > 0 else 0

rawDescription: Faster way to store a NLTK FreqDict?

description: Faster way to store a NLTK FreqDict


code:
f2.delete(1.0, 'end') # erase all the text on the 2nd tab

f3.insert('end', 'hello, world') # insert text on the 3rd tab

rawDescription: Python tkinter: Handle multiple tabs

description: Python tkinter: Handle multiple tabs


code:
import collections
import itertools

def build_catalog(L):
    counter = itertools.count().next
    names = collections.defaultdict(counter)
    result = []
    for t in L:
        new_t = [ names[item] for item in t ]
        result.append(new_t)
    catalog = dict((name, idx) for idx, name in names.iteritems())
    return result, catalog

rawDescription: efficient list mapping in python

description: Efficient list mapping in python


code:
class ProductForm(ModelForm):
    class Meta:
        model = Product

rawDescription: Saving data using Django ModelForms

description: Saving data using Django ModelForms


code:
def type_split(sources):
    types = sorted(set(type(i) for i in sources))
    return [[item if type(item) == itype else None for item in sources]
            for itype in types]

rawDescription: Python : Split a list of length n into a table or further lists, by type, retaining order


code:
def np_array_addition_good():
    np_array = np.array([1, 2])
    np_array += np.sum(np.arange(NUM_ITERATIONS))

rawDescription: Numpy array indexing and/or addition seems slow


code: df[cols].apply(lambda s: (s > 0).sum(), axis=1)

rawDescription: pandas: conditional count across row

description: Pandas: conditional count across row


code: print(round(end_time-start_time, 3))

rawDescription: measuring the time to load a page - Python

description: Measuring the time to load a page - Python