code:
# list_of_lines is a list where each item is a line of data
whole_data = list()
for text in line_of_lines:
    data = text.split()
    whole_data.append({'title':''.join(data[:-3]), 'year': data[-3], 'oscars': data[-2], 'nominations': data[-1]})
    # Do something with your info

rawDescription: Separating contents of different types stored in a list using python


code: params = [{'name': xxx} for param in functionNode]

rawDescription: Dynamically building an "array of strcuts" in Python


code:
label3=Label(self.top,text='Add URL', bd=3,fg='red',bg='#FFFFFF',relief=GROOVE,padx=17,pady=4,justify="center")
entry3=Entry(self.top,relief=SUNKEN,justify=CENTER,bd=3,fg='#0000FF',font='arial')

label3.grid(row=3, column=0)
entry3.grid(row=3, column=1)

label3=Label(self.top,text='Add URL', bd=3,fg='red',bg='#FFFFFF',relief=GROOVE,padx=17,pady=4,justify="center")
entry3=Entry(self.top,relief=SUNKEN,justify=CENTER,bd=3,fg='#0000FF',font='arial')
label3.grid(row=4, column=0)
entry3.grid(row=4, column=1)

rawDescription: How to get radio button output in Tkinter?

description: Get radio button output in Tkinter


code:
v = VoiceRecognizer()
v.voiceRecognition()
v.last_phrase # is the last return of voiceRecognition

rawDescription: Python 2.7 Get return value from function without running what is in the function again?


code:
def test(input):
    for i in input:
        if not i > 2:
            return False
        do_something_with_i(i)
    return True

rawDescription: iterating through a list with an if statement

description: Iterating through a list with an if statement


code:
import socket
host="0.0.0.0"
port=43210 #or some high number unused port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
client,address = s.accept()
#this wont run until after something hits that port

rawDescription: a way to have a Raspberry Pi wait for a command

description: A way to have a Raspberry Pi wait for a command


code:
with sqlite3.connect(":memory:") as conn:
    # update will hold in transaction.
    for i in xrange(100):
        conn.execute("insert ....")

pass
# sqlite3 will commit now

rawDescription: Python disable while iterating

description: Python disable while iterating


code:
db.collection.aggregate([
    {"$redact": {
        "$cond": [
            {"$setIsSubset": [
                [["feldon","c15", "sp"]],
                "$wishlist"
            ]},
            "$$KEEP",
            "$$PRUNE"
        ]
    }},
    {"$group": {
        "_id": None,
        "ids": {"$push": "$_id"}
    }}
])

rawDescription: converting mongodb arrays into python arrays

description: Converting mongodb arrays into python arrays


code:
attrs = {'title': title}
if publisher is not None:
    attrs['publisher'] = publisher
Book.objects.create(**attrs)

rawDescription: django passing arguments based on value

description: Django passing arguments based on value


rawDescription: Why can't we access an object using its address in Python?


code:
h1 = np.histogram(s, bins=np.linspace(xmin, xmax, (xmax-xmin)/step))
h_plt = plt.hist(s, bins=6,alpha=0.5)

rawDescription: What is the difference between `np.histogram` and `plt.hist`? Why don't these commands plot the same graphics?


code: draw = ImageDraw.Draw(image)

rawDescription: How to output unicode characters and lines into an image file? -python

description: Output unicode characters and lines into an image file? -python


code: setattr(x, 'value', 99)

rawDescription: calling methods on an instance with getattr [ python ]

description: Calling methods on an instance with getattr [ python ]


code: parsed

rawDescription: Multidimensional dictionary in Python

description: Multidimensional dictionary in Python


code:
distances = ((k, abs(v - value)) for k, v in bucketed_items_dict.items())
return min(distances, key=lambda x:x[1])[0]

rawDescription: Python: Elegant way of determining the nearest match for numbers in a dictionary


code:
class Child_Method_Redirector(type):
    def __new__(meta, name, bases, cls_dict):
        if bases is not ():
            if "f" in cls_dict:
                cls_dict["_auto_renamed_helper_f"] = cls_dict["f"]
                del cls_dict["f"]
        return type.__new__(meta,name,bases,cls_dict)

class Parent(metaclass=Child_Method_Redirector):
    def f(self, *v_args):
        arg = self._auto_renamed_helper_f(*v_args)
        print("Received {}.".format(arg))
        return arg ** 3

class Child(Parent):
    def f(self):
        return 2

# now it does Print "Received 2." and Sets value to 8.
value = Child().f()

rawDescription: How can I return a value to a superclass without overriding the parent function?

description: Return a value to a superclass without overriding the parent function


code:
import sys

tasks = {}
def task (f):
    tasks[f.__name__] = f
    return f

def showHelp ():
    print('Available tasks:')
    for name, task in tasks.items():
        print('  {0}: {1}'.format(name, task.__doc__))

def main ():
    if len(sys.argv) < 2 or sys.argv[1] not in tasks:
        showHelp()
        return

    print('Executing task {0}.'.format(sys.argv[1]))
    tasks[sys.argv[1]]()

rawDescription: Is there a Cake equivalent for Python?

description: Is there a Cake equivalent for Python


code:
with sqlite3.connect("studentscores.db") as db:
                cursor = db.cursor()
                sql = "update tblStudents set FirstName =?,LastName=? where StudentID=?"
                cursor.execute(sql,(FirstName,LastName,StudentID))
                db.commit()

rawDescription: Is it possible to write a python program that will enable you to sort the content of a text file in python


code:
subq = session.query(
    func.unnest(Company.groups).label('group')
).filter(
    (Company.status == 'active') &
    (func.array_to_string(Company.groups, ',').like(term))
).limit(limit).subquery()

q = session.query(subq.c.group.distinct()).\
    filter(subq.c.group.like(term)).\
    order_by(subq.c.group).\
    limit(limit)

rawDescription: SQLAlchemy subquery in from clause without join


code:
list_a = ['B', 'C', 'D']
my_input = 'aaaa'

output = ''.join(x for x,a in zip(itertools.cycle(list_a), my_input))

rawDescription: Replacing letters from input with a cycled item in a list


rawDescription: Call a method on getattr() function

description: Call a method on getattr() function


code:
from time import sleep
import sys

for x in line_1:
    print(x, end='')
    sys.stdout.flush()
    sleep(0.1)

rawDescription: Create a typewriter-effect animation for strings in Python


code:
import struct

fieldwidths = (2, -10, 24)  # negative widths represent ignored padding fields
fmtstring = ' '.join('{}{}'.format(abs(fw), 'x' if fw < 0 else 's')
                        for fw in fieldwidths)
fieldstruct = struct.Struct(fmtstring)
parse = fieldstruct.unpack_from
print('fmtstring: {!r}, recsize: {} chars'.format(fmtstring, fieldstruct.size))

line = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n'
fields = parse(line)
print('fields: {}'.format(fields))

rawDescription: Efficient way of parsing fixed width files in Python


code:
from itertools import islice #, izip
string = 'abcdefghijklmnopqrstuvwxyz0123456789'
it = zip(islice(string, 0, None, 10), islice(string, 9, None, 10))
flat_it = (char for tpl in it for char in tpl)
tuple(flat_it)

rawDescription: how to pick chars from a string in defined but different sized steps?

description: Pick chars from a string in defined but different sized steps


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

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


code:
def pair_sorting(listA, listB, listC):
    # make all possible pairs of values from two lists
    # each pair has the structure ((number, origin_list),(number, origin_list))
    # so we know which lists the numbers came from
    all_pairs = []
    all_pairs += [((nA,0), (nB,1)) for (nA,nB) in itertools.product(listA,listB)]
    all_pairs += [((nA,0), (nC,2)) for (nA,nC) in itertools.product(listA,listC)]
    all_pairs += [((nB,1), (nC,2)) for (nB,nC) in itertools.product(listB,listC)]
    all_pairs.sort(key = lambda p: distance(p[0][0], p[1][0]))
    # make a dict to track which (number, origin_list)s we've already seen
    pairs_by_number_and_list = collections.defaultdict(list)
    min_distance = INFINITY
    min_triplet = None
    # start with the closest pair
    for pair in all_pairs:
        # for the first value of the current pair, see if we've seen that particular
        # (number, origin_list) combination before
        for pair2 in pairs_by_number_and_list[pair[0]]:
            # if so, that means the current pair shares its first value with
            # another pair, so put the 3 unique values together to make a triplet
            this_triplet = (pair[1][0], pair2[0][0], pair2[1][0])
            # check if the triplet agrees more than the previous best triplet
            this_distance = distance(this_triplet)
            if this_distance < min_distance:
                min_triplet = this_triplet
                min_distance = this_distance
        # do the same thing but checking the second element of the current pair
        for pair2 in pairs_by_number_and_list[pair[1]]:
            this_triplet = (pair[0][0], pair2[0][0], pair2[1][0])
            this_distance = distance(this_triplet)
            if this_distance < min_distance:
                min_triplet = this_triplet
                min_distance = this_distance
        # finally, add the current pair to the list of pairs we've seen
        pairs_by_number_and_list[pair[0]].append(pair)
        pairs_by_number_and_list[pair[1]].append(pair)
    return min_triplet

rawDescription: Finding the most similar numbers across multiple lists in Python


code:
from operator import itemgetter
mygetter = itemgetter(i1, i2, ..., iN)
for tup in lots_of_tuples:
    result = mygetter(tup)

rawDescription: Efficient multiple, arbitrary index access in Python tuple?


code: mask = pd.Index(base).union(pd.Index(base - 1)).union(pd.Index(base + 1))

rawDescription: pandas get position of a given index in DataFrame

description: Pandas get position of a given index in DataFrame


code:
def age(amount):
    def _age(particle):
        particle.alive += amount
    return _age

rawDescription: How to implement a particle engine

description: Implement a particle engine


code: 'foo bar bar bar'.replace('bar', 'XXX', 1).find('bar')

rawDescription: Find the nth occurrence of substring in a string


code:
from django.conf import settings

def root_url(request):
    """
    Pass your root_url from the settings.py
    """
    return {'SITE_URL': settings.ROOT_URL_YOU_WANT_TO_MENTION}

rawDescription: Current way to get Home URL (Domain) in Django Template?


code:
from collections import defaultdict

result = defaultdict(list)
for k, v in itemList:
    result[k].append(v)

rawDescription: Is there a more compact way to convert a sequence of (key,value) tuples into a {key:[value,..],..} dict?


code: path = os.path.abspath(__file__)[:-8]

rawDescription: Accessing a file relatively in Python if you do not know your starting point?


code:
import sys

import __builtin__
_orgimp = __builtin__.__import__

import logging
FORMAT = "%(asctime)-15s %(message)s"
logging.basicConfig(format=FORMAT, level=logging.INFO)

def __import__(name, *a):
  r = sys.modules.get(name)
  if r is not None: return r
  logging.info('import bgn %s', name)
  r = _orgimp(name, *a)
  logging.info('import end %s', name)
  return r
__builtin__.__import__ = __import__

import pyparsing

rawDescription: How to measure Python import latencies

description: Measure Python import latencies


rawDescription: Python prevent subprocess from consuming keypress


rawDescription: Python: Make last item of array become the first


code:
#step 2
#format output file for tsv
#ordered chronologically, with Key:Value pairs orgainzed alphabeticallv by key (Domain Name)

date_workspace=''
domain_workspace=''

for date in sorted(valid_dict.iterkeys()):
    date_workspace+=date + "\t"

    for domain_name in sorted(valid_dict[date].iterkeys()):
        domain_workspace+="%s:%s\t" % (domain_name, valid_dict[date][domain_name])

    date_workspace+=domain_workspace
    date_workspace+="\n"
    domain_workspace=''

