code:
[myList[slice(*s)] for s in slice_indices(l=11, n=1)]
[myList[slice(*s)] for s in slice_indices(l=11, n=11)]

rawDescription: Splitting a list into a list of block indices


code:
import re

results = []
for line in fl:
  # [,/] means "match if either a , or a / is present"
  results.append(re.split('[,/]',line.strip()))

rawDescription: Splitting string with multiple delimiters


code:
for upfile in request.FILES.getlist('form_file'):
    filename = upfile.name
    fd = open(filename, 'w+')  # or 'wb+' for binary file
    for chunk in upfile.chunks():
        fd.write(chunk)
    fd.close()

rawDescription: Uploading multiple files in Django without using django.forms


code:
variables = {
    variable1: None,
    variable2: None,
    variable3: None,
    variable4: None,
    variable5: None
}

values = [1, 2, 3, 4]

for i, value in enumerate(values):
    variables['variable' + (i + 1)] = value

rawDescription: Assign a value to a list of variables using a loop


code:
def computeSubtreeSizes(self):
    stack = [(self.rootID, [])] #e.g. rootID = 1
    visited = self.sizes = {}

    while stack:
        nodeID, subnodes = stack[-1]
        size = visited.get(nodeID)
        if size is None:
            # Haven't seen it before.  Add totals of
            # all previously visited subnodes, and
            # add the others to the list of nodes to
            # be visited.
            size = 1
            for sn in self.nodes[nodeID]:
                sn_size = visited.get(sn)
                if sn_size is None:
                    subnodes.append(sn)
                else:
                    size += sn_size
            visited[nodeID] = size

        if subnodes:
            # Process all the subnodes one by one
            stack.append((subnodes.pop(), []))
        else:
            # When finished, update the parent
            stack.pop()
            if stack:
                visited[stack[-1][0]] += size

rawDescription: Iteratively compute subtree sizes for all nodes?


code:
def divisibility_predicate(number):
    digits = str(number)
    for n in range(1, len(digits) + 1):
        if int(digits[:n]) % n != 0:
            return n - 1
    return n

def generate_digits_permutation(n=1, number=0, digits=frozenset(range(1, 10))):
    # precondition: number has n-1 digits
    assert len(set(str(number))) == (n - 1) or (number == 0 and n == 1)
    # and the divisibility condition holds for n-1
    assert divisibility_predicate(number) == (n - 1) or (number == 0 and n == 1)

    number *= 10
    if n == 10:
        assert not digits and divisibility_predicate(number) == 10
        yield number  # divisible by 10
    else:
        for digit in digits:
            candidate = number + digit
            if candidate % n == 0:  # divisible by n
                yield from generate_digits_permutation(n + 1, candidate, digits - {digit})

from string import digits
print([n for n in generate_ints_nth_digit_divisible_by_n()
       if set(str(n)) == set(digits)])
print(list(generate_digits_permutation()))

rawDescription: Python: Code to find a number where first N digits are divisible by N (from 0-9)


code:
class FG:
    def __init__(self, accuracy=1e-3, nstep=10):
        self.accuracy = accuracy
        self.nstep = nstep

    def f(self):
        print ('f', self.accuracy, self.nstep)

    def g(self):
        self.f()
        print ('g', self.accuracy, self.nstep)

FG().f()
FG(1e-5).g()
FG(nstep=20).g()

rawDescription: Avoiding code repetition in default arguments in Python


code:
from numpy import random, nanmax, argmax, unravel_index
from scipy.spatial.distance import pdist, squareform

A = random.randint(-5,5, (500,3))
D = pdist(A)
D = squareform(D);
N, [I_row, I_col] = nanmax(D), unravel_index( argmax(D), D.shape )

rawDescription: Max Distance between 2 points in a data set and identifying the points


code: MyAbstractClass()

rawDescription: Pure virtual methods in Python

description: Pure virtual methods in Python


code:
img = Image.open(GIF_FILENAME)
rgbimg = Image.new("RGBA", img.size)
rgbimg.paste(img)
rgbimg.save('foo.jpg')

rawDescription: Python Pil Change GreyScale Tif To RGB

description: Python Pil Change GreyScale Tif To RGB


code: max_value_observed  == 3 # at the end of this step

rawDescription: Learning Python: Find and Add value inside file


code: u''.join(word) + u': ' + unicode(e)

rawDescription: Treat all Unicode characters as single letters


rawDescription: Check if an arbitrary user is in Administrator Group with Python


code:
issues = {'fields': {'assignee': None}}
issues['fields']['assignee'] or {}  # fallback to an empty dictionary
(issues['fields']['assignee'] or {}).get('displayName', 'Unassigned')

rawDescription: Checking null object from JSON response in Python


code:
def examplebdc():
    # lets assume we need to set up the 50 second timer immediately
    timer = threading.Timer(50, examplebdc)   # save a reference to the Timer object
    timer.start()                             # start it with a separate statement

    wordv = 'asdfsdfm'

    if any("m" in s for s in wordv):
        print("new post")
        timer.cancel()                        # cancel the previous timer
        threading.Timer(60*60, examplebdc).start()   # maybe save this timer too?

examplebdc()

rawDescription: pause threading.Timer for 1hr

description: Pause threading.Timer for 1hr


rawDescription: Detect and extract changing numbers in list of strings


code:
thingy = root.find('hosts')
thingy

rawDescription: etree xml parsing and deletion

description: Etree xml parsing and deletion


code: list_ip = list(set(host_list) - set(ip_value))

rawDescription: How to execute two loop simultaneously in python?

description: Execute two loop simultaneously in python


code:
# assumes Python 3
from functools import partial

def dist(row, col1, col2):
    return sum((c2 - c1)**2 for c1,c2 in zip(row[col1], row[col2])) ** 0.5

# compose a function (name the columns it applies to)
s_dist = partial(dist, col1="x", col2="center")
# apply it
S["dist"] = S.apply(s_dist, axis=1)

rawDescription: Calculating distance between two elements only in the array in python


code: blogpost.tags[:] = new_tags

rawDescription: How to remove all items from many-to-many collection in SqlAlchemy?

description: Remove all items from many-to-many collection in SqlAlchemy


code:
[{'gold': ' room 123'},
 {'better gold': 'room 1234'},
 {'best gold': 'in cellar'}]

rawDescription: Parse JSON from response with python requests


code: os = OSMOD

rawDescription: Why doesn't `sys.modules.keys()` include name from `import...as`?


code:
def get(self):
    # Work with GAE's 32MB-per-request limit, set to 30MB to stay under
    RANGE = 30*(1024**2)

    url = self.request.get('url')
    request = urllib2.Request(url)

    request.get_method = lambda: 'HEAD'
    response = urllib2.urlopen(request)
    info = response.info()
    logging.debug('Downloading {}B video'.format(info.get('Content-length')))

    request.get_method = lambda: 'GET'
    _buffer = ''
    start = 0
    while True:
        end = start + RANGE
        request.headers['Range'] = 'bytes={}-{}'.format(start, end)
        logging.debug('Buffering bytes {} to {}'.format(start, end))
        _bytes = urllib2.urlopen(request, timeout=60).read()
        _buffer += _bytes
        logging.info('Buffered bytes {} to {}'.format(start, end))

        # If there are less bytes than requested then all bytes
        # have been received, break to avoid an HTTP 416
        if len(_bytes) < (end - start):
            break

        start += (RANGE + 1)

    filename = '/MY-BUCKET/video/test_large.mp4'
    with gcs.open(filename, 'w', content_type='video/mp4') as f:
        f.write(_buffer)
    logging.info('Wrote {}B video to GCS'.format(len(_buffer)))

rawDescription: Can AppEngine *pull* in data over 32MB?

description: Can AppEngine *pull* in data over 32MB


code:
import textwrap
splitme = "Hello this is a long string and it may contain an extremelylongwordlikethis bye!"
textwrap.wrap(splitme, width=10)

rawDescription: Break up long line of text into lines of fixed width in Python 2.7


code:
import random

import tkinter as tk

# --- constants --- # UPPERCASE name

RES_X = 800
RES_Y = 600

# --- classes --- # CamelCase name

class Enemies(object):

    def __init__(self, canvas):

        # access to canvas
        self.canvas = canvas

        # started amount of enemies
        self.amount = 5

        # list for all enemies
        self.enemies = list()

        # create enemies
        for _ in range(self.amount):
            self.create_one_enemy()

    def create_one_enemy(self):
        radius = 12.5 # random

        x = random.uniform(radius, RES_X-radius)
        y = random.uniform(radius, RES_Y-radius)

        oval = self.canvas.create_oval(x-radius, y-radius, x+radius, y+radius, fill="black", outline="black")

        # one enemy
        enemy = [x, y, radius, oval]

        # apped to list - but I don't need this list
        self.enemies.append(enemy)

        # move this enemy after random time
        random_time = random.randint(150, 3000)
        root.after(random_time, self.move_one_enemy, enemy)

    def move_one_enemy(self, enemy):

        #print('moving:', enemy)

        # get old values
        x, y, radius, oval = enemy

        direction = random.randint(1,4)

        if direction == 1: # up
            y -= radius
        elif direction == 2: # down
            y += radius
        elif direction == 3: # left
            x -= radius
        elif direction == 4: # right
            x += radius

        self.canvas.coords(oval, x-radius, y-radius, x+radius, y+radius)

        # remember new values
        enemy[0] = x
        enemy[1] = y

        # move this enemy after random time
        random_time = random.randint(150, 3000)
        root.after(random_time, self.move_one_enemy, enemy)

# --- functions --- # lower_case name

def add_new_enemy():

    enemies.create_one_enemy()

    # add next enemy after random time
    timer = random.randint(150, 3000)
    root.after(random_time, add_new_enemy)

# --- main ---

root = tk.Tk()
root.title("")

canvas = tk.Canvas(root, width=RES_X, height=RES_Y, bg="white")
canvas.pack()

# create enemies and move it using `root.after`
enemies = Enemies(canvas)

# add new enemy after random time
random_time = random.randint(150, 3000)
root.after(random_time, add_new_enemy)

root.mainloop()

rawDescription: appending code to create multiple random moving sprites - python tkinter

description: Appending code to create multiple random moving sprites - python tkinter


code: mylist = [math.sqrt(n) for n in xrange(0,101)]

rawDescription: Python SyntaxError when creating a list using a generator


code:
import array
my_array = array.array("b", (True for n in range(56000)))

rawDescription: Reducing memory used by a large dict

description: Reducing memory used by a large dict


code:
def iterate_template( template, items):
   AZ=[ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i:i+1] for i in range(26) ] # ['A','B',... 'Z']
   tem = Template(template)
   return [ tem.safe_substitute( dict(zip( AZ, elem ))) for elem in items ]

rawDescription: How can I use a list-like type to generate a markdown with string.Template python?

description: Use a list-like type to generate a markdown with string.Template python


code: chars = list()

rawDescription: How can I analyze or improve my niece's simple compression algorithm that is based on Morse code?

description: Analyze or improve my niece's simple compression algorithm that is based on Morse code


code:
import random

class Game(object):

    def __init__(self, inventory, health):
        self.inventory = inventory
        self.health = health

    def randDmg(self):
        dealtDamage = random.randint(1,10)
        print("You have taken "+str(dealtDamage)+" damage.")
        return dealtDamage

    def dmgCheck(self):
        damage = self.randDmg()
        if "Armour" in self.inventory:
            damage = damage/2
        else:
            damage = damage
        self.health -= damage
        return self.health

    def play(self):
        result = self.dmgCheck()
        print("Your new health is %s" % result)

