code:
import pycurl
conn = pycurl.Curl()
conn.setopt(pycurl.URL, "http://bit.ly/rgCbf")
conn.setopt(pycurl.FOLLOWLOCATION, 1)
conn.setopt(pycurl.CUSTOMREQUEST, 'HEAD')
conn.setopt(pycurl.NOBODY, True)
conn.perform()
conn.getinfo(pycurl.EFFECTIVE_URL)

rawDescription: Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS


code: grid

rawDescription: Generation of multidimensional Grid in Python


code:
angles = {'east':0, 'northeast':np.pi/4, 'north':np.pi/2, 'northwest':3*np.pi/4,
          'west':np.pi, 'southwest':5*np.pi/4, 'south':3*np.pi/2, 'southeast':7*np.pi/4}
wind_angle = np.array([angles[i] for i in wind])

rawDescription: plot qualitative data on matplotlib

description: Plot qualitative data on matplotlib


code:
g.dropna()
g.dropna().reset_index()

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


code:
def find_sublists(seq, sublist):
    length = len(sublist)
    for index, value in enumerate(seq):
        if value == sublist[0] and seq[index:index+length] == sublist:
            yield index

rawDescription: Python: Acessing index numbers within an if statement nested within a for loop


rawDescription: Transposing a multi-dimensional matrix in Python with list comprehensions


code:
import auto_name
n = auto_name.Name()
print(n.__dict__)
print(auto_name.Name.__dict__)

rawDescription: Extract assigned variable name

description: Extract assigned variable name


rawDescription: How do I use a for loop to add new entries to a python dictionary?

description: Use a for loop to add new entries to a python dictionary


code:
from os.path import dirname
dirname('/home/kristina/desire-directory/scripts/script.py')
dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))

rawDescription: Get parent of current directory from Python script


rawDescription: Store mouse click event coordinates with matplotlib


code: letters = ''.join([choice(ascii_lowercase) for _ in range(5)])

rawDescription: Sequence of letters in Python

description: Sequence of letters in Python


rawDescription: Comparing an arbitrary number of lists element by element


code:
inds=np.triu_indices_from(a,k=1)
mask = (inds[1]>2) #Again change 2 for whatever columns you want to start at.
a[inds][mask]
max_index = np.argmax(a[inds][mask])
inds[mask][max_index]

rawDescription: Efficient way to find the index of the max upper triangular entry in a numpy array?


code:
with open("data.txt", encoding="utf-8") as fh:
    for line in fh:
        if line.startswith("City2"):
            for _ in range(3):
                print(line.strip())
                line = next(fh)
            continue

rawDescription: Python - delimited list from file

description: Python - delimited list from file


code:
from xml.dom.minidom import parseString

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

xml = """<root>
<shortcut>
33060
<label2>Common Shortcut</label2>
</shortcut>
<shortcut>
Test
</shortcut>
</root>"""
xmldoc = parseString(xml)
labels = xmldoc.getElementsByTagName("label")
for label in labels:
    text = getText(label.childNodes)
    if text == "Test":
        print("node found : " + label.toprettyxml())
        break

rawDescription: Search for specific text in an element of XML with DOM (Python)


code:
f = open("outputFile","wb")
subprocess.call(argsArray,stdout=f)

rawDescription: Why os.system is not able to redirect to a file? How to enable that?


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


code:
from decimal import Decimal
Decimal('Inf')

rawDescription: What is the largest number the Decimal class can handle?


code: indexes = {word: re.search("\b{word}\b".format(word=word),text) for word in badpositions}

rawDescription: Add in word boundary syntax to list of strings


code:
for field in MyModel._meta.fields:
    FIELD_PYTHON_TYPES[field.get_internal_type()]

rawDescription: How to get native type of a model in django

description: Get native type of a model in django


code:
for slicelist, text in zip(lists_of_lists, just_a_list):
    for start, stop in zip(*([iter(slicelist)]*2)):
        print(text[int(start):int(stop) + 1])

rawDescription: Iterating between 2 lists

description: Iterating between 2 lists


code:
def any(iterable):
    for item in iterable:
        if item: return True
    return False

rawDescription: Comparing list of unique objects with custom function


code:
idx = df.groupby(["GENE", "DIRECTION"])['SUMRANGE'].agg(lambda col: col.idxmax())
print(idx)
# GENE  DIRECTION
# BB-2  +            16
#       -            18
# EE-3  +            23
#       -            29
# TT-1  +             7
# Name: SUMRANGE

rawDescription: Finding and deleting repeated data entries with two identical features identified by a third unique feature


code:
@tail_call_optimized
def countup(N, n=0):
    print(n)
    if n < N:
        countup(N, n + 1)

rawDescription: python recursive function that prints from 0 to n?

description: Python recursive function that prints from 0 to n


code:
order = {u'custom_attributes_desc': {u'text': u'Food truck', u'name': u'Bob', u'email': u'bob@yahoo.com'}, u'account_id': 12345, u'state_desc': u'open', u'start_dt': u'2013-07-25 15:41:37', u'end_dt': u'2013-07-25 19:41:37', u'product_nm': u'foo', u'transaction_id': 12345, u'product_id': 1111}
match = ['transaction_id', 'account_id', 'product_nm']
list(zip(match, order.keys()))

rawDescription: compare dict.keys() with list, bug in expression

description: Compare dict.keys() with list, bug in expression


code:
x = []
for i in range(1000):
    x.append(numpy.all((x[i],y[i])))

rawDescription: Why is numpy.all much slower than python standard all?


code:
import sys
del sys.modules['MyPak.MyMod']
reload(MyPak)
from MyPak import MyMod

rawDescription: how to reload a Class in python shell?

description: Reload a Class in python shell


code:
import csv
import collections
seen = set()
data = collections.OrderedDict()
with open("file1.csv", "rU") as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        key = row[3].split('_')[0]
        if key in seen:
            del data[key]
        else:
            data[key] = row
            seen.add(key)

with open('output.csv', 'w') as f_out:
    writer = csv.writer(f_out, delimiter=',')
    writer.writerows(data.values())

rawDescription: Python exract unique record from csv file


code:
import json
import pandas as pd

df = pd.read_csv('data.csv')

def get_nested_rec(key, grp):
    rec = {}
    rec['PrimaryId'] = key[0]
    rec['FirstName'] = key[1]
    rec['LastName'] = key[2]
    rec['City'] = key[3]

    for field in ['CarName','DogName']:
        rec[field] = list(grp[field].unique())

    return rec

records = []
for key, grp in df.groupby(['PrimaryId','FirstName','LastName','City']):
    rec = get_nested_rec(key, grp)
    records.append(rec)

records = dict(data = records)

print(json.dumps(records, indent=4))

rawDescription: Python csv to nested JSON

description: Python csv to nested JSON


code: x if x not in seen and not seen.add(x) else ''

rawDescription: Remove following duplicates in a tuple

description: Remove following duplicates in a tuple


code:
dayOfWeek={0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}
df['weekday'] = df['datetime'].dt.dayofweek.map(dayOfWeek)

rawDescription: Num day to Name day with Pandas

description: Num day to Name day with Pandas


code:
d = NoisyDict()

d.add_handler('spam', print)

d['bar'] = 3
d['spam'] = 'spam spam spam'

rawDescription: Pythonic way of polling a dictionary - using the key's value once it exists


code:
for element1 in soup.find_all(True, text="1"):
    print(element1)

rawDescription: Python 3 BeautifulSoup4 search for text in source page


code:
['one', 'two'] ['one two three four five\n', 'one two five six seven\n']
['three', 'four'] ['three four something\n', 'three four something else\n']
['one', 'two'] ['one two start of new one two block\n']

rawDescription: Python- group lines by first two words

description: Python- group lines by first two words


code:
from tkinter import *

# ---

def test(event):
    print(event)

# ---

window = Tk()

# created befor binding
Button(window, text="Button #1").pack()
Button(window, text="Button #2").pack()
Button(window, text="Button #3").pack()

window.bind_class('Button', '<Enter>', test)

# created after binding
Button(window, text="Button #4").pack()

window.mainloop()

rawDescription: Adding a hovering option to my buttons in a class


code:
for i in range(1, 6, 1):
    print( " ".join(map(str, range(1, 10, 1))) )

rawDescription: Aligning text in a table using string formatting with a loop inside a loop


rawDescription: Converting a single dictionary value in to a list?


code:
A,B,C,D = zip(*((this_[:n],this_[n:],next_[:n],next_[n:])
                  for this_,next_ in zip(matrix_x,matrix_x[1:])))

rawDescription: Better way to do multiple list comprehensions over the same range?


rawDescription: Using the split function

description: Using the split function


code:
# The data of the plot will be added in these lists
x_data_plot=[]
y_data_plot=[]

rawDescription: Plotting within a for loop, with 'hold on' effect in matplotlib?


code:
ob1 = Thing("ob1")
ob1.inside.extend([Thing("ob1sub1"), Thing("ob1sub2"), Thing("ob1sub3")])

ob2 = Thing("ob2")
for i in xrange(1,4):
    name = "ob2sub{}".format(i)
    thing = Thing(name)
    thing.inside.append(Thing(name + "sub1"))
    ob2.inside.append(thing)

ob3 = Thing("ob3")

things = [ob1, ob2, ob3]

rawDescription: setting up iterative item query in python

description: Setting up iterative item query in python


code:
'''Backport of 2.7.4 EINTR handling'''

import errno
import select
import SocketServer

def _eintr_retry(func, *args):
    """restart a system call interrupted by EINTR"""
    while True:
        try:
            return func(*args)
        except (OSError, select.error) as e:
            if e.args[0] != errno.EINTR:
                raise

def serve_forever(self, poll_interval=0.5):
    """Handle one request at a time until shutdown.

    Polls for shutdown every poll_interval seconds. Ignores
    self.timeout. If you need to do periodic tasks, do them in
    another thread.
    """
    self._BaseServer__is_shut_down.clear()
    try:
        while not self._BaseServer__shutdown_request:
            # XXX: Consider using another file descriptor or
            # connecting to the socket to wake this up instead of
            # polling. Polling reduces our responsiveness to a
            # shutdown request and wastes cpu at all other times.
            r, w, e = _eintr_retry(select.select, [self], [], [],
                                   poll_interval)
            if self in r:
                self._handle_request_noblock()
    finally:
        self._BaseServer__shutdown_request = False
        self._BaseServer__is_shut_down.set()

def handle_request(self):
    """Handle one request, possibly blocking.

    Respects self.timeout.
    """
    # Support people who used socket.settimeout() to escape
    # handle_request before self.timeout was available.
    timeout = self.socket.gettimeout()
    if timeout is None:
        timeout = self.timeout
    elif self.timeout is not None:
        timeout = min(timeout, self.timeout)
    fd_sets = _eintr_retry(select.select, [self], [], [], timeout)
    if not fd_sets[0]:
        self.handle_timeout()
        return
    self._handle_request_noblock()

# patch in updated methods
SocketServer.BaseServer.serve_forever = serve_forever
SocketServer.BaseServer.handle_request = handle_request

rawDescription: setting a counter with a basic HTTP server

description: Setting a counter with a basic HTTP server


code:
from collections import Counter

c = Counter(b['Item'] for b in bookings)
item = min(c, key=c.get)

rawDescription: Pythonic way to find fewest occurrences of object in list


code:
from mysql.connector.cursor import MySQLCursor
cursor = MySQLCursor()
cursor
getattr(cursor, 'fetchall')
getattr(cursor, 'fetchall')()

rawDescription: how to call `getattr()` to get a Python MySQLCursor method?

description: Call `getattr()` to get a Python MySQLCursor method


