code:
import StringIO
import re
from itertools import imap
from functools import partial

keys = ("red", "green", "blue", "alpha")
# Create an object we can read from
str_iter = StringIO.StringIO(re.sub("\xff.*", "", bitstream))
# A callable which reads 8 bytes at a time from str_iter
read_8_bytes = partial(str_iter.read, 8)
# Convert an 8-byte string into a tuple of 4 integer values
unpack_rgba = partial(struct.unpack, "<HHHH")
# An iterable of 8-byte strings
chunk_iter = iter(read_8_bytes, '')
# Map unpack_rgba over the iterator to get an iterator of 4-tuples,
# then zip each 4-tuple with the key tuple to create the desired dict
rgba = [dict(zip(keys, rgba_values))
         for rgba_values in imap(unpack_rgba, chunk_iter)]

rawDescription: Splitting a byte list into a list of dicts


code:
import struct
struct.pack('<I', 40000)

rawDescription: Writing hex value into file Python

description: Writing hex value into file Python


code: results = re.findall(r'Mike',data)

rawDescription: Urllib html not showing

description: Urllib html not showing


code:
def mergeData(file1name, file2name, outfilename, a_filter_func):
    """ Merge the data of two files. """
    mergedData = defaultdict(list)
    with open(file1name, 'r') as file1, open(file2name, 'r') as file2, open(outfilename, 'w') as outfile:
        for line in file1:
            splt = line.split()
            if a_filter_func(splt[1]):
                mergedData[splt[0].lstrip('0')].append(line)
        for line in file2:
            splt = line.split()
            if a_filter_func(splt[1]):
                mergedData[splt[0]].append(" ".join(splt[:4]))
        for k in mergedData:
            outfile.write("\n".join(mergedData[k]) + "\n")

rawDescription: Python: Search a text file and then output specific data


code:
A("foo").egg
A("foo").baz # exception

rawDescription: How to tell what is a method and what is an object constructor in this class in Python?

description: Tell what is a method and what is an object constructor in this class in Python


code:
clicmd = "/usr/local/bin/cli -s 10.1.213.226 -n Administrator -p password"
cliargs = clicmd.split()

rawDescription: Interactively writing/reading from an external program


code:
df = pd.DataFrame(index=range(0), columns=['date', 'word', 'freq'])
i = 0
for j, word in enumerate(words):
    for d, f in word:
        df.loc[i] = [d, j, f]
        i += 1

rawDescription: creating a dataframe from a dictionary of tuples in pandas

description: Creating a dataframe from a dictionary of tuples in pandas


rawDescription: NLTK - Counting Frequency of Bigram

description: NLTK - Counting Frequency of Bigram


code:
input_queue = initialize_input_queue()
ouput_queue = initialize_output_queue()

stop_flag = Event()
create_and_start_save_thread(output_queue) # read from output queue, save to DB
create_and_start_fetch_threads(input_queue, output_queue) # get sites to crawl from input queue, push crawled results to output_queue
join_fetch_threads() # this will block until the fetch threads have gone through everything in the input_queue
stop_flag.set() # this will inform the save thread that we are done
join_save_thread() # wait for all the saving to complete

rawDescription: python threading Queue producer-consumer with thread-safe

description: Python threading Queue producer-consumer with thread-safe


code:
def increment(self):
    for i, num in enumerate(reversed(self.numbers)):
        if num:  # that is, if num is not 0
            self.numbers[-i - 1] = 0 if num == 9 else num + 1
            break  # once one number is changed, we stop

rawDescription: How to use a while loop to start at the right end of the list

description: Use a while loop to start at the right end of the list


code: arg_list = sys.argv[1:]

rawDescription: Function to write lines in CSV file? Or parse list?


code:
class Child(Parent):
    pass

rawDescription: How Inheritance works in Python

description: How Inheritance works in Python


code:
d={'left':[],'right':[]}
for e in (random.random() for i in xrange(50)):
    d['left' if e<0.5 else 'right'].append(e)

rawDescription: Pythonic way to partition a list in exactly two groups


code:
directory = 'C:/Users/Geekman2/Documents/Tests/'
extension = '.txt'
...
def AddDirTo(filename):
     return directory + filename + extension
...
box1 = AddDirTo('box1') #note: you did close box1's quote on your question
cupcake = Button(donut,text = "Box #1", command = open(box1))

rawDescription: Retrieve multiple files from same directory


code:
import shared

shared.shared.do_stuff("foo")

rawDescription: Good practice sharing resources between modules?


code: {k: str(v) for k, v in d.items()}

rawDescription: Python dictionary with objects into dictionary with strings


code:
import math
math.ceil((max((x,y)) / float(x+y)) * n) * min((x,y))

rawDescription: Algorithm for distributing tasks to two printers?


code:
def _is_clean(self):
    return not self.identity_map.check_modified() and \
        not self._deleted and \
        not self._new

rawDescription: SQLAlchemy - Is there a way to see what is currently in the session?


code:
all_words1 = get_file(filename_1)
all_words2 = get_file(filename_2)

rawDescription: How to avoid repetion with my code

description: Avoid repetion with my code


code:
t1 = testclass()
t2 = testclass()
t1.myList.append(1)
t2.myList.append(2)
t1.myList
t2.myList

rawDescription: Puzzling scope behaviour

description: Puzzling scope behaviour


rawDescription: How do I update dataframe column values with Pandas?

description: Update dataframe column values with Pandas


code: re.split(r" (?:\|[^\|]+:[^\|]+\| ?)+", "As shown in Fig. 6, 1-h pretreatment of cells with 25 muM PhoCho or DiC8 inhibited by 30% DNA fragmentation |A1:1M| |A2:1S| |A4:1S| induced by 1 muM DNR and MXT. |A1:2S| |A2:2S| |A3:1M| |A4:2S| |A5:1M|")

rawDescription: How to divide sentences based on some special contents, Python,

description: Divide sentences based on some special contents, Python,


code:
class Integer(object):
    def __init__(self, name, default=None):
        self.name = name
        self.default = default

    def __get__(self, instance, owner):
        return getattr(instance, self.name, self.default)

    def clean(self, value):
        if isinstance(value, int) or str(value).isdigit():
            return int(value)
        return value

    def __set__(self, instance, value):
        if isinstance(self.clean(value), int):
            setattr(instance, self.name, value)
        else:
            raise TypeError('`{}` not a valid integer'.format(value))

class PositiveInteger(Integer):
    def clean(self, value):
        x = super(PositiveInteger, self).clean(value)
        if isinstance(x, int) and x < 0:
            raise ValueError('`{}` is not a positive integer'.format(value))
        return x

rawDescription: Reusable validating class attributes

description: Reusable validating class attributes


rawDescription: Duplicate values in a dictionary

description: Duplicate values in a dictionary


code:
import csv

from flask import Response

class Line(object):
    def __init__(self):
        self._line = None
    def write(self, line):
        self._line = line
    def read(self):
        return self._line

def iter_csv(data):
    line = Line()
    writer = csv.writer(line)
    for csv_line in data:
        writer.writerow(csv_line)
        yield line.read()

def csv_response(data):
    response = Response(iter_csv(data), mimetype='text/csv')
    response.headers['Content-Disposition'] = 'attachment; filename=data.csv'
    return response

rawDescription: Streaming a generated CSV with Flask

description: Streaming a generated CSV with Flask


code:
def Function(n):
    count = 0
    for i in range(n / 2, n):  # Outer loop execute n/2 times
        j = 1
        while j + n / 2 <= n:  # Middle loop executes n/2 times
            k = 1
            while k <= n:  # Inner loop execute logn times
                count = count + 1
                k = k * 2
            j = j + 1

    print (count)

Function(20)

rawDescription: Time complexity of a python program with nested loops


code:
# given a list of indicies...
indexes = [int(i) for i in input_col_index]

# select only those columns from each row
rdd = rdd.map(lambda x: [x[idx] for idx in indexes])

# for all rows, choose longest columns
longest_per_column = rdd.reduce(
    lambda x, y: [max(a, b, key=len) for a, b in zip(x, y)])

# convert longest column string values into lengths
print([len(x) for x in longest_per_column])

rawDescription: How to select certain columns from a csv file in pyspark based on the list of index of columns and then determine their distinct lengths

description: Select certain columns from a csv file in pyspark based on the list of index of columns and then determine their distinct lengths


code:
dictionary = {"can_optin" : "17", "appPrevAddrStreet": "33"}
fname = "test.txt"
infile = open(fname, 'r')
data = infile.readlines()
infile.close()

rawDescription: Why can't I write() multiple times on an open file?


code:
def uniform(lines):
    return random.uniform(-1, 1, [lines, 2])

rawDescription: python(numpy) -- another way to produce array (from another array)

description: Python(numpy) -- another way to produce array (from another array)


code: os.system('cp item INPUT')

rawDescription: Iterate through a list of files and copy them using python


code:
def func(lst, ln=None):
    if not ln:
        return lst
    ln = max(ln, len(lst))
    return [i for i in lst if len(i) <= ln]

rawDescription: Pythonic way to set a maximum length parameter


code:
if (not env.use_shell) or (not shell):
    real_command = "%s %s" % (sudo_prefix, _shell_escape(command))

rawDescription: Can I prevent fabric from prompting me for a sudo password?

description: Prevent fabric from prompting me for a sudo password


code: class CxxBase : CBase

rawDescription: Set base to object of undetermined size

description: Set base to object of undetermined size


rawDescription: Speeding up timestamp operations

description: Speeding up timestamp operations


rawDescription: search in pandas series des not work

description: Search in pandas series des not work


code:
if number.startswith('0'):
    ...

rawDescription: Determining the First Digit

description: Determining the First Digit


code:
class Comment(models.Model):
    text = models.TextField(max_length = 300)
    author = models.ForeignKey(User)
    timestamp = models.DateTimeField(auto_now_add = True)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique = True)
    comments = models.ManyToManyField(Comment)

rawDescription: Django ManyToMany doubt

description: Django ManyToMany doubt


code: self.g[key] if key in self.g else None

rawDescription: Python: using __getitem__ in a class and using in to find that item


rawDescription: Store additional keys in dict of dicts

description: Store additional keys in dict of dicts


code:
def http_hello_world():
    ctx = zmq.Context()
    sock = ctx.socket(zmq.ROUTER)
    sock.router_raw = True
    sock.bind("tcp://*:8080")
    while True:
        id_bytes, request = sock.recv_multipart()
        print("id: %r" % id_bytes)
        print("request:", request.decode('utf8'))
        if b'/close' in request:
            return

        # send the body of the response
        sock.send_multipart([
            id_bytes,
b"""HTTP/1.0 200 OK
Content-Type: text/plain

Hello, world!
"""
        ])
        # send an empty message to finish the response
        sock.send_multipart([
            id_bytes,
            b''
        ])

rawDescription: Send NULL message in PyZMQ

description: Send NULL message in PyZMQ


code: super().__init__(self, name, "Dog")

rawDescription: Python inheritance. Why is it so messy?

description: Python inheritance. Why is it so messy


code: import weakref

rawDescription: Using the observer pattern to delete an Observer when a Subject has been "deleted" in Python


rawDescription: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b


code:
x = 'Hello World'
any(i in x for i in ('rl', 'ld'))

rawDescription: How to extend an 'in' test?

description: Extend an 'in' test


code:
num1 = raw_input("ENter a number :")
nam1 = raw_input("What is your name:")

rawDescription: multiple inputs in python

description: Multiple inputs in python


code:
def add(a, b, type_check=False):
    if type_check:
        if not isinstance(a, (float, int)) or not isinstance(b, (float, int)):
            raise TypeError("Invalid Parameters")
    return add(a, b)