game = Game(["Armour","Sword","Healing Potion"], 100)

game.play()
game.play()

rawDescription: Python - Get a function to overwrite a variable


rawDescription: Integrating using scipy's trapz function


code:
df
df.groupby('Letters').filter(lambda x: len(x) > 2)

rawDescription: How to filter based on a boolean in a column and return a groupby obj

description: Filter based on a boolean in a column and return a groupby obj


code:
n_images = 2
images = [PhotoImage(file="filename"+str(i)+".gif") for i in range(n_images)]
current_image = -1
def change_image():
    displayFrame.delete('Animate')
    displayFrame.create_image(0,0, anchor=NW,
                        image=StaticFrame[current_image], tag='Animate')
    displayFrame.update_idletasks() #Force redraw

callback = None
def animate():
    global callback
    forward()
    callback = root.after(1000, animate)

rawDescription: Tkinter Image Viewer Method

description: Tkinter Image Viewer Method


code:
pd.rolling_std(s, window=5).head(10)
abs(s) > pd.rolling_std(s, window=5) * 3

rawDescription: Speeding up outliers check on a pandas Series


code:
class MyAction(argparse._StoreTrueAction):
    def __init__(self, *args, **kwargs):
        super(MyAction, self).__init__(*args,**kwargs)
        self.default=argparse.SUPPRESS
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, 'flaga', True)
        setattr(namespace, 'flagb', True)

rawDescription: CLI option that is an aggregation of two other options and precedence, in python


rawDescription: Combining 2-d arrays to form a 3-d array


code:
def dumpDataBlob(blob):
    """ Print data object in required format """

    timesliceEndTime = blob.timesliceEndTime

    for entry in blob.metricData:
        # gather values
        metricName = entry.metricName
        metricValue = entry.metricValue
        (serverName, appName, instanceName) = entry.agentName.split('|')

        print('{met},{app},{ser},{ins},{val},{tim}'.format(
            met=metricName,
            app=appName,
            ser=serverName,
            ins=instanceName,
            val=metricValue,
            tim=timesliceEndTime))

rawDescription: convert json to a data frame like output in python

description: Convert json to a data frame like output in python


code:
with open(filename) as fh:
    out.write(fh.readline()) # ticker
    for line in fh: #iterate through lines 'lazily', reading as you go.
        c = line.split(',')

rawDescription: Improve efficiency in Python matching

description: Improve efficiency in Python matching


code:
a
master
dups = Counter({e : min((count_a[e], count_master[e])) for e in count_a if count_both[e] > count_a[e]})
tuple(dups.elements())

rawDescription: using FOR statement on 2 elements at once python

description: Using FOR statement on 2 elements at once python


code:
if (sign == 1 and answer == number1 * number2) or (sign == 2 and answer == number1 + number2) or (sign == 3 and answer == number1 - number2) :
    score += 1

rawDescription: Python v3.3.5 maths questions program

description: Python v3.3.5 maths questions program


code:
mask = m['Name'] == 'Other'
m.loc[mask, 'Name'] = ''
m.loc[mask, 'Group'] = 'Other'
m

rawDescription: Pandas Melt Function

description: Pandas Melt Function


code:
from asyncio import coroutine
import asyncio

@asyncio.coroutine
def some_function():
    yield from asyncio.sleep(.5)
    return 5

@coroutine
def do_something():
    result = yield from some_function()
    return result

@coroutine
def do_something_else():
    future = asyncio.Future()
    result = yield from some_function()
    future.set_result(result)

@coroutine
def main():
    print((yield from do_something()))
    print((yield from do_something_else()))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

rawDescription: Python asyncio: return vs set_result

description: Python asyncio: return vs set_result


code:
import csv

with open("itemids.csv","rb") as fp:
    reader = csv.reader(fp, skipinitialspace=True)
    fp.readline() # skip header
    name_to_id = {name: int(id) for id, name in reader}

def getIDs(name_to_id, names):
    return [name_to_id[name] for name in names]

rawDescription: Input List of Items, Output List of ItemIDs


code: button[i] = ttk.Button(loadProject, text=data_files[i], command = Command(load,data_files[i])).grid(column=1, row=i, sticky=W)

rawDescription: How to make a button open a specific .csv file using Python Tkinter?

description: Make a button open a specific .csv file using Python Tkinter


code:
def find_neighbors(pindex, triang):
    neighbors = list()
    for simplex in triang.vertices:
        if pindex in simplex:
            neighbors.extend([simplex[i] for i in range(len(simplex)) if simplex[i] != pindex])
            '''
            this is a one liner for if a simplex contains the point we`re interested in,
            extend the neighbors list by appending all the *other* point indices in the simplex
            '''
    #now we just have to strip out all the dulicate indices and return the neighbors list:
    return list(set(neighbors))

rawDescription: How to find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay?

description: Find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay


code:
@route('/')
@authenticated
def index():
    return 'This is /.'

@route('/login')
def login():
    return 'This is login.'

rawDescription: bottle hooks with beaker session middleware and checking logins

description: Bottle hooks with beaker session middleware and checking logins


code:
length_freq = collections.defaultdict(int)
for l in lengths:
    length_freq[l] += 1
best_length = max(length_freq, key=length_freq.get)

rawDescription: Total number of similar items which meet uniqueness criteria


code:
[['acp',
  ['SOLO1',
   '"solo-100"',
   '"hi here is the giftMaximum amount of money, goes"',
   '430',
   '90']],
 ['jhk',
  ['SOLO2',
   '"solo-101"',
   '"hi here goes the wind.and, they go beyond"',
   '1000',
   '320']]]

rawDescription: Parsing text file in python using pyparsing


code:
x
d
# Extract values and keys
x

rawDescription: Numpy broadcast through dictionary

description: Numpy broadcast through dictionary


code:
def dropEvent(self, event):
    if(event.mimeData().hasFormat("application/x-imgname")):
        event.accept()
        data = event.mimeData().data("application/x-imgname")
        stream = QDataStream(data, QIODevice.ReadOnly)
        text = stream.readQString()
        item = QGraphicsPixmapItem(QPixmap("images/{}".format(text)))
        item.setFlags(QGraphicsItem.ItemIsSelectable|
                      QGraphicsItem.ItemIsMovable)
        position = QPointF(event.scenePos())
        item.setPos(position)
        self.addItem(item)

rawDescription: PyQt: How to transfer text data between widgets?


code:
self.image = tkinter.PhotoImage(width=w, height=h)
lines = []
for _ in range(h):
    line = []
    for _ in range(w):
        rgb = [randint(0, 255) for _ in range(3)]
        line.append("#{:02x}{:02x}{:02x}".format(*rgb))
    lines.append('{{{}}}'.format(' '.join(line)))
self.image.put(' '.join(lines))

rawDescription: Python Tkinter puzzling result

description: Python Tkinter puzzling result


rawDescription: Fetching a number from an Entry widget and running it through a function called by a button in Python 2 Tk


code: soup.find('html') is None

rawDescription: Beautifulsoup functionality not working properly in specific senario


code:
import re
anodict
re.search(r'ID\:\s([\w\.]+)', anodict['expected']).group(1)

rawDescription: Extracting elements from dictionary of list of dictionaries


rawDescription: Case insensitive sort with peewee

description: Case insensitive sort with peewee


code:
xi = linspace(min(X), max(X))
yi = linspace(min(Y), max(Y))
zi = griddata(X, Y, Z, xi, yi)
contour(xi, yi, zi)

rawDescription: Plotting 3-tuple data points in a surface / contour plot using matplotlib


code: v1, v2, v3 = itemgetter(0, 3, 4)(bar)

rawDescription: Compact way to assign values by slicing list in Python


code:
sorted_candidates = sorted(card_candidates,
                           key=lambda card: (sort_map[card[0]], card[1]))

rawDescription: sorting list of cards

description: Sorting list of cards


code:
my_dict = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}]

# Finds the common keys
common_keys = set.intersection(*map(set, my_dict))

# Makes a new dict with only those keys and sums the values into another dict
summed_dict = {key: sum(d[key] for d in my_dict) for key in common_keys}

rawDescription: Python: find common keys and sort by value


rawDescription: Inverse cumsum for numpy

description: Inverse cumsum for numpy


code:
class SubState(State):
    pass

class OtherSubState(State):
    pass

assert State.on_enter is State.on_enter
assert State.on_enter is not SubState.on_enter
assert State.on_enter is not OtherSubState.on_enter
assert SubState.on_enter is SubState.on_enter

instance = SubState()
assert instance.on_enter is not SubState.on_enter

rawDescription: Class variables and inheritance in Python


code: histogram(a, bins=10, range=None, normed=False, weights=None, new=None)

rawDescription: making binned boxplot in matplotlib with numpy and scipy in Python

description: Making binned boxplot in matplotlib with numpy and scipy in Python


rawDescription: Adding a custom validator for a new country


code: shift(xs, -3, cval=np.NaN)

rawDescription: Shift elements in a numpy array

description: Shift elements in a numpy array


code:
for i in xrange(value):
    if condition:
        continue

rawDescription: What's the best way of skip N values of the iteration variable in Python?


code:
for message in range(10):
    message = sock.recv(1024)

    splits = message.split(None, 5) # split into six pieces at most

rawDescription: how to show each element of array separately

description: Show each element of array separately


code:
class Symbol():
    # ...

    def __add__(self,other):
        from add import Add
        return Add(self,other)

rawDescription: Python, split a module into several files


code:
line_1
line_2
line_3

rawDescription: Python, Writing Multiple Lines

description: Python, Writing Multiple Lines


code:
template = select_template(self.get_template_names())
latex_content = template.render(context)
latex_content = re.sub(r'\{§', '{', latex_content)
latex_content = re.sub(r'§\}', '}', latex_content)

rawDescription: How to properly set variables in a latex template for Django

description: Properly set variables in a latex template for Django


code:
# Save a dictionary into a pickle file.
import pickle

favorite_color = { "lion": "yellow", "kitty": "red" }

pickle.dump( favorite_color, open( "save.p", "wb" ) )

# Load the dictionary back from the pickle file.

favorite_color = pickle.load( open( "save.p", "rb" ) )
# favorite_color is now { "lion": "yellow", "kitty": "red" }

rawDescription: How to load file and create infinite save files?

description: Load file and create infinite save files


code:
ITEM_PIPELINES = ['jelly.pipelines.jellyImagesPipeline']
IMAGES_STORE = '/path/to/where/you/want/to/store/images'

rawDescription: Scrapy: customize Image pipeline with renaming defualt image name


code: re.sub("[^a-z]", "", input_str)

rawDescription: python substring with unknown symbol

description: Python substring with unknown symbol


code:
new_dir = "path/to/dir/"
for file1, file2 in zip(files_in_folder_1, files_in_folder_2):
    dftask = pd.read_csv(file2)
    dfresource = pd.read_csv(file1)
    # work on df's  .......

    # save to new dir
    dftask.to_csv(os.path.join(new_dir,os.path.basename(file2)))
    dfresource.to_csv(os.path.join(new_dir,os.path.basename(file1)))

rawDescription: Different file name when saving in loop python/pandas