code: sorted(dict1, key=lambda k: dict1[k]['Name'])

rawDescription: Worth using sorted( ,key=) on a nested dictionary?


code:
for business in soup.find_all('div', class_="info"):
    days = business.find("div", class_="days")

    print(" ".join(sibling.get_text(strip=True)
                   for sibling in reversed(days.find_previous_siblings())))

rawDescription: Parsing div children with Beautiful Soup


rawDescription: Why is re.sub is not replacing string with empty string


code: dict(map(int, x.split(':')) for x in s.split(','))

rawDescription: Transforming the string representation of a dictionary into a real dictionary


code:
world = [['g'] * 60 for _ in xrange(60)]
add(world, 'e', 25)
add(world, 't', 5)

rawDescription: How to create a random multidimensional array from existing variables

description: Create a random multidimensional array from existing variables


code: df.loc[df.groupby('User')['X'].filter(lambda x: x.sum() == 0).index]

rawDescription: How to subset a data frame using Pandas based on a group criteria?

description: Subset a data frame using Pandas based on a group criteria


code:
for loop in xrange(240):
    os.system(kjor)
    time.sleep(seconds)

rawDescription: Can I damage the system by running time.sleep() with this newbie code in Python?

description: Damage the system by running time.sleep() with this newbie code in Python


code:
url(r'^results/(\d+)/$', views.user_results, name='user_results'),  # will dispatch here and stop searching url patterns if a digit occurs after results
url(r'^results/', views.results, name='results')

rawDescription: Django: url dispatcher

description: Django: url dispatcher


code:
mask = (flat >= 0.2) & (flat < 0.7)
flat[mask] = func(flat, 0)[mask]

rawDescription: How to modify a Numpy array with conditional and function

description: Modify a Numpy array with conditional and function


code: cal.set(y, m - 1, d);

rawDescription: Week of year calculation differences between Java and Python


rawDescription: Find number in string between spaces and parse it


code:
for start_end in Months:
    func(start_end)

rawDescription: Loop through list of tuples, call elements independently


code:
row_index = np.argmax(y, axis=0)

# Alternately
row_index = y.argmax(axis=0)

rawDescription: Finding row index of max column values in a numpy matrix


rawDescription: How to remove a string with varying numbers at the end

description: Remove a string with varying numbers at the end


code: prime = {x for x in range(2, 100) if all(x % y != 0 for y in range(2, int(math.floor(math.sqrt(x))) + 1))}

rawDescription: Python generating prime numbers using Set Comprehension


code:
fc = '0x'
for i in b[0x15c:0x15f]:
    fc += hex(ord(i))[2:].zfill(2)

rawDescription: Python , Printing Hex removes first 0?

description: Python , Printing Hex removes first 0


code: true < 3

rawDescription: javascript comparison operators

description: Javascript comparison operators


rawDescription: calculating rolling mean pandas with time-weighted values

description: Calculating rolling mean pandas with time-weighted values


code: import datetime

rawDescription: Python - datetime of a specific timezone


code: rules = yara.compile()

rawDescription: Writing yara rules in Python

description: Writing yara rules in Python


code:
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

rawDescription: Correct layout for dictionary literals

description: Correct layout for dictionary literals


code:
for m in re.finditer(psq_re_f, ref_seq):
    count=count+1
    outputfileg.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s' % (count,
                      chr1[0], len(ref_seq), m.start(),
                      m.start() + len(m.group(1)), len(m.group(1)),
                      '+',m.group(1))+'\n')

rawDescription: How to obtain overlapping patterns with Python finditer?

description: Obtain overlapping patterns with Python finditer


rawDescription: How to reshape a networkx graph in Python?

description: Reshape a networkx graph in Python


code:
url(r'$', 'display', name='dyn_optional_display')
url(r'(?P<category>[a-z]+)$', 'display', name='dyn_display')

rawDescription: pass kwargs for the view in reverse; django 1.5

description: Pass kwargs for the view in reverse; django 1.5


code:
# since you can't set attributes on a normal dict, use a subclass
class MyDict(dict): pass

my_dict = MyDict({
  'foo' : 'bar',
  'subdict':{
    'sub1' : 1,
    'sub2' : 2
  }
})

my_list = [1, 2]

x = 'x'

# we're going to set multiple things in my_dict to x, let's not repeat ourselves
set_my_dict_to_x = LocationProxy.object_value_setter(my_dict, x)

# we'll use set_to_x as you used it later on my_list
set_to_x = LocationProxy.value_setter(x)

rawDescription: Descend through an object and sub-objects to set an arbitrary item or attribute in the hierarchy


code:
def pv(var):
    (filename,line_number,function_name,text)=traceback.extract_stack()[-2]
    print('%s: %s'%(text[text.find('(')+1:-1],var))

x=5
pv(x)
# x: 5

rawDescription: How can I detect if the caller passed any variables to my function in Python?

description: Detect if the caller passed any variables to my function in Python


code:
from PyQt4 import QtGui
import sys

imagePath = "enter the path to your image here"

class ImgWidget1(QtGui.QLabel):

    def __init__(self, parent=None):
        super(ImgWidget1, self).__init__(parent)
        pic = QtGui.QPixmap(imagePath)
        self.setPixmap(pic)

class ImgWidget2(QtGui.QWidget):

    def __init__(self, parent=None):
        super(ImgWidget2, self).__init__(parent)
        self.pic = QtGui.QPixmap(imagePath)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawPixmap(0, 0, self.pic)

class Widget(QtGui.QWidget):

    def __init__(self):
        super(Widget, self).__init__()
        tableWidget = QtGui.QTableWidget(10, 2, self)
        tableWidget.setCellWidget(0, 1, ImgWidget1(self))
        tableWidget.setCellWidget(1, 1, ImgWidget2(self))

if __name__ == "__main__":
    app = QtGui.QApplication([])
    wnd = Widget()
    wnd.show()
    sys.exit(app.exec_())

rawDescription: Adding images to a QTableWidget in PyQt

description: Adding images to a QTableWidget in PyQt


code:
def purchase():
    from bisect import bisect_left
    data = {"b": [10, 20, 30, 40], "c": [100, 200, 330], "m": [20, 40, 50], "d": [70, 80, 90], "t": [50, 85, 100]}
    for _ in range(2):
        item_type = raw_input("Enter the item type-b,m,d,t,c:")
        max_cost = int(input("Enter the maximum item cost:"))
        v = data[item_type]
        ind = bisect_left(v, max_cost, hi=len(v) - 1)
        if v[ind] <= max_cost:
            print("Sold for {}".format(v[ind]))
            v.remove(v[ind])
        else:
            print("Sorry, cheapest is {}".format(v[0]))

rawDescription: Python: Find an item in a list

description: Python: Find an item in a list


code: print(reversed(binary)[0], reversed(binary)[1], ..., sep='')

rawDescription: Python what is '*' used for

description: Python what is '*' used for


code:
from django.views import generic
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from .models import Deal
from .forms import DealForm

class IndexView(generic.ListView):
    context_object_name = 'latest_deals_list'

    def get_queryset(self):
        return Deal.objects.order_by('-created_date')[:10]

class DetailView(generic.DetailView):
    model = Deal

def add_model(request):

    form = DealForm(request.POST or None)
    if form.is_valid():
        deal = form.save()
        return HttpResponseRedirect(reverse('deals:detail', args=(deal.id,)));

    return render(request, "deals/deal_form.html", {'form': form, 'title': 'Add New Deal'})

def update_model(request, pk):

    deal = get_object_or_404(Deal, pk=pk)

    form = DealForm(request.POST or None, instance=deal)
    if form.is_valid():
        deal = form.save()
        return HttpResponseRedirect(reverse('deals:detail', args=(deal.id,)));

    return render(request, "deals/deal_form.html", {'form': form, 'title': 'Editing "' + deal.title + '"'})

def delete_model(request, pk):

    deal = get_object_or_404(Deal, pk=pk)

    if request.method == 'POST':
        deal.delete()
        return HttpResponseRedirect(reverse('deals:index'));

    return render(request, "deals/deal_confirm_delete.html", {'object': deal, 'title': 'Confirm deleting "' + deal.title + '"'})

rawDescription: Python/Django handling HTTP requests in the right way


code:
new_d = [list(zip(repeat(row["index"]), map(it(0), sorted(row[1:].iteritems(), key=it(1) ,reverse=1)[:n])))
                     for _, row in df.iterrows()]

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


code:
classes = [Class() for _ in range(5)]
classes

rawDescription: Different class variables and usage

description: Different class variables and usage


code:
for line in iter(p.stdout.readline, ''):
    for word in line.split():
        print(word)
    sys.stdout.flush()

rawDescription: How can I print a long line in realtime in python?

description: Print a long line in realtime in python


code:
seq = (1, 2, 4, 8, 16, 32, 64)

def compare(a, b):
    print('%s ~ %s' % (a, b))

if __name__ == '__main__':
    for i, item in enumerate(seq, start=1):
        for other in seq[i:]:
            compare(item, other)

rawDescription: What's the most Pythonic way to make all 2-way comparisons in a sequence?


code:
counts = np.bincount(i,v)
d[:counts.size] = counts

rawDescription: Numpy sum elements in array based on its value


code:
o=MyClass()
o.foo
o.foo=3

rawDescription: How to lock a method in python (prevent it to be overwritten)?

description: Lock a method in python (prevent it to be overwritten)


code: levels = raw_input("Enter Levels: ")

rawDescription: Using csh script to input user specified arguments into a python script


rawDescription: How to calculate timedelta until next execution for scheduled events

description: Calculate timedelta until next execution for scheduled events


code:
from rest_framework.pagination import PageNumberPagination
from collections import OrderedDict # requires Python 2.7 or later

class PageNumberPaginationWithoutCount(PageNumberPagination):
    # Set any other options you want here like page_size

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data)
        ]))

rawDescription: Django Rest Framework pagination extremely slow count


rawDescription: Adding characters to certain laces in string


fruit_name: Apple

country: Nepal

rawDescription: Django Tastypie: Filtering by ForeignKey


code:
for item in myList:
    if item == something:
        doStuff(item)

rawDescription: Understanding pythons enumerate

description: Understanding pythons enumerate


code:
def withself(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        return f(f, *args, **kwds)
    return wrapper

@withself
def aa(self):
      print(self.__name__)
      # etc.

rawDescription: is there a self flag can reference python function inside itself?

description: Is there a self flag can reference python function inside itself


code: datetime.datetime(year, month, day, hour, minute, second)

rawDescription: Parse timestamps containing different lengths Python


code:
if new:
    # handle the case where there is no end separator
    print("Error in input file: no ending separator")
    return ''
else:
    return ''.join(rec)

rawDescription: how to read from a particular line upto a particular line in python

description: Read from a particular line upto a particular line in python


code:
import socket
import struct

# create a socket object
requestCore = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM)
responseCore = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM)

# get local machine name
host = socket.gethostname()
port = 8100

# bind to the port
requestCore.bind((host, port))
# queue up to 5 requests
requestCore.listen(5)
client,addr = requestCore.accept()

port = 9999
responseCore.connect((host, port))

while True:
    msg = input("User Input: ")
    client.send(bytes(msg.encode('UTF-8')))

    msgFrmServ = responseCore.recv(64)
    print("message from Server",msgFrmServ)

client.close()
responseCore.close()

rawDescription: Implementing Client- Sever model using Go and Python on Windows OS


code: b, a = sorted((a, b), key=len)

rawDescription: How to elegantly interleave two lists of uneven length in python?

description: Elegantly interleave two lists of uneven length in python


code:
command_line = 'mail -s "おお様からの天気予報" abc@gmail.com < foo'
li = command_line.split()
process = subprocess.Popen(li)