rawDescription: What is the best way to implement different versions of the same function?


code:
temp = []
for sub_list in documents:
    temp.append(sub_list[0])
documents = temp

rawDescription: How to iterate through a list of lists in python?

description: Iterate through a list of lists in python


code:
TimeDelta=FF.index[-1]-FF.index[0]
ax = fig.add_subplot(111)
my_x_axis_format(ax, TimeDelta)

rawDescription: format x-axis automatically

description: Format x-axis automatically


rawDescription: Filtering textual data in Python

description: Filtering textual data in Python


code:
rectangle.left += speed.x
rectangle.top += speed.y

rawDescription: Adding a speed vector to a position vector only works with integers


code: print(tuple('\\?'))

rawDescription: Convert from string to tuple with "\" in python


code:
@property
def c(self):
    return self.__c

rawDescription: Dynamically update attributes of an object that depend on the state of other attributes of same object


code: newRow = row1 + row2[1:]

rawDescription: Programatically do a natural join on two tables


code:
import timeit
import re

TEST = 'ABC ; DEF123,GHI_JKL ; MN OP'
SEPS = (',', ';')

rsplit = re.compile("|".join(SEPS)).split
print(timeit.timeit(lambda: [s.strip() for s in rsplit(TEST)]))
# 1.6733491150007467

print(timeit.timeit(lambda: split(TEST, SEPS)))
# 1.6442800510003508

rawDescription: Python: Split string by list of separators


code: my_string = str(number)

rawDescription: Strings won't compare properly

description: Strings won't compare properly


code:
x = np.arange(6)
v = x[1:4]
v = v - 1
v
x

rawDescription: - vs -= operators with numpy

description: - vs -= operators with numpy


rawDescription: How can I train a Genetic Programming algorithm onto a variable sequence of descriptors?

description: Train a Genetic Programming algorithm onto a variable sequence of descriptors


code:
from threading import Thread
from collections import deque
import time

# Create a new class that inherits from Thread
class Worker(Thread):

    def __init__(self, inqueue, outqueue, func):
        '''
        A worker that calls func on objects in inqueue and
        pushes the result into outqueue

        runs until inqueue is empty
        '''

        self.inqueue = inqueue
        self.outqueue = outqueue
        self.func = func
        super().__init__()

    # override the run method, this is starte when
    # you call worker.start()
    def run(self):
        while self.inqueue:
            data = self.inqueue.popleft()
            print('start')
            result = self.func(data)
            self.outqueue.append(result)
            print('finished')

def test(x):
    time.sleep(x)
    return 2 * x

if __name__ == '__main__':
    data = 12 * [1, ]
    queue = deque(data)
    result = deque()

    # create 3 workers working on the same input
    workers = [Worker(queue, result, test) for _ in range(3)]

    # start the workers
    for worker in workers:
        worker.start()

    # wait till all workers are finished
    for worker in workers:
        worker.join()

    print(result)

rawDescription: How to process input in parallel with python, but without processes?

description: Process input in parallel with python, but without processes


code:
import csv
import tempfile
import shutil
from itertools import izip

with open(filename, 'rb') as infile1, open(outfilename, 'r+b') as infile2:
    outfile = tempfile.TemporaryFile()
    outcsv = csv.writer(outfile, delimiter=' ')

    for line1, line2 in izip(infile1, infile2):
        row1, row2 = line1.split(), line2.split()
        outcsv.writerow(row2 + [row1[2]])

    # rewind files to start; alternative is to close both and use `shutil.copyfile()`
    outfile.seek(0)
    infile2.seek(0)
    shutil.copyfileobj(outfile, infile2)
    outfile.close()

rawDescription: how to separate a column of one ASCII file and add it to the last column of another ASCII file in Python?

description: Separate a column of one ASCII file and add it to the last column of another ASCII file in Python


code:
del_ids = [2, 4]
ids = [3, 2, 4, 1]
other = ['a', 'b', 'c', 'd']
zip(*((id, other) for id, other in zip(ids, other) if id not in del_ids))

rawDescription: Filtering two lists simultaneously

description: Filtering two lists simultaneously


code:
from dateutil import parser
import re
input_ls = ['Nov-2015', 'Quarter 1, 2016', 'Jan-2016', 'Dec-2015','Feb-2016', 'Quarter 4, 2015']

def sort_key(x):
    qtr = re.findall('(\d),\s(\d{4})',x)
    #If match not found parse it as date by prefixing '1,' to the string
    if len(qtr) == 0:
        return parse('1,' + x)
    #If matching then format it to a string format that is acceptable to the dateutil parser
    else:
        return parse(str(int(qtr[0][0])*3)+'-30-'+qtr[0][1])

input_ls.sort(key=sort_key)

rawDescription: Custom sorting a list in python

description: Custom sorting a list in python


code:
def newickNode(newickString, parent=None):
    String = newickString[1:-1].split(',')
    nodes = []
    for x in String:
        splitString = x.split(':')
        nodeName = splitString[0]
        nodeDistance = float(splitString[1])
        node = Node(nodeName, nodeDistance, parent)
        nodes.append(node)
    return nodes

rawDescription: Python For...loop iteration

description: Python For...loop iteration


code:
@register.simple_tag
def url_with_changed_parameter(request, param, value):
    params = request.GET
    request[param] = value
    return "%s?%s" % (request.path, params.urlencode())

rawDescription: Dealing with URLs in Django

description: Dealing with URLs in Django


code: {'gorilla': [CountByYear(year=2010, count=120302), CountByYear(year=2008, count=89323)], 'aardvark': [CountByYear(year=2007, count=123948), CountByYear(year=2008, count=120423), CountByYear(year=2004, count=96323)], 'raptorjesus': [CountByYear(year=1996, count=214)]}

rawDescription: Putting objects into a list into a dictionary


rawDescription: How to combine lines in two files with condition in python?

description: Combine lines in two files with condition in python


rawDescription: Why can't Javascript give accurate results for scientific calculations compared to python


code: data.index[-1] - pd.DateOffset(weeks=5)

rawDescription: Date Time Selection Python

description: Date Time Selection Python


code:
def updateAllWidgets():
    for widget in QApplication.allWidgets():
        widget.update()

rawDescription: PySide and Qt Properties: Connecting signals from Python to QML


code:
class Final(type):
    def __new__(cls, name, bases, classdict):
        for b in bases:
            if isinstance(b, Final):
                raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__))
        return type.__new__(cls, name, bases, dict(classdict))

class C(metaclass=Final): pass

class D(C): pass

rawDescription: Final classes in Python 3.x- something Guido isn't telling me?


code:
for i in seq:
  seqDic[i] = 1 + seqDic.get(i, 0)
  if seqDic[i] == 1: dv.append(i)

rawDescription: Learning Python and using dictionaries

description: Learning Python and using dictionaries


code:
def func():
    print("my module says hi!")

rawDescription: Is there a python 3 file extension that acts exactly like a *.py extension?


code:
@property
def string(self):
    """Convenience property to get the single string within this tag.

    :Return: If this tag has a single string child, return value
     is that string. If this tag has no children, or more than one
     child, return value is None. If this tag has one child tag,
     return value is the 'string' attribute of the child tag,
     recursively.
    """
    if len(self.contents) != 1:
        return None
    child = self.contents[0]
    if isinstance(child, NavigableString):
        return child
    return child.string

rawDescription: Beautifulsoup find element by text using `find_all` no matter if there are elements in it


code:
distance = [[[0 for k in range(10)] for j in range(3)] for i in range(3)]

distance[0][0][0] = '*'
distance[0][1][0] = 2
distance[0][2][0] = 3
distance[1][0][0] = 4
distance[1][1][0] = 5
distance[1][2][0] = 6
distance[2][0][0] = 7
distance[2][1][0] = 8
distance[2][2][0] = 9

for i in range(0,3):
    for j in range(0,3):
        if distance[i][j][0] == '*':
            for k in range(1,10):
                distance[i][j][k] = 1

if distance[0][0][0] == '*':
    for i in range(0,3):
        for j in range(0,3):
            if distance[i][j][0] != '*':
                k = distance[i][j][0]
                for i in range(0,3):
                    for j in range(0,3):
                        distance[i][j][k] = 0
print (distance)

rawDescription: Python sudoku solver blocks

description: Python sudoku solver blocks


code:
self.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')
self.set_header('Pragma', 'no-cache')
self.set_header('Expires', '0')

rawDescription: tornado.web.authenticated back button issue

description: Tornado.web.authenticated back button issue


code:
eu = make_instance(...)
other = make_instance(...)
p = Proxy(eu, other)
p.somemethod(foo)

rawDescription: Is there a way to inspect incoming args from within __getattr__ or to somehow otherwise redirect a call based upon incoming arguments?


rawDescription: largest array, sorted in reverse order from the given array

description: Largest array, sorted in reverse order from the given array


code:
def get_template_names(self):
    """
    Return a list of template names to be used for the view.
    """
    model_type = self.get_model_type()
    model_name = self.get_model_name()

    templates = [
        'zinnia/%s/%s/entry_list.html' % (model_type, model_name),
        'zinnia/%s/%s_entry_list.html' % (model_type, model_name),
        'zinnia/%s/entry_list.html' % model_type,
        'zinnia/entry_list.html']

    if self.template_name is not None:
        templates.insert(0, self.template_name)

    return templates

rawDescription: Refactoring Django class-based views, clean up 18 repetitive classes.


rawDescription: Specify list of possible values for Pandas get_dummies


code:
from calculator import greeting

greeting() # call imported function

rawDescription: How do i use function call properly. I am gonna do 2 batch python script. The one is in input the other one is output

description: Use function call properly. I am gonna do 2 batch python script. The one is in input the other one is output


code:
for i in range(k, 0, -1):
    x = np.random.binomial(n, 1./i)
    coins_per_slot[i-1] = x
    n -= x

rawDescription: How to vectorize simulation of distributing coins in numpy?

description: Vectorize simulation of distributing coins in numpy


code:
print (num_list[1]) # since num_list[0] holds 1
print (num_list[1]) # since num_list[1] holds 1
print (num_list[2]) # since num_list[2] holds 2
print (num_list[3]) # since num_list[3] holds 3
print (num_list[5]) # since num_list[4] holds 5

rawDescription: Can someone tell me where the numbers disappear?


code:
data = [u'Gluten free menu includes gluten free rolls for sandwiches and gluten free brownies! There are also many dishes that can be adjusted to be gluten free.',
 u"They use the same slicing machine for diary and meats.  Manager was knowledgable about food prep, servers were not.\r\r\r\n\r\r\r\nWe've been very select about which foods to order, but haven't had any issues.",
 u'The restaurant has a whole gluten free section of the menu and says that they will accommodate any allergies.  I myself do not have allergies but grandchildren have dairy, egg nut and niece has gluten.',
 u'Got sick from crosscontam Bfast. I suggest ordering the Mexican dishes if cross contam is an issue. My fav place in Sedona tho food is great!']
for sentence in data:
    print(' '.join(sentence.split()))

rawDescription: remove blank lines & extra space within lists - python

description: Remove blank lines & extra space within lists - python


code: sorted(rows, key=lambda x: x[0])

rawDescription: custom sort a list of list of numbers in ascending order

description: Custom sort a list of list of numbers in ascending order


code:
df[df.A != 0].plot()
df[df.B != 0].plot()

rawDescription: Mask zero values from pandas plot

description: Mask zero values from pandas plot