code:
import xml.dom.minidom as md
s = """<items>
    <item>
        <Tag1>Some Value</Tag1>
        <Tag2>Some Value</Tag1>
        <Tag3>Some Value</Tag1>
    </item>
</items>"""
root = md.parseString(s)
from xml.dom.minidom import Node
for elem in root.getElementsByTagName('item'):
    for x in elem.childNodes:
            if x.nodeType == Node.ELEMENT_NODE:
                    print(x.tagName, x.childNodes[0].data)

rawDescription: Getting list of tags from Python minidom XML


code: item.setData( QtCore.Qt.UserRole, "<b>{0}</b>".format('data to store for this QListWidgetItem'))

rawDescription: How to style (rich text) in QListWidgetItem and QCombobox items? (PyQt/PySide)

description: Style (rich text) in QListWidgetItem and QCombobox items? (PyQt/PySide)


code:
def get_dataset_as_type(d, dtype='float32'):

    # creates a new Dataset instance that points to the same HDF5 identifier
    d_new = HDF.Dataset(d.id)

    # set the ._local.astype attribute to the desired output type
    d_new._local.astype = np.dtype(dtype)

    return d_new

rawDescription: Creating reference to HDF dataset in H5py using astype


code: "({} goals, ${})".format(self.goals, self.penalties)

rawDescription: String Formatting in Python 3

description: String Formatting in Python 3


code:
_mystring()
u = uppercase()
u.str = 'a'
u.str

rawDescription: Inheriting setter, overwriting getter in python abstract class


rawDescription: Eliminate dups and sum corresponding terms in lists


rawDescription: Is there an algorithm to find unique combinations of 2 lists? 5 lists?


rawDescription: How to dynamically check logged-in state from View in web2py

description: Dynamically check logged-in state from View in web2py


code:
total_days = 3
days = []
for _ in range(total_days):
    days.append(0)

rawDescription: Simple Python loop counter issue

description: Simple Python loop counter issue


code: from __future__ import unicode_literals

rawDescription: List of unicode strings

description: List of unicode strings


code: [k for k, v in d.iteritems() if v == desired_value]

rawDescription: Finding key from value in Python dictionary:


code:
x = SomeObject()
x.y = 1
a = x.y
x.y = 2
print(a) #a is still 1, not 2

rawDescription: Two instances of the same Python module?

description: Two instances of the same Python module


rawDescription: Speeding up past-60-day mean in pandas

description: Speeding up past-60-day mean in pandas


code: many_lambdas = lambda x: lambda y: lambda z: lambda q: x + y * z ** q

rawDescription: Function Calling With 3 or More Argument Input Fields - function()()()


code: align[:, x]

rawDescription: How to filter alignment columns based on list of position in biopython?

description: Filter alignment columns based on list of position in biopython


code:
[('TestA', testType1.TestA),
 ('TestB', testType1.TestB),
 ('TestType1', testType1.TestType1)]

rawDescription: How do I programatically find what symbols were imported with Python import * command?

description: Programatically find what symbols were imported with Python import * command


code: count = np.all(listScore == np.array([2,0]),axis=1).sum()

rawDescription: Equivalent of count list function in numpy array


code:
steam_ids = open('d:\python\SteamUserIDs.txt').read().splitlines()
steam_str = ','.join(steam_ids)    # This make a comma separated string that we will use in our API calls

owned_games = {}