rawDescription: Send email in python using subprocess module


code: score = score + SCRABBLE_LETTER_VALUES[letter]

rawDescription: dictionaries in python: summing the values returned from searching the keys

description: Dictionaries in python: summing the values returned from searching the keys


code:
listOne = ['!'.join(i) for i in listOne]
listOne

rawDescription: Put a symbol between every letter in a list of strings


code:
def save(self, *args, **kwargs):
    if not self.first_name:
        self.first_name = self.user.first_name
    # now call the default save() method
    super(MyModel, self).save(*args, **kwargs)

rawDescription: Django empty field fallback

description: Django empty field fallback


code:
import traceback
from threading import Thread
try:
    import queue as Queue  # Python3.x
except ImportError:
    import Queue

class ThreadPool(object):
    def __init__(self, no=10):
        self.alive = True
        self.tasks = Queue.Queue()
        self.threads = []
        for _ in range(no):
            t = Thread(target=self.worker)
            t.start()
            self.threads.append(t)

    def worker(self):
        while self.alive:
            try:
                fn, args, kwargs = self.tasks.get(timeout=0.5)
            except Queue.Empty:
                continue
            except ValueError:
                self.tasks.task_done()
                continue

            try:
                fn(*args, **kwargs)
            except Exception:
                # might wanna add some better error handling
                traceback.print_exc()

            self.tasks.task_done()

    def add_job(self, fn, args=[], kwargs={}):
        self.tasks.put((fn, args, kwargs))

    def join(self):
        self.tasks.join()

    def deactivate(self):
        self.alive = False
        for t in self.threads:
            t.join()

rawDescription: Limiting Threads within Python Threading, Queue


code:
import timeout_decorator

class TestCaseWithTimeouts(unittest.TestCase):

    # ... whatever ...

    @timeout_decorator.timeout(LOCAL_TIMEOUT)
    def test_that_can_take_too_long(self):
        sleep(float('inf'))

    # ... whatever else ...

rawDescription: How to specify test timeout for python unittest?

description: Specify test timeout for python unittest


rawDescription: Extracting href ID from block of code using Python


code:
class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        authentication = TestResource.Meta.authentication # works (because of the inheritance)

rawDescription: How to access the meta attributes of a superclass in Python?

description: Access the meta attributes of a superclass in Python


code:
df = pd.DataFrame({"ORGANIZATION": ["Org1", "Org1 - Dave", "Org1 - Lisa", "Org2 - Bob", "Org3 - Sally"]})
df
df[df["ORGANIZATION"].str.contains("Org1")]
df[~df["ORGANIZATION"].str.contains("Org1")]

rawDescription: Filtering content by whether field contains a value


code:
rand_iter = lambda start, end: iter(random.randint(start, end), None)
rand_bytes = rand_iter(0, 256)

rawDescription: python: iterator from a function

description: Python: iterator from a function


code:
heatmap = ax.pcolor(data, cmap=plt.cm.seismic,
                    vmin=np.nanmin(data), vmax=np.nanmax(data))

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


code:
def multipleApply(df):
    for j, val in df.iteritems():
        for i, row in enumerate(val):
            if i == 0:
                continue
            df[j].iloc[i] = row + val[i-1]*np.exp(-0.05)

rawDescription: Exponential Decay on Python Pandas DataFrame


code:
url(r'^(api|internal|admin)/', SomeView.as_view()),
url(r'^.*', MainView.as_view())

rawDescription: Match all urls without the prefix in Django


code:
class MySpider(BaseSpider):
    name = "myspider"
    allowed_domains = ["example.com"]
    pid = "4545-fw"
    person = "bob"

    def start_requests(self):
        start_urls = (
            ('http://www.example.com/person/%s/person.xml' % self.person, PersonItem),
            ('http://www.example.com/%s/product.xml' % self.pid, ProductItem),
        )
        for url, cls in start_urls:
            yield Request(url, meta=dict(cls=cls))

    def parse(self, response):
        item = response.meta['cls']()

rawDescription: How to crawl only two pre-defined pages, but they scrape different items?

description: Crawl only two pre-defined pages, but they scrape different items


code:
def join_rows(rows):
    def join_tuple(tup):
        for x in tup:
            if x:
                return x
        else:
            return ''
    return [join_tuple(x) for x in zip(*rows)]

rawDescription: Joining all rows of a CSV file that have the same 1st column value in Python


code:
class User:

    def __init__(self, id_):
        self.user_id = id_

    def __getattr__(self, attr):
        return _global_user_data[self.user_id][attr]

    def set_x(self, val):
        if val < 0:
            raise ValueError
        _global_user_data[self.user_id]['x'] = val

    x = property(lambda self: self.__getattr__('x'), set_x)

rawDescription: Use __getattr__ instead of a getter and still have a setter?


rawDescription: Pygame cannot find include file "sdl.h"

description: Pygame cannot find include file "sdl.h"


rawDescription: Defined dict entries Python

description: Defined dict entries Python


code:
url = url_for('static', filename='rawxml.txt', t=time.time())
return redirect(url)

rawDescription: Serving changing files with Flask

description: Serving changing files with Flask


code:
def insert_3d2(A,B,C):
    mi = np.ravel_multi_index([np.arange(A.shape[0]), C], A.shape[:2])
    bvals = np.take(B.reshape(-1, B.shape[-1]), mi, axis=0)
    # result = np.insert(A.reshape(-1, A.shape[2]), mi + 1, bvals, axis=0)
    # which does:

    mi += np.arange(len(mi))
    A1 = A.reshape(-1, A.shape[2])
    shape = list(A1.shape)
    shape[0] += len(mi)
    A2 = np.empty(shape,dtype=A1.dtype)
    mask = np.ones(shape[0], dtype=bool)
    mask[mi] = False
    A2[mask,:] = A1
    A2[mi,:] = bvals

    A2 = A2.reshape(A.shape[0], -1, A.shape[2])
    return A2

rawDescription: Insertion of non aligned elements in 4-dimensional matrices in numpy


code: cmd="python script1.py %s"%i

rawDescription: Call same python script in for loop from another python script


code:
meta_list = dict((i, []) for i in range(0, num_lines))

for file in files:
    with open(file, 'rb') as f:
          line_num = 1
          for line in f:
              if condition_met(line):
                  meta_list[line_num].append(float(line))
              line_num = line_num + 1

rawDescription: Python: gathering corresponding lines that meet certain condition from multiple files


code:
total_count = dir_count = 0, 0
# .. increment either as needed
return total_count, dir_count

rawDescription: Using the recursive code, I want to return a set of 2 values (total files, folders)


code:
def check_movement(self):
    from twisted.internet.threads import deferToThread
    def get_input():
        # this is run in a thread
        return GPIO.input(11)
    def check_input(sensor_state):
        # this is back on the main thread, and can safely call send_m
        if sensor_state == 1:
            self.send_m("sensor movement detected")
    return deferToThread(get_input).addCallback(check_input)

rawDescription: Call a twisted protocol method from another thread


code:
@subtracter(b=5)
def dot(x,y):
    temp1=[]
    for i in range(len(x)):
        temp1.append(float(x[i])*y[i])
    tempdot=sum(temp1)
    return tempdot

rawDescription: How to decorate a function while adding variables in Python

description: Decorate a function while adding variables in Python


rawDescription: Python using classmethod for multiple constructors


Why does 9007199254740993 != 9007199254740993.0


code:
if __name__ == '__main__':
   import contract
   contract.checkmod(__name__)
   import doctest, GA
   doctest.testmod(GA)

rawDescription: PyContract check functions in an imported module


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from pandas.io.parsers import StringIO

rawDescription: Pandas Merge on Name and Closest Date

description: Pandas Merge on Name and Closest Date


code:
import io
import shutil
from urllib.request import urlopen

with urlopen('http://stackoverflow.com') as u, \
     open('so.html', 'w', encoding='utf-8', newline='') as file, \
     io.TextIOWrapper(u, encoding=u.headers.get_content_charset('utf-8'), newline='') as t:
    shutil.copyfileobj(t, file)

rawDescription: how to convert UTF-8 code to symbol characters in python

description: Convert UTF-8 code to symbol characters in python


code:
import time, telnetlib

host    = "host.example.com"
port    = 223
timeout = 9999

try:
    session = telnetlib.Telnet(host, port, timeout)
except socket.timeout:
    print ("socket timeout")
else:
    session.write("command1\n")
    session.write("command2\n")
    with open("test.xml", "w") as logfile:
        output = session.read_some()
        while output:
            logfile.write(output)
            time.sleep(0.1)  # let the buffer fill up a bit
            output = session.read_some()

rawDescription: Python 3.3 telnet issue

description: Python 3.3 telnet issue


code:
class A(some_function()):
  def f(self):
    self.member = 42
    self.method()

rawDescription: Python: How to avoid explicit  'self'?

description: Python: How to avoid explicit  'self'


rawDescription: Given a date range how can we break it up into N contiguous sub-intervals?


Python: convert "5,4,2,4,1,0" into [[5, 4], [2, 4], [1, 0]]


code:
import pandas as pd

from tempfile import TemporaryFile
with open("in.csv") as f, TemporaryFile("w+") as t:
    for line in f:
        t.write(line.replace(" ", ""))
    t.seek(0)
    ln = len(line.strip().split(","))
    header = t.readline().strip().split(",")
    header += range(ln)
    print(pd.read_csv(t,names=header))

rawDescription: read_csv with missing/incomplete header or irregular number of columns

description: Read_csv with missing/incomplete header or irregular number of columns


rawDescription: gnuplot linecolor variable in matplotlib?

description: Gnuplot linecolor variable in matplotlib


code:
from itertools import islice, izip, chain, tee
def compress(seq, x):
    seq, shift = tee(seq)
    shift = chain(islice(shift, 1, None), (object(),))
    return (i for i, j in izip(seq, shift) if (i, j) != (x, x))

rawDescription: Remove certain consecutive duplicates in list


rawDescription: How to check if an element from List A is not present in List B in Python?

description: Check if an element from List A is not present in List B in Python


code:
e2 = Elements[:,1:].astype(int)
I,J,K = np.where(e2==n[:,None,None])
results2 = np.zeros((e2.shape[0],e2.shape[1],2),nodes.dtype)
results2[J,K] = nodes[I,1:]
results2.reshape(2,4)   # still requires a reshape

rawDescription: Python - Replace data of an array by 2 values of a second array


code:
import svmutil
param = svmutil.svm_parameter('-q')
...

rawDescription: Suppressing the output in libsvm (python)


code: from mymodule import GLOBAL_VAR

rawDescription: How do you declare a global constant in Python?

description: Declare a global constant in Python


code:
result = subprocess.call(cmd) # This will block until cmd is complete
p = subprocess.Popen(cmd) # This will return a Popen object right away

rawDescription: Python subprocess calls hang?

description: Python subprocess calls hang


code:
import dill
from pathos.multiprocessing import ProcessingPool as Pool
p = Pool()

def squared(x):
  return x**2

dill.dumps(squared)

p.map(squared, range(10))

rawDescription: pickling and mulitprocessing

description: Pickling and mulitprocessing


code:
import pandas as pd
mydata = pd.read_csv(filename)
target = mydata["Label"]  #provided your csv has header row, and the label column is named "Label"

#select all but the last column as data
data = mydata.ix[:,:-1]

rawDescription: Loading a dataset from file, to use with sklearn


code:
class Child(db.Model):
    __tablename__ = 'children'

    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('parents.id'), nullable=True)
    parent = db.relationship('Parent', backref=db.backref('children'))
    name = db.Column(db.String)