# Step 3
# write output
validfile.write(date_workspace)

for line in invalid_list:
    invalidfile.write(line)

rawDescription: creating proper tsv output from dictionary of dictionaries

description: Creating proper tsv output from dictionary of dictionaries


code:
import pandas as pd

d = {'one':[None, 2, 3, 4],
     'two':[4, 1, 4, 2],
     'three':[3, 4, 6, 8],}
df = pd.DataFrame(d, index = list('ABCD'))

#    one  three  two
# A  NaN      3    4
# B    2      4    1
# C    3      6    4
# D    4      8    2

arr = df.values
arr.sort(axis=0)
df = pd.DataFrame(arr, index=df.index, columns=df.columns)

print(df)

rawDescription: pandas rearrange dataframe to have all values in ascending order per every column independently

description: Pandas rearrange dataframe to have all values in ascending order per every column independently


code: lis

rawDescription: How risky is using list.index() for getting the index of a set?


code:
class square_result(object):
    def __init__(self, f):
        pass

    def __call__(self, x, y):
        return (x+y)**2

class append_abc(object):
    def __init__(self, f):
        self.f = f

    def __call__(self, *args):
        return str(self.f(*args)) + "abc"

@append_abc
@square_result
def add_two_numbers(x, y):
    return x + y

print(add_two_numbers(2,5))

rawDescription: Chaining decorators that are defined as classes?


code:
import scrapy

class Spider(scrapy.Spider):
    name = 'comp'
    start_urls = ['https://compare.switchon.vic.gov.au/energy_questionnaire/submit']

    form1 = {"energy_category": "electricity",
             "location": "home",
             "location-home": "shift",
             "distributor": "7",
             "postcode": "3000",
             "energy_concession": "0",
             "solar": "0",
             "disclaimer_chkbox": "disclaimer_selected",
             }

    sub_url = "https://compare.switchon.vic.gov.au/submit"
    form2 = {"person-count":"1",
    "room-count":"4",
    "refrigerator-count":"0",
    "gas-type":"3",
    "pool-heating":"0",
    "spaceheating[]":"none",
    "spacecooling[]":"none",
    "cloth-dryer":"0",
    "waterheating[]":"other"}

    def start_requests(self):
        return [scrapy.FormRequest(
            self.sub_url,
            formdata=form1,
            callback=self.parse
        )]

    def parse(self, response):
        return scrapy.FormRequest.from_response(
            response,
            formdata=form2,
            callback=self.after
        )

    def after(self, response):
        print("
Your electricity offers
" in response.body)

rawDescription: Multi POST query (session mode)

description: Multi POST query (session mode)


code: re.search('Register\("(\w+)", %s\);' % re.escape(str(myvar)), s).group(1)

rawDescription: regex to match a variable and get the words inside the quotations from the matching line in python

description: Regex to match a variable and get the words inside the quotations from the matching line in python


code:
from collections import OrderedDict
from itertools import chain, combinations

def partition(L):
    n = len(L)//2 + 1
    xs = chain(*[combinations(L, i) for i in range(1, n)])
    pairs = (tuple(sorted([x, tuple(set(L) - set(x))])) for x in xs)
    return OrderedDict.fromkeys(pairs).keys()

rawDescription: All ways of partitioning a list into two non-empty lists


code:
import binascii
message = '''hQIOA68nz9GqU7SREAgAxWfwvpziO4N6KquxmeuYD/txfTceyXRZGVqAGFUGmOdE
+K9PCLp/+p3cFC8OcOZg8WReI4wlpYzgS3/XsB4LL9MegSHwjjI9jNsnQOr9EeLA
IgDEb1NeXZ499qnSY1ZvCy/VCF1O7H71y77VQTckpfyHgWvzkaaaheMC0r+JGLZO
0w3NCTERFJ8XaXKz/+qw4gA7xxbpT9nXVXMwEwYgiAviJBJhdYw63oTlRYGgGzPh
H2YVNv2TWnpWp816xi+sbM1ZsJJERnAZSADKFYZzYw4E73VhUlrX5YBY4WN7UmQw=
'''
binascii.a2b_base64(message)

rawDescription: Convert ASCII armored output to binary data


code:
blog_years=[]
for entry in blog_entries:
    if entry.date.year not in blog_years:
        blog_years.append(entry.date.year)

rawDescription: How do I get each distinct 'year' value out of a Django model with a datetime field?

description: Get each distinct 'year' value out of a Django model with a datetime field


code: socket.mechanism = zmq.NULL # or zmq.PLAIN or zmq.CURVE

rawDescription: Send NULL message in PyZMQ

description: Send NULL message in PyZMQ


code: MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))

rawDescription: Sorting a tuple that contains tuples

description: Sorting a tuple that contains tuples


code:
import bpy, bmesh

for ob in bpy.context.scene.objects:
    if ob.type != 'MESH':
        continue
    bm = bmesh.new()
    bm.from_object(ob, bpy.context.scene)

    if len(bm.faces) > 0 and 0 not in (len(e.link_faces) for e in bm.edges):
        print(ob.name, "is valid")
    else:
        print(ob.name, "has errors")

rawDescription: Scene object selective export using Blender Python API 2.6


rawDescription: Flask - how can I always include language code in url


code: return [diff_unique(a[key][1],b[key][1]) for key in common_keys ]

rawDescription: comparing list of tuple elements python

description: Comparing list of tuple elements python


code:
with open('tmp') as f:
    result = [line.split()[2] for line in f]
    # now result contains list ['c', '4', 'Z']

rawDescription: How do you simulate awk in python, for multiline output?

description: Simulate awk in python, for multiline output


code:
x = map(int, x)
y = map(int, y)

rawDescription: How to use re.findall in a string with different patterns?

description: Use re.findall in a string with different patterns


rawDescription: keep/slice specific columns in pandas

description: Keep/slice specific columns in pandas


code: L = [(f1, int(f2)) for x in a.split(",") for f1, f2 in (x.split(":"),)]

rawDescription: Separate objects and put them into pairs


rawDescription: How to chunk any type of file in python and convert that file into string

description: Chunk any type of file in python and convert that file into string


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

# Make a 9x9 grid...
nrows, ncols = 9,9
image = np.zeros(nrows*ncols)