for s in steam_ids:
    request = urllib2.Request('http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=<<YOURKEY>>&steamid=%s&format=json' % s,headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36"})
    response = json.load(urllib2.urlopen(request))['response']
    if response.get('game_count', None):
        owned_games[s] = response['game_count']
    else:
        owned_games[s] = None

# This call will only work if you have less than 100 steam ids. If you have more, you
# will need to build steam_str differently for batches of 100
request2 = urllib2.Request('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0001/?key=<<YOURKEY>>&steamids=%s&format=json' %steam_str, headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36"})
response2 = json.load(urllib2.urlopen(request2))

rawDescription: Skipping JSON output in a loop

description: Skipping JSON output in a loop


code:
num1=int(input('Enter your number range: '))
items = list()
for x in range(1,num1+1):
    if x % 5 == 0 and x % 3 == 0:
        items.append('FizzBuzz')
    elif x % 3 == 0:
        items.append("Fizz")
    elif x % 5 == 0:
        items.append('Buzz')
    else:
        items.append(str(x))

print(*items, sep=',')

rawDescription: how do i properly make a for loop sit on one line, with commas and no spaces

description: Properly make a for loop sit on one line, with commas and no spaces


code:
def repfunc(row,evalcol,replacecol):
    if row[evalcol] > 0:
        row[replacecol] = 999 #replace value goes here!
    return row

def repframe(df,repindex,evalcol,replacecol):
    df.sort_index(inplace=True)
    df.loc[repindex][replacecol] = df.loc[repindex].apply(lambda x: repfunc(x,evalcol,replacecol), axis=1).loc[:,replacecol]

rawDescription: Conditionally replace data in a pandas multi-indexed dataframe


code:
import ply.lex as lex

states = ( ('value', 'exclusive'),)
tokens = ( 'BEG', 'NAME', 'COLON', 'END', 'COMMA', 'TYPE', 'PAD', 'NUMBER')
linepos = 0

def t_COLON(t):
    r':'
    t.lexer.begin('value')
    return t

def t_ANY_BEG(t):
    r'{'
    t.lexer.begin('INITIAL')
    return t

def t_value_TYPE(t):
    r'[cbB?hHiIlLqQnNfdp]|\d*[sP]'
    t.lexer.begin('INITIAL')
    return t

def t_value_PAD(t):
    r'x'
    t.lexer.begin('INITIAL')
    return t

def t_value_NUMBER(t):
    r'\d+'
    return t

def t_ANY_NAME(t):
    r'\w+'
    t.lexer.begin('INITIAL')
    return t

t_COMMA = ','
t_ANY_ignore= ' \t\r'
t_END=r'}'

def t_newline(t):
    r'\n'
    t.lexer.lineno += 1
    global linepos
    linepos = t.lexpos

# Error handling rule
def t_ANY_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

def getpos(lexer):
    global linepos
    return lexer.lineno, lexer.lexpos - linepos

rawDescription: Unpacking deeply nested struct with given C header into dictionary?


code: fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # in inches!

rawDescription: How to make pylab.savefig() save image for 'maximized' window instead of default size

description: Make pylab.savefig() save image for 'maximized' window instead of default size


code:
for k,v in finder.ngram_fd.items():
  print(k,v)

rawDescription: NLTK - Counting Frequency of Bigram

description: NLTK - Counting Frequency of Bigram


code:
def parse(self, response):
    """ make some manipulation here ... """

    yield Request(my_url, meta={'cookiejar': response.meta['cookiejar']}, callback = my_callback)

rawDescription: Scrap multiple accounts aka multiple logins


code: entry = g.en(text=word)

rawDescription: Randomly generated text will not update in entry widget


code: ''.join(map(str, xrange(10)))

rawDescription: list comprehension without [ ], Python

description: List comprehension without [ ], Python


code: print(letter, end='')

rawDescription: print slowly in python, (Simulate typing)

description: Print slowly in python, (Simulate typing)


code:
class ResSelect(bpdb.Select):
    def accept_residue(self, res):
        if res.id[1] >= start_res and res.id[1] <= end_res and res.parent.id == chain_id:
            return False
        else:
            return True

rawDescription: remove parts from a pdb file using python

description: Remove parts from a pdb file using python


rawDescription: Inserting an array of points into postgres from python


rawDescription: Recursive sorting function for list in Python


code:
class Item(models.Model):
    parent = models.ForeignKey('self', related_name='children')

rawDescription: Django related key of the same model

description: Django related key of the same model


code: a[a != np.array(None)]

rawDescription: efficient way of removing None's from numpy array

description: Efficient way of removing None's from numpy array


code:
from itertools import product

def multi_product(lists, repeats):
    repeated_iterables = [
        lst
        for lst, repeat in zip(lists, repeats)
        for i in range(repeat)
    ]
    return product(*repeated_iterables)

rawDescription: Can itertools allow for list to be created from multiple lists where I set a limit to how many selections per list?


code:
from itertools import groupby

keyfunc = lambda p: p[:2]
mypoints = []
for k, g in groupby(sorted(zip(x, y, z), key=keyfunc), keyfunc):
    mypoints.append(list(g)[0])

rawDescription: Python: method to remove all duplicate points from a X,Y,Z file that have identical x and y coordinates


rawDescription: Count rows that match string and numeric with pandas


code:
line = line.strip()
# split line...

rawDescription: How to remove \n from a list element?

description: Remove \n from a list element


rawDescription: Stuck with Number Float format in Python Decimal


rawDescription: Python coin-toss

description: Python coin-toss


rawDescription: How to change for-loop iterator variable in the loop in Python?

description: Change for-loop iterator variable in the loop in Python


rawDescription: How can I index group elements in re.sub?

description: Index group elements in re.sub


rawDescription: Reading binary data (image data type) from SQL database and inflate it, Matlab vs. Python


code:
import re

class LastSiteUrl(object):
    def is_admin_url(self, url):
        return re.search('^(http:\/\/.*){0,1}\/admin\/', url) is not None

    def process_request(self, request):
        if self.is_admin_url(request.path) and \
            not self.is_admin_url(request.META.get('HTTP_REFERER','')):
            request.session['last_site_url'] = request.META.get('HTTP_REFERER','')

rawDescription: Adding link to django admin page

description: Adding link to django admin page


code:
myList=['one','two','three']
'The number {1} is larger than {0} but smaller than {2}.'.format(*myList)

rawDescription: String Formatting Easiest Prettiest

description: String Formatting Easiest Prettiest


code:
for i, v in enumerate(EvenlyDistribute(lst, 3)):
    print(v)

rawDescription: How would you evenly distribute a list of sublists that each have a numerical value across three lists?


rawDescription: extracting data from multiple text files using python

description: Extracting data from multiple text files using python


code:
class ThemeBackground(Screen):
    myslider = ObjectProperty(None)

rawDescription: Apps in Kivy: get values in kv file

description: Apps in Kivy: get values in kv file


code:
a = np.eye(3)
a
a = np.hstack([a, np.array(range(3)).reshape(3,1)])
a

rawDescription: How do I add Columns to an ndarray?

description: Add Columns to an ndarray


code:
class Ball:
    def __init__(self,X,Y,imagefile):
        self.vulnerable = False
        self.velocity = [3,3]
        self.normal_ball_image = pygame.image.load (imagefile). convert()
        self.v_ball_image = pygame.image.load("images/vulnerable.png").convert()
        self.ball_image = self.normal_ball_image
        self.ball_boundary = self.ball_image.get_rect (center=(X,Y))
        self.sound = pygame.mixer.Sound ('Thump.wav')

    def toggle(self):
        self.vulnerable = not self.vulnerable
        self.ball_image = self.v_ball_image if self.vulnerable else self.normal_ball_image

rawDescription: What do i call if its in a special method


code:
string = "howdie how are you? are you good? sdfsdf"
''.join(string.rpartition('?')[:2])

rawDescription: Python : go backwards through a string, then remove everything after a specific character


code:
def repo_changes(commit):
  "Iterator over repository changes starting with the given commit."
  number = 0
  next_parent = None
  yield commit                           # return the first commit itself
  while len(commit.parents) > 0:         # iterate
    same_parent(commit.parents)          # check only one grandparent
    for parent in commit.parents:        # go over all parents
      yield parent                       # return each parent
      next_parent = parent               # for the next iteration
    commit = next_parent                 # start again

rawDescription: GitPython: get list of remote commits not yet applied


code:
class A(object):
    def __init__(self, val):
        self.idx = val

    @property
    def idx(self):
        return self._idx

    @idx.setter
    def idx(self, val):
        try:
            value1, value2 = val
        except ValueError:
            raise ValueError("Pass an iterable with two items")
        else:
            """ This will run only if no exception was raised """
            self._idx = sha512(value1+value2)

rawDescription: Property setter with multiple values

description: Property setter with multiple values


rawDescription: How to format a list of phone numbers e.g. 202.202.2020 into (202) 202-2020 using Python?

description: Format a list of phone numbers e.g. 202.202.2020 into (202) 202-2020 using Python


code:
from PIL import Image
import cStringIO
import base64

from embeddedImage import background
# or copy paste the background variable found in embeddedImage.py
im = Image.open(cStringIO.StringIO(base64.b64decode(background)))

rawDescription: Include picture data in Python, possible?


code:
string_list = [ "foo",1,None, "null","[]","bar"]
none_items = {"null", "[]"}  # or set(("null", "[]"))
[None if item in none_items else item for item in string_list]

rawDescription: check for null fields in json python

description: Check for null fields in json python


code:
for row in range(len(board)):
    for col, value in enumerate(board[row]):
        if value == 'd':
            print('[{},{}]'.format(row,col))

rawDescription: Finding a string in a string in a list python


rawDescription: Iterate over a list inside a nested dictionary


code:
import numpy as np

a = np.array((1,2,3,4))
b = np.array((2,3,4,5))
c = np.array((3,4,5,6))

arr_list = [a, b, c]

nr = len(arr_list)
row_lengths = [len(aa) for aa in arr_list]
nc = np.max(row_lengths) + nr - 1

digits = np.zeros((nr, nc), a.dtype)

for ii, aa in enumerate(arr_list):
      digits[ii, ii:(ii + row_lengths[ii])] = aa

print(digits)
# [[1 2 3 4 0 0]
#  [0 2 3 4 5 0]
#  [0 0 3 4 5 6]]

print(digits.sum(0))
# [ 1  4  9 12 10  6]

rawDescription: Adding numpy arrays in specific way

description: Adding numpy arrays in specific way


code:
In [1]: dct = {'key1': 1, 'key2': 2}

In [2]: vars().update(dct) # creates variables with name as keys and value as their corresponding value of 'dct' dictionary

In [3]: key1 # access 'key1' as variable
Out[3]: 1

In [4]: key2 # access 'key2' as variable
Out[4]: 2

rawDescription: Dictionary items to variables

description: Dictionary items to variables


rawDescription: How can I delete a row in a Pandas dataframe if the entire row is null?

description: Delete a row in a Pandas dataframe if the entire row is null


code: next(filter(lambda x: 'check' in SERVICES[x], SERVICES))

rawDescription: Python search by value

description: Python search by value


rawDescription: Adding an element from a tuple within a list to another list


code:
middle_parts_random = random.shuffle(middle_parts)
middle_parts_random # Huh? nothing is printed!
middle_parts_random == None # Ah, that's why. Darn you in-place methods!

rawDescription: Python splitting strings and jumbling the middle


code:
n, bins=histogram(q, bins=30)
bin_updated=[item for item, jtem in zip(bins, n) if do_Sobel_stuff_on(jtem)]
plt.hist(data, bins=bin_updated)

rawDescription: Edge detection of histogram - python

description: Edge detection of histogram - python


code:
from psycopg2.extensions import register_adapter

register_adapter(mytype, myadapter)

rawDescription: How to quote a string value explicitly (Python DB API/Psycopg2)

description: Quote a string value explicitly (Python DB API/Psycopg2)


code:
def myfunction(some_object_from_which_an_array_will_be_made, my_index=np.s_[:,:]):
    my_array = whatever(some_object_from_which_an_array_will_be_made)
    return my_array[my_index]
I = np.s_[1:5:2,::3]
myfunction(obj, my_index=I)

rawDescription: Store Numpy array index in variable

description: Store Numpy array index in variable


code:
import http.server
exec(compile(http.server.__loader__.get_source(http.server.__name__),
             http.server.__file__, 'exec'), dict(__name__='__main__'))

rawDescription: Start SimpleHTTPServer in python

description: Start SimpleHTTPServer in python


code: areas_neg = 0.5 * dx_intersect * abs(z[:-1]) + 0.5 * (dx - dx_intersect) * abs(z[1:])

rawDescription: Find the area between two curves ploted in matplotlib (fill_between area)


code:
data.loc[0,'a'] = data.loc[1,:]
data

rawDescription: How to assign one row of a hierarchically indexed Pandas DataFrame to another row?

description: Assign one row of a hierarchically indexed Pandas DataFrame to another row


code:
files = ["file1.txt", "file2.txt", "file3.txt", etc]
for each in  files:
    text=[]
    with open(str(each),'r') as f:
        for line in f:
            for word in line.split(": "):
                text.append(word)

    sorted = [lst[i:i+2] for i in range(0, len(lst), 2)]

    with open('save_file.csv', 'a') as f:
        writer = csv.writer(f)
        writer.writerows([zip(*sorted)[1]])

rawDescription: Transpose multiple txt data files and import into excel or database


code:
def some_method_in_your_serializer(self, obj):
    # here comes your logic to get fields from other models, probably some query
    return some_value # this is the value that comes into your custom_field

rawDescription: Django REST framework serializing model combinations


rawDescription: pandas groupby on a values based on n-1 index record

description: Pandas groupby on a values based on n-1 index record


code:
MULTIPLIER = {
    'M': 1000000,
    'K': 1000,
    '': 1,
}
PATTERN = re.compile(r'(\d+)\(([-+.\d]+)([kKmM]?)\)')

def parse(num):
    match = PATTERN.match(num)
    if match is None:
        raise ValueError("Failed to parse")
    first, second, suffix = match.groups()
    suffix = suffix.upper()
    if suffix not in MULTIPLIER:
        raise ValueError("Unrecognised multiplier %s" % suffix)
    return float(first), float(second) * MULTIPLIER[suffix]

rawDescription: Regular Expression for Financial Numbers


rawDescription: Best way to obtain information from a dict

description: Obtain information from a dict


code:
f = StringIO()
plt.savefig(f)

rawDescription: Saving a matplotlib graph as an image field in database


code:
"""Evaluating the difference in execution time between n*n and n**2"""

from time import time

n = 2
t = time()
for i in range(5000000):
    n**2
print("Time for n**2:\t%0.3f" % (time()-t))
t = time()
for i in range(5000000):
    n*n
print("Time for n*n:\t%0.3f" % (time()-t))

def test(n):
    """
    Difference in execution time between n*n and n**2
    within function scope.
    """
    t = time()
    for i in range(5000000):
        n**2
    print("Time for n**2:\t%0.3f" % (time()-t))
    t = time()
    for i in range(5000000):
        n*n
    print("Time for n*n:\t%0.3f" % (time()-t))

test(n)

rawDescription: * vs ** for a power of 2 operation

description: * vs ** for a power of 2 operation


code:
import csv

headers = []
rows = {}
filenames = []

outfile = csv.writer(open('flat.csv', 'w'))
infile = csv.reader(open('out.csv'))
infile.next()

for filename, key, value in infile:
    if not filename in rows:
        rows[filename] = {}
        filenames.append(filename)
    if key not in headers:
        headers.append(key)
    rows[filename][key] = value

outfile.writerow(headers)
for filename in filenames:
    outfile.writerow([rows[filename].get(header, '') for header in headers])

rawDescription: Python - Parsing structured text to excel


code:
for i,j in dictCaseId.iteritems():
    listItems=[None]*6
    for x,y in j:
        if x=='cond':
            tuppo = y
            listItems[0]=tuppo
        if x=='act':
            tuppo = y
            listItems[1]=tuppo
        if x=='correc':
            tuppo = y
            listItems[2]=tuppo

rawDescription: python list with fixed number of elements

description: Python list with fixed number of elements


code:
import os
import cffi
import subprocess

pth = os.path.abspath(os.path.dirname(__file__))
os.environ['PATH'] += ';%s' % pth

# preprocess: modify this for your compiler
# Using Microsoft's cl.exe that comes with VC++.
# cdef chokes on __declspec, so define DEF_FILE.
cmd = 'cl.exe /DDEF_FILE /EP %s' % os.path.join(pth, 'atc3dg.h')
hdr = subprocess.check_output(cmd, universal_newlines=True)

ffi = cffi.FFI()
ffi.cdef(hdr)

# using __declspec(dllimport) links more efficiently,
# but skipping it still works fine
lib = ffi.verify(hdr, library_dirs=[pth], libraries=['atc3dg'])
buf = ffi.new('char[100]')

err = lib.InitializeBIRDSystem()
lib.GetErrorText(err, buf, len(buf), lib.SIMPLE_MESSAGE)
print(ffi.string(buf).decode('ascii'))
# output:
# System         : No BIRDs were found anywhere

rawDescription: How to call a __cdel decorated function with cffi?

description: Call a __cdel decorated function with cffi


rawDescription: Python Pandas cumulative column between datetime ranges


rawDescription: Variable/unknown length string/unicode dtype in numpy


code: raw_img_data = img.tostring()

rawDescription: Convert string to image in python

description: Convert string to image in python


code: matches = list(dict_matcher(dict1, dict2 , 2, 6, (2, 3), (6, 8)))

rawDescription: Help using *args in tuple matching Python function


code:
x = np.arange(-5, 5)
y = x

line, = plt.plot(x, y)
center_spines()
plt.axis('equal')
plt.show()

rawDescription: Center origin in matplotlib

description: Center origin in matplotlib


code:
timeit.timeit('[x_o_r(zip(list(a), list(b))) for a in x for b in x]', 'from __main__ import x_o_r, x', number=10000)
timeit.timeit('[x_o_r_new(a, b) for a, b in product(x, repeat=2)]', 'from __main__ import x_o_r_new, x, product', number=10000)

rawDescription: Python - Result returns generator instead of list (comprehension)


code:
out = np.zeros(gray.shape+(3,))
out[:,:,1] = gray != 0

rawDescription: Making nonzero elements in grayscale array equal to 1 in 'G' column in an RGB array in Python


code:
from click import command, option, Option, UsageError

class MutuallyExclusiveOption(Option):
    def __init__(self, *args, **kwargs):
        self.mutually_exclusive = set(kwargs.pop('mutually_exclusive', []))
        help = kwargs.get('help', '')
        if self.mutually_exclusive:
            ex_str = ', '.join(self.mutually_exclusive)
            kwargs['help'] = help + (
                ' NOTE: This argument is mutually exclusive with '
                ' arguments: [' + ex_str + '].'
            )
        super(MutuallyExclusiveOption, self).__init__(*args, **kwargs)

    def handle_parse_result(self, ctx, opts, args):
        if self.mutually_exclusive.intersection(opts) and self.name in opts:
            raise UsageError(
                "Illegal usage: `{}` is mutually exclusive with "
                "arguments `{}`.".format(
                    self.name,
                    ', '.join(self.mutually_exclusive)
                )
            )

        return super(MutuallyExclusiveOption, self).handle_parse_result(
            ctx,
            opts,
            args
        )

rawDescription: Mutually exclusive option groups in python Click


rawDescription: Timedeltas in Python

description: Timedeltas in Python


code:
def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

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

rawDescription: Negative power in modular pow()

description: Negative power in modular pow()


code:
import datetime

class Reminder(models.Model):
    email = models.EmailField("e-mail")
    event = models.ForeignKey(Event, unique=True, related_name='event',)

    def date(self):
        return self.event.date - datetime.timedelta(days=7)

class Event(models.Model):
    date = models.DateTimeField(_(u"Event Date"), auto_now_add=True,)

rawDescription: How to initialize model with calculated value

description: Initialize model with calculated value


code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

groups = df.groupby('label')

# Plot
plt.rcParams.update(pd.tools.plotting.mpl_stylesheet)
colors = pd.tools.plotting._get_standard_colors(len(groups), color_type='random')

fig, ax = plt.subplots()
ax.set_color_cycle(colors)
ax.margins(0.05)
for name, group in groups:
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend(numpoints=1, loc='upper left')

plt.show()

rawDescription: Scatter plots in Pandas/Pyplot: How to plot by category


code:
dates = youtube_df['sample_date'].apply(lambda x: x.date())
youtube_total = youtube_df.groupby([dates]).sum()
print(youtube_total)
# sample_date
# 2012-10-03    19136

rawDescription: Transformations with DataFrame exporting series


code:
import collections

def a2s(a):
    res = ''
    if isinstance(a, collections.Iterable):
        for item in a:
            res +=  str(a2s(item)) + ' '
    else:
        res = str(a)
    return res

rawDescription: How to convert list of lists (tuples) to string in python with nice delimiters

description: Convert list of lists (tuples) to string in python with nice delimiters


rawDescription: xor matrix multiplication for AES mix column stage

description: Xor matrix multiplication for AES mix column stage


code:
from collections import defaultdict
import os
import os.path

def tree():
    return defaultdict(tree)
d = tree()

d["dir1"]["subdir1"]["subsubdir"]["folder1"]
d["dir1"]["subdir2"]["subsubdir"]["folder1"]["folder2"]["folder3"]
d["dir1"]["subdir3"]["subsubdir"]

def rec(directory, current_path):
    if len(directory):
        for direc in directory:
            rec(directory[direc], os.path.join(current_path, direc))
    else:
        os.makedirs(current_path)

rec(d, "")

rawDescription: Python: Create File Directories based on Dictionary Key names


code: df = DataFrame(val=rand(8), injury = [rep("shoulder",4), rep("leg",4)])

rawDescription: Julia storing a partitioned data frame to a dictionary


code:
import collections
from itertools import islice

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

rawDescription: is there some way execute every element simply?

description: Is there some way execute every element simply


code:
if (hashesFile[h].strip() == hashlib.md5(wordsFile[j]).hexdigest()):
    print ('ok')

rawDescription: Python md5 hashes comparison

description: Python md5 hashes comparison


code:
# file configParser.py
userfile = 'users_file.txt'
values = {}
with open(userfile, 'r') as infile:
    for line in userfile:
        name, value = line.strip().split('=')
        values[name] = value

rawDescription: Dynamically import file

description: Dynamically import file


code:
arr = np.ndarray((10,4),dtype = object)
arr[:,0] = int(10)
arr[:,1:] = float(10)
arr

rawDescription: how to (simply) build a integer and float mixed numpy array


code:
with open('file') as file:
  lines = file.readlines()

headers = lines[0:1]
rest = lines[1:]
chunk_size = 4

def chunks(lst, chunk_size):
  for i in xrange(0, len(lst), chunk_size):
    yield lst[i:i + chunk_size]

def write_rows(rows, file):
  for row in rows:
    file.write('%s' % row)

part = 1
for chunk in chunks(rest, chunk_size):
  with open('part%d' % part, 'w') as file:
    write_rows(headers, file)
    write_rows(chunk, file)
  part += 1

rawDescription: chunk a text database into N equal blocks and retain header

description: Chunk a text database into N equal blocks and retain header


rawDescription: Python 3.3: All possible combinations of list


code:
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User

class Command(BaseCommand):

    def handle(self, *args, **options):
        user_emails = User.objects.values_list('email', flat=True)
        with open('myfile.txt', 'w+') as fh:
            fh.write(", ".join(list(user_emails)))

rawDescription: How can I create a script where it will print all email addresses of my Django users into a small .txt file?

description: Create a script where it will print all email addresses of my Django users into a small .txt file


code:
import random
import string
from sys import getsizeof

# random generation of a string with 50k characters
st = ''.join(random.choice(string.ascii_uppercase) for _ in range(50000))

# Function that returns the original list for this string
def original_track(s):
    l = []
    for position, char in enumerate(s):
        l.append([char, position])
    return l

# Testing sizes
original_list = original_track(st)
dict_format = track_char(st)

getsizeof(original_list)
406496
getsizeof(dict_format)
1632

rawDescription: Memory consumption of python lists of lists


code:
from itertools import groupby
by_status = {}
for category, group in groupby(reports, lambda x: x.status):
    by_status[category] = list(group)

rawDescription: Is there a better way to split of objects by one of its attributes?


code:
urls_queue = [url for inurl in sys.argv[1:] for url in process(inurl) if any([url.startswith(sr) for sr in site_roots])]
urls_queue = list( set(urls_queue) ) # Get rid of duplicates

rawDescription: Extracting links in a class from a webpage


code:
from timeit import timeit
timeit("'01'[b]", "b = False")
timeit("str(int(b))", "b = False")

rawDescription: Is multiple type-casting in python bad?

description: Is multiple type-casting in python bad


code:
coll = connection['Puzzles']['Users']

# after each assignment

coll.update_one(
   { "_id": puz_dict["_id"] },
   {
       "$setOnInsert": { "username": puz_dict["username"] },
       "$push": { "puzzles": puz_dict["puzzles"] },
       "$inc": { "attempts": puz_dict["attempts"] }
   },
   upsert = True
)

rawDescription: Checking for existence of _id using and updating subdocument Pymongo


code: mock_func.__name__ = 'foo'

rawDescription: python mock: @wraps(f) problems

description: Python mock: @wraps(f) problems


rawDescription: Converting 3D matrix to cascaded 2D Matrices


code: label4Text.set("0.0.0.0\nThis subnet mask is non-routable\nas there is no network portion")

rawDescription: Continue printed text to next line in Python


code:
astr=['a header line']
for row in x:
    astr.append('%i %.2f   %s'%tuple(row))
astr='\n'.join(astr)

rawDescription: Writing row from structured numpy array with varying delimiter


code: import theCPPlibrary

rawDescription: Swig-generated Constants in Python

description: Swig-generated Constants in Python


code:
nodesAt5 = []
for (p, d) in P.nodes(data=True):
    if d['at'] == 5:
        nodesAt5.append(p)

rawDescription: Select network nodes with a given attribute value


code:
f=lambda x:x**2
f(4)

rawDescription: Lambda function returns function name instead of value in Python


code: [dict(zip(d.keys(), [np.array(d.values()).mean().round().astype(int)])) for d in L]

rawDescription: Average of key values in a list of dictionaries


code:
class LazyWrapper(object):
    def __init__(self, func):
        self.func = func
        self.value = None
    def __call__(self):
        if self.value is None:
            self.value = self.func()
        return self.value

lazy_wrapper = LazyWrapper(lambda: function_that_generates_huge_array_slowly(0))

rawDescription: python lazy variables?  or, delayed expensive computation

description: Python lazy variables?  or, delayed expensive computation


code:
f = data[:, 3].reshape(Nx1, Nx2, Nx3)
g = data[:, 4].reshape(Nx1, Nx2, Nx3)
h = data[:, 5].reshape(Nx1, Nx2, Nx3)

rawDescription: Converting coordinate tuple information to numpy arrays


code:
def job_categories():
    categories = JobCategory.objects.all()
    return {'categories': categories}

rawDescription: Is it possible to filter on a related item in Django annotations?


rawDescription: Python finding most common pattern in list of strings


code:
dic = {}
dic['New York'] = {}
dic['New York']['Chicago'] = 25

rawDescription: How to create a Dictionary in Python with 2 string keys to access an integer?

description: Create a Dictionary in Python with 2 string keys to access an integer


rawDescription: Collecting like term of an expression in Sympy


code: stuff = positions.get(tutle.pos())

rawDescription: List Title Depends on Variable in Python


code:
s="0013a200419e323b <=>€#356894040#XBEE#0#STR:XBee frame#BAT:1#"
s.split(None,1)
var1,var2 = s.split(None,1)
var1
var2

rawDescription: Python : saving variables from a text file created


code:
nm = mult.reset_index().set_index('level_2')
nm

rawDescription: copying a single-index DataFrame into a MultiIndex DataFrame

description: Copying a single-index DataFrame into a MultiIndex DataFrame


foo/bar: bar/baz

rawDescription: Python http response decoding

description: Python http response decoding


code: X <- (X < rep( colMeans(X), each=nrow(X) ) )

rawDescription: Increasing speed for R recoding task

description: Increasing speed for R recoding task


code:
import numpy as np

xcol_a = 6
ycol_a = 7
xcol_b = 0
ycol_b = 1
a = np.loadtxt('file1.txt')
b = np.loadtxt('file2.txt')

check_x = np.in1d(a[:, xcol_a], b[:, xcol_b])
check_y = np.in1d(a[:, ycol_a], b[:, ycol_b])
check = (check_x & check_y)
non_existing_indices = np.where(np.logical_not(check))[0]
non_existing_values = a[non_existing_indices]

a = a[check] # taking only the values of a that where also found in b
aind = np.lexsort((a[:, ycol_a], a[:, xcol_a]))
orig_order = np.argsort(aind)
bind = np.lexsort((b[:, ycol_b], b[:, xcol_b]))

a = a[aind][orig_order]
b = b[bind][orig_order]

rawDescription: Finding the correspondence of the elements of two columns in a two dimensional array in another 2D array


code: files = os.listdir(".")

rawDescription: Storing bash commands in python list

description: Storing bash commands in python list


code:
import os
for (dirpath, dirnames, filenames) in os.walk('G:/cycont'):
    for filename in filenames:
        print(filename, isCyrillic(filename), isCyrillicOrd(filename))

rawDescription: Renaming Cyrillic file names

description: Renaming Cyrillic file names


code:
pandas.read_csv('file',
  parse_date=0,  # 0th column
  date_parser=lambda x: pandas.Timestamp('1995-1-1')+timedelta(x))

rawDescription: Manipulating csv files from long format using numpy or pandas


code:
import readline

def rl_autoindent():
    """Auto-indent upon typing a new line according to the contents of the
    previous line.  This function will be used as Readline's
    pre-input-hook.

    """
    hist_len = readline.get_current_history_length()
    last_input = readline.get_history_item(hist_len)
    indent = ''
    try:
        last_indent_index = last_input.rindex("    ")
    except:
        last_indent = 0
    else:
        last_indent = int(last_indent_index / 4) + 1
    if len(last_input.strip()) > 1:
        if last_input.count("(") > last_input.count(")"):
            indent = ''.join(["    " for n in range(last_indent + 2)])
        elif last_input.count(")") > last_input.count("("):
            indent = ''.join(["    " for n in range(last_indent - 1)])
        elif last_input.count("[") > last_input.count("]"):
            indent = ''.join(["    " for n in range(last_indent + 2)])
        elif last_input.count("]") > last_input.count("["):
            indent = ''.join(["    " for n in range(last_indent - 1)])
        elif last_input.count("{") > last_input.count("}"):
            indent = ''.join(["    " for n in range(last_indent + 2)])
        elif last_input.count("}") > last_input.count("{"):
            indent = ''.join(["    " for n in range(last_indent - 1)])
        elif last_input[-1] == ":":
            indent = ''.join(["    " for n in range(last_indent + 1)])
        else:
            indent = ''.join(["    " for n in range(last_indent)])
    readline.insert_text(indent)

readline.set_pre_input_hook(rl_autoindent)

rawDescription: How to enable python repl autocomplete and still allow new line tabs

description: Enable python repl autocomplete and still allow new line tabs


code:
mylist = [2, 3, 4, 7, 8, 9, 0, 1, 2, 3, 10, 11, 12, 20, 19, 18, 17, 17, 18, 19,
          20, 21]

result = []

temp_list = [mylist[0]]

for i in range(1, len(mylist)):
    if abs(mylist[i] - mylist[i - 1]) != 1:
        result.append(temp_list)
        temp_list = [mylist[i]]
    else:
        temp_list.append(mylist[i])

if temp_list:
    result.append(temp_list)

print(result)

rawDescription: Split a list with consecutive block items but discontinued blocks into sub-lists


code:
c.most_common()
c.most_common(2)[-1]

rawDescription: How to find the 2nd max of a Counter - Python

description: Find the 2nd max of a Counter - Python


code: result = one * 100 + two * 10 + three

rawDescription: Showing numbers one after the other instead of them adding up


code:
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    import copy
    from django.conf import settings
    from django.utils.importlib import import_module
    from django.utils.module_loading import module_has_submodule

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = copy.copy(site._registry)
            import_module('%s.admin' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site._registry = before_import_registry

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'admin'):
                raise

rawDescription: Why isn't admin.autodiscover() called automatically in Django when using the admin, why was it designed to be called explicitly?


code: to_delete = images[5:]

rawDescription: Openstack - Selectively deleting images based on some criteria?


code:
def step1():
    whatever

def step2():
    whatever

def step2_alternative():
    whatever

def original( args ):
    step1()
    step2()

def revised( args, step2_choice ):
    step1()
    step2_choice()

rawDescription: What is an elegant way to abstract functions - not objects?


code:
lasti = None
for i in range(5):
    if i % 2 == 0:
        lasti = i
lasti

rawDescription: Perform an operation during the last iteration of a for loop in python


code:
import csv

with open("input.csv", "r") as f_input, open("output.csv", "wb") as f_output:
    csv_input = csv.reader(f_input, delimiter=" ")
    csv_output = csv.writer(f_output)
    headers = next(csv_input)

    cur_row = ""
    for cols in csv_input:
        if cur_row != cols[0]:
            cur_row = cols[0]
            csv_output.writerow([cur_row])
        csv_output.writerow(cols[1:])

rawDescription: Python sort CSV File

description: Python sort CSV File


code:
accumulationList = []
for x in originalList:
    accumulationList.extend(doSomething(x))
return accumulationList

rawDescription: How can I use a list comprehension to extend a list in python?

description: Use a list comprehension to extend a list in python


code:
with open('input.csv', 'rb') as f_input:
    entries = [[dict_row[col] for col in required] for dict_row in csv.DictReader(f_input)]

rawDescription: Python: How to pass multiple keys at a time to dictionary


code:
for i in lst_select:
    UsrFCList.append(lbox.get(i))

rawDescription: get multiple items chosen in a listbox and populate new list with the values, using Tkinter

description: Get multiple items chosen in a listbox and populate new list with the values, using Tkinter


code: dis.dis('a + b + c + d')

rawDescription: Why does string concatenation matter in Python?


rawDescription: Manually installing python package

description: Manually installing python package


rawDescription: Python - Printing/Reading first Element generally any element of bytes object


code:
post = db.session.query(Post).get(1)
post.tags.remove(sometag)
db.session.commit()

rawDescription: Flask and SqlAlchemy how to delete records from ManyToMany Table?


code:
len('\n')
len('ram\n')

rawDescription: Print length of strings from each line of stdin in python


code:
all_poses = pm.ls(type = 'dagPose') or []
bind_poses = [k for k in all_poses if k.bindPose.get()]

rawDescription: Selecting bindpose nodes

description: Selecting bindpose nodes


code:
with open('Emp schedule.txt','a') as schedule:
   schedule.write("{}\n{}\n{}\n".format(get_name,get_pay_rate,get_the_hours))

rawDescription: How to write text to an output file in a structured, organize manner

description: Write text to an output file in a structured, organize manner


code:
def nearest_applicable_conversion(x):
  try:
    return int(x)
  except ValueError:
    pass
  try:
    return float(x)
  except ValueError:
    pass
  return x

rawDescription: How does one parse a file to a 2d array whilst maintaining data types in Python?

description: Parse a file to a 2d array whilst maintaining data types in Python


code: signed = unpack('B', character)[0]

rawDescription: convert ascii character to signed 8-bit integer python

description: Convert ascii character to signed 8-bit integer python


code:
self.html.RunScript("""
    //javascript goes here
    // variable we wish to retrieve is called return_value
    document.title = return_value
    """)
r =  self.html.GetCurrentTitle()

rawDescription: wxWidgets/wxPython: Migrating from htmlWindow to Webview

description: WxWidgets/wxPython: Migrating from htmlWindow to Webview


code: df.loc[(cond1) & (cond2), 'column_name']

rawDescription: extract the subset of a pandas multi index data frame

description: Extract the subset of a pandas multi index data frame


code: [(x, dfrm.columns[y]) for x,y in np.argwhere(dfrm > 0.8)]

rawDescription: Python pandas: Getting the locations of a value in dataframe


rawDescription: Python space+time efficient Data Structure to store 2D Bit Arrays


code:
def retro_dictify(frame):
    d = {}
    for row in frame.values:
        here = d
        for elem in row[:-2]:
            if elem not in here:
                here[elem] = {}
            here = here[elem]
        here[row[-2]] = row[-1]
    return d

rawDescription: Convert pandas DataFrame to a nested dict


code:
# Custom static data
@app.route('/cdn/<path:filename>')
def custom_static(filename):
    return send_from_directory(app.config['CUSTOM_STATIC_PATH'], filename)

rawDescription: More than one static path in local Flask instance


code:
def get_key(my_dict, key):
    return reduce(dict.get, key.split("."), my_dict)

def set_key(my_dict, key, value):
    key = key.split(".")
    my_dict = reduce(dict.get, key[:-1], my_dict)
    my_dict[key[-1]] = value

def del_key(my_dict, key):
    key = key.split(".")
    my_dict = reduce(dict.get, key[:-1], my_dict)
    del my_dict[key[-1]]

rawDescription: Accessing python dict with multiple key lookup string


code:
class MyViewSet(ViewSet):
   serializer_class = MySerializer

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


code:
dic={'value':'123','sort':'desc','type':'float'}
str=''
for i in dic:
    str = str + i + '=' + dic[i] + '&'
str[:-1]

rawDescription: Convert Dictionary to String

description: Convert Dictionary to String


code:
import json
json_string = json.dumps(search_doc)

rawDescription: How to make a valid format JSON in python?

description: Make a valid format JSON in python


code: consecutives = strided.sum(axis=-1)

rawDescription: Reasoning about consecutive data points without using iteration


code:
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            # urlparse chokes on lazy objects in Python 3, force to str
            resolved_login_url = force_str(
                resolve_url(login_url or settings.LOGIN_URL))
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return _wrapped_view
    return decorator

rawDescription: how to test view with custom decorator relate to user in django?

description: Test view with custom decorator relate to user in django


code:
begin = pygame.time.get_ticks()

while pygame_loop:
    time_now = pygame.time.get_ticks()

    if time_now-begin > 1000:
        begin=pygame.time.get_ticks()
        statement = True

rawDescription: Pygame time control

description: Pygame time control


code:
ratio_sl = [sum(ib, 0.0) / sum(v != 0 for v in ia)  for ia, ib in zip(a, b)]
result = [[0 if not v else v + r for v in i] for i, r in zip(a, ratio_sl)]

rawDescription: Sum and length of lists of list

description: Sum and length of lists of list


code: #!/usr/bin/env python

rawDescription: Should I put the shebang line in every python file?


code:
from re import sub

...

raw_text = sub(r'     .*\n', '', raw_text)

rawDescription: Identifying sections tabbed in from raw text


code:
class DictWriter:
  def __init__(self, worksheet, fieldnames):
    self.worksheet =worksheet
    self.fieldnames = fieldnames
    self.nrow = 1

  def writerow(self, d):
    for k in d:
       ncol = self.fieldnames.index(k)
       self.worksheet.write(self.nrow, ncol, d[k])
    self.nrow += 1

  def writeheader(self):
    for ncol , fieldname in enumerate(self.fieldnames):
      self.worksheet.write(0, ncol, fieldname )

rawDescription: How to write data with xlsxwriter iteratively with no precise row:column coordinate?

description: Write data with xlsxwriter iteratively with no precise row:column coordinate


code:
pd.to_datetime('29JAN14:21:16:00') #Not working
pd.to_datetime('29JAN14:21:16:00',format='%d%b%y:%H:%M:%S') #Working

rawDescription: Extract date from string Pandas data frame


code: len(dict[key])

rawDescription: Obtaining length of list as a value in dictionary in Python 2.7


code:
words = {
    'man' : 'Bill',
    'store' : 'bar',
    'drink' : 'beer',
    'owner' : 'bartender',
    'action' : 'drink',
    }

text = '''
{man} walks into a {store} and orders a {drink}.
The {owner} asks {man} what he would like to {action}
'''

print(text.format(**words))

rawDescription: Python: Interpolate array of unknown size into string


rawDescription: Pandas: df.refill, adding two columns of different shape


rawDescription: Python pandas dataframe max in a group based on conditions on other columns


code:
a = np.linspace(1, 10, num=10)
truncatevalue = 5.5
a_truncated = a[a < truncatevalue]
a_truncated

rawDescription: How to truncate a numpy array for values greater than a specified value?

description: Truncate a numpy array for values greater than a specified value


code: product_list = sorted(product_list, key=lambda k: (k['verifier'] == 1, k['index']))

rawDescription: sort python list of dictionaires based on value of 2 keys

description: Sort python list of dictionaires based on value of 2 keys


code:
class UserLimitedFormset(BaseInlineFormset):
    def _construct_forms(self):
        super(UserLimitedFormset, self)._construct_forms()
        for form in self:
            form.fields['bowl'].queryset = self.instance.bowl_set.all()

PeaFormset = inlineformset_factory(django.contrib.auth.models.User, Pea, formset=UserLimitedFormset)

rawDescription: Passing queryset to foreignkeyfield in django inlineform


code: MySecondList = MyList[:]

rawDescription: List being identified with another, using new items in the loop


rawDescription: Making "durable" objects

description: Making "durable" objects


code:
from django.db import transaction

@transaction.commit_manually
def viewfunc(request):
    ...
    for item in items:
        entry = Entry(a1=item.a1, a2=item.a2)
        entry.save()
    transaction.commit()

rawDescription: What is an efficent way of inserting thousands of records into an SQLite table using Django?


code:
def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)

rawDescription: I can not make my code iterate x -= 1

description: I can not make my code iterate x -= 1


code:
url = raw_input("Enter url:-")
url

rawDescription: Parse Json data to Excel

description: Parse Json data to Excel


code:
import numpy as np
N = 100000

# Generate some random data...
n1 = np.random.random(N)
n2 = np.random.random(N)
c1, c2, c3, c4 = np.random.random(4)

ctr = np.arange(N)
list1 = n1 - n1[0] - ctr * c1
list2 = n2 - n2[0] - ctr * c2
list3 = c3 - ctr
list4 = c4 - ctr

rawDescription: Optimizing Python for loop

description: Optimizing Python for loop


code:
def re_round(li, _prec=5):
    for x in li:
        try:
            yield round(x, _prec)
        except TypeError:
            yield type(x)(re_round(x, _prec))

rawDescription: Python Quickest way to round every float in nested list of tuples


code:
if sys.version_info[0] == 2:
    input = raw_input

rawDescription: User Defined Interrupt

description: User Defined Interrupt


code:
#Given graph G(V,E) and NNodeLimit (Natural number)
#Produce a set Q of BFS proper subgraphs bearing the characteristics of U.
Q = []
nextBFSNode = [0]

while len(nextBFSNode):
    #Pop the node
    startingPoint = nextBFSNode.pop()
    #Build a BFS graph starting from some node
    q = BFS(G, startingPoint)
    #Truncate its output and save it to the list.
    Q.append(subgraph(G,q[:NNodeLimit]))
    #Add the remaining nodes as future starting points
    nextBFSNode = set(q[NNodeLimit+1:])

rawDescription: APGL (Another Python Graph Library) - Set subgraph size after a Breadth First Search


code:
# inside html_template_utils.py

import html_utils
from django import template

register = template.Library()

@register.simple_tag
def image_tag(image):
    return html_utils.image_to_html(image)

rawDescription: How can I efficiently render an image in Django?

description: Efficiently render an image in Django


code:
x = None
y = None

rawDescription: Python initialize multiple variables to the same initial value


rawDescription: Creating a dictionary with specific items from a list


code:
target_list = [1,2,8,20]
sorted(target_list, key=lambda x: abs(4-x))

rawDescription: sorting a list with respect to the closest number in the list python

description: Sorting a list with respect to the closest number in the list python


rawDescription: Extract string and assign to the variable using regex in Python


code:
for value in stats: # this is the key ['strength', 'dexterity', 'intelligence']
    value = random.randint(1,18)
    print (value)

rawDescription: How to store a random integers in a dictionary?

description: Store a random integers in a dictionary


code:
import ephem
from pprint import pprint
pprint(ephem._libastro.builtin_planets())

rawDescription: look up planet or moon by name in pyephem?

description: Look up planet or moon by name in pyephem


rawDescription: python open() escape backslash

description: Python open() escape backslash


code:
with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()])