code:
import subprocess
import sys
inputfile = open('input.txt', 'r')
inputfile.readline()
inputfile.readline()
p = subprocess.Popen(['/usr/bin/python', 'b.py'],stdin=subprocess.PIPE,stdout=sys.stdout)
p.communicate(inputfile.read())
inputfile.close()

rawDescription: How do I create a python subprocess using a file for stdin starting at a certain line?

description: Create a python subprocess using a file for stdin starting at a certain line


code:
def stdout2file(status, prefix='pre', msg=False):
    import datetime as dt
    import os
    import sys
    if not hasattr(stdout2file, 'sav'):
        stdout2file.sav = None
    if status == 'on':
        if stdout2file.sav:
            print('You have already triggered this once  Ignoring this request.')
        else:
            now = dt.date.today()
            repname = repnameprefix = prefix + now.strftime("%Y%m%d") + '.txt'
            count = 0
            while os.path.isfile(repname):
                count += 1
                repname = repnameprefix + (".%02d" %(count))
            stdout2file.sav = sys.stdout
            f = open(repname,'w')
            sys.stdout = f
            stdout2file.fhr = f
    elif status == 'off':
        if not stdout2file.sav:
            print('Redirect is "off" already.  Ignoring this request')
        else:
            sys.stdout = stdout2file.sav
            stdout2file.fhr.close()
            if msg:
                print('output to:' + stdout2file.fhr.name)
            stdout2file.sav = None
    else:
        print('Unrecognized request')

rawDescription: replace class method with simple function

description: Replace class method with simple function


rawDescription: Python: how to have dynamicly generated function arguments without using an eval


code:
# one result
return HttpResponse(json.dumps(result.as_json()), content_type="application/json")

# a list of results
results = [ob.as_json() for ob in resultset]
return HttpResponse(json.dumps(results), content_type="application/json")

rawDescription: How to serialize to JSON a list of model objects in django/python

description: Serialize to JSON a list of model objects in django/python


code:
import numpy
lst = [6.72599983, -7.15100002, 4.68499994]
numpy.asarray(lst)
list(numpy.asarray(lst))

rawDescription: Converting numpy array to a list

description: Converting numpy array to a list


code:
def get_query_results(*filters):
    res = models.Item.query
    for i, filt in enumerate(filters, 1):
        if filt is not None:
            d = {'filter{}'.format(i): filt}
            res = res.filter(**d)
    return res.all()

rawDescription: sqlalchemy - elegant way to deal with several optional filters?

description: Sqlalchemy - elegant way to deal with several optional filters


code:
def stock_sim(price,time,mu,std):
    return [price]+[price + random.lognormvariate(mu,std) for i in range(time)]

rawDescription: I am creating a list and need to return the initial value


code:
{
  "tags": [ "mongodb", "mongoengine" ],
  "title": "Fun with MongoEngine"
}
{
  "tags": [ "mongodb" ],
  "title": "Loving Mongo"
}

rawDescription: Trouble querying ListField with mongoengine


code:
#!/usr/bin/env python
# Prey implementation in Python using PyGame

from __future__ import division # required in Python 2.7

import sys
import pygame
import random
import math

# === constants === (UPPER_CASE names)

SCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600

BLACK = (0, 0, 0)

MAX_VELOCITY = 10
NUM_BOIDS = 50

BORDER = 25

# === classes === (CamelCase names for classes / lower_case names for method)

class Prey(pygame.sprite.Sprite):

    def __init__(self, x, y):
        super(Prey, self).__init__()

        # Load image as sprite
        self.image = pygame.image.load("ressources/img/prey.png").convert()

        # Fetch the rectangle object that has the dimensions of the image
        self.rect = self.image.get_rect()

        # Coordinates
        self.rect.x = x
        self.rect.y = y

#        self.velocityX = random.randint(-10, 10) / 10.0
#        self.velocityY = random.randint(-10, 10) / 10.0

        self.velocityX = random.randint(1, 10) / 10.0
        self.velocityY = random.randint(1, 10) / 10.0

    def distance(self, prey):
        '''Return the distance from another prey'''

        distX = self.rect.x - prey.rect.x
        distY = self.rect.y - prey.rect.y

        return math.sqrt(distX * distX + distY * distY)

    def move_closer(self, prey_list):
        '''Move closer to a set of prey_list'''

        if len(prey_list) < 1:
            return

        # calculate the average distances from the other prey_list
        avgX = 0
        avgY = 0
        for prey in prey_list:
            if prey.rect.x == self.rect.x and prey.rect.y == self.rect.y:
                continue

            avgX += (self.rect.x - prey.rect.x)
            avgY += (self.rect.y - prey.rect.y)

        avgX /= len(prey_list)
        avgY /= len(prey_list)

        # set our velocity towards the others
        distance = math.sqrt((avgX * avgX) + (avgY * avgY)) * -1.0

        self.velocityX -= (avgX / 100)
        self.velocityY -= (avgY / 100)

    def move_with(self, prey_list):
        '''Move with a set of prey_list'''

        if len(prey_list) < 1:
            return

        # calculate the average velocities of the other prey_list
        avgX = 0
        avgY = 0

        for prey in prey_list:
            avgX += prey.velocityX
            avgY += prey.velocityY

        avgX /= len(prey_list)
        avgY /= len(prey_list)

        # set our velocity towards the others
        self.velocityX += (avgX / 40)
        self.velocityY += (avgY / 40)

    def move_away(self, prey_list, minDistance):
        '''Move away from a set of prey_list. This avoids crowding'''

        if len(prey_list) < 1:
            return

        distanceX = 0
        distanceY = 0
        numClose = 0

        for prey in prey_list:
            distance = self.distance(prey)

            if  distance < minDistance:
                numClose += 1
                xdiff = (self.rect.x - prey.rect.x)
                ydiff = (self.rect.y - prey.rect.y)

                if xdiff >= 0:
                    xdiff = math.sqrt(minDistance) - xdiff
                elif xdiff < 0:
                    xdiff = -math.sqrt(minDistance) - xdiff

                if ydiff >= 0:
                    ydiff = math.sqrt(minDistance) - ydiff
                elif ydiff < 0:
                    ydiff = -math.sqrt(minDistance) - ydiff

                distanceX += xdiff
                distanceY += ydiff

        if numClose == 0:
            return

        self.velocityX -= distanceX / 5
        self.velocityY -= distanceY / 5

    def update(self):
        '''Perform actual movement based on our velocity'''

        if abs(self.velocityX) > MAX_VELOCITY or abs(self.velocityY) > MAX_VELOCITY:
            scaleFactor = MAX_VELOCITY / max(abs(self.velocityX), abs(self.velocityY))
            self.velocityX *= scaleFactor
            self.velocityY *= scaleFactor

        self.rect.x += self.velocityX
        self.rect.y += self.velocityY

# === main === (lower_case names)

# --- init ---

pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
#screen_rect = screen.get_rect()

# --- objects ---

# lists
# This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'Group.'
prey_list = pygame.sprite.Group()

# This is a list of every sprite. All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()

# create prey_list at random positions
for i in range(NUM_BOIDS):
    prey = Prey(random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT))
    # Add the prey to the list of objects
    prey_list.add(prey)
    all_sprites_list.add(prey)

# --- mainloop ---

clock = pygame.time.Clock()

running = True

while running:

    # --- events ---

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    # --- updates ---

    for prey in prey_list:
        closeBoids = []
        for otherBoid in prey_list:
            if otherBoid == prey:
                continue
            distance = prey.distance(otherBoid)
            if distance < 200:
                closeBoids.append(otherBoid)

        prey.move_closer(closeBoids)
        prey.move_with(closeBoids)
        prey.move_away(closeBoids, 20)

        # ensure they stay within the screen space
        # if we roubound we can lose some of our velocity
        if prey.rect.x < BORDER and prey.velocityX < 0:
            prey.velocityX = -prey.velocityX * random.random()
        if prey.rect.x > SCREEN_WIDTH - BORDER and prey.velocityX > 0:
            prey.velocityX = -prey.velocityX * random.random()
        if prey.rect.y < BORDER and prey.velocityY < 0:
            prey.velocityY = -prey.velocityY * random.random()
        if prey.rect.y > SCREEN_HEIGHT - BORDER and prey.velocityY > 0:
            prey.velocityY = -prey.velocityY * random.random()

        prey.update()

    # Calls update() method on every sprite in the list
    #all_sprites_list.update()

    # --- draws ---

    screen.fill(BLACK)

    # Draw all the spites
    all_sprites_list.draw(screen)

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Limit to 60 frames per second
    # Used to manage how fast the screen updates
    clock.tick(120)

# --- the end ---
pygame.quit()
sys.exit()

rawDescription: Python boids implementation

description: Python boids implementation


code:
1 and 4
False and 4
1 and 2 and 3
0 and 4

rawDescription: Python Logical Operators

description: Python Logical Operators


code: d

rawDescription: Matching array elements to dictionary keys in Python


rawDescription: Mode of grouped data in (py)Spark

description: Mode of grouped data in (py)Spark


code:
with open('test.xml', "w+") as outfile:
    sys.stdout = outfile

sys.stdout = sys.__stdout__

rawDescription: How to print to screen after redirect print to file, in python?

description: Print to screen after redirect print to file, in python


code:
def rollDie(number):
    counts = [0] * 6
    for i in range(number):
        roll = random.randint(1,6)
        counts[roll - 1] += 1
    return counts

rawDescription: Python dice rolling simulation

description: Python dice rolling simulation


code: resultText = '\n'.join(res)

rawDescription: String slicing in python

description: String slicing in python


code:
class Ball(object): pass

balls = [ Ball() for _ in range(10) ]
balls
balls.remove(balls[4])
balls
len(balls)

rawDescription: How to remove specific object from a list, if I can't use the variable it is attached to, to find its index?

description: Remove specific object from a list, if I can't use the variable it is attached to, to find its index


code:
def get_first(line):
    return line.split(None, 1)[0]

def readline():
    with open("textfile1.txt",'r') as file, open("textfile2.txt",'r') as file2:
        string = set(map(get_first,file2))
        file2.seek(0)
        file2_dict = {}
        for line in file2:
            file2_dict[line.split(None, 1)[0]] = line
        for line in file:
            if line.strip() in string:
                print(file2_dict[line.rstrip()])
            else:              ##if spl not in string print new line
                print()

rawDescription: Compare lines in two .txt files, print out new line for not contained words


code:
def wordCount(paragraph):
    splited = paragraph.split()
    wordnum = len(splited)
    eWord = []
    for aWord in splited:
        if "e" in aWord:
            eWord.append(aWord)
    eWordnum = len(eWord)
    percent = round(eWordnum / wordnum * 100,2)
    return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'".format(wordnum, eWordnum, percent)

rawDescription: Python: turning a tuple from return statement into a string


rawDescription: decorate specific methods of a class

description: Decorate specific methods of a class


code:
return random.choice(max(result.items(), key=lambda kv: len(kv[1]))[1])
#      ^^^^^^^^^^^^^^                                              ^^^^

rawDescription: Selecting a random value from a dictionary in python


code:
def player(l, cache=None):
    n = len(l)
    if cache is None:
        cache = [-1] * (n + 1)
    if cache[n] < 0:
        cache[n] = min(player(l[:-1], cache), player(l[:-2], cache)) + l[-1] if l else 0
    return cache[n]

rawDescription: Need Help Writing Recursive function that find cheapest route through a list of numbers


code:
fieldsets = (
    (None,
        {'fields':('title',)}
    ),
    ('Extra',
        {
            'fields':  ('content',),
            'classes':('collapse',),
        }
    ),
)

rawDescription: How To Collapse Just One Field in Django Admin?


code:
def __init__(self, name="", age="", job=""):
    self.name = name
    self.age = age
    self.job = job