# Set every other cell to a random number (this would be your data)
image[::2] = np.random.random(nrows*ncols //2 + 1)

# Reshape things into a 9x9 grid.
image = image.reshape((nrows, ncols))

row_labels = range(nrows)
col_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
plt.matshow(image)
plt.xticks(range(ncols), col_labels)
plt.yticks(range(nrows), row_labels)
plt.show()

rawDescription: custom matplotlib plot : chess board like table with colored cells

description: Custom matplotlib plot : chess board like table with colored cells


code: [some_list[0], some_list[-1]]

rawDescription: Python slice first and last element in list


rawDescription: Shortest Syntax To Use numpy 1d-array As sklearn X


rawDescription: Updating variables in a list using python's csv module


code:
today_ids = ['id1', 'id2', 'id5']
base_line_ids = ['id1','id2','id3','id4']

added_ids = set(today_ids).difference(base_line_ids)
removed_ids = set(base_line_ids).difference(today_ids)

# specific message for: no added, no removed
if set(today_ids) == set(base_line_ids):
    print('No ids added or removed')
    exit(0)

if len(removed_ids):
    print('The following ids were removed:\n{}'.format('\n'.join(removed_ids)))
else:
    print('No ids removed')

if len(added_ids):
    print('The following ids were added:\n{}'.format('\n'.join(added_ids)))
else:
    print('No ids added')

rawDescription: Handling the various permutations of the diff between two lists


code: ed /tmp/test.py

rawDescription: SQLAlchemy expects an object, but finds a Table


code: c = np.zeros(shape=a.shape)

rawDescription: Python: Comparing all elements of two arrays and modifying 2nd array


rawDescription: How to do numpy structural arrays

description: Do numpy structural arrays


rawDescription: Find overlap of two lists, preserving sequence order


code:
from itertools import chain
def check_valid(matrix, n):
   valid_set = set(range(1, n+1))
   return all(not(set(row) - valid_set) for row in chain(matrix, zip(*matrix)))

rawDescription: check whether an element is in list or not

description: Check whether an element is in list or not


rawDescription: Grouping values using pandas cut

description: Grouping values using pandas cut


code:
f = open('your-file.dat')
yourList = f.readlines()

rawDescription: Reading from a plain text file

description: Reading from a plain text file


code: QComboBox.addItems (self, item)

rawDescription: Combobox unable to display 2-digits in a line


rawDescription: Creating table and calculation of min from txt file


rawDescription: Creating a Multiindex on a Dataframe to perform PanelOLS


rawDescription: Show only 6th digit of reaction time

description: Show only 6th digit of reaction time


rawDescription: How to Get a line of text from html to Python

description: Get a line of text from html to Python


code:
from psychopy import visual
w1 = visual.Window()
w1.close()
# do other things here, perhaps a GUI
w2 = visual.Window()  # another, new window pops open

rawDescription: Exiting PsychoPy Window

description: Exiting PsychoPy Window


code:
{ "_id" : ObjectId("5339c9ff0bb9bc1b3a5bf7a4"), "name" : "Nicholas", "friends" : [ "Amy", "Joe", "Amanda" ] }
{ "_id" : ObjectId("5339ca120bb9bc1b3a5bf7a5"), "name" : "John", "friends" : [ "Amy", "Amanda", "Sam", "Steve" ] }

rawDescription: How do you do $elemMatch in Mongokit?

description: Do $elemMatch in Mongokit


code:
class IPv4Pool(models.Model):
    name = models.CharField(max_length=255)

class IPRange(models.Model):
    pool = models.ForeignKey(IPv4Pool, related_name='ip_ranges')
    ...

class Subscriber(models.Model):
    pool = models.ForeignKey(IPv4Pool, related_name='subscribers')
    ...

rawDescription: Field calculated from Foreign Keys, need to save twice?


code:
import operator as op

nestedList.sort(key=op.itemgetter(0))

rawDescription: Python: Sort a Nested List With Specific Criteria


rawDescription: How to get euclidean distance on a 3x3x3 array in numpy

description: Get euclidean distance on a 3x3x3 array in numpy


code:
import copy
c = number("one", 1)
d = c
e = copy.copy(c)

print(c.number, d.number, e.number)
d.number = 2
e.number = 5
print(c.number, d.number, e.number)

rawDescription: Why variable = object doesn't work like variable = number


rawDescription: Connecting signal with lambda does not work in some cases?


code:
'x' in b.__class__.__dict__
'y' in b.__class__.__dict__

rawDescription: How to get an attribute just from the current class and not from possible parent classes?

description: Get an attribute just from the current class and not from possible parent classes


code: c = map(next, random.sample([iter(a)]*len(a) + [iter(b)]*len(b), len(a)+len(b)))

rawDescription: Randomly Interleave 2 Arrays In Python

description: Randomly Interleave 2 Arrays In Python


rawDescription: How to query an HDF store using Pandas/Python

description: Query an HDF store using Pandas/Python


code:
line, = ax.plot([1, 2, 3], label='Inline label')
# Overwrite the label by calling the method.
line.set_label('Label via method')
ax.legend()

rawDescription: Matplotlib editing legend labels

description: Matplotlib editing legend labels


code:
ax.set_xticks([i for i in range(0,IMAGE_SIZE,_EVERY_XTH_COORD_LABELED)]) #python3 code to create 90 tick marks
ax.set_xticklabels([-i for i in range(-90,90,EVERY_XTH_COORD_LABELED)]) #python3 code to create 90 labels

rawDescription: Change axis range into latitude and longitude using matplotlib in python


rawDescription: simple and best way of list manipulation in python

description: Simple and best way of list manipulation in python


rawDescription: Gradient calculation with python

description: Gradient calculation with python


code:
def bisect_right(a, x, lo=0, hi=None):
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if x > a[mid][-1]:
            hi = mid
        else:
            lo = mid + 1
    return lo

array = []
n = 3
for row in rows:
    b = bisect_right(array, row[-1])
    array.insert(b, row)
    if len(array) > n:
        array.pop()
print(array)

rawDescription: How to store lists over criteria in Python?

description: Store lists over criteria in Python


code:
from .forms import ResendActivationEmailForm
from django.core import signing
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string

def resend_activation_email(request):

    email_body_template = 'registration/activation_email.txt'
    email_subject_template = 'registration/activation_email_subject.txt'

    if not request.user.is_anonymous():
        return HttpResponseRedirect('/')

    context = Context()

    form = None
    if request.method == 'POST':
        form = ResendActivationEmailForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data["email"]
            users = User.objects.filter(email=email, is_active=0)

            if not users.count():
                form._errors["email"] = ["Account for email address is not registered or already activated."]

            REGISTRATION_SALT = getattr(settings, 'REGISTRATION_SALT', 'registration')
            for user in users:
                activation_key = signing.dumps(
                    obj=getattr(user, user.USERNAME_FIELD),
                    salt=REGISTRATION_SALT,
                    )
                context = {}
                context['activation_key'] = activation_key
                context['expiration_days'] = settings.ACCOUNT_ACTIVATION_DAYS
                context['site'] = get_current_site(request)

                subject = render_to_string(email_subject_template,
                                   context)
                # Force subject to a single line to avoid header-injection
                # issues.
                subject = ''.join(subject.splitlines())
                message = render_to_string(email_body_template,
                                           context)
                user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
                return render(request, 'registration/resend_activation_email_done.html')

    if not form:
        form = ResendActivationEmailForm()

    context.update({"form" : form})
    return render(request, 'registration/resend_activation_email_form.html', context)

rawDescription: Django-registration resend activation Email with new code


code:
[0, 1, 2]
'xxxxxxxxxxxxxxxxxxxx...'

rawDescription: Automatically shorten long strings when dumping with pretty print


code:
output = {'persons': []}
with open('my_csv.csv') as csv_file:
    for person in csv.DictReader(csv_file):
        output['persons'].append({
            'type': 'config.profile',
            'id': person['id'],
            # ...add other fields (email etc) here...
        })

        # ...do similar for config.pictures, config.status, etc...

output_json = json.dumps(output)

rawDescription: Create nested JSON from CSV

description: Create nested JSON from CSV


rawDescription: Appending/Merging in Python

description: Appending/Merging in Python


code:
def getLogger(name=None):
    """
    Return a logger with the specified name, creating it if necessary.

    If no name is specified, return the root logger.
    """
    if name:
        return Logger.manager.getLogger(name)
    else:
        return root

rawDescription: How python logging get it's configuration


code:
fig, ax = plt.subplots(1, 1)

ax.grid(True, which='minor', axis='both', linestyle='-', color='k')

ax.set_xticks(lon_grid, minor=True)
ax.set_yticks(lat_grid, minor=True)

ax.set_xlim(lon_grid[0], lon_grid[-1])
ax.set_ylim(lat_grid[0], lat_grid[-1])

rawDescription: How to plot the grid line only using pcolor/pcolormesh

description: Plot the grid line only using pcolor/pcolormesh


code: result

rawDescription: Sum the nested dictionary values in python


code: readfile = open(fileName, "w") # remove quote marks

rawDescription: python Writing to a file

description: Python Writing to a file


code:
while not done:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEMOTION:
            mousex, mousey = pygame.mouse.get_pos()
            if mousex < wx_coord:
                angle += 10

rawDescription: Pygame: Mouse Specific Axis Detection

description: Pygame: Mouse Specific Axis Detection


code:
seen = set()
for lst in data:
    lst_as_set = set(lst)               # this step eliminates internal duplicates
    deduped_set = lst_as_set - seen     # set subtraction!
    seen.update(deduped_set)

    # now do stuff with deduped_set, which is iterable, but in an arbitrary order

rawDescription: Python unique values in a list

description: Python unique values in a list


rawDescription: Match surrounding text around a group match


code:
from datetime import date, timedelta

def weeks_for_year(year):
    last_week = date(year, 12, 28)
    return last_week.isocalendar()[1]

rawDescription: The number of calendar weeks in a year?

description: The number of calendar weeks in a year


rawDescription: Django queryset that returns all unassigned fks


code:
import maya.cmds as cmds

sphere1 = cmds.sphere(nsp=10, r=50)

sphere2 = cmds.sphere(nsp=4, r=5)
cmds.setAttr(sphere2[0] + ".translateX",-12.583733)
cmds.setAttr(sphere2[0] + ".translateY",-2.2691557)
cmds.setAttr(sphere2[0] + ".translateZ",48.33736)

nurbsBool1 = cmds.nurbsBoolean("nurbsSphere1", "nurbsSphere2", nsf=1, op=1)

sphere3 = cmds.sphere(nsp=4, r=5)
cmds.setAttr(sphere3[0] + ".translateX",-6.7379503)
cmds.setAttr(sphere3[0] + ".translateY",3.6949043)
cmds.setAttr(sphere3[0] + ".translateZ",49.40595)

nurbsBool2 = cmds.nurbsBoolean(nurbsBool1[0], sphere3[0], nsf=1, op=1)

cmds.refresh(currentView=True)  # Force evaluation, of current view only

print(cmds.listRelatives(nurbsBool2[0], children=True, type="transform"))

rawDescription: Maya transform node not appearing in list


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

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


rawDescription: to slice columns in a tuple present in a numpy array

description: To slice columns in a tuple present in a numpy array


rawDescription: Converting string to normal text

description: Converting string to normal text


rawDescription: How to save my variables to a txt file from a program

description: Save my variables to a txt file from a program


code:
def foo(bar):
    def callback_for_boz(result):
        return qux(bar, result)
    return boz().addCallback(callback_for_boz)

rawDescription: Twisted / Amp networking: Respond to all clients, not just one making a request


code:
single_arg = 'data2'
data.single_arg = 100

# you can NOT set an attribute by a string this way.
# You're just setting an attribute called single_arg to 100 which isn't a model
# field, so it's not going to be saved.

rawDescription: Saving data to a column without deleting others in a Django script


code: datetime.combine(date.today(), time()) + timedelta(hours=2)

rawDescription: How to get the sum of timedelta in Python?

description: Get the sum of timedelta in Python


code:
A = ord('A')
tempSum = sum(ord(c) - A + 1 for c in tempWord if 'A' <= c <= 'Z')

rawDescription: Faster way to assign numerical value to letters?


code:
c.execute('insert into foo (baz) values (1)')
c.execute('SELECT 1 FROM sqlite_sequence WHERE name="foo"')
c.fetchone()

rawDescription: How to programmatically determine whether a column is set to AUTOINCREMENT in SQLite?

description: Programmatically determine whether a column is set to AUTOINCREMENT in SQLite


code:
def execute_tasks(self, application):
    """
    Executes all currently queued tasks, and also removes them from the
    queue.
    The tasks are execute against the provided web application.
    """

    # Set up the application for webtest to use (resetting _app in case a
    # different one has been used before).
    self._app = None
    self.APPLICATION = application

    # Get all of the tasks, and then clear them.
    tasks = self.get_tasks()
    self.clear_task_queue()

    # Run each of the tasks, checking that they succeeded.
    for task in tasks:
        response = self.post(task['url'], task['params'])
        self.assertOK(response)

rawDescription: GAE: unit testing taskqueue with testbed


code:
class Root(object):
  d = {'za': 23}

class Trunk(Root):
  d = {'ki': 45}

class Branch(Root):
  d = {'fu': 67}

class Leaf(Trunk, Branch):
  d = {'po': 89}

rawDescription: How to aggregate all attributes of a hierarchy of classes?

description: Aggregate all attributes of a hierarchy of classes


code:
all_lines = []
for line in file:
    all_lines.append(line.split('|'))

rawDescription: Python regex, how to capture multiple rules from 1 string


code: self.client = Client(url, plugins=[MyPlugin()])

rawDescription: How do I force a namespace prefix on an attibute in a SOAP request created using suds

description: Force a namespace prefix on an attibute in a SOAP request created using suds


rawDescription: Some python date manipulation

description: Some python date manipulation


code:
root = Tk()
v = Test()
v.test(root)
root.mainloop()
points = v.get_points()

rawDescription: Draw same lines drawn on a Tkinter Canvas on an OpenCV image


code:
scaler.std_
scaler.mean_

rawDescription: scale two matrices with scipy or sklearn

description: Scale two matrices with scipy or sklearn


code: scipy.stats.hypergeom.pmf(k, M, n, N)

rawDescription: Drawing cards from a deck in SciPy with scipy.stats.hypergeom


code:
from random import sample

print(sample(xrange(33, 126),8))

rawDescription: How do I generate 8 different random numbers in python?

description: Generate 8 different random numbers in python


code:
b = dict.fromkeys([1,2,3,4], [])
[id(x) for x in b.values()]

rawDescription: python: Why listA.append('a') affects listB?

description: Python: Why listA.append('a') affects listB


rawDescription: Get the highest possible gmtime for any architecture


code: B.__module__= 'a'

rawDescription: Masquerading real module of a class

description: Masquerading real module of a class


code:
from __future__ import print_function

while True:
    username = raw_input("Please give me a username: ")
    if not any(c in username for c in '0123456789'):
        print("Username needs to contain at least one number.")
        continue
    if len(username) >= 8:
        print("Well done")
    elif len(username) <= 1:
        print("More characters please.")
        print("Please try again, input your username again.")
        continue
    break

rawDescription: python 2.7 username with minimum and max

description: Python 2.7 username with minimum and max


code:
writer = connectmaker("127.0.0.1")
writer("send this text")
writer("send this other text")

rawDescription: Python Factory Function

description: Python Factory Function


code:
df
df.unstack()

rawDescription: index and column for the max value in pandas dataframe

description: Index and column for the max value in pandas dataframe


code:
somevar = 'foo'
getattr(x, somevar)

rawDescription: Why use setattr() and getattr() built-ins?


code:
from flask import Flask
class WebViewFlask(Flask):
    """
    Adds the ability to load a uri without the
    need of a HTTP server.
    """
    def load_from_uri(self, uri):
        """
        Loads a uri without a running HTTP server.
        """
        with self.test_client() as c:
            response = c.get(uri)
            return response.data, response.mimetype

rawDescription: How can I load a Python flask app into a gtk webview (Webkit)

description: Load a Python flask app into a gtk webview (Webkit)


code:
char_mappings = [(u"\u2019", u"'"),
                 (u"`", u"'")]
translate_mapping = {ord(k):ord(v) for k,v in char_mappings}

rawDescription: How to normalize unicode encoding for iso-8859-15 conversion in python?

description: Normalize unicode encoding for iso-8859-15 conversion in python


rawDescription: Accessing list item in django template

description: Accessing list item in django template


code: lambda: self.waitmuchmore(value)

rawDescription: self.after doesn't wait when passing value

description: Self.after doesn't wait when passing value


code:
lines = file.readlines()

line = lines[line_number]

rawDescription: Reading specific lines from a file in a loop (optimization)


code:
@app.route('/')
def home():
    thing = do_fun_stuff()
    return render_template('home.html', foo=thing)

rawDescription: Flask view methods and SRP

description: Flask view methods and SRP


code: 1 < five() and five() <= 5

rawDescription: What does "evaluated only once" mean for chained comparisons in Python?


code:
if tt.select('li.review-rating'):
      soup = tt.select('li.review-rating').find("li", {"class", "review-rating"})
      keys = soup.findAll("h5", {"class" : "review-rating__title"})
      values = soup.findAll("span", {"class" : "review-rating__score"})
      for key, value in zip(keys, values):
       print(key.text + ": " + value.text)

rawDescription: Print all elements in <li> - BeautifulSoap


code: import maya.cmds as cmds

rawDescription: Maya Python : How to change current renderer in render setting


code:
decompose = lambda number: divmod(number, m)

m = 2
decompose(5)
m = 4
decompose(5)

rawDescription: Decomposition function

description: Decomposition function


code:
import re
# This regular expression will match '(<group1>,<group2>)'
# with any whitespace between ',' and <group2> being discarded
tuple_pattern = tuple_pattern = re.compile("\(([^,)]+),\s*([^)]+)\)")

with open(fileName) as f:
    # Find all occurences of the tuple pattern in the file, this gives
    # us an array of tuples where each tuple is (<group1>,<group2>)
    # for each match
    tuples = tuple_pattern.findall(f.read())

rawDescription: Python: Read line by line, performing an operation at each end line


code: np.random.choice(a, size=n, p=w)

rawDescription: Probabilistic selection from a numpy array


code:
def player_url(url):
    # here. if timeout, return 1. otherwise do I/O and return 0.
    ...
    if timeout:
        return (1, url)
    else:
        return (0, url)

urls = [...]
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
    while urls:
        future_to_url = executor.map(player_url, urls)
        urls = []  # Clear urls list, we'll re-add any timed out operations.
        for future in future_to_url:
            if future.result()[0] == 1:
                urls.append(future.result()[1]) # stick url into list

rawDescription: Python 3 concurrent.futures: How to add back failed futures to ThreadPoolExecutor?


code:
my_list = []
not my_list

rawDescription: Single linked list in Python, how to write pop and push


code: df

rawDescription: Python Pandas Panel4D resample

description: Python Pandas Panel4D resample


rawDescription: How do I add elements from one numpy array to another at certain indices?

description: Add elements from one numpy array to another at certain indices


rawDescription: Extracting email body in python

description: Extracting email body in python


code:
# [...]
import platform
if platform.system == "Windows":
    os.environ['SDL_VIDEODRIVER'] = 'windib'
# [...]

rawDescription: Embedding a Pygame window into a Tkinter or WxPython frame


code:
def eachMasterList(allLists):
  allSets = [ set(lst) for lst in allLists ]
  for lst, s in zip(allLists, allSets):
    if not any(s is not otherSet and s < otherSet for otherSet in allSets):
      yield lst

rawDescription: How to check if array contains array in elegant way?

description: Check if array contains array in elegant way


code:
exec(urllib2.urlopen('http://www.ics.uci.edu/~eppstein/PADS/UnionFind.py').read())
uf = UnionFind()

rawDescription: How to execute a remote page?

description: Execute a remote page


code:
@classmethod
def search(cls):
    item = DBSession.query(cls).with_polymorphic('*').filter(...) #do search stuff here
    return item

rawDescription: sqlalchemy access parent class attribute

description: Sqlalchemy access parent class attribute


code:
from itertools import dropwhile
lines = ['', '', 'line1', 'line2', '', '']
list(dropwhile(lambda line: not line, lines))

rawDescription: Additional condition in Python list comprehension


code:
def sendGroupChatMessage(topic=""):
    """
    Send Group Chat Messages.
    """
    import Skype4Py as skype
    skypeClient = skype.Skype()
    skypeClient.Attach()
    messageSent = False
    for elem in skypeClient.ActiveChats:
        if len(elem._GetMembers()) > 2 and elem.Topic == topic:
            elem.SendMessage("SomeMessageHere")
            messageSent = True

    if not messageSent:
        for chat in skypeClient.BookmarkedChats:
            if chat.Topic == topic:
                chat.SendMessage("SomeMessageHere")
                messageSent = True

    return messageSent

rawDescription: How can I send a message to a group conversation with Skype4Py in Python

description: Send a message to a group conversation with Skype4Py in Python


code:
for x in range(1, 13):
    locals()['double_{0}'.format(x)] = x * 2

double_3

rawDescription: Using a loop in Python to name variables


code:
messages = get_messages(request)
the_last_message = last_message(messages)
the_last_success_message = last_message(messages, message_level.SUCCESS)

rawDescription: In Django, how do I display the message (using Message Framework) without looping through?


code:
s = "abcbbbbcbabcabcbcab"
N = len(s)
k = 3
m = 3

rawDescription: Average time a substring occurs

description: Average time a substring occurs


code:
"{} at {}".format(locals()[arg], arg)
"{} at {}".format(locals()[arg_2], arg_2)

rawDescription: how to get string itself as a variable

description: Get string itself as a variable


code: mylist = filter(lambda rgb: any(rgb), mylist)

rawDescription: Remove items from array

description: Remove items from array


code:
def sign(x, value=1):
    """Mathematical signum function.

    :param x: Object of investigation
    :param value: The size of the signum (defaults to 1)
    :returns: Plus or minus value
    """
    return -value if x < 0 else value

def prefix(x, dimension=1):
    """Give the number an appropriate SI prefix.

    :param x: Too big or too small number.
    :returns: String containing a number between 1 and 1000 and SI prefix.
    """
    if x == 0:
        return "0  "

    l = math.floor(math.log10(abs(x)))
    if abs(l) > 24:
        l = sign(l, value=24)

    div, mod = divmod(l, 3*dimension)
    return "%.3g %s" % (x * 10**(-l + mod), " kMGTPEZYyzafpnµm"[div])

rawDescription: Pretty-printing physical quantities with automatic scaling of SI prefixes


code:
ll1 = [(i, "l1") for i in l1]
ll2 = [(i, "l2") for i in l2]

rawDescription: Merge two lists with labels

description: Merge two lists with labels


code:
for action, file in results:
  full_filename = os.path.join (path_to_watch, file)
  if not os.path.exists (full_filename):
    file_type = "<deleted>"
  elif os.path.isdir (full_filename):
    file_type = 'folder'
  else:
    file_type = 'file'
  yield (file_type, full_filename, ACTIONS.get (action, "Unknown"))

rawDescription: Exlude a file from a directory listing

description: Exlude a file from a directory listing


code:
from collections.abc import Set

class A(Set):
    def __init__(self, list_id):
        self.list_id = list_id
        self.reload()

    def reload(self):
        values = get_values(self.list_id)
        self._values = frozenset(values)

    def __contains__(self, item):
        return item in self._values

    def __iter__(self):
        return iter(self._values)

    def __len__(self):
        return len(self._values)

rawDescription: reload subclass of frozenset

description: Reload subclass of frozenset


code:
print(tree.entry["content"])
# Hello World!

rawDescription: Using objectify to get items with a different namespace prefix


code:
class ArticleForm(forms.ModelForm):
    ...
    def save(self):
        instance = self.instance      # Do with instance what every you want
        super(ArticleForm, self).save()

rawDescription: Binding ModelForm to Model's instance when saving


code:
import pprint

pprint.pprint(tweet)

rawDescription: Getting a tweet's ID with Twython?

description: Getting a tweet's ID with Twython


code:
class Actor(object):

  def __init__(self, **kwargs):
    self._image_getter = kwargs['image_getter']
    self.pos = kwargs['pos']
    ...

  def draw(self, surface):
    surface.blit(self._image_getter(), self.pos)

rawDescription: How should I serialize game objects containing pygame surfaces?


code: data = [table.objects.filter(t) for t in timeseq(start,stop,interval)]

rawDescription: Get Intervals Between Two Times

description: Get Intervals Between Two Times


code:
class AndGate(ndb.Model):
    a_received = ndb.BooleanProperty()
    b_received = ndb.BooleanProperty()

rawDescription: Some events completed make another event in python


code:
d = {}
d[name] = 'VarData'
d[name]

rawDescription: Equivalent of "genvarname" in Python

description: Equivalent of "genvarname" in Python


code:
from abc import ABCMeta, abstractproperty

class AbstractTestClassMeta(ABCMeta):

    def __new__(metacls, cls, bases, clsdict):
        # create new class
        new_cls = super().__new__(metacls, cls, bases, clsdict)
        # collect all base class dictionaries
        base_dicts = [b.__dict__ for b in bases]
        if not base_dicts:
            return new_cls
        # iterate through clsdict looking for properties
        for name, obj in clsdict.items():
            if not isinstance(obj, (property)):
                continue
            prop_set = getattr(obj, 'fset')
            # found one, now look in bases for validation code
            validators = []
            for d in base_dicts:
                b_obj = d.get(name)
                if (
                        b_obj is not None and
                        isinstance(b_obj.fset, ValidateProperty)
                        ):
                    validators.append(b_obj.fset)
            if validators:
                def check_validators(self, new_val):
                    for func in validators:
                        func(new_val)
                    prop_set(self, new_val)
                new_prop = obj.setter(check_validators)
                setattr(new_cls, name, new_prop)

        return new_cls

rawDescription: How to provide value validation at abstract class level?

description: Provide value validation at abstract class level


code:
dd={'swd':'SomeString', 'int':35, 'f':True}
dd
argparse.Namespace(**dd)

rawDescription: Python: how can I ingest arguments from JSON file?


code:
@classmethod
def _product_list(cls):
    """
    return a list containing the one product_id contained in the request URL,
    or a query containing all valid product_ids if not id present in URL

    used to limit the choice of foreign key object to those related to the current product
    """
    id = threadlocals.get_current_product()
    if id is not None:
        return [id]
    else:
        return Product.objects.all().values('pk').query

rawDescription: How do I restrict foreign keys choices to related objects only in django

description: Restrict foreign keys choices to related objects only in django


code:
@app.route("/some-route")
def some_route():
    # Of course, in real life you would determine these values
    # on the basis of user / condition lookups, rather than
    # hardcoding values in your render_template call
    render_template("custom.jinja", base_template="AB/A/base.jinja",
        custom_functionality_provider="macros/lowcostplan.jinja",
        feature_x_include="AB/A/features/feature_x.jinja",
        features=some_features_object)

rawDescription: Flask - SubViews

description: Flask - SubViews


code:
y = []
for elem in soup.select("div.product *"):
    y.append(elem.string.strip().encode('utf8'))

y

rawDescription: Parsing HTML tags using python

description: Parsing HTML tags using python


code:
with io.open(filename, 'r', encoding=sys.getfilesystemencoding()) as f:
    contents = f.read().encode('utf-8')

rawDescription: Python: Upload huge amount of files via FTP


code:
_enumerate = enumerate

def enumerate(collection, start=0, stop=None):
    if stop is not None:
        return zip(range(start, stop), collection)
    return _enumerate(collection, start)

rawDescription: How can I limit iterations of a loop in Python?

description: Limit iterations of a loop in Python


code:
from __future__ import print_function

def bars_and_stars(bars=3, stars=5, _prefix=''):
    if stars == 0:
        print(_prefix + ', '.join('0'*(bars+1)))
        return
    if bars == 0:
        print(_prefix + str(stars))
        return
    for i in range(stars+1):
        bars_and_stars(bars-1, stars-i, '{}{}, '.format(_prefix, i))

rawDescription: General bars and stars

description: General bars and stars


code:
# some code
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "[project name].settings")
if __name__ == "__main__":
    import startup
    # the rest of the code