rawDescription: How to read numbers from file in Python?

description: Read numbers from file in Python


rawDescription: How to make a sprite follow your mouse cursor using pygame?

description: Make a sprite follow your mouse cursor using pygame


code:
result = pd.melt(df.reset_index(), id_vars=['index'])
mask = result['value'] == True
result = result.loc[mask, ['index', 'variable']]
result.columns = [0, 1]
print(result)

rawDescription: Row and column indexes of True values

description: Row and column indexes of True values


code:
driver.add_cookie({'name': 'PHPSESSID', 'value': 'the value of that cookie'})
print(driver.get_cookie('PHPSESSID'))

rawDescription: Python and Selenium - PHPSESSID cookie is logging me in


rawDescription: How to swap one value with next value in Python?

description: Swap one value with next value in Python


rawDescription: numpy get values in array of arrays of arrays for array of indices

description: Numpy get values in array of arrays of arrays for array of indices


code:
import numpy as np

# Input array
A = np.array([[1,2,4.0],
             [1,1,5.0],
             [1,2,3.0],
             [0,1,9.0]])

# Extract xy columns
xy = A[:,0:2]

# Perform lex sort and get the sorted indices and xy pairs
sorted_idx = np.lexsort(xy.T)
sorted_xy =  xy[sorted_idx,:]