rawDescription: How to nullify childre's foreign key when parent deleted using sqlalchemy?

description: Nullify childre's foreign key when parent deleted using sqlalchemy


code: graph.add((URIRef('http://stackoverflow.com/q/24017320/1281433/ontology.owl'), RDF.type, OWL.Ontology ))

rawDescription: Using owl:Class prefix with rdflib and xml serialization


code:
import numpy as np

datacolumn = 3
outputcolumns = 3
data = np.genfromtxt('path/to/csvfile',skip_header=True)
column = data[:,datacolumn]
reshaped = column.reshape((len(column)/outputcolumns,outputcolumns))
np.savetxt('path/to/newfile',reshaped)

rawDescription: Splitting Text File - Column to Rows in Python


code:
print(flatten(_dict1, '', {}))

{'this.example.too': 3, 'example': 'fish', 'this.is.another.value': 4, 'this.is.an.example': 2}

rawDescription: How would I flatten a nested dictionary in Python 3?


code:
import sys
import urllib
for tweet in sys.stdin:
    t, u, w = tweet.split('\t')
    path=urlparse(w).path.strip('/')
    result= "{0}\t{1}\t{2}\t{3}".format( t, u, w, path )
    sys.stdout.write( result )

rawDescription: Processing a huge file (9.1GB) and processing it faster -- Python


code:
class DocumentFidsourceForm(forms.ModelForm):
    classeur = forms.ModelChoiceField(
        queryset=Classeur.objects.filter(type_classeur=1).order_by('rang')
    )
    #some piece of code

    class Meta:
        model = Document

rawDescription: django modelForm filter isn't effective?

description: Django modelForm filter isn't effective


code: print(result)

rawDescription: Filtering out sublist from list based on contents of entire sublist?


rawDescription: Use a colourmap to change line colour

description: Use a colourmap to change line colour


code:
from numpy.ctypeslib import ndpointer
lib = ctypes.CDLL(...)
lib.find_vertex.argtypes = [ndpointer(dtype=vertex_dtype, flags="C_CONTIGUOUS"),
                            ctypes.c_int,
                            ctypes.POINTER(Vertex),
                            ctypes.POINTER(Vertex)]
lib.find_vertex.restypes = None

rawDescription: A way to pass milions of items in python to C program many times in rapid succesion


code: {k: v for k, v in sns.axes_style().items() if "color" in k}

rawDescription: Best way to display Seaborn/Matplotlib plots with a dark iPython Notebook profile

description: Display Seaborn/Matplotlib plots with a dark iPython Notebook profile


code:
#myapp/views.py:
from myapp.myclasses import Alphabet

rawDescription: Where to implement python classes in Django?


code:
menubar.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="Exit", command=quit, accelerator="Ctrl+Q")
config(menu=menubar)

rawDescription: Keyboard shortcuts with tkinter in Python 3


code: splitted.sort(key = lambda residue: int(residue.split()[5]))

rawDescription: Sorting string by specific column

description: Sorting string by specific column


code:
inverted = {v:k for k, v in d.iteritems()}
reverted = {v:k for k, v in inverted.iteritems()}

rawDescription: More efficient way to get unique first occurrence from a Python dict


code: volumes = conn.get_all_volumes(filters={'attachment.instance-id': [instance.id]})

rawDescription: AWS BOTO - find volume ID of an ec2 instance using tag


rawDescription: Convert an int to a CSS colour

description: Convert an int to a CSS colour


code:
def translate(lettered_code):
    "".join([translation[letters] for letters in lettered_code ])

rawDescription: Caesar Cipher: How to print from dictionary *all* letters from input?


code:
def split_not_neighbour(seq, mark):
    """Split the sequence on each item where the item is not the mark, or next
    to the mark.

    split_not_neighbour([1, 0, 2, 3, 4, 5, 0], 0) --> (1, 2), (5)

    """
    neighboured = neighbours(seq)
    for _, items in itertools.groupby(neighboured, key=lambda x: mark not in x):
        yield [item for _, item, _ in items if item != mark]

rawDescription: Finding neighbors in a list

description: Finding neighbors in a list


rawDescription: Number of repeats in a regex in python

description: Number of repeats in a regex in python


rawDescription: Python mock: mocking base class for inheritance


rawDescription: Scikit Learn HMM training with set of observation sequences


code: set(x for x, count in common if count == common[0][1])

rawDescription: Python max with same number of instances


code: corrs = df.corr()

rawDescription: Pandas: How to drop self correlation from correlation matrix


code:
df = args.df_dt[0]
dt = args.df_dt[1]

rawDescription: Python argparse mutually exclusive group with 1 vs 2 arguments


code:
with open('test.txt') as f:
    text = f.readlines()

rawDescription: Python - Loadtext for specific number of lines


rawDescription: How would I use django.forms to prepopulate a choice field with rows from a model?


rawDescription: Change values in CSV or text style file

description: Change values in CSV or text style file


code:
class StringInside(object):

    def __init__(self, data=''):
        self._data = []
        self._data.append(data)

    def write(self, data):
        self._data.append(data)

    def read(self):
        return ''.join(self._data)

rawDescription: subclass str, and make new method with same effect as +=

description: Subclass str, and make new method with same effect as +=


code:
asf
bf

rawDescription: Python - Opposite of dictionary search

description: Python - Opposite of dictionary search


code:
k = numpy.arange(k0, kN + 1)
result = numpy.exp(numpy.outer(x, k)).sum(axis=0)

rawDescription: Theano scan for fast computations on an array


rawDescription: Sublime Text 2 shortcut for show/hide tabs


code:
with open('test1.csv', newline='') as f:
    cols = {'count' : [], 'mean' : [], 'median' : [], 'minimum' : [], 'maximum' : [], 'std dev' : []}
    names = []
    for line in f:
        row = line.split(',')
        numbers = [float(i) for i in row[1:-1]]
        num_count = len(numbers)
        mean = sum(numbers) / num_count
        name = row[0]
        names.append(name)
        cols['count'].append(num_count)
        cols['mean'].append(mean)
        cols['minimum'].append(min(numbers))
        cols['maximum'].append(max(numbers))

rawDescription: How to count numbers in a list from a csv file filtering out words and commas

description: Count numbers in a list from a csv file filtering out words and commas


code:
indices = np.where(a[:, 4] == 0)
b[indices[0]]

rawDescription: Using matlab's find like operation in python


code:
hours, milliseconds = divmod(miliseconds, 3600000)
minutes, milliseconds = divmod(miliseconds, 60000)
seconds = float(milliseconds) / 1000
s = "%i:%02i:%06.3f" % (hours, minutes, seconds)

rawDescription: How to convert time format into milliseconds and back in Python?

description: Convert time format into milliseconds and back in Python


code:
button1 = Button(..., command=ButtonOneCallback)
button2 = Button(..., command=ButtonTwoCallback)

def ButtonOneCallback():
    value = user_input.get()
    DoSomething(value)

def ButtonTwoCallback():
    value=choice.get(choice.curselection()[0])
    DoSomething(value)

def DoSomething(value):
    ...

rawDescription: Python Tkinter one callback function for two buttons


code:
for k, v in month_code.items():
    line = line.replace(k, v)

rawDescription: Need to convert 3 letter month code to two letter month code python


code:
r = rows.flat[reindex]
c = cols.flat[reindex]
matrix[r[0], c[0]]
matrix[r[-1], c[-1]]

rawDescription: Sorting cells of big numpy matrices

description: Sorting cells of big numpy matrices


code:
from functools import reduce

chains = (
    (doStuff1,),
    (doStuff1, doStuff2),
    (doStuff1, doStuff2, doStuff3),
)

for textfile in path:
    for chain in chains:
        data = reduce(lambda data, func: func(data), chain, textfile)
        calculateandPrint(data)

rawDescription: Python 3 - cumulative functions alternatives


code:
n = 10
sum(p(a(i))*a(i) for i in range(1, n+1))

rawDescription: Expected value with symbolic probabilities in SymPy


rawDescription: retrive minimum maximum values of a ctype

description: Retrive minimum maximum values of a ctype


rawDescription: copy 2D array into 3rd dimension, N times (Python)

description: Copy 2D array into 3rd dimension, N times (Python)


code:
def make_defaultdict(depth, data_structure):
    d = defaultdict(data_structure)
    for _ in range(depth):
        d = defaultdict(lambda d=d: d)
    return d

rawDescription: list of tuples to dictionary of dictionaries

description: List of tuples to dictionary of dictionaries


code: artist_list = ax.get_children()

rawDescription: how to remove generic content of matplotlib regardless of type plotted

description: Remove generic content of matplotlib regardless of type plotted


code:
LOWER_BOUND = 0
UPPER_BOUND = 100  # both in caps because this is a constant

def get_score(house_name, event_name):
    # an extra argument so you can tell which event is being scored.
    # removed the min, max cause we are using the constants!
    score = -1
    while score < LOWER_BOUND or score > UPPER_BOUND:
        try:
            score = int(input("Please enter score for %s in the event %s:" % (house_name, event_name)))
            if score < LOWER_BOUND :
                print ("Score is too low, minimum score is %i.\nPlease try again." % min_score)
            if score > UPPER_BOUND:
                print ("Score is too high, maximum score is %i\nPlease try again." % max_score)
        except ValueError:
            print("Invalid Input please enter an integer. Thanks")
    return score  # note the use of return to avoid using global

def get_number_of_events():
    print("Please enter the number of events there is.")
    while True:
        try:
            n_events = int(input(">>"))
        except ValueError:
            print("Enter only a number, Thanks.")
        if n_events > 100:
            print("WOW, that's a lot of events, please be reasonable. Thanks.")
        elif n_events < 1:
            # this is a different condition that would get a wrong error in your program,
            # note the use of 'elif', in Python this an 'else if'.
            print ("That's too few events! Try Again.")
        else:
            # no need to use Flag, just use break when you want to leave a loop.
            break
    return n_events

def get_events_names(n_events):
    print ("Please enter the events names")
    events = []
    for n in range(1, n_events + 1):
        # starting at 1 to give a better display
        event_name = input("Event %i name: " % n)
        events.append(event_name)
    return events

def get_data(events):
    data = []
    while True:
        house_name = input("Please enter house names <<<Enter XXX when finished>>> :")
        if house_name.upper() == "XXX":
        # using .upper() to avoid checking twice for either 'xxx' or 'XXX'.
        # I would ask the user for how many houses are there instead, but your choice ;)
            break

        print ("Please enter the events points in ascending order.")
        # not actually need to be in ascending order, you can sort them later if you want.
        scores = []
        for event_name in events:
            # don't use range(len(something)), loops in Python are easy!
            score = get_score(house_name, event_name)
            scores.append([event_name, score])
        data.append([house_name, scores])
        # use .append() instead of data = data + [...]
    return data

def main():
    print("Welcome!\n")

    n_events = get_number_of_events()
    events_names = get_events_names(n_events)
    print()
    data = get_data(events_names)
    print()
    for house_name, event_data in data:
        print ("House " + house_name)

        for event_name, score in event_data:
            # note the use of tuple unpacking
            print ("\tEvent: %s Score: %i" % (event_name, score))

if __name__ == '__main__':
    main()

rawDescription: points code program

description: Points code program


code:
n = 2
np.kron(np.eye(n), a)
n = 3
np.kron(np.eye(n), a)

rawDescription: Create block diagonal numpy array from a given numpy array


code:
keys = ['key1', 'key2', 'key3']
words = u'word1 word2 word3'
vals = words.split()

d = dict(zip(keys, vals))

rawDescription: Parse a unicode string in python to a dictionary


code:
import collections
import uuid