rawDescription: django + uwsgi, where to place my startup code?

description: Django + uwsgi, where to place my startup code


code: df.apply(lambda row: row[row != 0].index.tolist(), axis=1)

rawDescription: Group by pandas

description: Group by pandas


code:
@blueprint.route('/', methods=['GET', 'POST'])
def admin_login():
    # Located at https://yourdomain.com/login
    return render_template('admin_login.html')

@blueprint.route('/login/', methods=['GET', 'POST'])
def login():
    # Located at https://yourdomain.com/login/login
    return  render_template('adminPage1.html')

@blueprint.route('/addnew/', methods=['GET', 'POST'])
def adminPage1():
    # Located at https://yourdomain.com/login/addnew
    return  render_template('adminPage1.html')

rawDescription: Can multiple webpages be implemented using a single Flask app?


rawDescription: String composed of only acceptable characters


code:
def refactorMe(func):
    def wrapper(parm1, parm2):
        if parm1:
            code_chunk_1

        func(parm1)

        if parm2[-1]:
            code_chunk_2

    return wrapper

rawDescription: Code refactoring with python decorators?

description: Code refactoring with python decorators


code:
from PIL import Image
filenames = ['/home/you/Desktop/chstamp.jpg', '/home/you/Desktop/something.jpg']
sizes = [Image.open(f, 'r').size for f in filenames]
max(sizes)