# Differentiation along rows for sorted array
df1 = np.diff(sorted_xy,axis=0)
df2 = np.append([True],np.any(df1!=0,1),0)
# OR df2 = np.append([True],np.logical_or(df1[:,0]!=0,df1[:,1]!=0),0)
# OR df2 = np.append([True],np.dot(df1!=0,[True,True]),0)

# Get unique sorted labels
sorted_labels = df2.cumsum(0)-1

# Get labels
labels = np.zeros_like(sorted_idx)
labels[sorted_idx] = sorted_labels

# Get unique indices
unq_idx  = sorted_idx[df2]

# Get counts and unique rows and setup output array
counts = np.bincount(labels, weights=A[:,2])
unq_rows = xy[unq_idx,:]
out = np.append(unq_rows,counts.ravel()[:,None],1)

rawDescription: NumPy array sum reduce

description: NumPy array sum reduce


code:
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'your.own.authentication.backed',
)

rawDescription: how to use user authentication in django

description: Use user authentication in django


code:
import json
def results2json(results):
   return json.dumps([r for r in results])

rawDescription: Instant search with Whoosh - Index and search a MySQL table using Whoosh outputing JSON results


code:
x=2
y=3

def func(x,y):
    x=200
    y=300

func(x,y) #inside this function, x=200 and y=300
#but by this line the function is over and those new values are discarded
print(x,y) #so this is looking at the outer scope again