@property
def greet(self):
    txt = 'Hello'
    if self.name:
        txt += " " + self.name

    if self.age:
        txt += ". Good to know that you is " + self.age + " years old"

    if self.job:
        txt += ". I think being a " + self.job + " is amazing."

    return txt

rawDescription: Changing an instance variable when another has been changed


rawDescription: Inserting values into a list whilst looping over it (Python)


code:
# Add the worksheet data that the charts will refer to.
headings = ['ID', ' Reading 1', ' Avg Reading 1']
data = [
    [0,    1,    2,    3,    4],
    [4.2,  4.4,  4.5,  5.6,  1.2],
    ['=AVERAGE($B$2:$B$6)'] * 5,
]

rawDescription: xlsxwriter combining chart types

description: Xlsxwriter combining chart types


code:
# This replaces the last loop in your example:
for i in range(N):
    spike_times = spiketimes[i]
    datarow = data[i]
    if len(spike_times) > 0:
        for spike_time in spike_times:
            start=max(spike_time-dtbin,0)
            end=min(spike_time+dtbin,t)
            #idx = np.all([times>=start,times<=end],0)
            #datarow[idx] = np.NaN
            datarow[int(start/dt):int(end/dt)] = np.NaN
    ## replaced this with equivalent for testing
    means[i] = datarow[~np.isnan(datarow)].mean()

rawDescription: how to create a mask from time points for a numpy array?

description: Create a mask from time points for a numpy array


code: subdict = {bet_pav: [kk]}

rawDescription: dictionary of dictionaries(nested dicts)

description: Dictionary of dictionaries(nested dicts)


code:
def chocolate_cupcake():
    ...
    return [totalFlour, totalSugar, totalButter, totalEggs]

rawDescription: How can I add together two local variables from different functions?

description: Add together two local variables from different functions


code:
import numpy as np

z = your_matrix_256_x_256
y, x = np.indices(z.shape)
x = x.ravel()
y = y.ravel()
z = z.ravel()

rawDescription: Fit a line to a matrix in python

description: Fit a line to a matrix in python


code:
from datetime import date, time, timedelta, datetime
# round to midnight
today = datetime.combine(date.today(), time())
yesterday = today - timedelta(days=1)

rc.db_query({'submitted': {
  '$lt': today, # less than midnight last night
  '$gt': yesterday, # greater than midnight the night before
}})

rawDescription: IPython parallel : how to recover job IDs from IPcontroller


code:
objects = set()

for _ in range(5):
    ins = Object(1)
    print(id(ins))
    objects.add(ins)

rawDescription: How do I make sure an attribute value is unique in Python?

description: Make sure an attribute value is unique in Python


code:
import csv

def read_csv(file):
    data = []
    for row in csv.reader(file):
        data.append(row)
    return data

if __name__ == '__main__':

    path = "test.csv"
    with open(path, 'r') as f:
        print(read_csv(f))

rawDescription: Python exits CSV File before the end of File


code: {'three', 'one', 'two'}

rawDescription: appending list in python with things not already in it

description: Appending list in python with things not already in it


code:
with open('output.txt', 'w') as fout:
    for el in lines:
        fout.write('{0}\n'.format(' '.join(el)))

rawDescription: Python : Sort file by arbitrary column, where column contains time values


code:
counts = {}
with open('path/to/input') as infile:
    for a,b in pairwise(char for line in infile for word in line.split() for char in word):
        given = ord(a) - ord('a')
        char = ord(b) - ord('a')
        if given not in counts:
            counts[given] = {}
        if char not in counts[given]:
            counts[given][char] = 0
        counts[given][char] += 1

answer = {}
for given, chardict in answer.items():
    total = sum(chardict.values())
    for char, count in chardict.items():
        answer[given][char] = count/total

rawDescription: How do I program bigram as a table in python?

description: Program bigram as a table in python


code:
def create_something(self):
    variable = loader.loadModel('myModel.bam')
    variable.setPos(123,1231,5)
    return variable

rawDescription: Accessing a variable defined inside a function Python


code:
from mock import Mock
import machines

def MockCalculator(multiplier):
    mock = Mock(spec=machines.Calculator, name='MockCalculator')

    def multiply_proxy(n):
        '''Multiply by 2*multiplier instead of multiplier so we can see the
        difference.
        '''
        return 2 * multiplier * n
    mock.multiply = multiply_proxy

    return mock

def increment_mock(n):
    '''Increment by 2 instead of 1 so we can see the difference.'''
    return n + 2

def decrement_mock(n):
    '''Decrement by 2 instead of 1 so we can see the difference.'''
    return n - 2

rawDescription: How to mock Python static methods and class methods

description: Mock Python static methods and class methods


code:
for o in myObjects:
    o.method()

rawDescription: best way to deal with a large number of objects in python

description: Deal with a large number of objects in python


code:
import rpyc

rpyc.core.protocol.DEFAULT_CONFIG['allow_pickle'] = True

def square(x):
    return x*x

c = rpyc.connect("localhost", port = 18861, config = rpyc.core.protocol.DEFAULT_CONFIG)
result = c.root.exposed_RemotePool(square, [1,2,3,4])
print(result)

rawDescription: Multiprocessing Python with RPYC "ValueError: pickling is disabled"


rawDescription: sort an array to fit another array with numpy

description: Sort an array to fit another array with numpy


code:
# You can create these array in a loop if you want
a = np.array([a1, a2, a3, ..., a9])
b = np.array([b1, b2, b3, ..., b9])
c = np.std(a / b, 0)

rawDescription: Python, iterate over multiple arrays to perform tasks


code:
fin = open ("miles.txt","r")
stats={}
for line in fin:
    if line[0].isalpha(): #its got a city, state, x, y and pop stat to keep
        city, state = line.split(', ')
        state = state[ :state.index('[') ]
        #get the two elements around the commas within the square brackets
        lat, lng = line[ line.index('[') +1 : line.index(']') ].split(',')
        #get the element after the last right bracket
        pop = line[line.index(']') +1 :]
        stats.update( {(city, state): (lat, lng, pop)} )
return stats

rawDescription: Splitting a state name with a city name, return a list containing both?


code: value = float(dic['value']) if dic['operator'] == "!=" else dic['value']

rawDescription: Python dictionary to equivalent pymongo statement


rawDescription: Python: How to make integers from a stream of character data?


rawDescription: Comparing dictionaries based on a combination of keys


code:
class StageOfWorkForm(ModelForm):
    def __init__(self, work, *args, **kwargs):
        super(StageOfWorkForm, self).__init__(*args, **kwargs)
        self.fields['gallery'].queryset = work.gallery_set.all()

rawDescription: How to customize a Queryset of a Field from a admin Inline that uses a pk of the primary form in Django?

description: Customize a Queryset of a Field from a admin Inline that uses a pk of the primary form in Django


rawDescription: How to access a function inside a function?

description: Access a function inside a function


code:
numbers = [int(s) for s in lines.split() if s.isdigit()]
for number in numbers:
    if number in open_numbers: ...

rawDescription: Create a list of numbers that exist in a file with Python


code:
pattern = r"""(?x)                   # set flag to allow verbose regexps
              (?:[A-Z]\.)+           # abbreviations, e.g. U.S.A.
              |\d+(?:\.\d+)?%?       # numbers, incl. currency and percentages
              |\w+(?:[-']\w+)*       # words w/ optional internal hyphens/apostrophe
              |(?:[+/\-@&*])         # special characters with meanings
            """

rawDescription: Python: Regular Expression not working properly


code:
def condition(objs, radio, **kwargs):
    if radio == 'equal to':
        filters = {'%s__icontains' % key: value for key, value in kwargs.iteritems()}
        objs = objs.filter(**filters)
    if radio == 'not equal to':
        filters = {'%s__icontains' % key: value for key, value in kwargs.iteritems()}
        objs = objs.exclude(**filters)
    return objs

rawDescription: How can I fix the following Django code? Using variables within function command

description: Fix the following Django code? Using variables within function command


code: j

rawDescription: Can anybody explain me the numpy.indices()?


code:
win.winHandle.maximize()
win.fullscr = True
win.winHandle.activate()
win.flip()

rawDescription: PsychoPy reopen window

description: PsychoPy reopen window


rawDescription: python : lxml xpath tag name with colon

description: Python : lxml xpath tag name with colon


code:
def test():
    num1 = random.randint(1, 10)
    num2 = random.randint(1, num1)

    def add(x, y):
        return x+y

    def sub(x, y):
        return x-y

    def mult(x, y):
        return x*y

    ops = {
        '+': add,
        '-': sub,
        '*': mult,
    }

    keys = list(ops.keys()) #=> ['+', '*', '-']
    rand_key = random.choice(keys)  #e.g. '*'
    operation = ops[rand_key]  #e.g. mult

    correct_result = operation(num1, num2)

rawDescription: python: Primary school Arithmetic quiz- saving results to a .txt file

description: Python: Primary school Arithmetic quiz- saving results to a .txt file


code:
import numpy as np
v = np.array([1, 1, 1])
u_list = [v]

print(id(v))
for i in range(2):
    v += np.array([i, i, i])
    u_list.append(v)
    print(id(v))

rawDescription: Python Numpy Array Operator x += y Different From x = x + y?


code:
items = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']
sorted_items = []
for item in items:
    sorted_items.append("".join(sorted(item)))

rawDescription: For loop - Sorting each character alphabetically within a list of words


code:
import operator
mylist.sort(key=operator.itemgetter('weight', 'factor'))

rawDescription: Ordering a list of dictionaries in python


code:
process = commandwrapper.WrapCommand(command, shell=True) # Also tried False with same behaivor.
cmd = process.prepareToRun()
# Stream the output to the console and stdoutfiles
for line in iter(cmd.stdout.readline,""):
    sys.stdout.write(line)

rawDescription: Subprocess displays sys.stdout correctly in PyCharm but not in the console


code:
import numpy
bin_halfway = pctile_boundaries[:-1] + (numpy.diff(pctile_boundaries)/2)

rawDescription: Pandas assign each row the mean of its bin