rawDescription: Find the largest image dimensions from list of images


code:
col_count, row_count = root.grid_size()

for col in xrange(col_count):
    root.grid_columnconfigure(col, minsize=20)

for row in xrange(row_count):
    root.grid_rowconfigure(row, minsize=20)

rawDescription: Tkinter.grid spacing options?

description: Tkinter.grid spacing options


code: tr = { 'critic' : '8_critic', 'foo' : 'bar' }

rawDescription: Transform Python HTML Inputs

description: Transform Python HTML Inputs


code: b = df.sort_values(by=[1], axis=0, ascending=True)

rawDescription: Pandas sort() ignoring negative sign

description: Pandas sort() ignoring negative sign


code:
from urllib.parse import parse_qs
query = parse_qs(str[1:])
query
query['q']
query['geocode']

rawDescription: Regular Expression to extract parts of Twitter query


code:
l = ["abc", "de", "", "fghi"]
list(itertools.izip_longest(*l, fillvalue=""))

rawDescription: Python: transposing uneven rows into columns


code: print(xmlreplace.sub("-" , "regex test"))

rawDescription: Replacing a single character by a substring in python 3


rawDescription: Python: SGMLParser can't get line number


code: (y_train == model.predict(X_train)).shape == (301, 301)

rawDescription: Difference between .score() and .predict in the sklearn library?


code:
import math
print(stats.norm.expect(f, loc=n*p, scale=math.sqrt((n*p*(1-p))), lb=0, ub=n))
# 2500.0

rawDescription: Log-computations in Python

description: Log-computations in Python


code:
import csv
import datetime
with open('test.txt','r') as infile, open('output.txt','w') as outfile:
    inr = csv.reader(infile,delimiter='\t')
    ouw = csv.writer(outfile,delimiter='\t')
    for row in inr:
            d = datetime.datetime.strptime(row[0],'%Y-%m-%d %H:%M:%S')
            p = float(row[1])
            nr = [d.day, d.hour, d.minute, p*0.2]
            ouw.writerow(nr)

rawDescription: Reformatting Dates after strptime Python


code:
class A(object):
    obj = None
    def __init__(self, one=None):
        self.one = one
        if self.one:
            if A.obj:
                A.obj.one = None
            A.obj = self
    def __str__(self):
        return str(self.one)

rawDescription: Python - Exclusive attribute value for object?


code:
import numpy as np
a = np.arange(10)

rawDescription: Repeat NumPy array without replicating data?


code:
with open('ClassA.txt') as f:
    scores = {name.strip():int(score) for score, name in zip(f, f)}

scores

rawDescription: Read two consecutive lines from a file into a dictionary as value, key pairs


code:
cl=c0.tolil()
cl.data
cl.rows

rawDescription: Python: Cumulative insertion of values in a sparse matrix (lil_matrix) due to repeated indices


rawDescription: Time series with appending issue in pandas data frame


code:
import re

def blah(r):
    return re.sub(r'[a-zA-Z]', r'^', r)

rawDescription: Replacing only the alphabetical letters in a string


rawDescription: Apply same permutation for every row in a 2D numpy array


code:
class AMeta(type):
    def _get_specialization(cls, selector):
        return As[selector]

class A(object, metaclass=AMeta): # I'm using Python 3 metaclass declarations
    pass # nothing defined in A is ever used, it is a pure dummy

rawDescription: Changing the bases of an object based on arguments to __init__


code:
mylist = [4, 5]
print(" ".join(map(str, mylist)))
#4 5
print(", ".join(map(str, mylist)))
#4, 5

rawDescription: How to remove the square brackets from a list when it is printed/output

description: Remove the square brackets from a list when it is printed/output


code: from django.db.models import manager

rawDescription: Add django model manager code-completion to Komodo


code:
with open("foo.txt", "w") as f:
    f.writelines("".join(chain.from_iterable(p)) + "\n"
                 for p in product(cr(ascii_lowercase, 3), digits, ascii_lowercase))

rawDescription: Simple code to generate a wordlist of specific type


rawDescription: Slice numpy array with other array

description: Slice numpy array with other array


code: fd = open('myfile.txt')

rawDescription: Distinction Between CWD and Import Search Path in Python?


rawDescription: GroupBy - Datetime diff() combining additional criteria


code: roidata = np.asarray([row[roipixels[0],roipixels[1]] for row in bigarray])

rawDescription: PyTables: indexing multiple dimensions of large arrays


code:
import sys, termios, tty

fd = sys.stdin.fileno()
o = termios.tcgetattr(fd)
tty.setraw(fd)
n = termios.tcgetattr(fd)
tcsetattr(fd, termios.TCSANOW, o)

print('iflag : {:10x} {:10x}'.format(o[0], n[0]))
print('oflag : {:10x} {:10x}'.format(o[1], n[1]))
print('cflag : {:10x} {:10x}'.format(o[2], n[2]))
print('lflag : {:10x} {:10x}'.format(o[3], n[3]))
print('ispeed: {:10d} {:10d}'.format(o[4], n[4]))
print('ospeed: {:10d} {:10d}'.format(o[5], n[5]))
print('cc    :')
for i, (oo, nn) in enumerate(zip(o[6], n[6])):
    print('  {:4d}: {:>10} {:>10}'.format(i, oo, nn))

rawDescription: Input not read in Python for Linux

description: Input not read in Python for Linux


code:
from matplotlib import pyplot
x = np.arange(0, 2*math.pi, math.pi/100)
y = np.sin(x) # using np.sin
y = [math.sin(r) for r in x] # using list comprehension
pyplot.plot(x, y)

rawDescription: How to Do Trigonometric Range of Floats in Python?


code: [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]

rawDescription: Is there universal if function in numpy?

description: Is there universal if function in numpy


code:
@jit
def gen_adj_loop(width, height, adj):
    i = 0
    for x in range(width):
        for y in range(height):
            if x > 0:
                adj[i,0] = x
                adj[i,1] = y
                adj[i,2] = x - 1
                adj[i,3] = y
                i += 1

            if x < width - 1:
                adj[i,0] = x
                adj[i,1] = y
                adj[i,2] = x + 1
                adj[i,3] = y
                i += 1

            if y > 0:
                adj[i,0] = x
                adj[i,1] = y
                adj[i,2] = x
                adj[i,3] = y - 1
                i += 1

            if y < height - 1:
                adj[i,0] = x
                adj[i,1] = y
                adj[i,2] = x
                adj[i,3] = y + 1
                i += 1
    return

rawDescription: Optimizing dict of set of tuple of ints with Numba?


rawDescription: Django pagination. What if I have 1 million of rows?


code:
class DictModelAdaptor():
    def __init__(self, model):
        self.model = model

    def __getitem__(self, key):
        return self.model.objects.get(key=key)

    def __setitem__(self, key, item):
        pair = self.model()
        pair.key = key
        pair.value = item
        pair.save()

    def __contains__(self, key):
        ...

rawDescription: Django: Converting an entire set of a Model's objects into a single dictionary


code: cur.execute("SELECT name, highest FROM scores WHERE class=1 ORDER BY highest DESC")

rawDescription: SQlite3 fetching data in order with a paramter


code:
from itertools import chain

d = Counter(chain.from_iterable(list_of_lists))

rawDescription: Fast dictionary population with list of keys


rawDescription: In pyqt how do I add items in a combobox?


rawDescription: Generate all unique permutations of 2d array


code:
def o(*args):
    return OrderedDict(zip(args[::2], args[1::2]))

things_to_evaluate = o(
    'thing 1', lambda: Thing(property = 'a'),
    'thing 2', lambda: Thing(property = 'b'),
    ...
    )

rawDescription: Globally Make Python Dictionaries Ordered


code:
from twisted.internet import threads, reactor

data = "\n".join("testing\n" * 10 for x in xrange(10000000))
print("Size of data is %d bytes" % len(data))

def blocking_write():
    print("Starting blocking_write")
    f = open("testing", "w")
    f.write(data)
    f.close()
    print("End of blocking_write")

def test_callback():
    print("Running test_callback, just for kicks")

d = threads.deferToThread(blocking_code)
reactor.callWhenRunning(cc)
reactor.run()

rawDescription: How to write to a file using non blocking IO?

description: Write to a file using non blocking IO


code: x = list(map(func, x))

rawDescription: What is the best way to appy changes in a list in Python


code:
class Language(Model):
    name = CharField()

    class Meta:
        database = DATABASE

rawDescription: Relational Mapping using Peewee

description: Relational Mapping using Peewee


code: text="devkit (c) 2012, ARM-3.4. aLL DATA conf"

rawDescription: How to do a non-greedy match

description: Do a non-greedy match


code:
nextmonth = calendar.month_name[1:][(calendar.month_name[1:].index(month) + 1) % 12]
[...]
if month == calendar.month_name[-1]: year = str(int(year + 1))

rawDescription: Dynamically naming edited csv, to include part of the old csv name


code:
from gcloud import datastore

# the location of the JSON file on your local machine
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/location/client_secret.json"

# project ID from the Developers Console
projectID = "THE_ID_OF_YOUR_PROJECT"

os.environ["GCLOUD_TESTS_PROJECT_ID"] = projectID
os.environ["GCLOUD_TESTS_DATASET_ID"] = projectID
client = datastore.Client(dataset_id=projectID)

rawDescription: How to access a remote datastore when running dev_appserver.py?

description: Access a remote datastore when running dev_appserver.py


code:
def get_text_name(arg):
    temp = [x.split(': ') for x in arg]
    return temp[0][0].split()[-2], [t[1] for t in temp]

text_to_name=dict([get_text_name(x) for x in [rating, opinion]])
text_to_name

rawDescription: Extracting multiple string values of variable length before and after a delimiter in a list


code:
_blacklist = ['_cached_thing']
def __getstate__(self):
    return {k: v for k, v in self.__dict__.iteritems() if k not in self._blacklist}
def __setstate__(self, state):
    self.__dict__.update(state)

rawDescription: Preventing fields from being pickled

description: Preventing fields from being pickled


code:
def find_shortest_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not graph.has_key(start):
        return None
    shortest = None
    for node in graph[start]:
        if node not in path:
            newpath = find_shortest_path(graph, node, end, path)
            if newpath:
                if not shortest or len(newpath) < len(shortest):
                    shortest = newpath
    return shortest

rawDescription: Connecting rows in a list if they exist?