class Person():
    def __init__(self, name="", age=69):
        self.name = name
        self.uid = str( uuid.uuid4( ) )
        self.age = age

    def __eq__(self, other):
        return isinstance(other, Person) and self.uid == other.uid
    def __ne__(self, other): return self != other # you need this

    def __hash__(self):
        return hash(self.uid)

# UI --------------------------------------------------------------------------
persons_count = collections.defaultdict(int) # belongs to your UI class
your_list_of_persons = []  # should be a set

def add_to_ui(person):
    persons_count[person] += 1
    # add it to the UI

def remove_from_ui(person):
    persons_count[person] -= 1
    if not persons_count[person]: your_list_of_persons.remove(person)
    # remove from UI

rawDescription: Removing list item if not in another list - python


code:
import time
from myfun import crawl_data
while(True):
 time.sleep(300)
 crawl_data()

rawDescription: How to define a view function in views.py file in django

description: Define a view function in views.py file in django


code:
www.mysite.com/weeklytop/2
weeklytop

www.mysite.com/week/day/2
week/day

www.mysite.com/week/4
week

rawDescription: String comparing in python

description: String comparing in python


code:
from django.db.models import Count

def view(request):
    # Calculate the counts at the same time we fetch the NewLink(s)
    links = NewLink.objects.annotate(post_count=Count('post_set'))
    return render(request, 'template.html', {'links': links})

rawDescription: How to count how many posts each link has on a reddit-like app?

description: Count how many posts each link has on a reddit-like app


rawDescription: Find 1 letter and 2 numbers using RegEx

description: Find 1 letter and 2 numbers using RegEx


code:
industries_list = ["Computers, Internet","Photography, Tourism","Motoring, Manufacturing"]
[s.split(',') for s in industries_list]

rawDescription: How to split a python list by comma

description: Split a python list by comma


code:
class Ship:
  # types is a class variable, and will be the same for all instances,
  # and can be referred to by using the class. ie `Ship.types`
  types = {
    "schooner": {'weight':50, 'speed':30, 'poopdeck':18},
    "galleon": {'weight':30, 'speed':14, 'poopdeck':14},
    "default": {'weight':11, 'speed':11, 'poopdeck':11}
  }
  def __init__(self, name):
    self.name = name
    # we update the instance dictionary with values from the class description of ships
    # this means that instance.speed will now be set, for example.
    if name in Ship.types:
      self.__dict__.update(Ship.types[name])
    else:
      self.__dict__.update(Ship.types["default"])

  def upgrade(self, attribute, value):
    if hasattr(self, attribute):
      setattr(self, attribute, getattr(self, attribute) + value )
    else:
      raise AttributeError("Can't upgrade non-existent attribute '{}'.".format(attribute))

ship = Ship("schooner")
print(ship.speed) #=> 30
ship.upgrade("speed", 10)
print(ship.speed) #=> 40

rawDescription: Modifying a variable class attribute

description: Modifying a variable class attribute


code:
import datetime
inputstring = u'May 12, 2014 8:00:40 PM'
datetime.datetime.strptime(inputstring, '%B %d, %Y %I:%M:%S %p').date()
datetime.datetime.strptime(inputstring.rsplit(None, 2)[0], '%B %d, %Y').date()

rawDescription: convert a full string type time into datetime type - Python

description: Convert a full string type time into datetime type - Python


code:
import pprint
import sys

orig_displayhook = sys.displayhook

def myhook(value):
    if value != None:
        __builtins__._ = value
        pprint.pprint(value)

__builtins__.pprint_on = lambda: setattr(sys, 'displayhook', myhook)
__builtins__.pprint_off = lambda: setattr(sys, 'displayhook', orig_displayhook)

rawDescription: Pretty print by default in Python REPL

description: Pretty print by default in Python REPL


code:
from datetime import datetime
mask = df['arrival_time'] > datetime(2016, 2, 15, 7, 35)  # now you need a date

rawDescription: Get nearest time value and convert format


rawDescription: pyqt and table widget clear contents

description: Pyqt and table widget clear contents


code:
func = timeout(timeout=16)(MyModule.MyFunc)
try:
    func()
except:
    pass #handle errors here

rawDescription: Timeout a python function in windows

description: Timeout a python function in windows


rawDescription: ctypes: Cast string to function?

description: Ctypes: Cast string to function


code:
def remove_img_tags(data):
    p = re.compile(r'<img.*?/>')
    return p.sub('', data)

rawDescription: Removing html image tags and everything in between from a string


code:
# cython candidate, like DavidW's StartEnd
class Gene(object):
    def __init__(self, values):
        self.chr = values[0]
        self.start = int(values[1])
        self.end = int(values[2])
        self.gene = values[3]
    def find(self, i):
        return self.start<=i<self.end
    def __repr__(self):
        return "%s(%s, %d:%d)"%(self.chr,self.gene,self.start,self.end)

# cython candidate
class Chrom(list):
    def add(self, aGene):
        self.append(aGene)
    def find(self, loc):
        # find - analogous to string find?
        i = int(loc)
        for gene in self:
             if gene.find(i):
                 return gene  # gene.gene
        return None
    def __repr__(self):
        astr = []
        for gene in self:
            astr += [repr(gene)]
        return '; '.join(astr)

rawDescription: cython: reducing the size of a class, reduce memory use, improve speed

description: Cython: reducing the size of a class, reduce memory use, improve speed


code:
from collections import defaultdict
d = defaultdict(list)

for sub in l:
    spl = sub.rsplit("-", 3)
    k = spl[-3],spl[-2]
    d[k].append(sub)

rawDescription: Sorting and Matching a Python list

description: Sorting and Matching a Python list


rawDescription: creating a matrix with randomly generated numbers

description: Creating a matrix with randomly generated numbers


code: interleave(s, "[[Media:]]", li)

rawDescription: How to change a string in a file to strings froma a list

description: Change a string in a file to strings froma a list


code:
class example(object):

    def __init__(self):
        self.veryImportantDict = {'A': 0}

    def set_veryImportantNumber(self,key,val):
        self.veryImportantDict[key] = val

rawDescription: unittest testcase setup new object

description: Unittest testcase setup new object


code:
def inherit_doc_class(cls):
    for name, obj in cls.__dict__.iteritems():
        if isinstance(obj, property_writable_doc) and obj.__doc__ is None:
            for t in cls.__mro__:
                if name in t.__dict__ and t.__dict__[name].__doc__ is not None:
                    obj.__doc__ = t.__dict__[name].__doc__
                    break
    return cls

class A(object):
    @property
    def a(self):
        "The a:ness of it"
        return True

@inherit_doc_class
class B(A):
    @property_writable_doc
    def a(self):
        return False

@inherit_doc_class
class C(A):
    @property_writable_doc
    def a(self):
        "The C:ness of it"
        return False

rawDescription: How to automatically document my class properties with decorators

description: Automatically document my class properties with decorators


rawDescription: Consecutive, Overlapping Subsets of Array (NumPy, Python)


code:
# i am calling the specific column 'foo'
df = pd.DataFrame( [ '190000', '170000', '120k', '110K', '100000s', '68ks' ],
                   index=[21, 27, 29, 31, 33, 38], columns=['foo'] )

def clean( x ):
    from re import sub
    # \g<1> is whatever matches the the first (...)
    x = sub( r'(\d+)[kK]', r'\g<1>000', x )
    return sub( r'[^\d]', '' , x ) # remove any non-digit character

df.foo.map( clean ).astype( int )

rawDescription: Pandas clean column and apply optional multiplier


code:
form.save()
entry_user_profile.save()

rawDescription: how to fill out the form initial data?

description: Fill out the form initial data


code:
from collections import defaultdict
import csv

graph = defaultdict(dict)

with open('inputfile', 'rb') as infh:
    reader = csv.reader(infh, delimiter='\t')
    next(reader, None)  # skip header

    for source, target, edge in reader:
        graph[source][target] = edge

rawDescription: Python - directed edge list to dictionary of dictionaries


rawDescription: Can .findall() match multiple values in python etree?


code:
Python
from ctypes import *

FUNC = CFUNCTYPE(c_int,c_int,c_int)

@FUNC
def add(a, b):
    return a + b

mutdll = cdll.LoadLibrary('x')

mutdll.set.argtypes = [FUNC]
mutdll.set.restype = None

mutdll.set(add) # set the global variable

pfuncExtB = FUNC.in_dll(mutdll,'pfuncExtB')
print(pfuncExtB(1,2)) # -> 3

funcB = mutdll.funcB
funcB.argtypes = [c_int, c_int]
funcB.restype = c_int

print(funcB(3 , 4)) # -> 7

rawDescription: Assigning Python function to ctypes pointer variable


code:
# Modulus must be prime
fmt_error = not isPrime(key.p)
# Verify Lagrange's theorem for sub-group
fmt_error |= ((key.p-1) % key.q)!=0
fmt_error |= key.g<=1 or key.g>=key.p
fmt_error |= pow(key.g, key.q, key.p)!=1
# Public key
fmt_error |= key.y<=0 or key.y>=key.p
if hasattr(key, 'x'):
    fmt_error |= key.x<=0 or key.x>=key.q
    fmt_error |= pow(key.g, key.x, key.p)!=key.y

rawDescription: Validating a DSA key pair with pycrypto ( getting pqg values )


code:
while posSeg < len(arrayJunto):
    for key in map_dict:
        if arrayJunto[posSeg:posSeg + len(key)] == key:
            posSeg += len(key)
            array_final.append(map_dict[key])
            break
    else:
        break

rawDescription: Compare string of bits with elements of a table python


code:
example = '''\
0 -> 1
3 -> 2
2 -> 6,5
8 -> 7
5 -> 9,4,1
'''.splitlines()
def genoutput(iterable):
    for line in iterable:
        first, second = (l.strip() for l in line.split('->'))
        for value in second.split(','):
            yield first + value.strip()

list(genoutput(example))

rawDescription: Extraction of variables from text, with completely different formatting, using Python


code:
import os
os.system('cls' if os.name == 'nt' else "printf '\033c'")

rawDescription: Is there a way to clear your printed text in python?


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

fig, ax = plt.subplots()
xlist = [[(0.21, 0.50), (0.42, 0.80)], [(0.13, 0.62), (0.46, 0.77), (0.81, 0.90)],
         [(0.32, 0.12), (0.64, 0.80)], [(0.54, 0.20), (0.87, 0.80)]]

normal_selected_color = np.array([[0, 0, 1, 1.0], [1, 0, 0, 1.0]])
selected = np.zeros(len(xlist), dtype=int)
colors = normal_selected_color[selected]
lines = LineCollection(xlist, pickradius=10, colors=colors)
lines.set_picker(True)

ax.add_collection(lines)

def on_pick(evt):
    if evt.artist is lines:
        ind = evt.ind[0]
        selected[ind] = 1 - selected[ind]
        lines.set_color(normal_selected_color[selected])
        fig.canvas.draw_idle()

fig.canvas.mpl_connect("pick_event", on_pick)
plt.show()

rawDescription: how to highlight line collection in matplotlib

description: Highlight line collection in matplotlib


code: res = [(x, my_dictionary[x]) for x in my_list if x in my_dictionary]

rawDescription: Is it possible to take an ordered "slice" of a dictionary in Python based on a list of keys?


rawDescription: retrieve values from interpolation object

description: Retrieve values from interpolation object


code:
import zipfile, io
zipfile.ZipFile(io.BytesIO(res.content))

rawDescription: Python Requests Not Returning Same Header as Browser Request/cURL


code:
import quopri

decoded = quopri.decodestring(emailMessage.get_payload())

rawDescription: Regex to Filter out ">" and "=20" from email.message_from_string


rawDescription: How to create a Mat image in OpenCV if i have the values of h, s and v?