code:
def completed_quarter(dt):
    prev_quarter_map = ((4, -1), (1, 0), (2, 0), (3, 0))
    quarter, yd = prev_quarter_map[(dt.month - 1) // 3]
    return (dt.year + yd, quarter)

from datetime import date
completed_quarter(date(2015, 1, 12))
completed_quarter(date(2015, 8, 31))
completed_quarter(date(2015, 12, 31))

rawDescription: finding the year and quarter from a datetime object in python

description: Finding the year and quarter from a datetime object in python


code:
def equal_dicts(d1, d2, ignore_keys):
    ignored = set(ignore_keys)
    for k1, v1 in d1.iteritems():
        if k1 not in ignored and (k1 not in d2 or d2[k1] != v1):
            return False
    for k2, v2 in d2.iteritems():
        if k2 not in ignored and k2 not in d1:
            return False
    return True

rawDescription: Compare dictionaries ignoring specific keys


code:
import numpy as np
import pandas as pd

HEADER = '''
<html>
    <head>
        <style>
            .df tbody tr:last-child { background-color: #FF0000; }
        </style>
    </head>
    <body>
'''
FOOTER = '''
    </body>
</html>
'''

df = pd.DataFrame({'a': np.arange(10), 'b': np.random.randn(10)})
with open('test.html', 'w') as f:
    f.write(HEADER)
    f.write(df.to_html(classes='df'))
    f.write(FOOTER)

rawDescription: Pandas Dataframes to_html: Highlighting table rows


code: filter(None, (data_grabber(x) for x in websites))

rawDescription: How can I prevent this from returning a long list of None values?

description: Prevent this from returning a long list of None values


rawDescription: Flask-Admin default filters

description: Flask-Admin default filters


code:
import lxml.html as lh
import io

somehtml = "
Here is my solution:

 some code here

this is not a code
"

doc=lh.parse(io.BytesIO(somehtml))
root=doc.getroot()
pres=root.xpath('//pre/code/..')

for pre in pres:
    pre.attrib['class']='foo'
print(lh.tostring(root))

rawDescription: adding a class via python

description: Adding a class via python


code:
fname = "data.yaml"
import yaml
with open(fname, "w") as f:
    yaml.dump(data, f)

rawDescription: Writing camera matrix into xml/yaml file


code:
import subprocess

with (open('message_stdout.log', 'w'), open('message_stderr.log', 'w')) as (stdout_file, stderr_file):
    my_process = subprocess.Popen(["iPython.exe", "script.py"],
                                   stdout=stdout_file,
                                   stderr=stderr_file)

rawDescription: redirect print to log files, in subprocesses too

description: Redirect print to log files, in subprocesses too


code:
df['Owner'].ffill()
ff = df['Owner'].ffill()
ff[ff == df['Owner'].bfill()]

rawDescription: Replacing missing values if lag and lead are the same


rawDescription: python - Extend 2-d array and interpolate the missing values

description: Python - Extend 2-d array and interpolate the missing values


code: Wait.timeout = 20

rawDescription: Class attribute or argument's default value


code:
def time_in_24h(time,time_day): #time is eastern time
    ''' (number, str)--> number
    This function converts a 12-hour time, represented by am/pm,to its equivalent 24-hour time.
    Returns time in the 24-hour format.
    '''
    cCentral = 'Central Time(CT)' #-1 hour offset
    mMountain = 'Mountain Time(MT)'#-2 hours offset
    pPacific = 'Pacific Time(PT)'#-3 hours offset
    eEst = 'EST is'

    if time_day!='pm' and time_day!='am':

        print('Input is not in the right format')  #this is where input is not in the right format
        return 0

    else:
        est_24hour = to_24hour(time, time_day)
        hour, ampm = to_12hour((est_24hour - 1 + 24) % 24)
        print(time, time_day, eEst, hour, ampm, cCentral)
        hour, ampm = to_12hour((est_24hour - 2 + 24) % 24)
        print(time, time_day, eEst, hour, ampm, mMountain)
        hour, ampm = to_12hour((est_24hour - 3 + 24) % 24)
        print(time, time_day, eEst, hour, ampm, pPacific)

rawDescription: Python - Convert time to different time zone with am/pm


code:
from elasticsearch_dsl import DocType, Nested, String

class MyType(DocType):
    name = String()
    nationality = String()

    address = Nested(
        include_in_parent=True,
        properties={
            'location': String(),
            'state': String(),
            'city': String(),
        }
    )

rawDescription: how to create a nested index in ElasticSearch with Python?

description: Create a nested index in ElasticSearch with Python


code: featured = sorted(filesToWrite, key=lambda k: ("myKey" not in k, k.get("myKey", None)))

rawDescription: Sort python list of dictionaries by key if key exists


code:
@pm.stochastic
def a(value=.5):
    if 0 <= value < 1:
        return np.log(1.-value)
    else:
        return -np.inf

rawDescription: How should I use @pm.stochastic in PyMC?

description: How should I use @pm.stochastic in PyMC


code: df2 = df.pivot(index='date', columns='Location')

rawDescription: How to use Pandas to take multi year average in Python

description: Use Pandas to take multi year average in Python


code: url(r'^(?P<resource>[a-z]+)_lists/view/$', 'admin.views.customlist_handler'), #Or whatever regex pattern is more appropriate

rawDescription: django Url endswith regex in url path

description: Django Url endswith regex in url path


code: employee = Employee(firstname='John', lastname='Smith')

rawDescription: generalised insert into sqlalchemy using dictionary

description: Generalised insert into sqlalchemy using dictionary


code: output.write("{}\t{}".format(a, am))

rawDescription: Writing Arrays to a Tab Delimited Text File


code:
records = []
with open('names.csv') as csvfile:
     reader = csv.reader(csvfile)
     for row in reader:
         records.append(row)

# cel "A4" would be
records[0][3]

rawDescription: Extract information from Excel with python 2.7/ pyMel?


code:
import random

new_list += random.sample(old_list, 5)

rawDescription: Choose 5 different elements from a list?

description: Choose 5 different elements from a list


code: ['I have a question', 'The answer is not there', 'Please Help']

rawDescription: how to extract all the data between

description: Extract all the data between


code:
from itertools import izip_longest

with open('dict.csv', 'ab') as out:
    writer = csv.writer(out)
    for row in izip_longest(array, array2, array3):
        writer.writerow([x.encode("utf-8") for x in row])

rawDescription: Combining variables from different sources and write them in a CSV (Python)


code:
line='protein_coding other stuff exon more stuff'
all(s in line for s in ("protein_coding", "exon", "words"))
all(s in line for s in ("protein_coding", "exon", "stuff"))

rawDescription: use regular expression in python to find two strings in line

description: Use regular expression in python to find two strings in line


rawDescription: How to plot a pandas df with labels on index, time series as list stored in one column

description: Plot a pandas df with labels on index, time series as list stored in one column


code:
import datetime
dt = datetime.datetime.fromordinal(due_date) + datetime.timedelta(seconds=due_time)

rawDescription: convert time in Python

description: Convert time in Python


code:
s1 = 'banana'
s2 = 'ana'
second_index = s1.find(s2, s1.find(s2)+1)
print(second_index)

rawDescription: Substring Occurrences

description: Substring Occurrences


code:
a = np.recfromcsv('test.csv')
b = a[a['first_visit_date'] != '']
has_op = b['trainer_operator'] != ''
trainer_col = np.where(name, b.trainer_operator, b.trainer_managing)
np.rec.fromarrays([b.id, b.enrollment_date, trainer_col],
                  names=['id', 'enrollment_date', 'trainer'])

rawDescription: Return column conditionally in python using numpy


code:
row_iter = iter(sheet)
keys = next(row_iter)[1:]
data = {}
for row in row_iter:
    data[row[0]] = dict(zip(keys, row[1:]))

rawDescription: Most Efficient Implementation of Spreadsheet Data


code:
import win32con
import win32gui
import win32api
import ctypes
import pywintypes

def convert_capsule_to_int(capsule):
    ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
    ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
    return ctypes.pythonapi.PyCapsule_GetPointer(capsule, None)

class WindowProcedure(object):
    self.handle_WM_DESTROY = False
    def __init__(self, handle):
        if isinstance(handle, int) or isinstance(handle, type(pywintypes.HANDLE())):
            self.handle = handle
        else:
            self.handle = convert_capsule_to_int(handle)
        self.old_proc = win32gui.GetWindowLong(self.handle, win32con.GWL_WNDPROC)
        if not self.old_proc:
            raise RuntimeError("Failed to set/get window procedure!")
        if not win32gui.SetWindowLong(self.handle, win32con.GWL_WNDPROC, self.new_window_procedure):
            raise RuntimeError("Failed to set/get window procedure!")

    def handle_old_procedure(self, hwnd, msg, wparam, lparam):
        # For some reason the executable would hang after a QtGui.QWidget exit
        # so I'm forcing it here if self.handle_WM_DESTROY is true
        if msg == win32con.WM_DESTROY and self.handle_WM_DESTROY:
            win32gui.DestroyWindow(hwnd)
            return 0
        return win32gui.CallWindowProc(self.old_proc, hwnd, msg, wparam, lparam)

rawDescription: How to deal with PyCapsule type inside Python

description: Deal with PyCapsule type inside Python


code:
from functools import partial
df = pd.DataFrame({'ints': ['3', '5'], 'Words': ['Kobe', 'Bryant']})
df.apply(partial(pd.to_numeric, errors='ignore')).info()

rawDescription: convert entire pandas dataframe to integers in pandas (0.17.0)

description: Convert entire pandas dataframe to integers in pandas (0.17.0)


rawDescription: Shallow copy, why does the list not change


rawDescription: Disable the underlying window when a popup is created in Python TKinter


code: return all( [a==b for a,b in zip(A,B)] )

rawDescription: Python-New To Python and programming in general-difference of two sets


code:
population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
population = set(population)
samples = random.sample(population, 3)

rawDescription: How do you pick "x" number of unique numbers from a list in python?

description: Pick "x" number of unique numbers from a list in python


code:
def register_POST(self, request):
     return {'project': request.POST}

rawDescription: Pyramid self.request.POST is empty - no post data available


code:
class Bullet(gameobject.GameObject):

    FRAME  = pygame.Rect(23, 5, 5, 5)
    STATES = config.Enum('IDLE', 'FIRED', 'MOVING', 'RESET')

    action_names = {
                     STATES.IDLE   : None          ,
                     STATES.FIRED  : 'start_moving',
                     STATES.MOVING : 'move'        ,
                     STATES.RESET  : 'reset'       ,
                    }

    def __init__(self):
        gameobject.GameObject.__init__(self)
        self.image = config.SPRITES.subsurface(self.__class__.FRAME)
        self.rect  = self.__class__.START_POS.copy()
        self.state = self.__class__.STATES.IDLE

        # Update actions table using getattr, so we get the correct
        # method for subclasses.
        self.actions = {}
        for state, method_name in self.action_names.items():
            if method_name and callable(getattr(self, method_name)):
                self.actions[state] = getattr(self, method_name)
            else:
                self.actions[state] = lambda self: None

    def update(self):
        self.actions[self.state]()

rawDescription: Python: Callback issue

description: Python: Callback issue


code:
def schedule_job(timestamp, job):
    job_id = add_job_to_shared_dict(job) # see below
    with scheduler_condition:
        scheduler_heap.push((timestamp, job))
        scheduler_condition.notify_all()

def scheduler_worker_run_once():
    with scheduler_condition:
        while True:
            top = scheduler_heap.peek()
            if top is not None:
                delay = top[0] - now()
                if delay <= 0:
                    break
                scheduler_condition.wait(delay)
            else:
                scheduler_condition.wait()
        top = scheduler_heap.pop()
        if top is not None:
            job = pop_job_from_shared_dict(top[1])
            process_job(job)

rawDescription: Implementing a Timer in Python

description: Implementing a Timer in Python


code:
import json
...
json.dumps(coords) #returns the json string containing your data

rawDescription: How to store arrays of pixels in Pygame

description: Store arrays of pixels in Pygame


code:
plt.hist(diff.astype(np.int32))
plt.ylabel('time difference [m]')

rawDescription: Plotting the difference between two datetime64[ns]


code:
Xmesh, Ymesh = np.meshgrid( np.linspace(0,1,Nx), np.linspace(0,1,Ny) )
Z = f( Xmesh, Ymesh )  # Nx x Ny
Znew = griddata( Xmesh.flatten(), Ymesh.flatten(), Z.flatten(), Xnew, Ynew )

rawDescription: Problem with 2D interpolation in SciPy, non-rectangular grid


rawDescription: django create profile or page for object

description: Django create profile or page for object


rawDescription: What is this structured comment and what is "updated" field for?


code:
x=1
oncemore = iter([True, False])
while x < 30 or next(oncemore):
    x+=1
    print(x)

rawDescription: how to make a while statement run one more time in python 3

description: Make a while statement run one more time in python 3


code:
def copyfileobj(fsrc, fdst, length=16*1024):
    """copy data from file-like object fsrc to file-like object fdst"""
    while 1:
        buf = fsrc.read(length)
        if not buf:
            break
        fdst.write(buf)

rawDescription: Python: saving large web page to file

description: Python: saving large web page to file


code:
# checks whether pt1 is in circ
def inCircle(pt1, circ):

    # get the distance between pt1 and circ using the
    # distance formula
    dx = pt1.getX() - circ.getCenter().getX()
    dy = pt1.getY() - circ.getCenter().getY()
    dist = math.sqrt(dx*dx + dy*dy)

    # check whether the distance is less than the radius
    return dist <= circ.getRadius()

def main():
    win = GraphWin("Click Speed", 700, 700)

    # create a simple circle
    circ = Circle(Point(350,350),50)
    circ.setFill("red")
    circ.draw(win)

    while True:
        mouse = win.getMouse()
        if inCircle(mouse,circ):
            print ("Good job")

main()

rawDescription: Checking if clicks are within a graphic object [Python Graphics Module]


code: a = create_SubElement(root,'a',_text="Some text")

rawDescription: Python lxml Subelement with text value?

description: Python lxml Subelement with text value


rawDescription: What is the difference between `tensorflow.nn.np` and `numpy`?


rawDescription: Python regex not matching at word boundary as required


code:
alist = []
anoth = [alist]
alist.append(anoth)

rawDescription: What are cycles ? in relation to python

description: What are cycles ? in relation to python


code:
#!/usr/bin/env python
from __future__ import print_function
from  mpi4py import MPI
import numpy as np

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

assert size > 1

def definetype(field_names, field_dtypes):
    num = 2
    dtypes = list(zip(field_names, field_dtypes))
    a = np.zeros(num, dtype=dtypes)

    struct_size = a.nbytes // num
    offsets = [ a.dtype.fields[field][1] for field in field_names ]

    mpitype_dict = {np.int32:MPI.INT, np.float64:MPI.DOUBLE}  #etc
    field_mpitypes = [mpitype_dict[dtype] for dtype in field_dtypes]

    structtype = MPI.Datatype.Create_struct([1]*len(field_names), offsets, field_mpitypes)
    structtype = structtype.Create_resized(0, struct_size)
    structtype.Commit()
    return structtype

if __name__ == "__main__":
    struct_field_names = ['int', 'dbl']
    struct_field_types = [np.int32, np.float64]
    mytype = definetype(struct_field_names, struct_field_types)
    data = np.zeros(1, dtype=(list(zip(struct_field_names, struct_field_types))))

    if rank == 0:
        comm.Recv([data, mytype], source=1, tag=0)
        print(data)
    elif rank == 1:
        data[0]['int'] = 2
        data[0]['dbl'] = 3.14
        comm.Send([data, mytype], dest=0, tag=0)

rawDescription: How to create struct for passing between nodes using mpi4py

description: Create struct for passing between nodes using mpi4py


rawDescription: Python: Iterate over each item in nested-list-of-lists and replace specific items


code:
from celery.signals import after_setup_task_logger
import logging

def foo_tasks_setup_logging(**kw):
    logger = logging.getLogger('foo.tasks')
    if not logger.handlers:
        handler = logging.FileHandler('tasks.log')
        formatter = logging.Formatter(logging.BASIC_FORMAT) # you may want to customize this.
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.propagate = False

after_setup_task_logger.connect(foo_tasks_setup_logging)

rawDescription: Send log messages from all celery tasks to a single file


code:
#! /usr/bin/python

from setuptools import setup

setup(name="myproj",
      description='shows how to create a python package',
      version='123',
      packages=['myproj'],  # python package names here
      scripts=['scripts/myproj-bin'],  # scripts here
      )

rawDescription: What's the best layout for a python command line application?


rawDescription: Using a stored value of a variable in a for loop


code:
def neighbours(word):
    for j in range(len(word)):
        for d in string.ascii_lowercase:
            word1 = ''.join(d if i==j else c for i,c in enumerate(word))
            if word1 != word and word1 in words: yield word1
{word: list(neighbours(word)) for word in words}

rawDescription: Efficiently build a graph of words with given Hamming distance


code:
import inspect
def pv(name):
    record=inspect.getouterframes(inspect.currentframe())[1]
    frame=record[0]
    val=eval(name,frame.f_globals,frame.f_locals)
    print('{0}: {1}'.format(name, val))

rawDescription: Printing Variable names and contents as debugging tool; looking for emacs/Python shortcut


code:
[len(x) for x in list(chunk_sequences(pattern,1))]
Out[60]: [3, 2, 1, 5]

rawDescription: Python: How to find sequences of readings with same id and calculating the interval between first and the last element for every such sequence


code:
a='Beautiful, is; better*than\nugly'
import re
re.split('; |, |\*|\n',a)

rawDescription: Python: Split string with multiple delimiters


code:
from nonedict import NoneDict
foo = NoneDict()

rawDescription: Classes Inside Modules

description: Classes Inside Modules


code:
import pandas as pd
df = pd.read_csv('/Users/nicolas/Downloads/GOOG-NYSE_SPY.csv', parse_dates=[0])
df['Year'] = df['Date'].apply(lambda x: x.year)
df['Month'] = df['Date'].apply(lambda x: x.month)
df.head()

rawDescription: Index or group by attributes of a DateTimeIndex in Pandas


code:
#!/usr/bin/python

# See http://stackoverflow.com/questions/4842057/python-easiest-way-to-ignore-blank-lines-when-reading-a-file

# convert file to list of lines, ignoring any blank lines
filename = 'loadfile2.txt'

with open(filename) as f_in:
    lines = filter(None, (line.rstrip() for line in f_in))

print(lines)

# convert list to a list of lists split on comma
lines = [i.split(',') for i in lines]
print(lines)

# create list of lists based on the key value (first item in sub-lists)
listofpgms = []
for key, group in groupby(lines, lambda x: x[0]):
    pgms = []
    for pgm in group:
        try:
            pgms.append(pgm[1].strip())
        except IndexError:
            pgms.append(pgm[0].strip())

    listofpgms.append(pgms)

print(listofpgms)

rawDescription: Load a list of lists from a file based on a grouping variable?


code:
def checkio(stones):
    def subcheckio(stones, left, rite):
        if len(stones) == 0:
            return abs(left - rite)

        scores = []
        nstones = stones[1:]
        scores.append(subcheckio(nstones, left + stones[0], rite))
        scores.append(subcheckio(nstones, left, rite + stones[0]))

        return min(scores)

    return subcheckio(stones, 0, 0)

rawDescription: How to calculate a number representing the lowest possible weight difference

description: Calculate a number representing the lowest possible weight difference


code:
def filterDataFrame(df1, filterByColumn):
    sizes = df1[filterByColumn].value_counts()
    ...

rawDescription: Reassigning strings by value count in Pandas


rawDescription: How do I get the Mac "command" symbol in a Tkinter menu

description: Get the Mac "command" symbol in a Tkinter menu


code:
from itertools import product

[map(sum, zip(*[v, y])) for y in product(o, repeat=2)]

rawDescription: combinations of the values of two lists

description: Combinations of the values of two lists


code: all_values.extend(map(int, row))

rawDescription: How to append from file into list in Python?

description: Append from file into list in Python


code:
s1 = pd.Series([1, np.nan, 3, 4, 5, np.nan])
s2 = pd.Series([7, 2, 3, np.nan, np.nan])

rawDescription: Overwriting (updating) a pandas Series with values from another Series?


code:
def read():
    with open('test.txt', 'r') as f:
        for line in f:
            print(line)

rawDescription: Trying to print only one line of a text document in python


rawDescription: How can I create a user defined data structure in python

description: Create a user defined data structure in python


code: key_obj = obj.ma_keys.contents

rawDescription: python 3.3 dict: how to convert struct PyDictKeysObject to python class?

description: Python 3.3 dict: how to convert struct PyDictKeysObject to python class


code:
if title in sites:
    screamandshout()

rawDescription: Python string comparisons?

description: Python string comparisons


rawDescription: Sort list of dictionaries by value, regardless of keyname in python


code:
mystr = str(id1)
splitmessage = mystr[:2]

rawDescription: How to take the first two letters of a variable in python?

description: Take the first two letters of a variable in python


code:
totals = df.sum(1)
print(totals)
# tz                     521
# Africa/Cairo             3
# Africa/Casablanca        1
# Africa/Ceuta             2
# Africa/Johannesburg      1
# Africa/Lusaka            1
# America/Anchorage        5

rawDescription: Weird Data manipulation in Pandas

description: Weird Data manipulation in Pandas


code: html_sidebars = {'**': ['localtoc.html', 'sourcelink.html', 'searchbox.html']}

rawDescription: Enabling sidebar on Python-Sphinx documentation based on a sphinx-bootstrap-theme


code:
def on_click_button_drop(element):
    db_name = entry_db_name.get()
    if not db_name:
        # print("db name empty")
        messagebox.showinfo("", "db name empty")

rawDescription: Pressed button after leaving messagebox in tkinter


rawDescription: Writing a type contract for a magic square


code:
class_names = []
for w in random.sample(WORDS, snippet.count("%%%")):
    class_names.append(w.capitalize())

rawDescription: Confused about a function in Learn Python the Hard Way ex41?


rawDescription: Detecting geographic clusters

description: Detecting geographic clusters


code: frame.resample('1H', how={'radiation': np.sum, 'tamb': np.mean})

rawDescription: How to resample a dataframe with different functions applied to each column?

description: Resample a dataframe with different functions applied to each column


code:
for i in range(len(somelist)):
    element = somelist[i]

rawDescription: If I use a for loop in python do I need to set the variable being used to count to 0 or will the for loop set it?


code:
PUT /test_index
{
   "mappings": {
      "doc": {
         "_id": {
            "path": "id"
         },
         "properties": {
            "id": {
               "type": "integer"
            },
            "memory": {
               "type": "integer"
            },
            "model": {
               "type": "string"
            }
         }
      }
   }
}

rawDescription: Elasticsearch - match_phrase query sort by int


code:
t = np.array([['one','two','three'],['four','five','six']], dtype=object)
np.min(t)
# gives 'five'
np.max(t)
# gives 'two'

rawDescription: Arrays of strings into numpy.amax

description: Arrays of strings into numpy.amax


code: new = T.dot(orig)

rawDescription: 3D matrix perspective transform

description: 3D matrix perspective transform


code:
pair_dist = d.cdist(position, position)
pair_d = pair_dist<=4
for i in range(len(pair_d)):
    for j in range(i+1, len(pair_d)):
        if pair_d[i, j]:
            ...

rawDescription: Many particles in box - physics simulation


code:
def lock_class(methodnames, lockfactory):
    return lambda cls: make_threadsafe(cls, methodnames, lockfactory)

def lock_method(method):
    if getattr(method, '__is_locked', False):
        raise TypeError("Method %r is already locked!" % method)
    def locked_method(self, *arg, **kwarg):
        with self._lock:
            return method(self, *arg, **kwarg)
    locked_method.__name__ = '%s(%s)' % ('lock_method', method.__name__)
    locked_method.__is_locked = True
    return locked_method

def make_threadsafe(cls, methodnames, lockfactory):
    init = cls.__init__
    def newinit(self, *arg, **kwarg):
        init(self, *arg, **kwarg)
        self._lock = lockfactory()
    cls.__init__ = newinit

    for methodname in methodnames:
        oldmethod = getattr(cls, methodname)
        newmethod = lock_method(oldmethod)
        setattr(cls, methodname, newmethod)

    return cls

@lock_class(['add','remove'], Lock)
class ClassDecoratorLockedSet(set):
    @lock_method # if you double-lock a method, a TypeError is raised
    def frobnify(self):
        pass

rawDescription: How to make built-in containers (sets, dicts, lists) thread safe?

description: Make built-in containers (sets, dicts, lists) thread safe


code:
users_in_day = defaultdict(set)
for dt, user_ids in users_by_time.iteritems():
    users_in_day[dt.date()].update(user_ids)

rawDescription: Group dictionary by key and find max value


code:
colors = tuple(['r'] * 11 + ['y'] * (len(df2) - 11))
df2.plot(kind='bar', color=[colors], legend=False)

rawDescription: Slicing plot using different colors - manually recolor the bars


code:
domain = ['a','b','c','d']
allf = [{'a':'a','b':'c','c':'d', 'd':'d'}, {'a':'b', 'b':'c', 'c':'d', 'd':'a'}]

def dictfunky(allf):
    return [dict(item) for item in allf]

def functmatnoz(dictfuncts, domain):
    return [[[f[f[f[f[element]]]],
                 f[f[f[element]]],
                    f[f[element]],
                       f[element]] for element in domain]
                                        for f in dictfuncts]

def sigma(matlist, domain):
    return [[[[results.count(element) for results in mat]
                                        for element in domain]]
                                            for mat in matlist]

dictfuncts = dictfunky(allf)
matlist = functmatnoz(dictfuncts, domain)
sigmamat = sigma(matlist, domain)

print('dictfuncts: {}'.format(dictfuncts))
print('   matlist: {}'.format(matlist))
print('  sigmamat: {}'.format(sigmamat))

rawDescription: From matrix as lists of lists: count number of elements from a set x in each column. (python3)


code:
plt.figure()
nx.draw_networkx(G, pos=pos2, with_labels=False, node_size = 15)
plt.show()

rawDescription: Python: how to visualize the Minimum Spanning Tree of a network?


code:
[add_force_coupling(i, j, 'G{}{}'.format(i, j))
 for i, j in product(range(l), repeat=2)]

rawDescription: Best pythonic way of mapping a specific function with multiple arguments


code:
for i in range(x):
    Entry(root, textvariable=StringVar()).grid(row=1, column=i+1)

rawDescription: multiple entry labels in tkinter

description: Multiple entry labels in tkinter


rawDescription: Change values of CSV based on user Response


code:
def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)