description: Connecting rows in a list if they exist


rawDescription: python list(zipobject) returns empty (list) container

description: Python list(zipobject) returns empty (list) container


code:
import os.path
import shutil
import sqlite3
import sys
import tempfile

from contextlib import contextmanager

@contextmanager
def sqlite_database(inmemory_data):
    path = tempfile.mkdtemp()
    with open(os.path.join(path, 'sqlite.db'), 'wb') as dbfile:
        dbfile.write(inmemory_data)
    conn = None
    try:
        conn = sqlite3.connect(os.path.join(path, 'sqlite.db'))
        yield conn
    finally:
        if conn is not None:
            conn.close()
        try:
            shutil.rmtree(path)
        except IOError:
            sys.stderr.write('Failed to clean up temp dir {}'.format(path))

rawDescription: Reading from sqlite3 remote databases

description: Reading from sqlite3 remote databases


rawDescription: Best way to develop a programme without using reload

description: Develop a programme without using reload


code:
# run.py
print("Hello, Python")

rawDescription: How to avoid reinstalling packages when building Docker image for Python projects?

description: Avoid reinstalling packages when building Docker image for Python projects


code:
import http.cookiejar as cookielib
import os
import urllib
import re
import string
from bs4 import BeautifulSoup

username = "user@email.com"
password = "password"

cookie_filename = "parser.cookies.txt"

class LinkedInParser(object):

    def __init__(self, login, password):
        """ Start up... """
        self.login = login
        self.password = password

        # Simulate browser with cookies enabled
        self.cj = cookielib.MozillaCookieJar(cookie_filename)
        if os.access(cookie_filename, os.F_OK):
            self.cj.load()
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPRedirectHandler(),
            urllib.request.HTTPHandler(debuglevel=0),
            urllib.request.HTTPSHandler(debuglevel=0),
            urllib.request.HTTPCookieProcessor(self.cj)
        )
        self.opener.addheaders = [
            ('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
                           'Windows NT 5.2; .NET CLR 1.1.4322)'))
        ]

        # Login
        self.loginPage()

        title = self.loadTitle()
        print(title)

        self.cj.save()

    def loadPage(self, url, data=None):
        """
        Utility function to load HTML from URLs for us with hack to continue despite 404
        """
        # We'll print the url in case of infinite loop
        # print "Loading URL: %s" % url
        try:
            if data is not None:
                response = self.opener.open(url, data)
            else:
                response = self.opener.open(url)
            return ''.join([str(l) for l in response.readlines()])
        except Exception as e:
            # If URL doesn't load for ANY reason, try again...
            # Quick and dirty solution for 404 returns because of network problems
            # However, this could infinite loop if there's an actual problem
            return self.loadPage(url, data)

    def loadSoup(self, url, data=None):
        """
        Combine loading of URL, HTML, and parsing with BeautifulSoup
        """
        html = self.loadPage(url, data)
        soup = BeautifulSoup(html, "html5lib")
        return soup

    def loginPage(self):
        """
        Handle login. This should populate our cookie jar.
        """
        soup = self.loadSoup("https://www.linkedin.com/")
        csrf = soup.find(id="loginCsrfParam-login")['value']
        login_data = urllib.parse.urlencode({
            'session_key': self.login,
            'session_password': self.password,
            'loginCsrfParam': csrf,
        }).encode('utf8')

        self.loadPage("https://www.linkedin.com/uas/login-submit", login_data)
        return

    def loadTitle(self):
        soup = self.loadSoup("http://www.linkedin.com/nhome")
        return soup.find("title")

parser = LinkedInParser(username, password)

rawDescription: Logging in to LinkedIn with python requests sessions


rawDescription: How to remove a column from a structured numpy array *without copying it*?

description: Remove a column from a structured numpy array *without copying it*


code: html = r.frame.toHtml().toUtf8().data()

rawDescription: How to get real source code of html page?

description: Get real source code of html page


code:
from sympy import var, Wild, exp
s = var("s")
t = var("t")
a = Wild("a")
b = Wild("b")
U = 3/(7+s)

rawDescription: SymPy: How to get values from expression


code: list_of_fifths = map(lambda x: x[4], Pressure)

rawDescription: How could I append a certain object from several lists into a new file?


code:
from string import whitespace
s = "TN 81   NZ\t\t0025\nfoo"
s.translate(None, whitespace)

rawDescription: How to remove white spaces from a string in Python?

description: Remove white spaces from a string in Python


code:
s = set(lst)
new_dict = {k: v for k, v in d.items() if k not in s}

rawDescription: Removing one or multiple keys from a dictionary


code:
def doit(self, foo):
  return X.foo(self, foo)

rawDescription: How do I initialize the base (super) class in Python?

description: Initialize the base (super) class in Python


code: user == "paper" or user == "Paper"

rawDescription: weird behaviour in python if clause

description: Weird behaviour in python if clause


code:
parties = set(legislators.values())

print(parties)
{'DAB', 'Democratic', 'Economic Synergy', 'Labour'}

rawDescription: Creating a list from specific elements of a dictionary


rawDescription: Grouping daily data by month in python/pandas and then normalising


code:
class Item(models.Model):
    name = models.CharField(max_length=40)
    default_price = models.DecimalField(max_digits=6, decimal_places=2, default=50)

    def __unicode__(self):
        return self.name

class SaleDetail(models.Model):
    item = models.ForeignKey(Item)
    deposit = models.ForeignKey(Deposit)
    quantity = models.PositiveIntegerField()
    entered_unit_price = models.DecimalField(max_digits=6, decimal_places=2, default=None)
    sale = models.ForeignKey(Sale)

    @property
    def unit_price(self, value):
        if self.entered_unit_price is None:
            return self.item.default_price
        else:
            return self.entered_unit_price

    @unit_price.setter
    def unit_price(self, value):
        self.entered_unit_price = value

rawDescription: Django - Update model field based on another field


rawDescription: Python pandas dataframe: Find last occurrence of value less-than-or-equal-to current row


rawDescription: Matching filenames containing a particular string in delimited format


code:
def strip_year(winner, year):
    in_year = ' in {}'.format(year)
    if winner.endswith(in_year):
        winner = winner[:-len(in_year)]
    return winner

rawDescription: Add a Year to each item in list or Dictionary


code:
with open(path_in + data_file) as csvfile:
    read_it = list(csv.reader(csvfile, delimiter=','))

rawDescription: Create an interactive command loop using inheritance python34


code: a = Dimarray(values, 'lat', lat, 'lon', lon)

rawDescription: How to retrieve the original order of key-word arguments passed to a function call?

description: Retrieve the original order of key-word arguments passed to a function call


code:
import csv
with open('/tmp/data.csv', 'wb') as f:
    writer = csv.writer(f)
    for key, grp in trans_set:
        writer.writerow([key]+grp)

rawDescription: Pandas dataframe to list of tuples

description: Pandas dataframe to list of tuples


code:
ternary(0)
ternary(1)
ternary(2)
ternary(3)
ternary(12)
ternary(22)

rawDescription: Convert decimal to ternary(base3) in python


code:
class MyPasswordMaker:
    def create_password(self):
        characters = string.ascii_letters + string.punctuation  + string.digits
        self.password =  "".join(choice(characters) for x in range(self.pass_char) )

    def store_password(self):
        try:
            connection = sqli.connect('pw.db')
        except:
            print("Error occurred!")

        with connection:
            cur = connection.cursor()
            cur.execute('''
                CREATE TABLE IF NOT EXISTS my_passwords(
                id INT PRIMARY KEY AUTOINCREMENT,
                password text
                '''
            )
        cur.execute('INSERT INTO my_passwords VALUES(?)', self.password)

rawDescription: Get Return Value from one function and use on another


code:
class GiftCardForm(forms.ModelForm):
    class Meta:
        model = Gift_Card
        widgets = {'denomination': forms.RadioSelect}

rawDescription: Django RadioSelect Choices From Model

description: Django RadioSelect Choices From Model


code:
def find_pay_period(date, df):
    # df[] use boolean mask to filter
    # .iloc[0, :] grabs first row of filtered DataFrame.
    # Keep in mind this is a Series.
    df = df[(df.START_DATE <= date) & (date <= df.END_DATE)].iloc[0, :]
    # add back your date
    df['actn_dt'] = date
    return df

rawDescription: pandas between statement for two dates from another dataset

description: Pandas between statement for two dates from another dataset


rawDescription: Array expansion in numpy

description: Array expansion in numpy


code:
def get_tile():
    from random import shuffle
    tiles = list("IJLOSTZ")
    while True:
        shuffle(tiles)
        for tile in tiles:
            yield tile

rawDescription: Tetris Random Generator: random.choice with permutations versus random.shuffle


code:
orgForm=OrganizationForm()
orgForm.organization.data = nameoforganization

rawDescription: pre-populate wtforms text field with values

description: Pre-populate wtforms text field with values


rawDescription: Suggestion for python regex and selecting columns


rawDescription: Sort bidimentional numpy array

description: Sort bidimentional numpy array


code:
class MyDictReader():
    def __init__(self, f, fieldnames=None, dialect='excel', *args, **kwrags):
        self.reader = csv.reader(f, dialect, *args, **kwrags)
        self._fieldnames = fieldnames
        if self._fieldnames is None:
            try:
                self._fieldnames = next(self.reader)
            except StopIteration:
                pass

    def __iter__(self):
        return self

    def next(self):
        d = {}
        row = self.reader.next()
        for index, fieldname in enumerate(self._fieldnames):
            if fieldname:
                d[fieldname] = row[index]
        return d

rawDescription: empty key while using dictread

description: Empty key while using dictread


code: d

rawDescription: How to get the value of a value as a key of a dictionary

description: Get the value of a value as a key of a dictionary


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

np.random.seed(2014)
A = np.random.randn(83, 83)
G = nx.from_numpy_matrix(A)

rawDescription: how to create weighted 2D array from networkx object in python

description: Create weighted 2D array from networkx object in python


code: spades=[A,B,C,D,E,F,G,H,I,J,K,L,M]

rawDescription: Set a variable to a random element from an array and not the elements value. ---python---


code:
mutate('ABC', 2, 'M')
mutate('ABC', 2, 'M')
mutate('ABC', 2, 'M')
mutate('ABC', 2, 'M')

rawDescription: Randomly replace items in a list

description: Randomly replace items in a list


code:
def isCircular(arr1, arr2):
    if len(arr1) != len(arr2):
        return False

    str1 = ' '.join(map(str, arr1))
    str2 = ' '.join(map(str, arr2))
    if len(str1) != len(str2):
        return False

    return str1 in str2 + ' ' + str2

rawDescription: How to check whether two lists are circularly identical in Python

description: Check whether two lists are circularly identical in Python


code:
import re

pattern = re.compile(r"\[\[([\w \|]+)\]\]")
text = "blah blah [[Alexander of Paris|poet named Alexander]] bldfkas"
results = pattern.findall(text)

output = []
for link in results:
    output.append(link.split("|")[0])

# outputs ['Alexander of Paris']

rawDescription: Python regex for finding contents of MediaWiki markup links


code:
with open("pro.txt") as file:
    count = sum(1 for line in file if regex.search(line))

rawDescription: Regular expression using python is not working


code:
import xml.etree.ElementTree as ET

xmlObject = ET.parse(xml_fname) # or ET.fromstring(xml_string)
pretty_xml_as_string = ET.tostring(xmlObject).decode()
print(pretty_xml_as_string)

rawDescription: Read an XML file with tags and indentation into a python variable


code: action = forms.CharField()

rawDescription: How to write a function in views.py that could handle more than two button?

description: Write a function in views.py that could handle more than two button