description: Create a Mat image in OpenCV if i have the values of h, s and v


rawDescription: How does one simplify a complicated ratio?

description: Simplify a complicated ratio


code:
p = '''{"sweep_enabled":true,"product":"XYZ","page":"XYZ Profile","list":" {\"id\":205782,\"name\":\"Robert Shriwas\",\"gender\":\"F\",\"practicing_since\":null,\"years\":21,\"specializations\":[\"Mentor\"]}","form":{"q":"","city":"Delhi","locality":null},"cerebro":true}'''
q = re.sub(r'(:)\s*"\s*(\{[^\}]+\})\s*"',r'\1\2', p[1:-1])
q
r = p[0] + q + p[-1]
r
json.loads(r)
s = json.loads(r)
s['list']

rawDescription: Extarct particulr part of json string using python regex


code:
with open ("words.txt", "r") as myfile:
    data = myfile.read().replace('\n', '')
    print(data)
    freq = data.count(Symbol)
    print(freq)

rawDescription: Counting specific letters or symbols in a text file in Python


code: [list(g) for _, g in groupby(gen, key=bool)]

rawDescription: Grouping 0s and 1s in python

description: Grouping 0s and 1s in python


code:
df = df1.join(df2, how='outer')
df['state'].fillna(method='ffill',inplace=True)
df.dropna()

rawDescription: associating entries from one pandas data frame to a second one based on time

description: Associating entries from one pandas data frame to a second one based on time


rawDescription: max row sequence from sorted list for each index

description: Max row sequence from sorted list for each index


code:
for i in range(N):
    x_root = scipy.optimize.bisect(lambda x: F(x, a[i], b[i]), x0[i], x1[i], xtol=1e-6)

rawDescription: Finding the roots of a large number of functions with one variable


code:
class DBConnection:
    def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME):
        self.host = DB_HOST
        self.port = DB_PORT
        self.name = DB_NAME
        self.user = DB_USER
        self.password = DB_PASSWORD
        self.conn = None

    def get_conn(self):
        self.conn = MySQLdb.connect(host = self.host,
                                    port = self.port,
                                    db = self.name,
                                    user = self.user,
                                    passwd = self.password)

rawDescription: Writing an object-oriented MySQLdb connection


code: dict3 = {k:(v, dict1[k]) for k, v in dict2.items()}

rawDescription: How to mixing two dictionaries in Python?

description: Mixing two dictionaries in Python


code: dict((c, c if c in other_list else 0) for c in correct_list)

rawDescription: Python lists comparing and merging

description: Python lists comparing and merging


rawDescription: pylab.show() forgets previous plots

description: Pylab.show() forgets previous plots


code: self.actions[(cond_1, cond_2)]()

rawDescription: How to write If statements for all 2^N boolean conditions (python)

description: Write If statements for all 2^N boolean conditions (python)


code: ["Batts did not take questions or give details of the report's findings...", "He did say that the city's police department would continue to work on the case under the direction of the prosecutor's office.", 'Gray was injured around the time he was arrested by Baltimore police and put in a police van on 12 April.']

rawDescription: NLTK PunktSentenceTokenizer ellipsis splitting


code: 'workflow' in children

rawDescription: How to compare strings in python in List?

description: Compare strings in python in List


code:
from datetime import datetime, timedelta
import time

def countdown(d=0, h=0, m=0, s=0):
    counter = timedelta(days=d, hours=h, minutes=m, seconds=s)
    while counter:
        time.sleep(1)
        counter -= timedelta(seconds=1)
        print("Time remaining: {}".format(counter))

rawDescription: python 3.4, timer count down not working

description: Python 3.4, timer count down not working


code:
# lambda
sqr = lambda n: n**2
assert sqr(2) == 4
assert sqr(3) == 9

# named function
def f(n):
    return n**2

sqr = f
assert sqr(2) == 4
assert sqr(3) == 9

rawDescription: How to get function object inside a function (Python)

description: Get function object inside a function (Python)


code:
record = struct.Struct('>HB10cL')

with open('myfile.bin', 'rb') as f:
    while True:
        buf = f.read(record.size)
        if not buf:
            break
        yield record.unpack(buf)

rawDescription: Can someone explain Python struct unpacking?


code:
Record = collections.namedtuple('Record', d.keys())
[Record(*t) for t in zip(*(d.values()))]

rawDescription: 'Zip' dictionary of lists in Python

description: 'Zip' dictionary of lists in Python


code:
mapper.connect("/user", controller=user_controller, action="get_user", conditions=dict(method=["GET"]))
mapper.connect("/user", controller=user_controller, action="add_user", conditions=dict(method=["POST"]))

rawDescription: Python Routes, giving request method

description: Python Routes, giving request method


rawDescription: How to avoid hanging Xvfb processes [while using PyVirtualDisplay]?

description: Avoid hanging Xvfb processes [while using PyVirtualDisplay]


code: [i for i in os.listdir('.') if i[-4:] in ('.png', '.jpg', 'jpeg')]

rawDescription: Python logical or operator acting strange


code:
from itertools import *
reduce(set.union, (starmap(set.intersection, combinations(map(set, ll), 2))))

rawDescription: Python: Find identical items in multiple lists


code:
class TstWidget(QtGui.QWidget):
    def __init__(self):
        super(type(self), self).__init__()

        self.bar = QRoundProgressBar()
        self.bar.setFixedSize(300, 300)

        self.bar.setDataPenWidth(3)
        self.bar.setOutlinePenWidth(3)
        self.bar.setDonutThicknessRatio(0.85)
        self.bar.setDecimals(1)
        self.bar.setFormat('%v | %p %')
        # self.bar.resetFormat()
        self.bar.setNullPosition(90)
        self.bar.setBarStyle(QRoundProgressBar.StyleDonut)
        self.bar.setDataColors([(0., QtGui.QColor.fromRgb(255,0,0)), (0.5, QtGui.QColor.fromRgb(255,255,0)), (1., QtGui.QColor.fromRgb(0,255,0))])

        self.bar.setRange(0, 300)
        self.bar.setValue(260)

        lay = QtGui.QVBoxLayout()
        lay.addWidget(self.bar)
        self.setLayout(lay)

rawDescription: Any PyQt circular progress bar?

description: Any PyQt circular progress bar


code:
def print_string(arg1=''):
    # mimicing your "pre-defined" function
    # Note I've put a default value in arg1 so that you
    # can call it without an argument to illustrate the priciple
    print(arg1)

def do_n(f , n):
    if n <=0:
        return
    f('test')         # This is the line that was close, but not quite right
    do_n(f, n-1)

do_n(print_string,10)

rawDescription: Defining function with function object passed in as argument


rawDescription: Get final elements of nested dictionary in Python


code:
import re
abb_pattern = re.compile(r'^ABB+$')
def has_abb(string):
    return abb_pattern.match(string) is not None

has_abb('ABBBBBBB')
has_abb('ABBBBA')
has_abb('ABB')
has_abb('BABBB')

rawDescription: Checking a String's format

description: Checking a String's format


code:
def __init__(self):
    super().__init__()
    ...
    findme_definer = [cls for cls in self.__class__.__mro__ if "findMe" in cls.__dict__][0]

rawDescription: How can one locate where an inherited variable comes from in Python?


code: df['col 1'].loc[df['col 1'].first_valid_index() : df['col 1'].last_valid_index()] = df['col 1'].loc[df['col 1'].first_valid_index(): df['col 1'].last_valid_index()].astype(float).interpolate()

rawDescription: Pandas: interpolation where first and last data point in column is NaN


code:
df_in = pd.read_csv('https://dl.dropboxusercontent.com/u/40513206/input.csv', sep = ';',      header = 0, index_col = None,
         na_values = [''], mangle_dupe_cols = False)

df1 = df_in.ix[:,:2].dropna().set_index('Countries1')
df2 = df_in.ix[:,2:4].dropna().set_index('Countries2')
df3 = df_in.ix[:,4:].dropna().set_index('Countries3')

rawDescription: parsing complex csv file

description: Parsing complex csv file


code:
df = df.bfill(axis=1)
df

rawDescription: Convert a list of timestamped state columns into a time-indexed list for each state during that time, as told with Chutes and Ladders


rawDescription: Parsing data from JSON file using Python


code:
def fconstruct():
    flist = []
    for x in range(5):
        def get_kol(y):
            def kol():
                return y
            return kol
        flist.append(get_kol(x))

    return flist

rawDescription: Function name is not reusable (python)

description: Function name is not reusable (python)


code:
def foo():
    return

def bar():
    pass

import dis
dis.dis(foo)
dis.dis(bar)
foo.__code__.co_code

rawDescription: Detecting blank/empty function in cpython calls?


code:
def split_at(i, l):
    it = iter(l)
    out = [next(it)]
    for ele in it:
        if ele != i:
            out.append(ele)
        else:
            yield out
            out = [ele]
    yield out

rawDescription: split list by certain repeated index value

description: Split list by certain repeated index value


code:
class AllVMeta(type):
    def __new__(typ, name, bases, attrs):
        cls = super(AllVMeta, typ).__new__(typ, name, bases, attrs)
        cls.ALL_V_ELEMENTS = cls.V_1 | cls.V_2
        return cls

rawDescription: Class variable V3 dependent on V1 and V2. How to define V3 in children classes


code:
from lxml import etree

tree = etree.fromstring(html) # or etree.parse from source
tree.xpath('.//div[@class="category5"]/text()')
[' test\n                 ']

rawDescription: BeautifulSoup: How to get nested divs

description: BeautifulSoup: How to get nested divs


code:
# several files with ext .pyx, that i will call by their name
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules=[
    Extension("primes",       ["primes.pyx"]),
    Extension("spam",         ["spam.pyx"]),
    ...
]

setup(
  name = 'MyProject',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules,
)

rawDescription: Cython setup.py for several .pyx

description: Cython setup.py for several .pyx


rawDescription: reshaping ndarrays versus regular arrays in numpy?

description: Reshaping ndarrays versus regular arrays in numpy


code:
stacked = pd.concat([df['Gene'], splitted],axis=1).set_index('Gene').stack()
stacked

rawDescription: How to split string from column to create long format dataframe

description: Split string from column to create long format dataframe


rawDescription: How can I obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy?

description: Obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy


code:
from models import Team

class TeamAdminForm(forms.ModelForm):
        url = forms.URLField(required=False, widget=CustomAdminURLFieldWidget)
        class Meta:
            model = Team

rawDescription: How can I extend a django admin widget so it's still optional?

description: Extend a django admin widget so it's still optional


code:
def lookup_grade(score):
    match = (lookup['Lower_Boundary'] <= score) & (lookup['Upper_Boundary'] > score)
    grade = lookup['Grade'][match]
    return grade.values[0]

df['Score'].apply(lookup_grade)

rawDescription: Pandas table lookup

description: Pandas table lookup


rawDescription: Pandas: How to edit values in a column

description: Pandas: How to edit values in a column


code:
def mix_combine(a, b):
    return a[0:int((len(a)+1)/2)] + b[0:int((len(b)+1)/2)] + a[int((len(a)+1)/2):] +b[int((len(b)+1)/2):]
a = "abcd"
b = "wxyz"
mix_combine(a,b)
a = "abcde"
b = "vwxyz"
mix_combine(a,b)

rawDescription: Google python class [string2.py] exercise F


code:
for n in range(0, 1000):
    result = your_function(n, other_parameters)

rawDescription: Finding zeros of equation using python

description: Finding zeros of equation using python


code:
def partialhelper(object=None):
    if isinstance(object, functools.partial):
        return pydoc.help(object.func)
    else:
        # Preserve the ability to go into interactive help if user calls
        # help() with no arguments.
        if object is None:
            return pydoc.help()
        else:
            return pydoc.help(object)