rawDescription: How to generate all permutations of a list in Python

description: Generate all permutations of a list in Python


code:
class FilesLineCounter(dict):
    def count_file_lines(self, path):
        with open(path) as file:
            self[path] = sum(1 for line in file if line.strip())

rawDescription: Python statement as method's argument

description: Python statement as method's argument


code:
with open("list.csv", "U") as file1, open("example.csv", "rb") as file2, open("output.csv", "wb+") as file3:
    reader1 = csv.reader(file1)
    reader2 = csv.reader(file2)
    writer = csv.writer(file3)

    reader1_rows = [row for row in reader1]
    reader2_rows = [row for row in reader2]

    for rowA, rowB in zip(reader1_rows, reader2_rows):
        for word in rowA:
            for item in (item for item in rowB if word in item):
                writer.writerow([word, item])

rawDescription: Similarities between two csv files

description: Similarities between two csv files


rawDescription: Pandas if statement across list of columns


rawDescription: How to interpret 4 bytes as a 32-bit float using Python

description: Interpret 4 bytes as a 32-bit float using Python


code:
class A(object):
    def __init__(self):
        self.foo = None

    def f(self):
        self._f_recursive()

    def _f_recursive(self):
        if not self.foo:
            print("Hello")
            self.foo = 100
            self._f_recursive()