code:
import sublime

def prompt_sequence(g):
    def progress(result):
        try:
            progress.caption, progress.initial_text = g.send(result)
            sublime.active_window().show_input_panel(
                progress.caption,
                progress.initial_text,
                progress, None, None
            )
        except StopIteration:
            pass

    progress(None)

def foo():
    first_answer = yield ('First question', '')
    second_answer = yield ('Second question', '')
    third_answer = yield ('Thirdquestion', '')

    sublime.message_dialog('Your answers: ' + answers)

prompt_sequence(foo())

rawDescription: Pythonic way to manage multiple callbacks


code:
w = Warehouse(...)
i = Item(name="kindle", price=...)
w[i] = 50 # sets the quantity to 50 of item _i_ in warehouse _w_
i[w] = 50 # same as above, if you configure it symmetrically

rawDescription: sqlalchemy / table setup

description: Sqlalchemy / table setup


code:
dict = {}

for key, items in groupby(FilteredTable1[1:], itemgetter(0)):
    #print key
    for subitem in items:
        #print ' ', subitem
        if subitem[EntryID] not in dict:
            dict[subitem[EntryID]] = {}
            dict[subitem[EntryID]]['EC'] = []
            dict[subitem[EntryID]]['Km'] = []
            dict[subitem[EntryID]]['Kcat'] = []

        if 'ECNumber' in subitem:
            dict[subitem[EntryID]]['EC'] = subitem[value]

        if 'Km' in subitem and 'Start Value' in subitem:
            dict[subitem[EntryID]]['Km'] = subitem[value]
            #print subitem

rawDescription: Python - nested dictionary. Where is the bug?


code:
'a\nb'.strip()
'a\nb\n'.splitlines()

rawDescription: convert output of find command into array of strings in python

description: Convert output of find command into array of strings in python


code:
import MainModule
arr = \
    ['Module1', 'Module2', 'Module3', 'Module4', 'Module5']
for string in arr:
    globals()[string] = getattr(MainModule, string)

rawDescription: How to use from import if I would like to import the module as a String?

description: Use from import if I would like to import the module as a String


rawDescription: Opposite of melt in python pandas

description: Opposite of melt in python pandas


code:
def main():
    print("In room 1")

rawDescription: How to move to the next file in python

description: Move to the next file in python


code:
foo = "bar"
baz = "eggs"
spam = "have fun stormin' the castle"
globals()

rawDescription: Split and Count a Python String

description: Split and Count a Python String


code:
import re
soup.find(text=re.compile(r"\.doc$"))
soup.find("td", text=re.compile(r"\.doc$")).get_text()
soup.find(text=lambda text: text and text.endswith("doc"))
soup.find("td", text=lambda text: text and text.endswith("doc")).get_text()

rawDescription: BeautifulSoup4 table

description: BeautifulSoup4 table


code:
replaced_lines = []
departments = {'1': 'I.T.',
               '2': 'Administration',
               '3': 'Human Resources',
               '4': 'Maintenance'}
for line in file.splitlines():
    the_split_line = line.split(',')
    replaced_lines.append(','.join(the_split_line[:-1]+ \
                                   departments.get(the_split_line[-1], "Unknown Dept")))
new_file = '\n'.join(replaced_lines)
# LOTS OF STRING MANIPULATION, YUCK!

rawDescription: What Regex to use in this example

description: What Regex to use in this example


code: doc.write(''.join(str(r) for v in a for r in v))

rawDescription: convert list of lists into a string

description: Convert list of lists into a string


code: import module

rawDescription: Clone a module and make changes to the copy


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

fig, ax = plt.subplots()

x = np.arange(5)
y = np.random.rand(5)

bars = ax.bar(x, y, color='grey')
bars[3].set_color('g')

rawDescription: How do I get all bars in a matplotlib bar chart?

description: Get all bars in a matplotlib bar chart


code:
d_truncated = datetime.date(dt.year, dt.month, dt.day)
d_truncated

rawDescription: Truncate Python DateTime

description: Truncate Python DateTime


rawDescription: Match series of (non-nested) balanced parentheses at end of string


code:
df = df.iloc[j]
df

rawDescription: Python Pandas - Split different entries into separate rows allowing only certain combinations


code:
from PythonMagick import Image, CompressionType
im = Image('tiger-rgb-strip-contig-16.tif')
im.compressType(CompressionType.ZipCompression)
im.write("tiger-rgb-strip-contig-16-zip.tif")

rawDescription: How convert image into 16bit zip (deflate) compressed TIF in python?


code: from my_package.my_module import my_class

rawDescription: How to dynamically load a Python class

description: Dynamically load a Python class


rawDescription: Convert from string containing hexadecimal characters to bytes in python 3


code:
for i in range(1, 11):
    print(i, end='')

rawDescription: python 3: print new output on same line

description: Python 3: print new output on same line


code:
MyModel._meta.db_table = '10293847_table'
MyModel.objects.all()

rawDescription: Single Django model, multiple tables?

description: Single Django model, multiple tables


code:
from collections import deque
with open("target.txt", "w") as out_f:
  for line in deque(open("source.txt"), maxlen = 4):
    out_f.write(line)

rawDescription: Python: splitlines() from text file then write them back to text file


code: df.product(axis=1, level=1).head()

rawDescription: Use Column and Row Multi-Index values in Pandas Groupby without unstacking


rawDescription: Python - Extract and reformat field names from rows of data


code:
for c in range(len(string1)):
    if string1[c] == string2[c]:
        logic()

rawDescription: How to extract the characters of a string and compare them with another string in Python?

description: Extract the characters of a string and compare them with another string in Python


code:
def col2num(col):
    num = 0
    for c in col:
        if c in string.ascii_letters:
            num = num * 26 + (ord(c.upper()) - ord('A')) + 1
    return num

rawDescription: Convert an excel or spreadsheet column letter to its number in Pythonic fashion


code:
def merge(d1, d2):
    return dict(list(d1.items()) + list(d2.items()))

[[merge({'foobar': key, 'animal': sub_key}, sub_sub_dict)
    for sub_key, sub_sub_dict in sub_dict.items()]
        for key, sub_dict in a.items()]

rawDescription: Flatten a nested dict structure into a dataset in Python


code:
try:
  x
except NameError:
  x_exists = False
else:
  x_exists = True

rawDescription: pythonic way to check if something exists?

description: Pythonic way to check if something exists


code:
from operator import itemgetter
from itertools import ifilter

points = set(ifilter(itemgetter(4), data))
getter = itemgetter(1,2)
final_list = [d for d in data if getter(d) in points]

rawDescription: Python fastest way to find values in big data


code:
a = CallableList([1, 2, 3])
a(2)
a(slice(None, 2, None))

nested = CallableList([1, 2, CallableList([4, 5, 6])])
nested(2)(-1)

rawDescription: How might one change the syntax of python list indexing?


rawDescription: trying to create a dictionary but do not know how to deal with \n

description: Trying to create a dictionary but do not know how to deal with \n


code:
g = MyGrid(self, size=(100,100))
g.SetColLabelRenderer(0, MyCornerLabelRenderer())

rawDescription: How can I show a bitmap in wxGrid header cell?

description: Show a bitmap in wxGrid header cell


code:
# method using np.maximum.accumulate
def accumulate_based(A2):
    A2[np.maximum.accumulate((A2 < 0)[:, ::-1], axis=1)[:, ::-1]] = 0
    return A2

# large sample array
A2 = np.random.randint(-4, 10, size=(100000, 100))
A2c = A2.copy()
A2c2 = A2.copy()

rawDescription: get the index of the last negative value in a 2d array per column

description: Get the index of the last negative value in a 2d array per column


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

def get_field_value(driver, field):
    field = field.capitalize() + ":"
    return driver.find_element_by_xpath("//div[@class = 'dc_label' and . = '%s']/following-sibling::div[@class = 'dc_value']" % field).text

driver = webdriver.Firefox()
driver.get("http://www.har.com/4311-Childress-St/sale_40763013")

# wait for the page to load
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.CLASS_NAME, "dc_title")))

county = get_field_value(driver, "county")
print(county)

rawDescription: How to use Selenium to get the housing data

description: Use Selenium to get the housing data


code: '\n'.join('%i %.2f   %s'%tuple(row) for row in x)

rawDescription: Writing row from structured numpy array with varying delimiter


code:
#filter all tweets from san francisco
myStream.filter(location= [-122.75,36.8,-121.75,37.8])

rawDescription: Scrape tweets by tweet location and user location


code:
one = [(1, 2), (3, 4)]
for o in one:
    print(o, end=' ')
print()    #and an optional print() to ensure that anything afterwords prints on a separate line

rawDescription: Python print a list of two element in one line in a loop


rawDescription: if statement depending on list len

description: If statement depending on list len


rawDescription: python pandas merging data based off 2 keys

description: Python pandas merging data based off 2 keys


code:
timeit.timeit('a += x', 'a = x = 1')
timeit.timeit('a = a + x', 'a = x = 1')

rawDescription: Why is a += x slower than a = a+x?

description: Why is a += x slower than a = a+x


code: result_df = combined[['mobile', 'pincode', 'model', 'Name', 'Address', 'Location', 'pincode', 'date']]

rawDescription: Rearrange CSV data

description: Rearrange CSV data


code:
def speed(score, attacks_per_second):
    """
    computes actual attack speed for a player with `score`,
    assuming a player with a score of 100 could attack at
    `attacks_per_second`.  Lower scores are better.
    """
    return attacks_per_second * (100 / score)

rawDescription: trying to figure out a weird math formula

description: Trying to figure out a weird math formula


rawDescription: Python: resolve problems with my Class

description: Python: resolve problems with my Class


code:
inventoryList = [['Steak', ' 10'], ['Milk', ' 2'], ['Fruits', ' 10'], ['Canned Corn', ' 0.50']]
highestPriceItem = 10.0
highestPriceList = []

for item in inventoryList:
    if float(item[1]) == highestPriceItem:
        highestPriceList.append(item[0])
print ("Item with highest wholsesale price: ",highestPriceList)

rawDescription: How to append a item from a list to another list?

description: Append a item from a list to another list


code: [(res, y) for x, y in input_list for res in (func(x),) if res]

rawDescription: Python: [(x, y) for (x, y) in list_of_tuples if f(x) is not empty]


rawDescription: Accessing the column of the matrix

description: Accessing the column of the matrix


code:
import numpy as np
import random
from matplotlib.mlab import rec_groupby

listA = [random.choice("abcdef") for i in range(20000)]
listB = [20 * random.random() for i in range(20000)]

names = np.array(listA)
values = np.array(listB)

def f_dict(listA, listB):
    d = {}

    for a, b in zip(listA, listB):
        d.setdefault(a, []).append(b)

    avg = []
    for key in d:
        avg.append(sum(d[key])/len(d[key]))

    return d.keys(), avg

def f_numpy(names, values):
    result_names = np.unique(names)
    result_values = np.empty(result_names.shape)

    for i, name in enumerate(result_names):
        result_values[i] = np.mean(values[names == name])

    return result_names, result_values

rawDescription: Average duplicate values from two paired lists in Python using NumPy


rawDescription: Get non-duplicate rows from numpy array

description: Get non-duplicate rows from numpy array


code:
cmds = [path_to_program, arg1, arg2]
subprocess.Popen(cmds)

rawDescription: How to iterate and execute scripts from the command line?

description: Iterate and execute scripts from the command line


rawDescription: Creating an N-Amount of Forms using WTForms


code:
Solution
df[((df == 0) | (df == 1)).any(axis=1)]

rawDescription: How to use pandas isin() to test values on a range of columns in a dataframe