rawDescription: Allow help() to work on partial function object


code:
with open('FILE.INI', 'w') as inifile:

    conf.write(inifile)

rawDescription: Config file for Python with repeated sections/objects


code: created_at = Column(TIMESTAMP, default=datetime.utcnow, nullable=False, server_default=text('0'))

rawDescription: SqlAlchemy TIMESTAMP 'on update' extra

description: SqlAlchemy TIMESTAMP 'on update' extra


rawDescription: Python change type of whole list?

description: Python change type of whole list


code:
from flask import Flask
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin.menu import MenuLink
from flask.ext.sqlalchemy import SQLAlchemy
from wtforms.widgets import TextArea, TextInput
from wtforms.fields import TextAreaField

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_ECHO'] = True
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'

db = SQLAlchemy(app)

class Test(db.Model):
    __tablename__ = 'tests'
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.UnicodeText)

class CKEditorWidget(TextArea):
    def __call__(self, field, **kwargs):
        if kwargs.get('class'):
            kwargs['class'] += " ckeditor"
        else:
            kwargs.setdefault('class', 'ckeditor')
        return super(CKEditorWidget, self).__call__(field, **kwargs)

class CKEditorField(TextAreaField):
    widget = CKEditorWidget()

class TestAdminView(ModelView):
    form_overrides = dict(text=CKEditorField)
    can_view_details = True
    create_template = 'edit.html'
    edit_template = 'edit.html'

@app.route('/')
def index():
    return 'Click me to get to Admin!'

# Create admin
admin = Admin(app, name='Admin')
admin.add_view(TestAdminView(model=Test, session=db.session, category='Tables', name='Test'))
admin.add_link(MenuLink(name='Public Website', category='', url='/'))

def build_db():

    tests = [
        {
            'text': "
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
"
        },
        {
            'text': "
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque
"
        },
        {
            'text': "
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium
"
        }
    ]

    db.drop_all()
    db.create_all()

    for test in tests:
        test_db = Test(**test)
        db.session.add(test_db)
    db.session.commit()

@app.before_first_request
def create_user():
    build_db()

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: Getting CKEditor to work with Flask Admin


rawDescription: pythonic way to split string into two lists

description: Pythonic way to split string into two lists


rawDescription: Pandas Group Columns into Level

description: Pandas Group Columns into Level


rawDescription: How to show a png image in Gtk3 with Python?

description: Show a png image in Gtk3 with Python


code: is_all_uppercase = word.isupper() and word.isalpha()

rawDescription: Check if any character of a string is uppercase Python


rawDescription: efficiently caclulating double integral

description: Efficiently caclulating double integral


code:
[{'designation': 'Salesman', 'dcount': 2},
 {'designation': 'Manager', 'dcount': 2}]

rawDescription: How to query as GROUP BY in django?

description: Query as GROUP BY in django


code:
line = re.findall(r'Tags:.+\n', text)
# line = ['Tags: #foo #bar\n']

rawDescription: Regex to Extract #hashtags from MMD metadata in Python


code:
import tempfile
import os

def produce(text):
    with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
        f.write(text)
        return f.name

def consume(filename):
    try:
        with open(filename) as f:
            return f.read()
    finally:
        os.remove(filename)

if __name__ == '__main__':

    filename = produce('Hello, world')
    print('Filename is: {0}'.format(filename))
    text = consume(filename)
    print('Text is: {0}'.format(text))
    assert not os.path.exists(filename)

rawDescription: how to create file names from a number plus a suffix in python

description: Create file names from a number plus a suffix in python


code:
root = ET.fromstring(content)
for network in root.iterfind('network_object'):
    name = network.find('Name')
    class_name = network.find('Class_Name')
    print (name.text,class_name.text)
    for subname in network.iterfind('members/reference/Name'):
        print(subname.text)

rawDescription: Python Looping with etree

description: Python Looping with etree


rawDescription: stretch, scale, or double up an array with numpy?

description: Stretch, scale, or double up an array with numpy


code:
class Object2(QObject):

    def __init__(self):
        super().__init__()

    @pyqtSlot(object)
    def slot(self, data):
        print("Received data %s in thread %s" % (data, QThread.currentThread()))
        while len(data) < 10:
            time.sleep(1)
            print("Current data is %s" % data)

class Object1(QObject):

    def __init__(self):
        super().__init__()

    sig = pyqtSignal(object)

    @pyqtSlot()
    def emit_in_thread(self):
        self.data = [1]
        print("Emitting data %s in thread %s" % (self.data, QThread.currentThread()))
        self.sig.emit(self.data)
        while len(self.data) < 10:
            time.sleep(1)
            self.data += [1]
            print("Modified data to %s" % self.data)

# App
q_app = QApplication(sys.argv)

# Setup
thread = QThread()
obj1 = Object1()
obj1.moveToThread(thread)
thread.start()
obj2 = Object2()
obj1.sig.connect(obj2.slot, type=Qt.QueuedConnection)

# Emit soon
QTimer.singleShot(200, obj1.emit_in_thread)

# Run event loop
sys.exit(q_app.exec_())

rawDescription: How often are objects copied when passing across PyQt signal/slot connections?


code:
import numpy as np
from scipy import signal

# Get the scaling factors and negate them to get kernel
kernel = -np.array([[0,1-2*t,0],[-1,1,0,],[t,0,0]])

# Initialize output array and run 2D convolution and set values into it
out = np.zeros((height,width))
out[1:-1,1:-1] = signal.convolve2d(gr, kernel, mode='same')[1:-1,:-2]

rawDescription: Converting a nested loop calculation to Numpy for speedup


code:
@cache.memoize(timeout=50)
def big_foo(a, b):
    return a + b + random.randrange(0, 1000)

rawDescription: Using render_templete and static file, which one is faster in Flask


code:
if self.GetText() == "level1":
    reach(node2, "bbb/ccc")

rawDescription: Python Tkinter: Tree selection

description: Python Tkinter: Tree selection


code:
import sys
sys.stdout.write(str(i))

rawDescription: Print a row of numbers and then have it make a new line and continue counting


code:
class TestHelpers (object):
    def test_long_to_bytes_big_endian_small_even (self):
        s = long_to_bytes(0x42)
        assert s == '\x42'

        s = long_to_bytes(0xFF)
        assert s == '\xff'

    def test_long_to_bytes_big_endian_small_odd (self):
        s = long_to_bytes(0x1FF)
        assert s == '\x01\xff'

        s = long_to_bytes(0x201FF)
        assert s == '\x02\x01\xff'

    def test_long_to_bytes_big_endian_large_even (self):
        s = long_to_bytes(0xab23456c8901234567)
        assert s == '\xab\x23\x45\x6c\x89\x01\x23\x45\x67'

    def test_long_to_bytes_big_endian_large_odd (self):
        s = long_to_bytes(0x12345678901234567)
        assert s == '\x01\x23\x45\x67\x89\x01\x23\x45\x67'

    def test_long_to_bytes_little_endian_small_even (self):
        s = long_to_bytes(0x42, 'little')
        assert s == '\x42'

        s = long_to_bytes(0xFF, 'little')
        assert s == '\xff'

    def test_long_to_bytes_little_endian_small_odd (self):
        s = long_to_bytes(0x1FF, 'little')
        assert s == '\xff\x01'

        s = long_to_bytes(0x201FF, 'little')
        assert s == '\xff\x01\x02'

    def test_long_to_bytes_little_endian_large_even (self):
        s = long_to_bytes(0xab23456c8901234567, 'little')
        assert s == '\x67\x45\x23\x01\x89\x6c\x45\x23\xab'

    def test_long_to_bytes_little_endian_large_odd (self):
        s = long_to_bytes(0x12345678901234567, 'little')
        assert s == '\x67\x45\x23\x01\x89\x67\x45\x23\x01'

rawDescription: Convert python long/int to fixed size byte array


rawDescription: How to extract a word from a text given a position index?

description: Extract a word from a text given a position index


code: ['text' + str(i) + '.txt' for i in range(19, 22)]

rawDescription: Python regex equivalent of bash's {1..4}


code:
aList = [
    Entry(headline="Django 1.0 Released"),
    Entry(headline="Django 1.1 Announced"),
    Entry(headline="Breaking: Django is awesome")
]
Entry.objects.bulk_create(aList)

rawDescription: Django 1.4 - bulk_create with a list

description: Django 1.4 - bulk_create with a list


rawDescription: Getting a list of all subdirectories in the current directory


code:
from django.shortcuts import get_object_or_404, render
def eventcateg_detail(request,slug):
    return render(request, "categ.html", {
        'obj' : get_object_or_404(EventCateg, Message_slug =slug) # You should change Message_slug to just slug
    })

rawDescription: How to pass values to defined template from views.py in Django-python

description: Pass values to defined template from views.py in Django-python


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

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


code:
GetModuleHandleW = kernel32.GetModuleHandleW
GetModuleHandleW.argtypes = [win.LPCWSTR]
GetModuleHandleW.restype = win.HMODULE

h_kernel32 = GetModuleHandleW('kernel32')

rawDescription: How to get the address of LoadLibraryA in Windows XP with Python 3?

description: Get the address of LoadLibraryA in Windows XP with Python 3


code:
xp = "//PropertySetProperty[Key/text()=$key]/Value/text()"
wanted = doc.xpath(xp, key="ConnectionFile")[0]

rawDescription: parsing single text items from xml with Python

description: Parsing single text items from xml with Python


code:
def f0(a, b) :
    a, b = 2 * a, 3 * b
    return ne.evaluate('2*a + 3*b + c')
f0(a, b)
4 * a + 9 * b + c

rawDescription: Numexpr: How to use "local_dict" and "global_dict"?


code:
x     = pm.Uniform('x', lower=xmin, upper=xmax)
alpha = pm.Normal('alpha', mu=0, tau=tau)
beta  = pm.Normal('beta', mu=0, tau=tau)
sigma = pm.Uniform('sigma', lower=0, upper=20)

# The deterministic:
y_gen = pm.Lambda('y_gen', lambda a=alpha, x=x, b=beta: a + b * x)

rawDescription: Getting the statistics of deterministic variables in PyMC


code:
def get_score(grade, grade_to_score = {'A': 10, 'B': 8, 'C': 6, 'D': 4, 'F': 0}):
    return grade_to_score.get(grade, -1)

rawDescription: local variable optimization in python method

description: Local variable optimization in python method


code:
# file2.py
import file1
file1.variable = 37

# file3.py
import file1
file1.variable = 42

rawDescription: Connection between objects in two Python files


rawDescription: how to put widgets inside a PyQt QMdiSubWindow

description: Put widgets inside a PyQt QMdiSubWindow


code:
b_set = set(map(tuple,a))  #need to convert the inner lists to tuples so they are hashable
b = map(list,b_set) #Now convert tuples back into lists (maybe unnecessary?)

rawDescription: Python : How to remove duplicate lists in a list of list?


rawDescription: using python nltk to find similarity between two web pages?

description: Using python nltk to find similarity between two web pages


code:
def check_axes(plot_fn):
    def _check_axes_wrapped_plot_fn(axes=None, *args):
        if not axes:
            fig = plt.figure()
            axes = fig.add_subplot(111)
            return plot_fn(axes, *args)  # pass all args after axes
        else:
            return plot_fn(axes, *args)  # pass all args after axes
    return _check_axes_wrapped_plot_fn

rawDescription: use python decorator to automatically replace function argument default value?

description: Use python decorator to automatically replace function argument default value


rawDescription: Merging duplicate lists and deleting a field in each list depending on the value in Python