rawDescription: Python recursive method calls with super


code:
x = Streams.objects.all() # all stream objects
y = x[0].content_type # CommentData ContentType object

rawDescription: Using Generic Foreign Keys to retrieve data


code:
with open('yourfile.txt') as f:
  result = ','.join(f.read().split('\t'))

rawDescription: How to add a comma to the end of a list efficiently?

description: Add a comma to the end of a list efficiently


code: [dict(zip(d, col)) for col in zip(*d.values())]

rawDescription: Transposing (pivoting) a dict of lists in python


code: re.findall(pattern, s, re.VERBOSE)

rawDescription: RegExp to split string according to different criteria in python


code:
a = [('Pineapple',1),('Orange',3),('Banana',1),('Apple',1),('Cherry',2)]
# sort a by index 1 first (in reverse order) and then by index 0 in non-reverse order
b = sorted(a,key=getsortfunction(a,[(1,True),(0,False)])) # gives desired list

rawDescription: Sort at various levels in Python

description: Sort at various levels in Python


code:
ds = df.sort(list(df.columns))
eqs = (ds != ds.shift()).all(axis=1).cumsum()
ds.index.groupby(eqs)

rawDescription: Pandas : determine mapping from unique rows to original dataframe


code: np.where(np.in1d(foo[:,0], [12, 1, 2]), False, True)

rawDescription: Alternative to using 'in' with numpy.where()


code:
name = forms.CharField(
                widget=forms.TextInput(attrs={'class':'special'}))

rawDescription: Generating custom forms from DB schema

description: Generating custom forms from DB schema