description: Use pandas isin() to test values on a range of columns in a dataframe


rawDescription: Changing ttk widget text color

description: Changing ttk widget text color


code:
type(ins_a)
type(ins_b)

rawDescription: What is difference between A.fun and A().fun?


code: float, float, int, int, bool, float, float, int, int, bool, ...

rawDescription: Read binary file which has different datatypes


code:
from joblib import Memory
mem = Memory(cachedir=cachedir)

@mem.cache
def f(arguments):
    """do things"""
    pass

rawDescription: Multiple processes sharing a single Joblib cache


code:
df['value'] *= np.where(df['when'] == 'before', -1, 1)
df

rawDescription: Group computation between rows on condition


code:
import bisect

def combinations_with_guaranteed(x, y, *guaranteed):
    values = set(range(x + 1))
    values.difference_update(guaranteed)
    for combo in combinations(sorted(values), y - len(guaranteed)):
        combo = list(combo)
        for value in guaranteed:
            bisect.insort(combo, value)
        yield combo

rawDescription: Combinations Including Select Elements (Python)


code:
X = np.empty((x.shape[0], x.shape[0]), dtype='complex128')
for i in range(x.shape[0]):
    for j in range(x.shape[0]):
        X[i, j] = np.vdot(x[i], x[j])

rawDescription: Pairwise vdot using Numpy

description: Pairwise vdot using Numpy


code: all(any(f(v) for f in functions) for v in values)

rawDescription: Search algorithm but for functions

description: Search algorithm but for functions


code:
def describe(obj):
    for key in dir(obj):
        try:
            val = getattr(obj, key)
        except AttributeError:
            continue
        if callable(val):
            help(val)
        else:
            print('{k} => {v}'.format(k = key, v = val))
        print('-'*80)

describe(self.panel)

rawDescription: Python - Saving state of a program between restarts?


code: rank, count, previous, result = 0, 0, None, {}

rawDescription: Ranking values in a Dictionary (and taking care of ex-aequos correctly)


code:
PythonActivity = autoclass('org.renpy.android.PythonActivity')
PackageManager = autoclass('android.content.pm.PackageManager')
pm = PythonActivity.mActivity.getPackageManager()
flash_available = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)

rawDescription: Accessing android flashlight(camera LED flash) with kivy/python


rawDescription: Selecting top N columns for each row in data frame


code:
def is_outlier(row):
    iq_range = statBefore.loc[row.ID]['q3'] - statBefore.loc[row.ID]['q1']
    median = statBefore.loc[row.ID]['median']
    if row.Value > (median + (1.5* iq_range)) or row.Value < (median - (1.5* iq_range)):
        return True
    else:
        return False
#apply the function to the original df:
df.loc[:, 'outlier'] = df.apply(is_outlier, axis = 1)
#filter to only non-outliers:
df_no_outliers = df[~(df.outlier)]

rawDescription: Python remove outliers from data

description: Python remove outliers from data


code:
import pandas as pd

df = pd.DataFrame({'D': {0: 6, 1: 4, 2: 6},
                    'A': {0: 1, 1: 2, 2: 3},
                    'C': {0: 2, 1: 7, 2: 5},
                    'B': {0: 4, 1: 5, 2: 6}})
print (df)
df = pd.concat([df]*1000, axis=1).reset_index(drop=True)

dfBool = pd.DataFrame({'a': [True, False, False, True]})
dfBool1 = pd.concat([dfBool]*1000).reset_index(drop=True)

rawDescription: Pandas filter columns of a DataFrame with bool


code:
man = Human()
man.age
man.height
Human(height=180).height

rawDescription: Python metaclass default attributes

description: Python metaclass default attributes


code: data = line.split(None, 1)

rawDescription: Adding characters to certain laces in string


code: new_class_obj.name = lambda *args, **kw: partial_obj(*args, **kw)

rawDescription: How to bind a method to class during its metaclass's __init__ method?

description: Bind a method to class during its metaclass's __init__ method


code:
import scrapy

class PublicationSpider(scrapy.Spider):

    name = 'pubspider'
    start_urls = ('http://eprints.bbk.ac.uk/view/subjects/csis.html',)

    def parse(self, response):

        # each publication is within a <p> element, let's loop on those
        for publication in response.css('div > div.ep_tm_page_content > div.ep_view_page.ep_view_page_view_subjects > p'):

            # the publication title is inside a <a> link, which also contains a URL
            for title in publication.xpath('./a'):
                pubtitle = title.xpath('normalize-space(.)').extract_first()
                publink = title.xpath('@href').extract_first()
                break
            # use a regex to find year digits inside brackets
            pubyear = publication.xpath('./text()').re_first(r'\((\d+)\)')

            # get text nodes from <span> before the link
            authors = publication.xpath('./span[@class="person_name"][./following-sibling::a]/text()').extract()

            # get text nodes after the link and use a regex matching either ISBN or ISSN,
            # get first result with re_first()
            # this can be an empty list is there no ISxN
            isxn = publication.xpath('./a/following-sibling::text()').re_first(r'(ISBN\s+\d+|ISSN\s+\d+-\d+)')
            yield {
                'title': pubtitle,
                'link': publink,
                'year':  pubyear,
                'authors': authors,
                'isxn': isxn
            }

rawDescription: duplicate data with scrapy

description: Duplicate data with scrapy


code:
locations = []
locations.extend("London")
locations

rawDescription: Transforming a checkboxGroupInput object into a vector


code:
# mysocket.py

import socket as _std_socket
from socket import *  # expose everything

def create_connection(address, *args, **kwargs):
    if address == ...:
       address = ...
    return _std_socket.create_connection(address, *args, **kwargs)

rawDescription: How can I overload a built-in module in python?

description: Overload a built-in module in python


rawDescription: The Bean Machine Function - Python

description: The Bean Machine Function - Python


code:
import pickle

# `highscores` is some previously populated high score dict

def save_scores(filename):
    with open(filename, 'w') as outfile:
        pickle.dump(highscores, outfile)

def load_scores(filename):
    with open(filename, 'r') as infile:
        highscores = pickle.load(infile)
    return highscores

rawDescription: Making each key store a maximum of 5 values in Python Dictionary


code:
original = md5('email@example.com').digest()
encoded = original.encode('base64')
original == encoded.decode('base64')

rawDescription: Django: Is Base64 of md5 hash of email address under 30 characters?


rawDescription: python collecting data from dataframe at specific row location

description: Python collecting data from dataframe at specific row location


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

fig, ax = plt.subplots()

x = np.linspace(0, 10, 100)
ax.plot(x, x, label='$y=x$')
ax.plot(x, 3 * x, label='$y=3x$')
ax.legend(loc='upper left')

ax.set(xlabel='Same X-values', ylabel='Same Y-values')

plt.show()

rawDescription: pyplot twinx() tickmark overlap

description: Pyplot twinx() tickmark overlap


code:
import lxml.etree as et

#...

self.xml = et.XML(filters.filtersxml)
self.tree_widget = QTreeWidget(parent)

def create_item(parent, xmlroot):
    item = QTreeWidgetItem(parent, [xmlroot.get('name')])
    for xmlchild in xmlroot.getchildren():
       create_item(item, xmlchild)
    return item

items = [create_item(None, xmlchild) for xmlchild in self.xml.getchildren()]
self.tree_widget.addTopLevelItems(items)
if ( items ):
    self.tree_widget.setCurrentItem(items[0])

rawDescription: QTreeWidget select first item

description: QTreeWidget select first item


code:
elevenpm = datetime.time(23, 0)
oneam = datetime.time(1, 0)
for s in ftimerange(elevenpm, oneam): print(s)

rawDescription: Adjust start and end range for time list in Python


code:
class Site(models.Model):
    name = models.CharField(max_length=200)
    prefix = models.CharField(max_length=1)
    secret = models.CharField(max_length=255)

    objects = manager.Manager()

    def __unicode__(self):
        return self.name

rawDescription: Add django model manager code-completion to Komodo


code:
import os
from subprocess import check_output
output = check_output(['/path/to/batch_file.bat'])
# parse the output, depending on what it is exactly, could be something like
temp, pressure = [int(l.strip()) for l in output.split(os.linesep) if l.strip()]

rawDescription: Retrieving a value from an executable/batch file using Python


rawDescription: Interpolation when no datarow exists

description: Interpolation when no datarow exists


code:
import numpy as np
A = np.loadtxt('data.m')
A

rawDescription: Create numpy array from matrix declared inside .m matlab file


rawDescription: How would I get the text AFTER a link in Python with BeautifulSoup?


code:
def noun_names(list):
    names = []
    for synset in list:
        for lemma in synset.lemmas():
            names.append(lemma.name())
    return names

names = noun_names(list(wn.all_synsets(wn.NOUN)))

rawDescription: transforming wordnet txt into lists in python nltk

description: Transforming wordnet txt into lists in python nltk


code: df[(df['emld'] == 'aol.com') & (df['bounce_type'] == 'hard')]

rawDescription: How to split pandas data frame by many criteria

description: Split pandas data frame by many criteria


code:
class MyList(list):
    def even(self):
        return [x for x in self if x % 2 == 0]

rawDescription: Creating custom "list" attributes

description: Creating custom "list" attributes


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

column_labels = list('ABCDEFGH')
row_labels = list('WXYZ')
fig, ax = plt.subplots()
data = np.array([[ 0.96753494,  0.52349944,  0.0254628 ,  0.5104103 ],
         [ 0.07320069,  0.91278731,  0.97094436,  0.70533351],
         [ 0.30162006,  0.49068337,  0.41837729,  0.71139215],
         [ 0.19786101,  0.15882713,  0.59028841,  0.06242765],
         [ 0.51505872,  0.07798389,  0.58790067,  0.44782683],
         [ 0.68975694,  0.53535385,  0.15696023,  0.35641951],
         [ 0.66481995,  0.03576846,  0.9623601 ,  0.96006395],
         [ 0.45865404,  0.50433582,  0.18182575,  0.35126449],])

data[3,:] = np.nan
data = np.ma.masked_invalid(data)

heatmap = ax.pcolor(data, cmap=plt.cm.seismic,
                    vmin=np.nanmin(data), vmax=np.nanmax(data))
# http://stackoverflow.com/a/16125413/190597 (Joe Kington)
ax.patch.set(hatch='x', edgecolor='black')
fig.colorbar(heatmap)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

rawDescription: Python: Leave Numpy NaN values from matplotlib heatmap and its legend


code:
class User(Base):
    # ...
    @classmethod
    def entries_count(cls, cond):
        return select([func.count(Entry.id)])\
                .where((Entry.author_id==cls.id) & cond)\
                .as_scalar()

session.query(User, User.entries_count(Entry.date>start_date))

rawDescription: Dynamic column_property with SQLAlchemy

description: Dynamic column_property with SQLAlchemy


code:
# Python 3.x only
import csv
with open('utf16.csv', 'r', encoding='utf16') as csvf:
    for line in csv.reader(csvf):
        print(line) # do something with the line

rawDescription: Python UTF-16 CSV reader

description: Python UTF-16 CSV reader


code:
myList = [(1,1), (2,2), (3,3), (4,4), (5,5)]
startIndex = 1
endIndex = 3
newTuple = (6,6)
myList[startIndex:endIndex] = [newTuple]
myList

rawDescription: Replace a list slice with a packed tuple


code:
emails = []
for participant in participants:
    emails.append(participant.email)

rawDescription: make a list of recipients to use it at send_mail

description: Make a list of recipients to use it at send_mail


code: "902".isdigit(), "2".isdigit() == True,True

rawDescription: Why does this Python boolean comparison return a triple?