rawDescription: How to change the scope of a variable in a function? Python

description: Change the scope of a variable in a function? Python


code:
class INPUT(Structure):
    class _I(Union):
        _fields_ = [
            ('mi', MOUSEINPUT),
            ('ki', KEYBDINPUT),
            ('hi', HARDWAREINPUT),
        ]

    _anonymous_ = ('i', )
    _fields_ = [
        ('type', DWORD),
        ('i', _I),
    ]

rawDescription: How would you recreate this Windows API Structure with ctypes?


code:
from news.models import News
from django.shortcuts import render
from django.template import RequestContext

def home(request):
   posts = News.objects.all()
   return render(request, 'home.html', {'posts':posts })

rawDescription: Cannot pass variables to django home template from another template in app


code:
class MyFormatter(logging.Formatter):
    converter=dt.datetime.fromtimestamp
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = ct.strftime(datefmt)
        else:
            t = ct.strftime("%Y-%m-%d %H:%M:%S")
            s = "%s.%03d" % (t, record.msecs)
        return s

...
formatter = MyFormatter(fmt='%(asctime)s %(message)s')
...
logger.debug('Jackdaws love my big sphinx of quartz.')
# 2011-06-09 08:14:38.343 Jackdaws love my big sphinx of quartz.

rawDescription: Python logging: use milliseconds in time format


code:
w = QtGui.QWidget()
w.resize(600,400)

layout = QtGui.QVBoxLayout(w)
layout.setMargin(10)
frame = QtGui.QFrame()
frame.setFrameShape(frame.Box)
layout.addWidget(frame)

layout2 = QtGui.QVBoxLayout(frame)
layout2.setMargin(20)
frame2 = QtGui.QFrame()
frame2.setFrameShape(frame2.Box)
layout2.addWidget(frame2)

rawDescription: PySide Qt: Auto vertical growth for TextEdit Widget, and spacing between widgets in a vertical layout


rawDescription: Add thousands separators to a number

description: Add thousands separators to a number


code:
import pygame
...
resolution = pygame.locals.TIMER_RESOLUTION

rawDescription: Importing a module and using its methods


rawDescription: Formatting text to be justified in Python 3.3 with .format() method


code:
class mySerial(threading.Thread):
    def __init__(self, queue):
        super(mySerial, self).__init__()
        self.queue = queue #the received data is put in a queue
        self.buffer = ''
        #configure serial connection
        self.ser = serial.Serial(port = 3, baudrate=9600)

    def run(self):
        while True:
            self.buffer += self.ser.read(self.ser.inWaiting() or 1) #read all char in buffer
            while '\n' in self.buffer: #split data line by line and store it in var
                var, self.buffer = self.buffer.split('\n', 1)
                self.queue.put(var) #put received line in the queue

rawDescription: PySerial loses data

description: PySerial loses data


code:
recordslist = [["Daniel", 18], ["John", 19], ["Paul", 20], ["Jack", 44], ["Daniel", 40]]
a_dict = dict(recordslist)
a_dict

rawDescription: Python List within List - References

description: Python List within List - References


code:
def escape4human(text):
    return text.replace('<', 'less than').replace('>', 'greater than')

rawDescription: Matching patterns in Python

description: Matching patterns in Python


rawDescription: in python, how to match Strings based on Regular Expression and get the non-matching parts as a list?

description: In python, how to match Strings based on Regular Expression and get the non-matching parts as a list


code:
def errfun(intcoef, *args):
    xs, ys = args
    return optfloat(intcoef, xs, ys)['errsqr']

rawDescription: curve fitting with integer inputs Python 3.3

description: Curve fitting with integer inputs Python 3.3


code:
import collections

subjects = [
              'Proposal to cooperate - Company Name',
              'Company Name Introduction',
              'Into Other Firm / Company Name',
              'Request for Proposal',
              'Some more Firm / Company Names'
           ]

def phrases(string):
    words = string.split()
    result = []
    for number in range(len(words)):
        for start in range(len(words)-number):
             result.append(" ".join(words[start:start+number+1]))
    return result

rawDescription: Python: Finding unknown repeated word(s) in a list of strings


code: data[numpy.where(data < 4)[0]]

rawDescription: Filter array returning arguments

description: Filter array returning arguments


code:
[c for c in '\w']
[c for c in '\n']

rawDescription: Python - What happens when I write statements in the interpreter without 'print'?


code:
mylist = ["aa","bb","cc","aa"]
list(set(mylist))

rawDescription: removing duplicates from a list of strings

description: Removing duplicates from a list of strings


code: len(val)

rawDescription: access value of a python dict() without knowing the keys

description: Access value of a python dict() without knowing the keys


code: 10 * np.random.randn(1, 100)

rawDescription: How do I match lomb-scargle and FFT plots of same dataset?

description: Match lomb-scargle and FFT plots of same dataset


rawDescription: How to get type of multidimensional Numpy array elements in Python

description: Get type of multidimensional Numpy array elements in Python


rawDescription: copying functions located in instances

description: Copying functions located in instances


code: current_adj_list = list(adj[v])

rawDescription: Finding a circle in an undirected graph

description: Finding a circle in an undirected graph


code:
import itertools
import random
import collections

choices = ['a', 'b']

list_ = [random.choice(choices) for _ in range(30)]

l_a = collections.deque([random.randint(1, 100) for _ in range(list_.count('a'))])
l_b = collections.deque([random.randint(1, 100) for _ in range(list_.count('b'))])

# Everything above is to build up the sample data.
# You can wrap your existing l_a, l_B lists in a collections.deque

# make a dictionary that holds the two dequeues keyed by the character we find in list_
lists_by_char = {'a': l_a, 'b': l_b}

# print it out to make sure we aren't cheating
print(list_)
print(l_a)
print(l_b)

for k, g in itertools.groupby(list_):
    # k will be the letter 'a' or 'b'
    # g will be the items in a _grouper.  We can call list on that to get the actual items.  But what we care about is the length of that list.
    items = [lists_by_char.get(k).popleft() for _ in range(len(list(g)))]
    # The we call popleft on the deque matching our current character as many times as our list of characters is long.
    print(k, items)