code: g = df.groupby(df.index // 2)

rawDescription: Perform function on pairs of rows in Pandas dataframe


code:
import random
''.join([chr(random.randint(32,126)) for _ in xrange(11)])

rawDescription: More efficient for loops in Python (single line?)


code:
import numpy as np
import numexpr as ne

def func1(A, B):
    A = A ** 3
    A = np.maximum(A, 0.001)
    return np.divide(B, A)

def func2(A, B):
    return ne.evaluate("B / where(A**3 > 0.001, A**3, 0.001)",
                       local_dict={'A':A,'B':B})

A, B = np.random.randn(2, 1000, 1000, 3)

print(np.allclose(func1(A, B), func2(A, B)))
# True

rawDescription: Time-efficient combination of numpy functions


code: re_type = type(re.match('', ''))

rawDescription: Find regular expression type in python

description: Find regular expression type in python


rawDescription: How we can down sample a 1D array values by averaging method using float and int window sizes?


code: t1 = threading.Thread(target=timeout, args=(CONS,5))

rawDescription: How to use the value of a global variable to determine the control flow of a function running in separate thread?

description: Use the value of a global variable to determine the control flow of a function running in separate thread


code: np.sort(csvdata, order=['year', 'month', 'day'])

rawDescription: Sorting from .csv file in Python

description: Sorting from .csv file in Python


code:
from concurrent.futures import *
from subprocess import *

def make_call():
    process = Popen(['echo', 'test'], stdout=PIPE)
    return process.communicate()[0]

executor = ThreadPoolExecutor(4)
future = executor.submit(make_call)
print(future.result())

rawDescription: concurrent.futures ThreadPoolExecutor fails to wait?

description: Concurrent.futures ThreadPoolExecutor fails to wait


code:
def basename(x):
    return x.split("/")[-1]

result = set(x for x in set(currList).union(set(processList)) if (basename(x) in [basename(y) for y in currList]) != (basename(x) in [basename(y) for y in processList]))

rawDescription: re-implement __eq__ to compare sets with symmetric_difference in python

description: Re-implement __eq__ to compare sets with symmetric_difference in python


rawDescription: Is it possible to display only first list element in for loop?


code:
a = X[:,0]
ans = [np.ones(len(i))*a[0]-a[i] for i in ind]

rawDescription: Implementing np.subtract.outer for index of array([[array .... structure in python


code: np.vstack([dydx, dydx[-1]])

rawDescription: simple but weird vstack/concatenate problems (python)

description: Simple but weird vstack/concatenate problems (python)


code:
from scrapy.item import Item, Field
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider

class RadioItem(Item):
    title = Field()
    interpret = Field()
    date = Field()

class RadioSpider(BaseSpider):
    name = 'radio'
    allowed_domains = ['dashitradio.de']
    start_urls = ["http://www.dashitradio.de/nc/search-in-playlist.html?tx_wfqbe_pi1%5BSTART%5D=2013-06-17%2006:00&tx_wfqbe_pi1%5BEND%5D=2013-06-21%2018:00&tx_wfqbe_pi1%5Bsubmit%5D=Suchen&tx_wfqbe_pi1%5Bshowpage%5D%5B3%5D=1"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)

        rows = hxs.select("//div[@id='playlist-results']/table/tbody/tr")
        for row in rows:
            item = RadioItem()

            item['title'] = row.select(".//td[1]/text()").extract()[0]
            item['interpret'] = row.select(".//td[2]/text()").extract()[0]
            item['date'] = row.select(".//td[3]/text()").extract()[0]

            yield item

rawDescription: Scrapy start_urls too long / Unsupported URL Scheme


code:
"""
Reading from Java DataInputStream format.
"""

import struct

class DataInputStream:
    def __init__(self, stream):
        self.stream = stream

    def read_boolean(self):
        return struct.unpack('?', self.stream.read(1))[0]

    def read_byte(self):
        return struct.unpack('b', self.stream.read(1))[0]

    def read_unsigned_byte(self):
        return struct.unpack('B', self.stream.read(1))[0]

    def read_char(self):
        return chr(struct.unpack('>H', self.stream.read(2))[0])

    def read_double(self):
        return struct.unpack('>d', self.stream.read(8))[0]

    def read_float(self):
        return struct.unpack('>f', self.stream.read(4))[0]

    def read_short(self):
        return struct.unpack('>h', self.stream.read(2))[0]

    def read_unsigned_short(self):
        return struct.unpack('>H', self.stream.read(2))[0]

    def read_long(self):
        return struct.unpack('>q', self.stream.read(8))[0]

    def read_utf(self):
        utf_length = struct.unpack('>H', self.stream.read(2))[0]
        return self.stream.read(utf_length)

    def read_int(self):
        return struct.unpack('>i', self.stream.read(4))[0]

rawDescription: Python equivalent of Java DataInputStream.readUTF()


code:
url ="http://store.highsnobiety.com/products/adidas-consortium-x-highsnobiety-ultraboost.xml"

import requests
from lxml.html import fromstring

page = requests.get(url)
tree = fromstring(page.content)
variants = tree.xpath("//variants[@type='array']//id[@type='integer']//text()")
print(variants)

rawDescription: Using LXML to print out individual strings from file


code:
from collections import defaultdict, Counter

by_store = defaultdict(Counter)

for info in sales_per_store_per_day:
    counts = Counter({k: v for k, v in info.items() if k not in ('store', 'date')})
    by_store[info['store']] += counts

sales_per_store = [dict(v, store=k) for k, v in by_store.items()]

rawDescription: How to reduce/aggregate a list of dicts per multiple keys in Python?

description: Reduce/aggregate a list of dicts per multiple keys in Python


code: qry = """SELECT id FROM tickets WHERE "Status" = 'Pending'"""

rawDescription: Python SQlite returning an Object rather than a string


rawDescription: all possible combinations from a configuration space model

description: All possible combinations from a configuration space model


code:
# Make sure your series has a name
# Make sure the index is pure dates, not date 00:00:00
most_liquid_contracts.name = 'most'
most_liquid_conttracts.index = most_liquid_contracts.index.date

data = df
data['day'] = data.index.date
combined = data.join(most_liquid_contracts, on='day', how='left')

rawDescription: python pandas filter dataframe by another series, multiple columns

description: Python pandas filter dataframe by another series, multiple columns


code:
('actualite', 'politique')
('palmares', 'palmares-immobilier')
('actualite', 'societe')

rawDescription: pandas/python: splitting url and adding columns to a database

description: Pandas/python: splitting url and adding columns to a database


code:
from itertools import chain

chain.from_iterable([c] * count for c, count in weighted)

rawDescription: Creating multiple copies of list elements


rawDescription: Filter by whether column value equals a list in spark


code:
import re
s = """Test 123:

This is a blue car

Test:

This car is not blue

This car is yellow

Hello:

This is not a test"""
re.findall(r'(?s)(?:^|\n)(Test|Hello) *([^:]*):\n(.*?)(?=\n(?:Test|Hello)|$)', s)

rawDescription: Python regex search lines that end with a colon and all text after until next line that ends with colon


code:
def star(color, side_length, x, y):
    print(color, side_length, x, y)
    turtle.color(color)
    turtle.begin_fill()
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    for i in range(5):
        turtle.forward(side_length)
        turtle.right(144)
        turtle.forward(side_length)
    turtle.end_fill()

rawDescription: Drawing Stars with turtle in python

description: Drawing Stars with turtle in python


code:
def get_data():
    return 'bar'

rawDescription: in python, how to manipulate namespace of an instance

description: In python, how to manipulate namespace of an instance


code:
np.bincount(np.random.choice(b.size, 100, p=b.flat),
            minlength=b.size).reshape(b.shape)

rawDescription: Discretization of probability array in Python


code:
def add_data(node, name, value):
    if '-' not in name:
        node[name] = value
    else:
        key = name[:name.index('-')]
        node_index = int(name[len(key) + 1:name.index('.')])
        node.setdefault(key, [])
        if node_index >= len(node[key]):
            node[key].append({})
        add_data(node[key][node_index],
                 name[name.index('.') + 1:],
                 value)

rawDescription: HTML form data to recursive json dict

description: HTML form data to recursive json dict


code:
foo = aList = ['qwerttyy\n', '123454\n', 'zxcv']
aList[:] = [s[:-1] if s.endswith('\n') else s for s in aList]
foo                         #All references are affected.
aList

rawDescription: Updating list in-place

description: Updating list in-place


rawDescription: How can I make a for-loop pyramid more concise in Python?

description: Make a for-loop pyramid more concise in Python


code:
g = df.groupby('category')
g['value'].apply(lambda x: x.ffill().shift(1))
df['last_value'] = g['value'].apply(lambda x: x.ffill().shift(1))

rawDescription: Pandas accessing last non-null value

description: Pandas accessing last non-null value


code:
with open("data.txt") as board_file:
    board_list = [list(line) for line in board_file.read().split('\n') if line]

rawDescription: list of list of str

description: List of list of str


rawDescription: Django admin pass variables to users and groups template


code:
from datetime import date
date.today().strftime('%Y/%m/%d')

rawDescription: Python equivalent of Tcl "clock add" command for date-spinning spinbox?


code:
import re
s = 'AN : GSHJ488GL67 Customer : sh3893 Acnt No : cgk379gu Name : xyz'
re.findall(r'\b(?:AN|Acnt No) : (\w+)', s)

rawDescription: Defining regular expression

description: Defining regular expression


code:
for attempt in range(5):
    password = input("Password: ")
    if password == "changeme":
        print("Thou Shall Pass Into Mordor")
        break
else:
    print("Thou Shall Not Pass Into Mordor")

rawDescription: Need help putting the else into the while with a counter


code:
caller = mock.Mock(return_value=None)
caller(1,2,3, arg=True)
caller.assert_called_with(Any(int), Any(int), Any(int), arg=True)
caller.assert_called_with(Any(int), Any(int), Any(int), arg=False)

rawDescription: Assert that a method was called with one argument out of several


code:
df = pd.DataFrame( {'Stock'  : ['Apple','Broadcomm','Citi','D&G','Samsung','Elite'],
                  'PE' : pd.Series([1.5,3.9,5.6,6.8,6,6])})
df.set_index('Stock',inplace=True)
df.sort_values('PE',inplace=True)
crosstable=pd.DataFrame(add.outer(df.PE,-df.PE),df.index,df.index)
v=crosstable.mask(triu(ones((len(df),len(df)),bool))) #keep valid comparisons

rawDescription: Smallest Difference Between 2 object in Dataframe


rawDescription: Clearing Python lists

description: Clearing Python lists


code:
def to_nested_dict(row):
    return {'employee_id': row.employee_id,
            'branch': {'year': row.branch_year, 'name': row.branch_name}}

list(df.apply(to_nested_dict, axis=1))

rawDescription: Pandas Group Columns into Level

description: Pandas Group Columns into Level


rawDescription: pandas - transform data view

description: Pandas - transform data view


code:
i = 1
print('{0:2s} {1:15s} {2}'.format('#', 'Name', 'Number'))
for name, number in book.items():
    print('{0:<2d} {1:15s} {2}'.format(i, name, number))
    i += 1

rawDescription: Phone book list formatting

description: Phone book list formatting


code:
with open('test_file.txt', 'r') as in_file:
    text = in_file.read()

with open('output_test_file.txt', 'w') as out_file:
    out_file.write(replace_all(text, spelling_dict))

rawDescription: Python 2.7 - find and replace from text file, using dictionary, to new text file


code: from models import Model1

rawDescription: common import statement for similar classes

description: Common import statement for similar classes


rawDescription: Tokenize a mathematical expression in Python


code:
from collections import deque

def node_depth_first_iter(node):
    stack = deque([node])
    while stack:
        # Pop out the first element in the stack
        node = stack.popleft()
        yield node
        # push children onto the front of the stack.
        # Note that with a deque.extendleft, the first on in is the last
        # one out, so we need to push them in reverse order.
        stack.extendleft(reversed(node.children))

rawDescription: Implementing a depth-first tree iterator in Python


code:
# Note that xmpp can be either a ClientXMPP or ComponentXMPP object.
xmpp['xep_0060'].map_node_event('blogupdates', 'blogupdates')
xmpp['xep_0060'].add_event_handler('blogupdates_publish', blogupdate_publish)
xmpp['xep_0060'].subscribe('pubsub.example.com', 'blogupdates')
# If using a component, you'll need to specify a JID when subscribing using:
# ifrom="specific_jid@yourcomponent.example.com"

def blogupdate_publish(msg):
    """Handle blog updates as they come in."""
    update_xml = msg['pubsub_event']['items']['item']['payload']
    # Do stuff with the ElementTree XML object, update_xml

rawDescription: sleekxmpp pubsub example

description: Sleekxmpp pubsub example


rawDescription: Python vs PHP speed

description: Python vs PHP speed


code:
mask = summary[-1:].squeeze() > 220
summary.loc[:, mask]

rawDescription: pandas: dropping columns based on value in last row

description: Pandas: dropping columns based on value in last row


code:
exclude = set()
for block in blocks:
    exclude.update(range(*block))

rawDescription: Python: delete substring by indices

description: Python: delete substring by indices


code:
num_bins = 72
# the histogram of the data
n, bins, patches = plt.hist(theta, num_bins, range=[0,180], normed = True,        histtype='bar',facecolor='green')
plt.xlabel(r'$\theta$($\degree$)')
plt.ylabel(r'$P(\theta)$')
plt.show()

rawDescription: Method to read data from a file when plot histogram with python?


code:
class Handler:
    def __init__(self, db):
        self._db = db

    @asyncio.coroutine
    def get_from_db(self, data):
        ...

    @asyncio.coroutine
    def handle_a(self, request):
        data = yield from self.get_from_db(
            self.extract_from_request_a(request))
        return web.Response(self.format_data(data))

    @asyncio.coroutine
    def handle_b(self, request):
        data = yield from self.get_from_db(
            self.extract_from_request_b(request))
        return web.Response(self.format_data(data))

handler = Handler(db)
app.router.add_route('GET', '/a', hadndler.handle_a)
app.router.add_route('GET', '/b', hadndler.handle_b)

rawDescription: Class-based views in aiohttp

description: Class-based views in aiohttp


code:
if 'N/A' not in data1:
    data1.append('N/A')

rawDescription: how does the re.finditer loop work?

description: How does the re.finditer loop work


code:
def convert(v):
    try:
        return int(v)
    except ValueError:
        return v
pandas.DataFrame([convert(c) for c in l] for l in df.values)\

rawDescription: numerical sort a column containing numbers and strings (pandas/python)

description: Numerical sort a column containing numbers and strings (pandas/python)


code: df.index.name = None

rawDescription: Pandas adding extra row to DataFrame when assigning index


rawDescription: Is it safe to make an old-style class into a new-style class using Multiple Inheritance?


rawDescription: checking if a string input lies between a range

description: Checking if a string input lies between a range


code:
economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes})
business = render_to_string('dbmanager/classes.html', {"classes": business_classes})

rawDescription: How to send two variables with html as a JSON in Django?

description: Send two variables with html as a JSON in Django


rawDescription: How to normalize only certain columns in scikit-learn?

description: Normalize only certain columns in scikit-learn


rawDescription: Issue with parsing HTML class elements using beautifulsoup


code:
def is_boid_colliding_with_obstacles(self, boid):
    return any(colliding(boid.pos[0], boid.pos[1], boid.radius,
                         obstacle[0][0], obstacle[0][1], obstacle[1])
               for obstacle in self.obstacles)

def create_boids(self):
    for boid in range(self.flock_number):  # add the specified number of boids to our flock within our screen's region.
        self.boids.append(Boid(random.randint(self.region[0], self.region[2]), random.randint(self.region[1], self.region[3])))

    for boid in self.boids:  # adjust our boids so they are not created on top of an obstacle and are within our screen's region.
        while self.is_boid_colliding_with_obstacles(boid):
            boid.pos[0] = random.randint(self.region[0], self.region[2])
            boid.pos[1] = random.randint(self.region[1], self.region[3])

rawDescription: Checking all items in a list simultaneously in Python


rawDescription: Get request python as a string

description: Get request python as a string


code:
def starmap(function, iterable):
   # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
   for args in iterable:
       yield function(*args)

rawDescription: Can you apply an operation directly to arguments within map/reduce/filter?

description: Apply an operation directly to arguments within map/reduce/filter


code: df['race_label'] = df.apply (lambda row: label_race (row),axis=1)

rawDescription: pandas create new column based on values from other columns

description: Pandas create new column based on values from other columns


rawDescription: Points, Vectors, Dot Product & Cross Product of python


rawDescription: Confirming function calls inside a function I'm unittesting with mock module


code:
import compress.utils
utils.compress.function_to_override = overriding_function

rawDescription: Best way to override a installed packge method

description: Override a installed packge method


rawDescription: A smarter & faster way to convert numpy ndarray to string in python


code:
from django.apps import AppConfig

class BAPCConfig(AppConfig):
    name = 'book_author_publisher_category'
    verbose_name = "Book's data"

rawDescription: Changing the label for the module when registering on Django admin


code: utf8data= unicode_data.encode('utf-8')

rawDescription: Python encoding ISO to UTF8

description: Python encoding ISO to UTF8


code:
@require_post_params(params=['email', 'password'])
def login(request):
    # 'email' and 'password' are here always!
    pass

rawDescription: Python decorator to check for POST parameters on Django


rawDescription: Most pythonic way to remove tuples from a list if first element is a duplicate


code:
class Example(object):
    @property
    def value(self):
        """help text"""
        return 1

help(Example.value)

rawDescription: How is the doc for a property accessed?

description: How is the doc for a property accessed


code:
P = [3, 0, 2, 1]
Q = [8, 7]
from itertools import izip_longest
[x+y for x,y in izip_longest(reversed(P), reversed(Q), fillvalue=0)][::-1]

rawDescription: Add two lists of different lengths in python, start from the right


code:
for item in seq:
    if someCondition:
       # Here is our code block
       if blah:
           more.stuff()

rawDescription: How does one use break, continue and return statements to avoid deeply nested code in Python?

description: Use break, continue and return statements to avoid deeply nested code in Python