code:
class TwitterProfile(models.Model):
    user = models.ForeignKey(User)
    oauth_token = models.CharField(
        max_length=200
        )
    oauth_secret = models.CharField(
        max_length=200
        )
    screen_name = models.CharField(
        max_length=50,
        blank=True, null=True
        )

    def __unicode__(self):
        return "{0}".format(self.user)

rawDescription: How can I use Django Social Auth to connect with Twitter?

description: Use Django Social Auth to connect with Twitter


code:
import traceh
traceh.install()

import inspect

try:
    raise NameError
    print(1)
    print(2)
    print(3)
    print(4)
    print(5)
    print(6)

except:
    traceh.jump_to(10, inspect.currentframe())

rawDescription: Python: resuming program at line number in the context before an exception using a custom sys.excepthook


code:
b = new_board()
display_board(b)

rawDescription: Return statements in python

description: Return statements in python


code:
from __future__ import division
eval('3/2')

rawDescription: Python - How to return a double with eval()


code:
class ESPNSpider(Spider):
    name = "ESPN"
    allowed_domains = ["espn.com"]
    start_urls = ["http://espn.go.com/nba/teams"]

    def parse(self, response):
        sel = Selector(response)
        sites = sel.xpath('//ul[@class="medium-logos"]//li')
        for site in sites:
            item = NBAItem()
            item['team_name'] = site.xpath('.//a[@class="bi"]/text()').extract()[0]
            item['team_link'] = site.xpath('.//a[@class="bi"]/@href').extract()[0]
            item['team_stats_link'] = site.xpath(".//a[text()='Stats']/@href").extract()[0]
            yield item

rawDescription: Extract href given text of anchor tag using Xpath


code:
cur = conn.cursor()
cur.callproc('return_curs')

rawDescription: How to use postgres cursor within Python code

description: Use postgres cursor within Python code


code: path = '%i-%i' % (year, id)

rawDescription: Write file to directory based on variable in Python


code:
crud = AtomicCRUD()
crud.delete()
# Calling 'delete' with Lock 3075059968
crud.delete()
# Calling 'delete' with Lock 3075059968
crud.create()
# Calling 'create' with Lock 3075059952
crud.create()
# Calling 'create' with Lock 3075059952

rawDescription: How to create a synchronized function across all instances

description: Create a synchronized function across all instances


code:
import argparse
parser = argparse.ArgumentParser(prog='PROG')
group = parser.add_mutually_exclusive_group()
group.add_argument('--arg1')
group.add_argument('--arg2')
parser.parse_args(['--arg1', 'foo'])
parser.parse_args(['--arg2', 'bar'])
parser.parse_args(['--arg1', 'foo', '--arg2', 'bar'])

rawDescription: How to disable an argument if another is present?

description: Disable an argument if another is present


code:
l1, a1, b1 = img1.split()
l2, a2, b2 = img2.split()
img1.putdata(zip(l1.getdata(), a2.getdata(), b2.getdata()))

rawDescription: Performing Photoshop's "Luminosity" filter programmatically


code:
df=pd.DataFrame(d)
changes = df.groupby('case')['change']
df['jail'] = (changes.diff()[df.ChangeEvent.shift(1)=='Jail']/np.timedelta64(1,'D'))
df['homeless'] = (changes.diff()[df.ChangeEvent.shift(1)=='Homeless']/np.timedelta64(1,'D'))
df['homeless'].fillna(0,inplace=True)
df['jail'].fillna(0,inplace=True)
df.loc[changes.idxmax(), 'last']=1
df.loc[changes.idxmin(), 'first']=1
df

rawDescription: add columns where condition is met, but preserve previous value in pandas python

description: Add columns where condition is met, but preserve previous value in pandas python


code: summed_params = np.array([res_wls.params for res_wls in all_my_res_wls]).sum(axis=0)

rawDescription: How to add regression functions in python, or create a new regression function from given coefficients?

description: Add regression functions in python, or create a new regression function from given coefficients


code:
from os import listdir
mypath = '.'
from os.path import isfile, join
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
onlyfiles

rawDescription: How to create a python code to count number of comment lines and lines containing whitespace in a file?

description: Create a python code to count number of comment lines and lines containing whitespace in a file


code:
import tkinter as tk

class MyButton(tk.Button):

    colors = ['red', 'blue', 'orange']

    def __init__(self, *args, **kwargs):
        tk.Button.__init__(self, *args, **kwargs)

        # current color number
        self.state = 0

        # set color
        self.config(bg=self.colors[self.state])

        # assign own function to click button
        self.config(command=self.change_color)

    def change_color(self):
        # change current color number
        self.state = (self.state + 1) % len(self.colors)

        # set color
        self.config(bg=self.colors[self.state])

root = tk.Tk()

for __ in range(5):
    MyButton(root, text="Hello World").pack()

root.mainloop()

rawDescription: Button parameter “command” executes when declared, but not when pressed


code:
from selenium.webdriver.remote.command import Command
driver.execute(Command.STATUS)
driver.quit()
driver.execute(Command.STATUS)

rawDescription: Python Selenium: How to check whether the WebDriver did quit()?


code:
my_cool_dict = {}
for element in some_parent_element:
    my_cool_dict[element.tag] = element.text

rawDescription: Create tuples in Python from an XML String/File


code:
if '' in (a, b):
    print('Either a or b is empty')

rawDescription: How do I compare two variables against one string in python?

description: Compare two variables against one string in python


rawDescription: what is the most efficient way to turn a list in python

description: What is the most efficient way to turn a list in python


code:
def ant_coordinates(ant_row, ant_col, orientation):
    color = orig_grid[ant_row][ant_col]
    if color == 'white': # goes in here if color is white
        orientation == 'East' # returns True or False, value not used anywhere
        ant_row += 1 # always increments row if color is white
        orientation == 'South' # returns True or False, value not used anywhere
        ant_col -= 1 # always decrements col if color is white
    return ant_row, ant_col, orientation

rawDescription: how to make langton's ant move a step in python

description: Make langton's ant move a step in python


code:
p = []
for i, j in enumerate(zip(*l)):
    if all(j[0]==k for k in j[1:]):
        p.append(i)

rawDescription: Compare equal length lists to find positions that share the same element


code:
my_sum(lst, 1)
my_sum(lst, 2)
my_sum(lst, 3)
my_sum(lst, 4)

rawDescription: Data type for summing next few items

description: Data type for summing next few items


code: VOLUME /path/to/mountpoint

rawDescription: Is there a way to stop a command in a docker container


code: word_substitutes = dict(zip(common100, characters))

rawDescription: How do I optimize the speed of my python compression code?

description: Optimize the speed of my python compression code


code:
exprs = [
    count(when(col("is_fav") == x, True)).alias(c)
    for (x, c) in [(1, "fv"), (0, "nfv")]
]
gpd.agg(*exprs)

rawDescription: PySpark count values by condition

description: PySpark count values by condition


code:
def OpenTextFile(self):
    dialog = QtGui.QFileDialog()
    dialog.setWindowTitle("Choose a file to open")
    dialog.setFileMode(QtGui.QFileDialog.ExistingFile)
    dialog.setNameFilter("Text (*.txt);; All files (*.*)")
    dialog.setViewMode(QtGui.QFileDialog.Detail)

    filename = QtCore.QStringList()

    if(dialog.exec_()):
        file_name = dialog.selectedFiles()
    plain_text = open(file_name[0]).read()
    self.Editor.setPlainText(plain_text)
    self.file_path = str(file_name[0])

rawDescription: Return value from button click

description: Return value from button click


code:
class Node(object):
    def __init__(self):
        self.dirs = {}
        self.files = []

rawDescription: Directory tree in a QTreeWidget

description: Directory tree in a QTreeWidget


rawDescription: Is there any way django does not save the file uploaded with form


code:
image_stacks = np.zeros(shape=(10, 400, 300, 3), dtype=np.uint8)
for i in xrange(image_stacks.shape[0]):
    # open image file and store in variable `im`, then
    image_stacks[i] = np.array(im)

rawDescription: Stack multiple images in python pillow

description: Stack multiple images in python pillow


code:
def method1(s):
    out = ((s == s.shift()) | (s == 13)).astype(int)
    for i, x in s.iteritems():
        if x == 13: out[i] = 0
        else: break
    return out

def method2(s):
    s13na = s.replace(13, np.nan).ffill()
    indic = (s13na == s13na.shift()).astype(int)
    return indic

rawDescription: Creating an indicator for strings of numbers, ignoring a particular one in python pandas


code:
farm = []

def sower(func):
    def wrapped(*args, **kw):
        farm.append([])
        return func(*args, **kw)
    return wrapped

def sow(val):
    farm[-1].append(val)
    return val

def reap(val):
    return val, farm.pop()

rawDescription: Python equivalent of Mathematica's Sow/Reap


rawDescription: Python copying defaultdict to dict with new order of key


code:
segment = Segment(Point(0, 0), Point(3, 3))
print(segment.p0)
# Point(0, 0)
print(segment.p0.x)
# 0
segment.p1.y = 4

rawDescription: Setting the property of a property

description: Setting the property of a property


code:
def ssum(n):
    return n * (n + 1) // 2

def dsum(a, b):
    res = 0

    if a == b:
        while a:
            res += a % 10
            a //= 10

    elif a < b:
        aa = a // 10
        bb = b // 10

        ra = a % 10
        rb = b % 10

        if aa == bb:
            res += ssum(rb) - ssum(ra - 1)
            res += (rb - ra + 1) * dsum(aa, bb)

        else:
            if ra > 0:
                res += 45 - ssum(ra - 1)
                res += (10 - ra) * dsum(aa, aa)
                aa += 1

            if rb < 9:
                res += ssum(rb)
                res += (rb + 1) * dsum(bb, bb)
                bb -= 1

            if aa <= bb:
                res += 45 * (bb - aa + 1)
                res += 10 * dsum(aa, bb)

    return res

rawDescription: Efficient way to find sum of digits of an entire sequence


rawDescription: Make utf8 readable in a file

description: Make utf8 readable in a file


rawDescription: How can I find the average of each similar entry in a list of tuples?

description: Find the average of each similar entry in a list of tuples


rawDescription: Building a general numpy array index dynamically


code:
@classmethod
def foo(cls):
    print(cls.foo_string)

rawDescription: How to access class-scope variables without self?

description: Access class-scope variables without self


code:
def insert(list1, var, i):
    # Reassign all elements at and beyond the insertion point to be the new
    # value, and all but the last value previously there (so size is unchanged)
    list1[i:] = var, *list1[i:-1]

rawDescription: insert element into list, move pre-existing elements

description: Insert element into list, move pre-existing elements


code:
from datetime import datetime
now = datetime.now()

rawDescription: Name 'now' is not defined?

description: Name 'now' is not defined


rawDescription: how to filter duplicate requests based on url in scrapy

description: Filter duplicate requests based on url in scrapy


code:
def shiftString(string, number, start=97, num_of_symbols=26):
    return "".join(map(lambda x: chr(((ord(x)+number-start) %
           num_of_symbols)+start) if start <= ord(x) <= start+num_of_symbols
           else x,string))

rawDescription: Printing alphabets advanced by n in Python


code:
from __future__ import print_function

for i in range(1, 10):
    for j in range(i):
        print(i, end='')
    print()

rawDescription: Nested Loop Python

description: Nested Loop Python


code:
t
b

rawDescription: Digitize numpy array

description: Digitize numpy array


code:
if form.is_valid():
    docrequest = form.save()
    return HttpResponseRedirect(reverse('thank_you', kwargs={'id': docrequest.id}))

rawDescription: Passing form data from my view to thank you page