rawDescription: Advanced (maybe) selection rule for lists in Python


code:
import subprocess, time

def found():
    print("FOUND INTERNET! :)")
def lost():
    print("LOST INTERNET! :(")

def ping(target):
    return True if subprocess.call(['ping', '-c 1', target]) == 0 else False

def wait_and_notify_connection(found, lost, already_found=False):
    while True:
        # Ping Google DNS Server (99.999% Uptime)
        # and check return code
        if ping('8.8.8.8'):
            if not already_found:
                found()
                already_found = True
        else:
            if already_found:
                lost()
                already_found = False
        time.sleep(1)

wait_and_notify_connection(found, lost)

rawDescription: python call function when internet is found

description: Python call function when internet is found


code:
# We will store (R, G, B, alpha)
colorshape = R.shape + (4,)
colors = np.empty( colorshape )
for y in range(ylen):
    for x in range(xlen):
        # Normalize the radial value.
        # 'jet' could be any of the built-in colormaps (or your own).
        colors[x, y] = plt.cm.jet(R[x, y] / maxR )

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,
        linewidth=0)

plt.show()

rawDescription: Distance dependent coloring in matplotlib


code:
# Let's split the data up into train and test.
train_feats, test_feats = split_label_feats(label_feat)

rawDescription: My Maxent Classifier works fine with gis algorithm but does not work with iis algorithm. It is not throwing any error, just some warnings


code:
filename = 'vudu_hail_20140101.xml'
acceptable_stems = ['vudu', 'google']
any([acceptable_stem in filename for acceptable_stem in acceptable_stems])
filename = 'vudu_hail_20140101.xml'
acceptable_stems = ['vuduf', 'google']
any([acceptable_stem in filename for acceptable_stem in acceptable_stems])

rawDescription: One-liner for partial string match in list lookup


code: soup.find_all("td", class_="pizza")[1]

rawDescription: BeautifulSoup4 Python 3.4 Scraping Issue


code:
s = (values.cumsum() - ALLOWANCE).clip_lower(0)
desired = s.diff().fillna(s)

rawDescription: Calculate new value based on decreasing value


code:
import os.path
for fname in os.listdir(search_folder):
    FilesToSearch.append(os.path.join(search_folder,fname))

rawDescription: Searching logs, outputting lines before and after match


code:
import numpy as np
prng = np.random.RandomState()
state = prng.get_state()
state
prng.random_sample()
prng.random_sample()
prng.random_sample()
prng.set_state(state)
prng.random_sample()
prng.random_sample()

rawDescription: Choose random seed and save it

description: Choose random seed and save it


code:
from django.db import models

# Create your models here.
class Document(models.Model):
    #docfile = models.FileField(upload_to='documents/%Y/%m/%d')
    docfile = models.FileField(upload_to='documents/')

rawDescription: Django Upload Image can not find uploaded image


code:
def cluster(dicts, key):
    current_value = None
    current_span = 0
    result = []

    for d in dicts:
        value = d[key]
        if current_value is None:
            current_value = value
        elif current_value != value:
            result.append({'colspan': current_span, key: current_value})
            current_value = value
            current_span = 0
        current_span += 1

    result.append({'colspan': current_span, key: current_value})
    return result

by_open = cluster(data, 'open')
by_serve = cluster(data, 'serve')

rawDescription: How to strip a list of tuple with python?

description: Strip a list of tuple with python


rawDescription: python how to get the data of this script

description: Python how to get the data of this script


rawDescription: Django unique filtering

description: Django unique filtering


rawDescription: Unable to parse json in python

description: Unable to parse json in python


code: href[7:href.index('&')] # may need +1 after .index call

rawDescription: Stripping links returned by beautfulsoup


rawDescription: Can python regex negate a list of words?

description: Can python regex negate a list of words


code: max(d.values(), key=len)

rawDescription: Returning the longest set in a dictionary of sets?


code:
YourTreeName = scipy.spatial.cKDTree(YourArray, leafsize=100)
#Play with the leafsize to get the fastest result for your dataset

rawDescription: Nearest Neighbor Search: Python

description: Nearest Neighbor Search: Python


code:
attendees = [(a.profile, a.verified, a.from_user)
                 for a in Attendee.objects.filter(event=event)]

rawDescription: Combining lists and performing a check

description: Combining lists and performing a check


code: data = [getter(row) for row in reader if row[1]=="7/1/2000" or row[1]=="7/1/2010"]

rawDescription: manipulating TSV file

description: Manipulating TSV file


code: run_folder = os.path.abspath('Folder_' + folder)

rawDescription: os.path.join producing an extra forward slash

description: Os.path.join producing an extra forward slash


rawDescription: launch HTML code without opening web-browser

description: Launch HTML code without opening web-browser


code:
from itertools import combinations

def all_splits(s):
    for numsplits in range(len(s)):
        for c in combinations(range(1,len(s)), numsplits):
            split = [s[i:j] for i,j in zip((0,)+c, c+(None,))]
            yield split

rawDescription: Separating a String

description: Separating a String


code: something = obj.attribute

rawDescription: Sending arguments to getter in python: Is this an acceptable solution?


rawDescription: Subtract two lists in Python without using classes


code:
def contact():
    if request.method == 'POST':
        if request.form['submit'] == 'Do Something':
            pass # do something
        elif request.form['submit'] == 'Do Something Else':
            pass # do something else
        else:
            pass # unknown
    elif request.method == 'GET':
        return render_template('contact.html', form=form)

rawDescription: Flask Python Buttons

description: Flask Python Buttons


code:
lines = []
def update(t, newxy):
    for line in lines:
        f.coord(line, *newxy)

class Create:
    def __init__(self, xy, t):
        self.xy = xy
        self.t = t
        for i in xrange(self.t):
            new_line = f.create_line(200,300,300,300, tags="main_line_tag%d" % (i+1))
            lines.append(new_line)

rawDescription: how to print tags or id in tkinter used in python

description: Print tags or id in tkinter used in python


code:
class Country(models.Model):

    RUSSIA = 'RUS'
    USA = 'USA'
    GERMANY = 'GER'

    COUNTRY_CHOICES = (
        (RUSSIA, "Russia"),
        (USA, "USA"),
        (GERMANY, "Germany"),
    )

    country = models.CharField(max_length=3, choices=COUNTRY_CHOICES,
        default=self.RUSSIA)

rawDescription: How to check field in django model?

description: Check field in django model


code:
import pandas as pd

df1 = pd.read_csv("fish1.csv")
df2 = pd.read_csv("fish2.csv")

df = pd.concat([df1, df2]).fillna(0)
df = df[["Date", "Time"] + list(df.columns[1:-1])]
df.to_csv("merged_fish.csv", index=False)

rawDescription: Merge two CSV's with unique columns in python


code:
allowed = [msg for msg in collected
           if not any( dm.search(msg['service'])
                       for dm in denied_metrics) ]

rawDescription: Filtering list of dictionaries by regex match


code:
# tests.py

import random
try:
    import unittest2 as unittest
except ImportError:
    import unittest

class SimpleTest(unittest.TestCase):
    @unittest.skip("demonstrating skipping")
    def test_skipped(self):
        self.fail("shouldn't happen")

    def test_pass(self):
        self.assertEqual(10, 7 + 3)

    def test_fail(self):
        self.assertEqual(11, 7 + 3)

rawDescription: Python unittests in Jenkins?

description: Python unittests in Jenkins


code:
the_list=[] # create list
the_list.append(1) # add number
for x in the_list:
    print(x) # print number
the_list=[] # clear list

rawDescription: Store a list (ArrayList?) of integers in python


code:
for name, age in csv.reader(file):
    scores.setdefault(name, []).append(age)

rawDescription: Converting values in a dictionary to integers - python


rawDescription: remove all occurences of a given value in multiple arrays at once

description: Remove all occurences of a given value in multiple arrays at once


code: df.groupby('Date').agg({'Name': lambda x: x.isnull().sum(), 'Date': 'count'})

rawDescription: Python count Null and not Null values in Dataframe


rawDescription: Counting matching dictionaries in python


code:
def CollisionDetect():

    for particle in Particles:
        if particle.y >430 or particle.y<160:
           Particles.remove(particle)
           continue

        c = (particle.x - circle_first_x) // circle_spacing_x
        r = (particle.y - circle_first_y) // circle_spacing_y
        circle = Circles[r*Nx + c]

        if ((circle.x - particle.x)**2 + (circle.y - particle.y)**2
            <= (circle.radius+particle.radius)**2):
                particle.speedx = int(circle.speedx)
                particle.speedy = int(circle.speedy)

rawDescription: more efficient wind tunnel simulation in Pygame, using numpy

description: More efficient wind tunnel simulation in Pygame, using numpy


code:
from django.forms import ModelForm, PasswordInput

class TwitterUserForm(ModelForm):
    class Meta:
        model = TwitterUser
        widgets = {
            'password': PasswordInput(),
        }

rawDescription: Making a CharField use a PasswordInput in the admin


code:
attributes = []
for element in selector.xpath('//element'):
    for index, attribute in enumerate(element.xpath('@*'), start=1):
        attribute_name = element.xpath('name(@*[%d])' % index).extract_first()
        attributes.append((attribute_name, attribute.extract()))

attributes
dict(attributes)

rawDescription: Getting name of attributes with Scrapy XPATH


code:
import os
import gzip
import bz2
try:
    import magic
except ImportError:
    has_magic = False
else:
    has_magic = True

mime_openers = {
    'application/x-bzip2': bz2.BZ2File,
    'application/x-gzip': gzip.GzipFile,
}

ext_openers = {
    '.bz2': bz2.BZ2File,
    '.gz': gzip.GzipFile,
}

def open_autodecompress(filename, mode='r'):
    if has_magic:
        ms = magic.open(magic.MAGIC_MIME_TYPE)
        ms.load()
        mimetype = ms.file(filename)
        opener = mime_openers.get(mimetype, open)
    else:
        basepart, ext = os.path.splitext(filename)
        opener = ext_openers.get(ext, open)
    return opener(filename, mode)

rawDescription: how to concatenate multiple files for stdin of Popen

description: Concatenate multiple files for stdin of Popen


code:
for f_a in glob.glob(file_directory + "*_data_a.dat"):
    process_file(f_a, file_type='a')
    process_file(file_directory + f_a[:-11] + "_data_b.dat", file_type='b')

rawDescription: Using glob twice in a Python script

description: Using glob twice in a Python script


rawDescription: How to insert a string between particular characters in Python?

description: Insert a string between particular characters in Python


code:
def onlyLocal(x, n):
    if n == 0:
        return x
    return onlyLocal(x*2, n-1)

rawDescription: Calling While loop Function in __main__?

description: Calling While loop Function in __main__


code:
from collections import namedtuple
FileInformation = namedtuple("FileInformation", "start end")
INFO01, INFO02, INFO03, INFO04 = map(FileInformation, ((0,2),(2,10),(10,15),(15,20)))

rawDescription: Designing a reusable parser in python

description: Designing a reusable parser in python


code:
class Item(db.Model):
   ...
   tag = db.StringProperty()

query.filter("tag IN", ["glam", "speaking"])

rawDescription: How to filter() for different items?

description: Filter() for different items


code: next(i for i,v in enumerate(l) if 12 in v)

rawDescription: Finding the index of an item in a list of lists