code:
from django.views.generic import RedirectView

urlpatterns = patterns('',
    url(r'^new_part/other/$', 'some_view'),
    url(r'^old_part/other/$',
        RedirectView.as_view(url='new_part/other/', permanent=True)),
)

rawDescription: Support old and new URI versions both working without breaking the reverse()


code:
text = 'textextextextext<tag>10005991</tag>textextextextext'
re.sub(r'<tag>1(\d+)</tag>','<tag>YYYYY</tag>',text)

rawDescription: Replace string between tags if string begins with "1"


code:
id,title,body,category_labels
0,greeting,hello,noun
1,affirm,yes,verb
2,deny,no,verb

rawDescription: Looking for a quick way to speed up my code


code:
import json
json_srz = json.dumps(srz_instance.spit())

rawDescription: Serialize django model with foreign key models


code:
for food in list_a:
    if food == ['meat']:
        list_c.extend(list_b)
    else:
        list_c.append(food)

print (list_c)

rawDescription: How to replace one element from a list with several element from another list?

description: Replace one element from a list with several element from another list


code:
data = collections.defaultdict(list)
for i in my_list:
    data[i['name']].append(i['score'])
output = [{'name': i, 'score': max(j)} for i,j in data.items()]

rawDescription: Given a list of dictionaries, how can I eliminate duplicates of one key, and sort by another


code: from __future__ import with_statement

rawDescription: Multithreaded Resource Access - Where Do I Put My Locks?


code:
import itertools, functools

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    # Direct from the recipes in itertools documentation
    t1, t2 = itertools.tee(iterable)
    return itertools.filterfalse(pred, t1), filter(pred, t2)

def prob_tree(data,ini) -> (float,tuple):
    """Generator of all end points of the probability tree contained
       in data, starting with ini"""
    for prob,path in data[ini]:
        no_more,more = map(tuple,partition(lambda x: x in data, path))
        if more:
            for node in itertools.product( *[prob_tree(data,x) for x in more] ):
                new_prob,new_path = functools.reduce(lambda acum,new: (acum[0]*new[0],acum[1]+new[1]),node,(prob,tuple()))
                yield new_prob, no_more + new_path
        else:
            yield prob, no_more

mydata = {1: [[.9, [2,3]], [.1, [4,5]]],
          4: [[.2, [6,7]], [.5, [8,9]], [.3, [10,11,12]]],
          5: [[.4, [13,14]], [.6, [15,16]]]
          }

mydata2 = {1: [[.8, [2,3]], [.1, [4,5]],[.05, [2,4]],[.05,[5,6]] ],
          4: [[.2, [6,7]], [.5, [8,9]], [.3, [10,11,12]]],
          5: [[.4, [13,14]], [.6, [15,16]]]
          }

mydata3 = {1: [[.8, [2,3]], [.1, [4,5]],[.05, [2,4]],[.05,[5,6]] ],
          4: [[.2, [6,7]], [.5, [8,9]], [.3, [10,11,12]]],
          5: [[.4, [13,14]], [.6, [15,16]]],
          13:[[.58,[23,32]],[.42,[42]] ],
          16:[ [.9,[17,18]], [.1,[20,21]] ],
          }

rawDescription: Calculate probabilities in a probability tree


code:
html = """
No
No
Yes.Yes!Yes?
No!"""
soup = BeautifulSoup(html, 'html.parser')
elm = soup.blockquote.next_sibling
txt = ""
while elm:
   txt += elm.string
   elm = elm.next_sibling

print(txt)

rawDescription: Extract content with BeautifulSoup and Python


code:
from datetime import datetime

def strToDatetime(dateStr):
    return datetime.strptime(dateStr, "%d/%m/%Y")

rawDescription: change (eg) 8 to 08...python

description: Change (eg) 8 to 08...python


code: temp = a[:]

rawDescription: Iteratively add elements to a list

description: Iteratively add elements to a list


code:
a
np.where(~a.any(axis=1))[0]

rawDescription: Finding which rows have all elements as zeros in a matrix with numpy


code:
#Assuming list is called lst
print(all(lst[i].lower() < lst[i+1].lower() for i in range(len(lst)-1)))

rawDescription: Creating a program that prints true if three words are entered in dictionary order


code: range(3, 6)

rawDescription: Learning python... stumped. Where is the loop in this function?


code:
class Point(namedtuple('Point', 'x y')):
    [...]

rawDescription: What are "named tuples" in Python?

description: What are "named tuples" in Python


code: ['harry', 'tom', 'dick', 'jim']

rawDescription: sorting a dictionary key based on values after they are converted to integers

description: Sorting a dictionary key based on values after they are converted to integers


code:
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

rawDescription: How to Customize the time format for Python logging?


code: len(number) - len(number.rstrip('0'))

rawDescription: Count only trailing elements of a number/string


code:
#!/usr/bin/env python3

import sys
from tkinter import *

mGui =Tk("")
mGui.geometry("480x480")
mGui.title("Leilani spelling test")
# You'll want to add this to enter the event loop that causes the window to be shown
mGui.mainloop()

rawDescription: tkinter with mac osx

description: Tkinter with mac osx


code: self.state_circles.append(StateCircle('yellow', coordx, coordy, label, i))

rawDescription: Python: How to call a class when something is done


rawDescription: How to select users which is not paired with a custom user through many-to-one?

description: Select users which is not paired with a custom user through many-to-one


code:
isinstance(A, (types.MethodType, types.BuiltinMethodType))
isinstance(a, (types.MethodType, types.BuiltinMethodType))
isinstance(A.__call__, (types.MethodType, types.BuiltinMethodType))
isinstance(a.__call__, (types.MethodType, types.BuiltinMethodType))

rawDescription: How to distinguish bound method or a function from a class?

description: Distinguish bound method or a function from a class


code:
# Utility options class
class Options:
    def __init__(self, defaults, user_opts):
        vars(self).update(defaults)
        vars(self).update(user_opts)

def func2(data, userOps):

    opt = Options({ 'lovesSO' : True}, userOps)

    print(data)
    print(opt.name)
    print(opt.lovesSO)

# Call
func2(data, userOps)

# OUTPUT
# (1, 2)
# joe
# True

rawDescription: Python convenient passing of dictionary arguments to function


code:
a = [1, 2, 9, 5, 1]
b = [9, 8, 7, 6, 5]
len(set(a) & set(b))     # & is intersection - elements common to both

rawDescription: Count duplicates between 2 lists

description: Count duplicates between 2 lists


code:
def search(request):

    if request.method == 'POST' and request.is_ajax():
        value = request.POST.get('value')
        products = product.objects.filter(p_name__icontains=u'%s' % value)#Convert to unicode

        #make json type array begin
        response_data = []
        final_response = {}

        for p in product:
            response_record = {}
            response_record['pname'] = p.name
            response_record['pid'] = p.id
            response_data.append(response_record)

        final_response["product"] = response_data
        #make json type array end
        return HttpResponse(json.dumps(final_response, default=date_handler, sort_keys=True), "application/json")

    else:
        return HttpResponse("Bad Request Detected!! :(")

rawDescription: making json array in django

description: Making json array in django


code:
{'param-1': {'param-2': {'param-X': {'gateway': {'<name>': {'protocol': {'param-Xv1': {'dpd': {}}},
                                                            'protocol-common': {'fragmentation': {},
                                                                                'nat-traversal': {}}}},
                                     'param-Z': {'ipsec-param-Z': {'<name>': {'ah': {'authentication': {}},
                                                                              'esp': {'authentication': {},
                                                                                'encryption': {}},
                                                                              'lifesize': {},
                                                                              'lifetime': {}}},
                                                 'param-X-param-Z': {'<name>': {'A': {},
                                                                                'B': {},
                                                                                'C': {},
                                                                                'D': {}}}}}},
             'param-3': {'param-3': {'ntp-servers': {},
                                     'param-5': {'param-6': {}},
                                     'update-schedule': {'global-protect-datafile': {'recurring': {'weekly': {}}}}}}}}

rawDescription: Text file with repeated elements to JSON


code:
class CheckBoxColumnWithName(tables.CheckBoxColumn):
    @property
    def header(self):
        return self.verbose_name

class SimpleTable(tables.Table):
    amend = CheckBoxColumnWithName(verbose_name="Amend", accessor="pk")

rawDescription: django-tables2 checkbox column name

description: Django-tables2 checkbox column name


rawDescription: Processing a select range of values in a numpy array


code: reload(foo)

rawDescription: revert/undo/redo/refresh, an `import` in interactive python session

description: Revert/undo/redo/refresh, an `import` in interactive python session


rawDescription: Executing a program from python so that it opens in separate cmd.exe window


rawDescription: Python 2: Why is floor division operator faster than normal division operator?


code: print(M)

rawDescription: pointers in sparse matrix in python scipy

description: Pointers in sparse matrix in python scipy


code:
l = [['str', 'foo'], ['bar', 'so']]
s = 'foo'
any(s in x for x in l)
s = 'nope'
any(s in x for x in l)

rawDescription: check if a string from a file exists in a list of list of strings: python

description: Check if a string from a file exists in a list of list of strings: python


code:
def read_exons(line):
    parts = iter(line.split())
    name = next(parts)
    chrom = next(parts)
    starts = map(int, next(parts).strip(',').split(','))
    ends = map(int, next(parts).strip(',').split(','))
    base = starts[0]
    return name, [(s-base, e-base) for s, e in zip(starts, ends)]

rawDescription: Reinitializing numbers in file (with differing amounts of columns?)


code:
segments = []
for path in paths:
    vertices = [vertex for vertex, _ in path.iter_segments()]
    vertices = np.asarray(vertices)
    segments.append(vertices)

rawDescription: 3D CartoPy similar to Matplotlib-Basemap


code: [dt for dt in dates if hasattr(dt, 'hour') and dt.hour % 6]

rawDescription: Chaining operator functions in Python's filter


rawDescription: How to sort contents of a file.txt in python numerically

description: Sort contents of a file.txt in python numerically


code: _mysql_exceptions.OperationalError: (1153, "Got a packet bigger than 'max_allowed_packet' bytes")

rawDescription: Fast way to convert array to tuple/list in python?


code: scatter(x,y,c=z, cmap=cm.Greys)

rawDescription: Python: matplotlib - Black and White Scatter


code: go -a -b -c

rawDescription: Difference between single dash and double dash in argparse


rawDescription: Subsetting data in python

description: Subsetting data in python


code:
from foo import Foo
from bar import Bar

fooobj = Foo()
barobj = Bar(fooobj)

rawDescription: How do I import a variable from another class?

description: Import a variable from another class


code: return len(s) == 2 and s.isalpha()

rawDescription: Validate a two characters code using python


code:
3
scores

rawDescription: python split and reverse text file

description: Python split and reverse text file


rawDescription: How to remove parenthesis from elements in a list (Python)

description: Remove parenthesis from elements in a list (Python)


code: [x+y for x in '12345' for y in 'ab']

rawDescription: Python list comprehension for loops

description: Python list comprehension for loops


code:
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'created_at']

rawDescription: django can't create superuser

description: Django can't create superuser


code:
import tkinter
from tkinter import ttk

class MyButton(ttk.Button):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.configure(command=self.callback)

    def callback(self):
        self.master.destroy()

tk = tkinter.Tk()
b = MyButton(tk, text="close window!")
b.pack()  # or whatever geometry manager you're using

# we're done!

rawDescription: How to access a button's parent in Tkinter without writing class?

description: Access a button's parent in Tkinter without writing class


code:
l = [{'dist':56, 'responder':'n'}, {'dist':26, 'responder':'n'}, \
{'dist':86, 'responder':'n'}]

smallestTwo = sorted(l, key=lambda d: d['dist'])[:2]

rawDescription: Finding minimum values in a list of dicts


rawDescription: Create overlapping groups with pandas timegrouper


rawDescription: Python: Does a module exist which already find an angle and the distance between two points?


code: set(su for sus in lists for su in sus)

rawDescription: Append JSON elements to a list, then remove duplicates efficiently in Python


code: Invoke-Item /path/to/python.exe

rawDescription: Launch Python from Powershell

description: Launch Python from Powershell


code:
def clamp(n, minn, maxn):
    if n < minn:
        return minn
    elif n > maxn:
        return maxn
    else:
        return n

rawDescription: How to limit a number to be within a specified range? (Python)

description: Limit a number to be within a specified range? (Python)


rawDescription: Unpack NumPy array by column

description: Unpack NumPy array by column


code:
euro_scale_system = CalendarScaleSystem(*(HMSScales + EuroMDYScales))
tick_gen = ScalesTickGenerator(scale=euro_scale_system)

rawDescription: python chaco axis labels time formatting

description: Python chaco axis labels time formatting


rawDescription: Saving pygame display as pygame.Subsurface


code:
class mySet(set):
    def __str__(self):
        return super(Set,self).__str__()[4:-1]

rawDescription: Writing a Set To a File in Python

description: Writing a Set To a File in Python


code: result = round(centimeter / 100, -1)

rawDescription: Round Integers in Python

description: Round Integers in Python


code:
def log(s):
    print("my-prefix -- "+s)

log("hello")

rawDescription: How do I give a string object a custom method in Python?

description: Give a string object a custom method in Python


code:
data.apply(lambda row: row * beta, axis=1).head()
data.mul(beta, axis=1).head()  # just show first few rows with head

rawDescription: Python numpy or pandas equivalent of the R function sweep()


code:
import datetime
print("mdatetime = {}".format(datetime.datetime.fromtimestamp(mtime)))
# mdatetime = 2012-01-04 14:19:06.523398

rawDescription: Print file age in seconds using Python

description: Print file age in seconds using Python


code: #!/usr/bin/env python

rawDescription: How to write a cron job for a python method

description: Write a cron job for a python method


rawDescription: GroupBy in pandas divided by date range

description: GroupBy in pandas divided by date range


code:
class Base:
    def do( self ):
        self._member1 = 0
        self._member2 = 1

def add_do(a, b):
    def deco(cls):
        original_do = cls.do
        def do(self):
            original_do(self)
            self._member3 = a
            self._member4 = b
        cls.do = do
        return cls
    return deco

@add_do(0, 1)
class Derived1(Base): pass

@add_do(2, 3)
class Derived2(Base): pass

@add_do(9, 3)
class Derived3(Base): pass

rawDescription: Python: Simplify inheritor method

description: Python: Simplify inheritor method


code: c = a.isin(b)

rawDescription: Join two pandas series by values

description: Join two pandas series by values


code: ts.resample('M', how='sum')

rawDescription: .json extension file + timestamp + Pandas + Python


code:
def mean(sample, n):
    n = float(n)
    mean = sum(sample)/n
    return mean

def sample(x):
    length = 1000000
    new_array = random.sample(x, length)
    return new_array

def repeat_means(x):
    repeats = 100
    list_of_means = []
    for i in range(repeats):
        list_of_means.append(mean(sample(x)))
    return list_of_means

repeat_means(large_array)

rawDescription: Python 3.1 - Memory Error during sampling of a large list


rawDescription: asked to calculate the logical matrix P=mn

description: Asked to calculate the logical matrix P=mn


code:
import bs4

# load the file
with open("existing_file.html") as inf:
    txt = inf.read()
    soup = bs4.BeautifulSoup(txt)

# create new link
new_link = soup.new_tag("link", rel="icon", type="image/png", href="img/tor.png")
# insert it into the document
soup.head.append(new_link)

# save the file again
with open("existing_file.html", "w") as outf:
    outf.write(str(soup))

rawDescription: Edit and create HTML file using Python

description: Edit and create HTML file using Python


code:
class YourModel(models.Model):
    ...

class YourModelSerializer(serializers.ModelSerializer):
    ...

your_json = YourModelSerializer(YourModel.objects.get(pk=5)).data

rawDescription: zip and download Django Rest Framework generated json file

description: Zip and download Django Rest Framework generated json file


code:
out_basic_approach = my_func_basic(V,H,E,F,Q,n)
np.allclose(mask1,mask2)
np.allclose(out_basic_approach[mask1],out_vectorized_approach[mask1])

rawDescription: optimizing matrix operations in python, numpy

description: Optimizing matrix operations in python, numpy


code:
a = a.transpose((2,0,1))
a.shape

rawDescription: How to vectorize 3D Numpy arrays

description: Vectorize 3D Numpy arrays


code:
writer = None

# ...

if not writer:
    writer = csv.writer(open(filename, 'wb'))
    writer.writerow(headers)

writer.writerow(somerow)

rawDescription: Writing headers in CSV file

description: Writing headers in CSV file


code:
import csv
...
rd = csv.reader(inputfile)
wr = csv.writer(outputfile)
for row in rd:                       # split each line into a list of fields
    row = [ x.strip() for x in row ] # remove spaces around  fields
    outrow = row[1:]                 # of whatever builds the output row
    wr.writerow(outrow)

rawDescription: How to remove a word declared in a variable in .csv file with python?

description: Remove a word declared in a variable in .csv file with python


code:
import jsonpickle
import sqlalchemy.types as types

class JsonType(types.MutableType, types.TypeDecorator):
    impl = types.Unicode

    def process_bind_param(self, value, engine):
        return unicode(jsonpickle.encode(value))

    def process_result_value(self, value, engine):
        if value:
            return jsonpickle.decode(value)
        else:
            # default can also be a list
            return {}

rawDescription: SQLAlchemy JSON as blob/text

description: SQLAlchemy JSON as blob/text


code:
def __get__(self, instance, owner):
    if instance is None:
        return self
    return DecorMethod(self, instance)

rawDescription: Callable object decorator applied to method doesn't get self argument on input


code:
query = "Thomas Jefferson"
query = query.replace(' ', '+')

rawDescription: Pull Data/Links from Google Searches using Beautiful Soup


code:
def onDrag(self, event):
    data = wx.FileDataObject()
    obj = event.GetEventObject()
    dropSource = wx.DropSource(obj)

    dropSource.SetData(data)

    #next line will make the drop target window come to top, allowing us
    #to get the info we need to do the work, if it's Explorer
    result = dropSource.DoDragDrop(0)

    #get foreground window hwnd
    h = win32gui.GetForegroundWindow()

    #get explorer location
    s = win32com.client.Dispatch("Shell.Application")
    loc, outdir = None, None
    for w in s.Windows():
        if int(w.Hwnd) == h:
            loc = w.LocationURL
    if loc:
        outdir = loc.split('///')[1]
        outdir = urllib.unquote(outdir)

    #got what we need, now download to outfol
    if outdir and os.path.isdir(outdir):
        self.dloadItems(event, outdir)

    return

rawDescription: Drag and drop application-created file to explorer window


code: [float(x) if re.match(r'[-+]?(\d*\.?\d+|\d+\.)$', x) else 0 for x in values]

rawDescription: list comprehension that converts the numbers to integers and turns the non-numeric values into 0

description: List comprehension that converts the numbers to integers and turns the non-numeric values into 0


code:
increasing_pixels = np.product([(myArray[i] <= myArray[i+1]) for i in range(nbands-1)],axis=0)
decreasing_pixels = np.product([(myArray[i] >= myArray[i+1]) for i in range(nbands-1)],axis=0)

rawDescription: python array processing: how to generate new values on pixel by pixel basis

description: Python array processing: how to generate new values on pixel by pixel basis


code: Meta.shadowed.__get__(Foo, Meta)()

rawDescription: How to get the bound method derived from a metaclass when the class has a method of the same name

description: Get the bound method derived from a metaclass when the class has a method of the same name


code:
from collections import defaultdict

def transposeListOfDicts(listOfDicts):
    """Turn a list of dict into a dict of lists"""

    result = defaultdict(list)

    for d in listofDicts:
        for key, value in d.iteritems():
            result[key].append(item)

    return result

rawDescription: Python: DictReader returning a list of dictionaries?


code:
for abbr,cls in result.items():
    print("The abbreviation for {} is {}".format(cls,abbr))

rawDescription: Search and Find through a list Python

description: Search and Find through a list Python


rawDescription: Simulating ajax request with python using the requests lib


code:
import re
import calendar

regex = re.compile('|'.join(calendar.day_name))
sub_dict = dict(zip(calendar.day_name,calendar.day_abbr))
new_paragraph = regex.sub(lambda match: sub_dict[match.group(0)],paragraph)

rawDescription: shorten the weekdays from texts

description: Shorten the weekdays from texts


code:
import re
s = """
Saturday, February 08, 2014
br/>
Saturday, February 10, 2014
br/>
Saturday, February 12, 2014
br/>
"""
pattern = 'href="data/self/dated/([^"]*)"[^>]*>([\s\S]*?)'
re.findall(pattern,s)

rawDescription: Python Regex to extract relative href links


code:
papa.replace('papa', '')
app.replace('papa', '')

rawDescription: How to strip a specific word from a string?

description: Strip a specific word from a string


code:
import random
randomRange = range(len(listOfItems))
random.shuffle(randomRange)
for i in randomRange:
    singleSelectedItem = listOfItems[i]
    blahblah

rawDescription: Python - run through a loop in non linear fashion


code:
import urllib

values = { 'foo': 'bar' }
data = urllib.urlencode(values)

rawDescription: Python equivalent of Curl HTTP post

description: Python equivalent of Curl HTTP post


rawDescription: Python multiline regex + multi entries reading a file in one go


code:
import os.path
absolute1 = '/a/b/c/d.js'
relative = '../../e.js'
os.path.normpath(os.path.join(os.path.dirname(absolute1), relative))

rawDescription: get absolute path from one absolute and one relative

description: Get absolute path from one absolute and one relative


code:
def pause_wrapper(x, n):
    def decorator(f):
        config = [x, time.time()+n]
        def wrapped(*args, **kwargs):
            if config[0] == 0:
                time.sleep(config[1] - time.time())
                config = [x, time.time() + n]

            return f(*args, **kwargs)
        return wrapped
    return decorator

rawDescription: Dynamically pass parameters to function

description: Dynamically pass parameters to function


code:
import shelve
from datetime import datetime, timedelta

# create a "shelf"
shelf = shelve.open('hash_db.shelve')
shelf['123dfre345'] = {"file name": 'calc.pdf', "file size": 234, "last scanned time": datetime(2013, 12, 24, 12, 23)}
shelf['3gcdshj754'] = {"file name": 'star.pdf', "file size": 10, "last scanned time": datetime(2013, 10, 10, 10, 30)}
shelf.close()

# open, update and close
shelf = shelve.open('hash_db.shelve')
file_info = shelf['3gcdshj754']
file_info['last scanned time'] += timedelta(hours=+1, minutes=12)
shelf['3gcdshj754'] = file_info
shelf.close()

rawDescription: use pickle to save dictionary in python

description: Use pickle to save dictionary in python


rawDescription: Python Beautifulsoup4:

description: Python Beautifulsoup4:


rawDescription: Create multi-level index pandas dataframe from delimited string column


code:
import ipaddress

def is_subnet_of(a, b):
   """
   Returns boolean: is `a` a subnet of `b`?
   """
   a = ipaddress.ip_network(a)
   b = ipaddress.ip_network(b)
   a_len = a.prefixlen
   b_len = b.prefixlen
   return a_len >= b_len and a.supernet(a_len - b_len) == b

rawDescription: How do I check if a network is contained in another network in Python?

description: Check if a network is contained in another network in Python


code:
from datetime import datetime
t = [(datetime(2014, 1, 23, 14, 49, 6, 185955), datetime(2015, 4, 18, 14, 49, 6, 185955)), (datetime(2015, 2, 2, 14, 49, 6, 185955), datetime(2015, 10, 23, 14, 49, 6, 185955))]
def time_overlap(t):
    overlap = (min([x[1] for x in t]) - max([x[0] for x in t]))
    days = overlap.days+1
    hours, remainder = divmod(overlap.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    hours += days*24
    return (hours,minutes,seconds)
print(time_overlap(t))

rawDescription: Python - How to find datetime overlapping?


code: from flask_root.application import db

rawDescription: Python clean imports for models - SQL Alchemy


code:
request.user.profile.about = 'abc'
request.user.profile.save()

rawDescription: Getting logged in User's Profile in Django without repeating request.user a lot?


code:
from contextlib import contextmanager
@contextmanager
def neat_indent(parent=None):
    # OPTIONAL: This is also an opportunity to do something before the block of code runs!
    try:
        # During this is where your indented block will execute
        # Leave it empty
        yield
    finally:
        # OPTIONAL: This is where you can write code that executes AFTER your indented block executes.
        if parent:
            cmds.setParent(parent)

rawDescription: Is there a way to indent Python without affecting the code


code:
class QTableWidgetDisabledItem(QtGui.QItemDelegate):
    """
    Create a readOnly QTableWidgetItem
    """
    def __init__(self, parent):

        QtGui.QItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        item = QtGui.QLineEdit(parent)
        item.setReadOnly(True)
        #item.setEnabled(False)
        return item

    def setEditorData(self, editor, index):
        editor.blockSignals(True)
        editor.setText(index.model().data(index))
        editor.blockSignals(False)

    def setModelData(self, editor, model, index):
        model.setData(index, editor.text())

rawDescription: Set a whole column in `QTableWidget` read-only in python


rawDescription: Django get all records of related models


code:
import struct
data = ''.join(chr(i) for i in range(128)) * 10
hdr_fmt = 'I4sIIHL'
struct.calcsize(hdr_fmt)
struct.unpack_from(hdr_fmt, data, 0)

rawDescription: How to remove first 4 bytes from s string in python

description: Remove first 4 bytes from s string in python


code:
import numpy as np
blue = np.array([0.2, 0.2, 0.3])
red = np.array([0.1, 0.2, 0.3])
pink = np.array([0.1001, 0.221, 0.321])
car = np.array([0.6, 0.9, 0.5])
def cosine(x,y):
    return np.dot(x,y) / (np.linalg.norm(x) * np.linalg.norm(y))

cosine(pink, red)
cosine(pink, blue)
cosine(blue, red)
cosine(blue, car)
cosine(red, car)
cosine(pink, car)

rawDescription: How do I calculate the shortest path (geodesic) distance between two adjectives in WordNet using Python NLTK?

description: Calculate the shortest path (geodesic) distance between two adjectives in WordNet using Python NLTK


code:
for tic in ax.xaxis.get_major_ticks():
    tic.tick1On = tic.tick2On = False

rawDescription: Remove the x-axis ticks while keeping the grids (matplotlib)


code:
{'iq': 80, 'distance': 'low', 'name': 'Mike'}
{'iq': 100, 'distance': 'mid', 'name': 'John'}
{'iq': 150, 'distance': 'high', 'name': 'Peter'}

rawDescription: Doing mapping from range of numbers to words


code:
import sys
import re
import collections

logf = '/var/log/messages.log'
count = collections.Counter()
write = sys.stdout.write

with open(logf, 'r') as f:
    for line in f:
        line = re.sub(r'\d+','#',line)
        count[line] += 1

for line in sorted(count):
     write("{c}: {l}".format(c = count[line], l = line))

rawDescription: Summarizing log file to unique entries only


code:
import datetime
import pytz

unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC)

now_aware = pytz.utc.localize(unaware)
assert aware == now_aware

rawDescription: What does Django Date filter mean by 'Naive'?


code: timeit.timeit('dm(n, d)', 'n, d = 42, 7; dm = divmod')

rawDescription: Is divmod() faster than using the % and // operators?


code:
from random import *

class Card:
    def __init__(self):
        self.rank = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
        self.suit = ['s', 'h', 'c', 'd']
        self.card = choice(rank) + choice(suit)

rawDescription: Python 2.7.x - trying to get the hang of OOP and classes


code:
replacewith.update({'http://koala.org/':'http://koala.org/'})
replace_char("Koala eats http://koala.org/ a lot
", replacewith)

rawDescription: Replacing characters in a string and returning in python


code:
import numpy as np
...
shape = (6, 6) #This will be some pre-determined size
sigma = np.diag(S) #diagonalise the matrix - this works
sigma.resize(shape) #Resize the matrix and fill with zeros

rawDescription: Python: Resize an existing array and fill with zeros


code: t= calendar.monthrange(int(yearstring), 2) # This is to check if February has 29 or 28 (is leap year or no), you can do that by checking the day number of "datetime.date (int(yearstring), 3, 1) - datetime.timedelta (days = 1)"

rawDescription: difference between two dates python

description: Difference between two dates python


code:
if request.method == 'POST':
    form_year = YearForm(request.POST)
    form_gender = GenderForm(request.POST)
    if form_year.is_valid() and form_gender.is_valid():
        id_year = form_year.cleaned_data['years']
        id_gend = form_gender.cleaned_data['gender']
        filename = image #then insert this image into pdf file

rawDescription: how to redirect form after submit

description: Redirect form after submit


code:
import os
os.chdir( path )

rawDescription: Is it possible to specify the previous directory python?


code:
for item in points:
    p = Point(*item)

rawDescription: How to parse an item in a list containing two floats and omit its parentheses in Python

description: Parse an item in a list containing two floats and omit its parentheses in Python


code:
def f(df):
    df['streak2'] = (df['stat'] == 0).cumsum()
    df['cumsum'] = np.nan
    df.loc[df['stat'] == 1, 'cumsum'] = df['streak2']
    df['cumsum'] = df['cumsum'].fillna(method='ffill')
    df['cumsum'] = df['cumsum'].fillna(0)
    df['streak'] = df['streak2'] - df['cumsum']
    df.drop(['streak2', 'cumsum'], axis=1, inplace=True)
    return df

rawDescription: finding streaks in pandas dataframe

description: Finding streaks in pandas dataframe


code:
def plot_something(fig=None, ax=None):
    if fig is None and ax is None:
        fig, ax = plt.subplots()
    elif fig is None:
        fig = ax.get_figure()
    elif ax is None:
        ax = fig.gca()
    ax.plot(xrange(10))
    return fig, ax

rawDescription: Matplotlib: Copy one axes to another

description: Matplotlib: Copy one axes to another


code: button = Button(mainwin, text='blahblah', command=somefunction)

rawDescription: Modifying a variable in a function has no result


rawDescription: python - create a dynamic list of parameter for a method

description: Python - create a dynamic list of parameter for a method


rawDescription: Indexing float values in Python

description: Indexing float values in Python


code: mylist = map(lambda word: word.decode('utf-8'), mylist)

rawDescription: Intersection of two Unicode Arrays in Python


code: print(' '.join(message))

rawDescription: "IndexError: string index out of range" with a Python Program


code:
start_x = 250
start_y = 300
radius = 100
for i in range(36):
    degree0 = 0 + i*10
    degree1 = 10 + i*10
    radians0 = math.radians(degree0)
    radians1 = math.radians(degree1)
    dx0 = radius*(math.sin(radians0))
    dy0 = radius*(math.cos(radians0))
    dx1 = radius*(math.sin(radians1))
    dy1 = radius*(math.cos(radians1))

    m0 = dy0
    n0 = -dx0
    m1 = -dy0 + dy1
    n1 = dx0 - dx1

    w = dwg.path(d="M {0},{1} l {2},{3} a {4},{4} 0 0,0 {5},{6} z".format(start_x, start_y, m0, n0, radius, m1, n1),
             fill="#00ff00",
             stroke="none",
            )
    elem.append(w)

rawDescription: Arc, pie cut, in svgwrite

description: Arc, pie cut, in svgwrite


rawDescription: Pyglet Image Rendering

description: Pyglet Image Rendering


code:
from StringIO import StringIO
out = StringIO()
out = tree.export_graphviz(clf, out_file=out)

rawDescription: How do I find which attributes my tree splits on, when using scikit-learn?

description: Find which attributes my tree splits on, when using scikit-learn


code: st.seed.widget.clamp_to_bounds = False

rawDescription: Using python and mayavi to create a 3D streamplot


code:
dir
filename

rawDescription: Directory Name + File Name to Text File

description: Directory Name + File Name to Text File


code:
name = ['Hans', 'Peter', 'Eliza']
random_name = random.choice(name)

print('Your name is {}!'.format(random_name))

rawDescription: How to save a random string from a list of strings?

description: Save a random string from a list of strings


code:
display(first_var)
display(second_var)

rawDescription: retrieving a variable's name in python at runtime?

description: Retrieving a variable's name in python at runtime


code:
strs = "add(ten)sub(one)"
re.sub(r'\)(?=\S)',r') ', strs)

rawDescription: Using parentheses as delimiter in re or str.split() python


code:
def grouper(sequence):
    group, members = [], set()

    for item in sequence:
        if group and members.isdisjoint(item):
            # new group, yield and start new
            yield group
            group, members = [], set()
        group.append(item)
        members.update(item)

    yield group

rawDescription: Group Python list of lists into groups based on overlapping items


code: import BeautifulSoup

rawDescription: A few questions regarding Pythons 'import' feature


rawDescription: Creating 2 arrays from one array in python


code:
dict_a = {'one': {'bird':2, 'tree':6, 'sky':1, 'TOTAL':9},
          'two': {'apple':3, 'sky':1, 'TOTAL':4},
          'three': {'tree':6, 'TOTAL':6},
          'four': {'nada':1, 'TOTAL':1},
          'five': {'orange':2, 'bird':3, 'TOTAL':5}
          }
set1 = {'bird','tree'}
[key for key, value in dict_a.iteritems() if value.viewkeys() & set1]

rawDescription: Check if items in a list exist in dictionary


rawDescription: I want to loop through a string of numbers


code:
class ModelNameForm(forms.Form):

    data = forms.CharField()

    def clean_data(self):
        data = self.cleaned_data['data']
        return translate(data)

rawDescription: Django translate data on model save

description: Django translate data on model save


rawDescription: merge values in list

description: Merge values in list


code:
from flask import current_app

with current_app.test_request_context(path=path):
    # the cache key can use `request` so we need to provide the correct
    # context here
    cache_key = view.make_cache_key()

cache.delete(cache_key)

rawDescription: control flask-cache'ing from a view

description: Control flask-cache'ing from a view


code:
import pandas as pd

A = pd.DataFrame(
    [[1, 5, 2, 3, 4, 1], [2, 4, 4, 5, 5, 1], [3, 3, 1, 2, 5, 4],
     [4, 2, 2, 3, 5, 5], [5, 1, 4, 2, 3, 1]],
    columns=['A', 'B', 'C', 'D', 'E', 'F'], index=[1, 2, 3, 4, 5])

result = []
pairs = []
for col1, col2 in zip(list('ABC'), list('DEF')):
    pairs.append(col1+col2)
    mask = A[col1] > 1
    mask2 = mask & (A[col2] > 0)
    ser = A.loc[mask, col2]
    result.append((ser.mean(), ser.std(), mask2.sum()))

    mask = A[col1] < 1
    mask2 = mask & (A[col2] < 0)
    ser = A.loc[mask, col2]
    result.append((ser.mean(), ser.std(), mask2.sum()))

index = pd.MultiIndex.from_product([pairs, [1, 2]], names=['pair', 'cond'])
df = pd.DataFrame(result, index=index, columns=['mean', 'sum', 'count'])
print(df)

rawDescription: How to apply Pandas Groupby with multiple conditions for split and apply multiple calculations?

description: Apply Pandas Groupby with multiple conditions for split and apply multiple calculations


code:
def action(self, stimType):
    pygame.draw.rect(*self.stim[stimType])

rawDescription: Is there a more pythonic way of storing parameters so they can be used in a function call?


code: my_function(*[int(x) for x in list])

rawDescription: Unpack list and cast at the same time

description: Unpack list and cast at the same time


code:
u
map(list, u)

rawDescription: Sort multiple lists simultaneously

description: Sort multiple lists simultaneously


code:
text = soup.find('p').get_text()
if len(text) > 100:
    text = text.partition('.')[0] + '.'
print(text)

rawDescription: Python: print/get first sentence of each paragraph


code:
import urlparse

link = "http://www.test.com.tw/t/time.html"
date ="20150113"
url = urlparse.urlparse(link)

urlparse.urljoin(url.geturl(), '/'.join(link.rsplit('/', 1)+[date]))

rawDescription: Python urlparse urljoin

description: Python urlparse urljoin


code: lambda event: self.click_poligono(event,'%s' % i)

rawDescription: select a line and process its tags on mouse click (python tkinter)

description: Select a line and process its tags on mouse click (python tkinter)


code:
nouns = load_nouns()

def load_nouns():
    infile = open('Noun.txt', 'r')
    nouns = infile.readlines()
    infile.close()
    return nouns

def get_noun():
    index = 0
    while index < len(nouns):
        nouns[index] = nouns[index].rstrip('\n')
        index += 1
    noun = random.choice(nouns)
    return noun

rawDescription: Using a loop to make a random sentence generator


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(range(10), color='red', lw=3, zorder=4)
# Placing the text in data coordinates...
ax.text(5, 5, 'Test', color='white', fontsize=45,
        bbox={'facecolor':'black', 'pad':12})

plt.show()

rawDescription: How to put pylab.plot line over pylab.figtext?

description: Put pylab.plot line over pylab.figtext


rawDescription: Prototyping-orientated features in Python?


rawDescription: How to merge 2 numpy arrays and concatenate their values?

description: Merge 2 numpy arrays and concatenate their values


code:
from multiprocessing.pool import ThreadPool

# Done here because this must be done in the main thread
pool = ThreadPool(processes=50) # use a max of 50 threads

# do this instead of Thread(target=func,args=args,kwargs=kwargs))
pool.apply_async(func,args,kwargs)

pool.close() # I think
pool.join()

rawDescription: How to open Post Urls in multithreads in python

description: Open Post Urls in multithreads in python


code:
from app import app, models
from flask import g, redirect, url_for, render_template, request
from flask.ext.classy import FlaskView, route

@app.route('/user/<int:id>', strict_slashes=False)
@app.route('/user/<int:id>/<username>', strict_slashes=False)
def profile(id, username=None):
    user = models.User.query.get_or_404(id)
    if user.clean_username != username:
        return redirect(url_for('profile', id=id, username=user.clean_username))
    return render_template('profile.html', user=user)

class ClassyUsersView(FlaskView):
    @route('/<int:id>', strict_slashes=False)
    @route('/<int:id>/<username>', strict_slashes=False, endpoint='classy_profile')
    def profile(self, id, username=None):
        user = models.User.query.get_or_404(id)
        if user.clean_username != username:
            return redirect(url_for('classy_profile', id=id, username=user.clean_username))
        return render_template('profile.html', user=user)

ClassyUsersView.register(app)

rawDescription: Flask redirecting multiple routes

description: Flask redirecting multiple routes


rawDescription: Large networkx graph for nearest neighbors figure


rawDescription: Python: how to make a function visible throughout a program


code:
import scipy.stats as s
import matplotlib.pyplot as plt
import numpy as np

wei = s.weibull_min(2, 0, 2) # shape, loc, scale - creates weibull object
sample = wei.rvs(1000)
shape, loc, scale = s.weibull_min.fit(sample, floc=0)

x = np.linspace(np.min(sample), np.max(sample))
dx = x[1]-x[0]
deriv = np.diff(wei.cdf(x))/dx
plt.hist(sample, normed=True, fc="none", ec="grey", label="frequency")
plt.plot(x, wei.cdf(x), label="cdf")
plt.plot(x, wei.pdf(x), label="pdf")
plt.plot(x[1:]-dx/2, deriv, label="derivative")
plt.legend(loc=1)
plt.show()

rawDescription: Calculating the derivative of cumulative density function in Python


code:
from subprocess import PIPE,Popen

p = Popen(["sudo", "-s", "-S"], stdin=PIPE, stdout=PIPE, universal_newlines=True)

p.stdin.write("password\n")
p.stdin.write("ls -la\n")
p.stdin.write("/usr/bin/pip list\n")
p.stdin.write("id -u")
print(p.communicate()[0])

rawDescription: run Python file with root permission via php

description: Run Python file with root permission via php


code:
for c in x:
    celula = x[c]

rawDescription: Sum of specific elements in a list, if they are consecutive (python)


code:
from scipy.interpolate import RegularGridInterpolator
from numpy import linspace, zeros, array
x = linspace(1,4,11)
y = linspace(4,7,22)
z = linspace(7,9,33)
V = zeros((11,22,33))
for i in range(11):
    for j in range(22):
        for k in range(33):
            V[i,j,k] = 100*x[i] + 10*y[j] + z[k]
fn = RegularGridInterpolator((x,y,z), V)
pts = array([[2,6,8],[3,5,7]])
print(fn(pts))

rawDescription: interpolate 3D volume with numpy and or scipy

description: Interpolate 3D volume with numpy and or scipy


code:
def function(x):
    return expression_here

rawDescription: Python string vowel counter

description: Python string vowel counter


code: from __future__ import division

rawDescription: Integer division instead of regular one in Python


rawDescription: Split based by a-z character in an alphanumeric string in python


rawDescription: Python/Bottle/MongoDB: Unsupported response type: <type 'dict'>


code:
i, j = inds.T
i
j
a[i, j]

rawDescription: How to extract a list of elements given by their indices from a numpy array efficiently?

description: Extract a list of elements given by their indices from a numpy array efficiently


rawDescription: Using Xpath in Scrapy to select any text below paragraph


rawDescription: Find row corresponding to timestamp in pandas DataFrame


rawDescription: Replace a pattern in CSV file Python

description: Replace a pattern in CSV file Python


code:
from matplotlib.mlab import rec2csv
rec2csv(x,'foo.txt')

rawDescription: Insert field into structured array at a specific column index


code:
the_word = generate_random_word_from(word_list)
# which is probably as simple as random.choice(word_list)

guessed_letters = set()

def display_word():
    global the_word
    global guessed_letters
    # globals are bad in practice, but this is actually a great use case
    # for a global if you haven't wrapped this all up in OOP yet!

    masked_list = [letter if letter in guessed_letters else "_" for
                     letter in the_word]
    # this is literally:
    # # masked_list = []
    # # for letter in the_word:
    # #     if letter in guessed_letters:
    # #         masked_list.append(letter)
    # #     else:
    # #         masked_list.append("_")
    masked_word = ''.join(masked_list)
    # join the list on an empty string, e.g.:
    # ['s','_','m','e','w','_','r','d'] becomes 's_mew_rd'
    print(masked_word)
    # this wouldn't be a bad place to trigger your win condition, too.
    # Could be as simple as
    # # if "_" not in masked_word:
    # #     you_win()

def guess_letter():
    global the_word
    global guessed_letters

    guessed_letter = prompt_for_letter_somehow()
    if guessed_letter not in the_word:
        add_hangman_piece() # put another arm/leg/whatever on your dude
    guessed_letters.add(guessed_letter)
        # add that letter to the guessed_letters set anyway
    # validation would be nice here so you can't just keep guessing the same letters

rawDescription: How to reference a string in a list in python

description: Reference a string in a list in python


code:
if getargspec(g)[3]:
    ...

rawDescription: Why is inspect.getargspec() return unsized objects?


rawDescription: Precision of decimals in Python

description: Precision of decimals in Python


code:
expected_list = [1, 2, 3, 4]
output_list = calc_mortgage([10, 20, 30, 42])
for pair in zip(expected_list, output_list):
    self.assertEqual(pair[0], pair[1])

rawDescription: Using Python Unittest to test results in an array


code:
def main():
    scores = []
    scores_file = open('scores.txt', 'r')
    line_list = scores_file.readlines()
    scores_file.close()
    i = 0

    while i < len(line_list):
        scores.append(int(line_list[i].strip()))
        i += 1
    print(scores)

main()

rawDescription: Removing \n from file being read by while loop


code: points = [[int(i) for i in line.split(',')[:2]] for line in lasfile]

rawDescription: Reading all lines in a file with list comprehension


code:
m, s = time[0].split(':')
Min = int(m) if m != '' else 0
Sec = int(s)

rawDescription: How do I extract numbers from a string into multiple variables?

description: Extract numbers from a string into multiple variables


code:
from bs4 import BeautifulSoup
sample = '''\

Internet Access

Wired High Speed Internet Access in All Guest Rooms

        25 USD per day

'''
soup = BeautifulSoup(sample)
soup.li
soup.li.string
soup.li.text
soup.li.get_text(' ', strip=True)

rawDescription: Unable to scrape the text from a certain LI element


code:
for line in fin:
    if not True in [item in line for item in offending]:
        fout.write(line)

rawDescription: Python script to remove lines from file containing words in array


code: data

rawDescription: Python table titles into dictionary

description: Python table titles into dictionary


rawDescription: Interchange ordering of 4-D Numpy array

description: Interchange ordering of 4-D Numpy array


rawDescription: How to remove items from lista comparing with another list listb

description: Remove items from lista comparing with another list listb


rawDescription: How to dynamically change logging level of python app in Google App Engine?

description: Dynamically change logging level of python app in Google App Engine


code:
{
    'donald': {
        'phone': '123456',
        'first_name': 'donald',
        'last_name': 'duck',
        'email': 'donald@duck.com'
    },
    'suzy': {
        'phone': '78910',
        'first_name': 'suzy',
        'last_name': 'giraffe',
        'email': 'suzy@giraffe.com'
    }
}

rawDescription: reading lines from file to make 2D dictionary [python]

description: Reading lines from file to make 2D dictionary [python]


code: line1, = ax[1].plot(t,s, lw=2, color='green', label="green")

rawDescription: Dynamically change y limit

description: Dynamically change y limit


code:
q_has_boys = session.query(Parent).filter(Parent.has_a_boy_child).all()
q_no_boys = session.query(Parent).filter(~Parent.has_a_boy_child).all()
q_attr = session.query(Parent, Parent.has_a_boy_child).all()

rawDescription: How do I write a Hybrid Property that depends on a column in children relationship?

description: Write a Hybrid Property that depends on a column in children relationship


code:
timeit.timeit('search("HelloWorld"); search("HiThere")', 'from __main__ import reMatch as search')
timeit.timeit('search("HelloWorld"); search("HiThere")', 'from __main__ import genMatch as search')

rawDescription: If string equals item from list a, followed by item from list b


rawDescription: Using Gtk.spinner with a long time function


rawDescription: Python - Assigning Multiple Keys for a Single Value


code: df_view.apply(lambda x: x /2)

rawDescription: How to df.groupby(cols).apply(my_func) for some columns, while leave a few columns not tackled?

description: Df.groupby(cols).apply(my_func) for some columns, while leave a few columns not tackled


code:
month_perf = df.groupby(['Year', 'Month'])[['Close']].last()
month_perf['month_perf'] = month_perf.pct_change(periods=1)
month_perf = month_perf.reset_index()
month_perf.head()

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


code:
def fun(x):
   print(x)

fun("foo")

def fun2(x):
   print(x)

fun2("bar")

print("debug print")

rawDescription: Import only functions from a python file


code:
class MyXMLRPCServer(SimpleXMLRPCServer):
    def __init__(self, addr):
        self.idle_timeout = 5.0 # In seconds
        self.idle_timer = Timer(self.idle_timeout, self.shutdown)
        self.idle_timer.start()
        SimpleXMLRPCServer.__init__(self, addr)

    def process_request(self, request, client_address):
        # Cancel the previous timer and create a new timer
        self.idle_timer.cancel()
        self.idle_timer = Timer(self.idle_timeout, self.shutdown)
        self.idle_timer.start()
        SimpleXMLRPCServer.process_request(self, request, client_address)

rawDescription: Python server that shuts itself after some time being idle


code: a

rawDescription: Why can't I change a list in a method?

description: Why can't I change a list in a method


code:
mat
abs(np.diff(mat, axis=0))

rawDescription: Column wise subtraction in numpy

description: Column wise subtraction in numpy


rawDescription: Pythonic iteration over multiple lists in parallel


rawDescription: Iterating over fields of a layer in Scapy


code:
myList = ['this\n', 'is\n', 'sparta\n']
[elem for word in myList for elem in word.partition('\n') if elem]
myList = ['this\n', 'is', 'sparta\n']
[elem for word in myList for elem in word.partition('\n') if elem]

rawDescription: Extend a list based on its contents

description: Extend a list based on its contents


code: filtered = [item for index, item in enumerate(list2) if index not in list1]

rawDescription: Remove elements from a list according to indexes list efficiently


code:
def z(contfrac, a=1, b=0, c=0, d=1):
    for x in contfrac:
        while a > 0 and b > 0 and c > 0 and d > 0:
            t = a // c
            t2 = b // d
            if not t == t2:
                break
            yield t
            a = (10 * (a - c*t))
            b = (10 * (b - d*t))
            # continue with same fraction, don't pull new x
        a, b = x*a+b, a
        c, d = x*c+d, c
    for digit in rdigits(a, c):
        yield digit

def rdigits(p, q):
    while p > 0:
        if p > q:
           d = p // q
           p = p - q * d
        else:
           d = (10 * p) // q
           p = 10 * p - q * d
        yield d

rawDescription: Code to Generate e one Digit at a Time

description: Code to Generate e one Digit at a Time


code:
from operator import gt, ge, eq, le, lt

ops = {'>': gt, '>=':  ge, '=': eq, '<=': le, '<': lt}

rawDescription: using 3 variables in the beginning of an IF statement in python

description: Using 3 variables in the beginning of an IF statement in python


rawDescription: Getting the index of a players rank by points


code:
def recursive_sum(l1, l2, result = None, idx = 0):
    if result is None:
        result = []
    if idx < min(len(l1), len(l2)):
        result.append(l1[idx] + l2[idx])
        return recursive_sum(l1, l2, result, idx + 1)
    else:
        return result

rawDescription: sum two lists element-by-element in python recursively

description: Sum two lists element-by-element in python recursively


rawDescription: Regex for everything except certain matches


code: boxplot(data, flierprops=flierprops)

rawDescription: Remove edgewidth of matplotlib boxplot flier


rawDescription: python: dividing a number by a numpy array

description: Python: dividing a number by a numpy array


code:
course_details = CourseDetail.objects.get(course__name='Django 101', date='2013-03-01')
cc_attendance = CourseDetailAttendance.objects.filter(course_details=course_details).count()

rawDescription: Queryset across fours models

description: Queryset across fours models


code:
def get_all_descendants(nodes, include_self=True):
     result = set()
     for node in nodes:
        descendants = node.get_descendants(include_self=include_self)
        result.update(set(descendats.values_list('pk', flat=True)))
     return result

def detail(request, thread_id):
    thread = get_object_or_404(Thread, pk=thread_id)

    comments = thread.comment_set.all()
    descendants = get_all_descendants(comments, include_self=True)

    upvoted_comments = request.user.comment_upvotes.filter(
        id__in=descendants).values_list('pk', flat=True)

    downvoted_comments = request.user.comment_downvotes.filter(
        id__in=descendants).exclude(
        id__in=upvoted_comments).values_list('pk', flat=True)

    return render(request, 'threads/detail.html', {
        'thread': thread,
        'comments': comments,
        'upvoted_comments': set(upvoted_comments),
        'downvoted_comments': set(downvoted_comments)
    })

rawDescription: How to check if some post was voted for by the current user in a list

description: Check if some post was voted for by the current user in a list


code:
def window_stack(a, stepsize=1, width=3):
    return np.hstack( a[i:1+i-width or None:stepsize] for i in range(0,width) )

rawDescription: sliding window in numpy

description: Sliding window in numpy


rawDescription: Python procedure for changing an object

description: Python procedure for changing an object


code:
my_list = [[1, 2, 3], "abcd", (4, 5, 6)]
izip_longest(*my_list)

rawDescription: izip_longest on a list of lists

description: Izip_longest on a list of lists


code:
def my_ode(t, y, u, K, tau):
  return K*u/tau - y/tau  # dydt

rawDescription: Passing parameterized function handle in Python


code:
DATABASE_NAME = abspath('mydb.db')
MEDIA_ROOT = abspath('media/')

rawDescription: Any potential gotchas or things to be aware of for a newcomer to Django?


rawDescription: splitting a dot delimited string into words but with a special case

description: Splitting a dot delimited string into words but with a special case


code: model.class_weight = {0:100, 1:1}

rawDescription: class_weigths in claserization in lib scikit, python

description: Class_weigths in claserization in lib scikit, python


rawDescription: How to copy a matrix to a larger matrix in Python?

description: Copy a matrix to a larger matrix in Python


code:
with open ("from_baryon.csv", "r") as inFile:
    with open (self.filename, "a") as outFile:
        out_file = csv.writer (outFile)
        in_reader = csv.reader(inFile)
        data = []
        lencount = 0
        for row in in_reader:
            out_file.writerow(row)
            tlen = len(''.join(row))
            data.append([tlen] + row)
            lencount += tlen
        data.insert(0,[lencount])

rawDescription: Write CSV Python

description: Write CSV Python


code:
unq_items
unq_count

rawDescription: Grouping indices of unique elements in numpy


code:
#get current cursor position
curr_y, curr_x = window.getyx()

# depending on direction, update the cursor with
next_y, next_x = get_next_direction()

# place cursor in new position
window.move(next_y, next_x)

window.refresh()

rawDescription: Highlighting and Selecting text with Python curses


code:
def get_scores(filename):
    student_data = {}
    with open(filename) as infile:
        for line in infile:
            line = line.strip().split('=')
            name = line[0].strip()
            score = int(line[1].strip()) # If decimal scores allowed, change this line to float(line[1].strip())
            if name not in student_data:
                student_data[name] = []
            student_data[name].append(score)
            student_data[name].reverse()
    return sorted(student_data.items())

rawDescription: How do I order a file of scores in Python?

description: Order a file of scores in Python


code:
def op(*sequences):
    return product(*map(set, zip(*sequences)))

for combo in op(good, bad):
    print(combo)

for combo in op(good, bad, ugly):
    print(combo)

rawDescription: all combinations of differences of two lists

description: All combinations of differences of two lists


code: swig -python -c++ mymod.i

rawDescription: How to use swig with compiled dll and header file only

description: Use swig with compiled dll and header file only


code:
from django.db import models

class Contest(models.Model):
    name = models.CharField(max_length=50)
    # More fields here, if you like.
    contestants = models.ManyToManyField('Contestant', through='ContestResults')

class Contestant(models.Model):
    name = models.CharField(max_length=50)

class ContestResults(models.Model):
    contest = models.ForeignKey(Contest)
    contestant = models.ForeignKey(Contestant)
    rank = models.IntegerField()

rawDescription: Ordered ManyToManyField that can be used in fieldsets


rawDescription: Calculate range between list elements (int/str)


code:
import pandas as pd
df.Class = pd.factorize(df.Class)[0]

rawDescription: Python replacing column values with 0-x indexes (for xgboost)


code:
data = [[np.frombuffer(stream.readBytes(8*dimZ), dtype=np.dtype('complex64'))
         for y in range(dimY)]
         for x in range(dimX)]

rawDescription: Python: unpacking string of floats to complex numbers


rawDescription: Printing multiple strings on same line in a loop


code:
import selenium.webdriver as webdriver

url = 'http://dnainfo.com/chicago/2013-chicago-murders/timeline?mon=1'
driver = webdriver.Firefox()
driver.get(url)

soup = BeautifulSoup(driver.page_source)

rawDescription: Trying to retrieve data from a template in a website using urllib2 and BeautifulSoup


code:
self.start_x = self.canvas.canvasx(event.x)
self.start_y = self.canvas.canvasy(event.y)

rawDescription: Tkinter: Draw rectangle using a mouse

description: Tkinter: Draw rectangle using a mouse


code:
import datetime
myDatetime = datetime.datetime.now()
myDatetime.strftime('%Y-%m-%d')
myDatetime.strftime('%H:%M:%S')
str(myDatetime.date())
str(myDatetime.time())

rawDescription: how to get the date from datetime

description: Get the date from datetime


rawDescription: Python operator overloading and operator associativity


code:
import os
import tempfile

for _ in range(100):
    file_descriptor, file_path = tempfile.mkstemp(".txt", "prefix-", Dest_Dir)
    file_handle = open(file_path, "wb")
    # do stuff
    os.close(file_descriptor)
    file_handle.close()

rawDescription: Create multiply amount of files with random names in python and zip them


code:
a = OuterTest()
b = OuterTest()

rawDescription: How to create distinct instances of a class in Python?

description: Create distinct instances of a class in Python


rawDescription: Checking if today is a Wed or Sat with java.util.Calendar


code:
mylist = list(graph.degree().values())
unique_elements_list = list(set(mylist))

rawDescription: Python get degrees within nodes

description: Python get degrees within nodes


rawDescription: Easiest way to get a GAE datastore entry


code:
timerMananger.register(self.myMethod,5000)
# registers an event to be called after 5 seconds

rawDescription: How would I set a timer with Pygame and Livewires?


rawDescription: urlparse.urlparse returning 3 '/' instead of 2 after scheme

description: Urlparse.urlparse returning 3 '/' instead of 2 after scheme


code:
from collections import UserString

my_vars = [{'name': 'var1', 'value': 'first', "doc": "var1 docstring"},
           {'name': 'var2', 'value': 'second', "doc": "var2 docstring"}]

for var in my_vars:
    code = """\
{0} = UserString('{1}')
{0}.__doc__ = '{2}'""".format(var["name"], var["value"], var["doc"])
    exec(code)

rawDescription: Sphinx - autodata shows str.__doc__

description: Sphinx - autodata shows str.__doc__


code:
import opengraph
...
page = opengraph.OpenGraph(url=link, scrape=True)
...
if page.is_valid():
    ...
    image_url = page.get('image', None)
    ...
    if not image_url.startswith('http'):
        image_url = urljoin(page['_url'], page['image'])

rawDescription: Fetching the first image from a website that belongs to the post


code:
class LocationAdmin(admin.ModelAdmin):
    form = LocationAdminForm

rawDescription: Filtering cities by country in the django admin edit form


code:
# USING WRITE.TABLE()
utils_package.write_table(xmldf, save_path, sep=",", row_names=False)

# INCLUDING NON-DEFAULT ARGUMENTS
utils_package.write_table(x=xmldf, file=save_path, sep=",", row_names=False)

# INCLUDING ALL ARGUMENTS
utils_package.write_table(xmldf, save_path, False, True, ",", "\r", "NA", ".", False)

rawDescription: How to export DataFrame to csv without index using rpy2?

description: Export DataFrame to csv without index using rpy2


code:
ccvb #original
ccv1 #replace b with 1
ccb1 #replace v with b
ccbv #replace 1 with v

rawDescription: New to Python, replacing characters in a string


code:
for start, stop in np.atleast_2d(signal1Data):
    signal1Indicator[start:stop+1] = 1

rawDescription: Pythonify Some Simple Loops

description: Pythonify Some Simple Loops


code:
import regex

def match_words(words, string):
    return regex.search(r"\b\L<words>\b", string, words=words)

def match(string, include_words, exclude_words):
    return (match_words(include_words, string) and
            not match_words(exclude_words, string))

rawDescription: Python text search library

description: Python text search library


code:
def get_mapping_from_args(*args, **kws):
    if len(args) > 1:
        raise TypeError('Too many positional arguments')
    if not args:
        mapping = kws
    elif kws:
        mapping = _multimap(kws, args[0])
    else:
        mapping = args[0]
    return mapping

rawDescription: Python String Templating with Case Sensitivity


rawDescription: How do I use a C-style for loop in Python?

description: Use a C-style for loop in Python


code:
def loop(start, eind, step, ei):
    for a in range (start, eind, step):
        for b in range(a):
            yield " "
        for c in range(ei+1, a, -1):
            yield a
        for d in range(a, ei):
            yield a
        yield '\n'

def main():
    print("Welcome!  :) ")
    for x in loop(y,0,-1,y):
        print(x,end="")
    for x in loop(2,y+1,1,y):
        print(x,end="")

rawDescription: Returning in for loops python

description: Returning in for loops python


rawDescription: Appending input from csv file to a dictionary including duplicate values for a unique key


code:
u2 = u1.shift(1, freq='d')
u2

rawDescription: How to get an accumulative counting of rows in a data frame?

description: Get an accumulative counting of rows in a data frame


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

plt.ion()
mu, sigma = 100, 15
fig = plt.figure()
x = mu + sigma*np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
for i in range(50):
    x = mu + sigma*np.random.randn(10000)
    n, bins = np.histogram(x, bins, normed=True)
    for rect,h in zip(patches,n):
        rect.set_height(h)
    fig.canvas.draw()

rawDescription: How do I display real-time graphs in a simple UI for a python program?

description: Display real-time graphs in a simple UI for a python program


code: int_columns = [map(int, col) for col in columns[1:]]

rawDescription: reading files as both vertical lists and horizental lists(python 3.2)

description: Reading files as both vertical lists and horizental lists(python 3.2)


code:
class AddCountryForm(forms.ModelForm):
    country = forms.ChoiceField(choices=(('RUS', 'Russia'),))
    class Meta:
       model = Country
       fields = ('name_of_team',)

rawDescription: How to limit the choice in django

description: Limit the choice in django


code:
def my_key_function(original_name):
    return original_name.splitlines()[0].split()[-1]

rawDescription: Alphabetize a List of Multiline Values in Python?


code: lst = eval(s)

rawDescription: What is the fastest way to convert string to array in python?


code:
import contextlib
import lzma
import tarfile

with contextlib.closing(lzma.LZMAFile('test.tar.xz')) as xz:
    with tarfile.open(fileobj=xz) as f:
        f.extractall('.')

rawDescription: How to decompress a .xz file which has multiple folders/files inside, in a single go?

description: Decompress a .xz file which has multiple folders/files inside, in a single go


rawDescription: turn a number in an element of a string into a coefficient python

description: Turn a number in an element of a string into a coefficient python


code:
def listRecursive (d, key, path = None):
    if not path: path = []
    for k, v in d.items ():
        if isinstance (v, OrderedDict):
            for path, found in listRecursive (v, key, path + [k] ):
                yield path, found
        if k == key:
            yield path + [k], v

for path, found in listRecursive (mydict, 'powerpoint_color'):
    print (path, found)

rawDescription: Find a given key's value in a nested ordered dict python


code:
import itertools

def zip_with_scalar(l, o):
    return zip(l, itertools.repeat(o))

rawDescription: Python: zip list with a single element

description: Python: zip list with a single element


code:
from django.db import models
from django.contrib.auth.models import User

class Lecteur(User):
    bibliotheque = models.CharField(max_length=100)
    localisation = models.IntegerField()

rawDescription: Django doesn't load fixtures

description: Django doesn't load fixtures


code:
class Node(object):
    def __init__(self, item, children):
        self.item = item
        self.children = children

def get_class_tree(klass):
    bases = getattr(klass, '__bases__')
    return Node(klass, [get_class_tree(item) for item in bases])

def pprint_node(node, level=0):
    print ("  "*level) + str(node.item)
    for child in node.children:
        pprint_node(child, level+1)

rawDescription: generate a dependency tree of the inheritance hierarchy

description: Generate a dependency tree of the inheritance hierarchy


code:
dd2[1][0]=tuple(ddd2)
dd2

rawDescription: Best Way to Resize Numpy Dtype for Structured data


code:
def flatten_dicts(d):
    for v in d.itervalues():
        try:
            for n in flatten_dicts(v):
                yield n
        except AttributeError:
            yield v

rawDescription: extract multidimensional dictionary to list

description: Extract multidimensional dictionary to list


code: np.where(a == a.min())

rawDescription: How to get array's col and row for specific values in python numpy?

description: Get array's col and row for specific values in python numpy


rawDescription: selecting elements from list according to their labels in the other list

description: Selecting elements from list according to their labels in the other list


rawDescription: Numeric Sort in Python

description: Numeric Sort in Python


code:
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import os
from netCDF4 import Dataset as netcdf_dataset
from cartopy import config

fname = os.path.join(config["repo_data_dir"],
                 'netcdf', 'HadISST1_SST_update.nc'
                 )
dataset = netcdf_dataset(fname)
sst = dataset.variables['sst'][0, :, :]
lats = dataset.variables['lat'][:]
lons = dataset.variables['lon'][:]

fig, ax = plt.subplots(1, 1, figsize=(10,5),
                       subplot_kw={'projection': ccrs.PlateCarree()})

# Add the colorbar axes anywhere in the figure. Its position will be
# re-calculated at each figure resize.
cbar_ax = fig.add_axes([0, 0, 0.1, 0.1])

fig.subplots_adjust(hspace=0, wspace=0, top=0.925, left=0.1)

sst_contour = ax.contourf(lons, lats, sst, 60, transform=ccrs.PlateCarree())

def resize_colobar(event):
    plt.draw()

    posn = ax.get_position()
    cbar_ax.set_position([posn.x0 + posn.width + 0.01, posn.y0,
                          0.04, posn.height])

fig.canvas.mpl_connect('resize_event', resize_colobar)

ax.coastlines()

plt.colorbar(sst_contour, cax=cbar_ax)

ax.gridlines()
ax.set_extent([-20, 60, 33, 63])

plt.show()

rawDescription: Correct placement of colorbar relative to geo axes (cartopy)


code:
d = """name Smith city Boston country USA
name Meier city Berlin ZIP 12345 country Germany
name Grigoriy country Russia"""

keys = {}                                # will collect all keys
objs = []                                # will collect all lines
for line in d.split("\n"):               # split input by linebreak
    ks = [x for x in line.split()[::2]]  # even positions: 0, 2, 4, 6
    vs = [x for x in line.split()[1::2]] # odd positions:  1, 3, 5, 7
    objs.append(dict(zip(ks, vs)))       # turn line into dictionary
    for key in ks:
        keys[key] = True                 # note all keys

print(",".join(keys))                    # print header row
for obj in objs:
    print(",".join([obj.get(k, "") for k in keys]))

rawDescription: convert data to CSV with python

description: Convert data to CSV with python


code:
for i in range(0, clf.best_estimator_.coef_.shape[0]):
    top10 = np.argsort(clf.best_estimator_.coef_[i])[-10:]

rawDescription: Finding optimal feature using Lasso regression in binary classification


code:
def handleListItemClick(event):
    index = event.GetIndex() #this will return the index of the listctrl item that was clicked
    self.notebook.SetSelection(index) #this will open that same index in notebook

rawDescription: wxpython: How to make a tab active once it is opened via an event handler?

description: Wxpython: How to make a tab active once it is opened via an event handler


code:
d={}
for i in range(1,7):
   d['x_{}'.format(i)]=input("Enter data{}  :".format(i))

rawDescription: Defining multiple variables in python via enumeration


code:
x1,x2,y1,y2 = ax.axis()
x1 = min(x_normalised) - 1
x2 = max(x_normalised) + 1
ax.axis((x1,x2,(y1-1),(y2+1)))

#If the above is done, then before set_xticklabels,
#one has to add a first and last value. eg:

nonRepetitive_x.insert(0,x[0]-1) #for the first tick on the left of the graph
nonRepetitive_x.append(x[-1]+1) #for the last tick on the right of the graph

rawDescription: How to assign equal scaling on the x-axis in Matplotlib?

description: Assign equal scaling on the x-axis in Matplotlib


code:
count = 0
sample = {'a' : [False, 'count', 20], 'b' : [False, 'count', 60]}

d = input('give dict key: ')
print('count ' + str(count))
for each in sample:
    if each == d:
        sample[each][0] = True
        locals()[sample[each][1]] += sample[each][2]

print(sample)
print('count ' + str(count))

rawDescription: change global variable through dictionary (python)

description: Change global variable through dictionary (python)


rawDescription: Separate text from nested OrderedDict in Python


code:
def _helper():
   for i in range(1,100):
       for j in range(1,100):
           return
_helper()

rawDescription: break two for loops

description: Break two for loops


code:
for time_period in df['Time'].unique():
  df_group = df[df['Time'] == time_period][['Sample', 'Signal']]
  print(df_group)

rawDescription: Reorganizing a Pandas DataFrame

description: Reorganizing a Pandas DataFrame


code:
def _get_recursive_results(d, iter_key, get_keys, h=None):
    if h is None:
        h = []
    h.append({k:d.get(k) for k in get_keys})
    d2 = d.copy()
    for k in iter_key:
        if not d2:
            continue
        d2 = d2.get(k)
    for td in d2:
        d3 = td.copy()
        for k in iter_key:
            if not d3:
                continue
            d3 = d3.get(k)
        if d3:
            return _get_recursive_results(td, iter_key, get_keys, h)
        h.append({k:td.get(k) for k in get_keys})
    else:
        l = [k for k in h]
        return l

rawDescription: Python Recursive Search of Dict with Nested Keys


code: values

rawDescription: Scrape Yahoo Finance Income Statement with Python


code:
# Find the storage class and call setup (first time only).
storage_class = storage_type.title() + 'Session'
storage_class = globals()[storage_class]
if not hasattr(cherrypy, "session"):
    if hasattr(storage_class, "setup"):
        storage_class.setup(**kwargs)

# Create cherrypy.session which will proxy to cherrypy.serving.session
if not hasattr(cherrypy, "session"):
    cherrypy.session = cherrypy._ThreadLocalProxy('session')

rawDescription: Initializing cherrypy.session early

description: Initializing cherrypy.session early


rawDescription: Matrix indexing in Numpy

description: Matrix indexing in Numpy


code:
def infinite_divide(numerator, denominator):
    if numerator > denominator:
        raise ValueError('This function only returns digits after the decimal')
    while numerator != 0:
        numerator *= 10
        digit, numerator = divmod(numerator, denominator)
        yield digit

rawDescription: python calculate decimal fraction part to arbitrary length

description: Python calculate decimal fraction part to arbitrary length


code:
from distutils.core import setup

setup(name='Some_name',
version='1.0',
author='Author_name',
author_email='abc@xyz.com',
packages=['source']
)

rawDescription: I have created pyd file with SWIG and want it to be installable


code:
mysignal = django.dispatch.Signal(providing_args=["foo", "bar"])

...

class Command(BaseCommand):
    args = '<foo> <bar>'

    def handle(self, foo, bar):

        mysignal.send(sender=self, foo=foo, bar=bar)

rawDescription: Fire Django Signal's from the command line


code:
from operator import itemgetter
getter = itemgetter("name", "description")
print([getter(item) for item in data])
# [('a', '1'), ('b', '2')]

rawDescription: How can I convert list of dictionaries to list of lists?

description: Convert list of dictionaries to list of lists


rawDescription: how to receive regex from command line in python

description: Receive regex from command line in python


rawDescription: Remove all occurrences of a value from a Python list


code:
df1 = pd.DataFrame({1: [1,2,3]})
df2 = pd.DataFrame({1: [1,2,3]})
hash(tuple(tuple(x) for x in df1.values)) == hash(tuple(tuple(x) for x in df2.values))
id(df1) == id(df2)

rawDescription: Memoize a costly computation of a data frame


rawDescription: Adding elements in arrays that fall within a criteria in Python


code: plt.clim(vmin, vmax) # use dark blue for vmin -> red for vmax

rawDescription: Custom colormap and change user range to plot 2D function not defined on the whole range


code:
def faster_polyval(p, x):
    y = np.zeros(x.shape, dtype=float)
    for i, v in enumerate(p):
        y *= x
        y += v
    return y

rawDescription: A faster numpy.polynomial?

description: A faster numpy.polynomial


code:
import gc
gc.collect()

rawDescription: Numpy hstack explodes memory

description: Numpy hstack explodes memory


rawDescription: How can I assign a value to a different column for each row in a dataframe?

description: Assign a value to a different column for each row in a dataframe


code:
import random
my_list = ['A'] * 5 + ['B'] * 5 + ['C'] * 90
random.choice(my_list)

rawDescription: generating random numbers in python with percentage function on what selected value in python

description: Generating random numbers in python with percentage function on what selected value in python


code: ['The maximum in line %d is in column %d' %(linenum, line.split().index(max(line.split()))) for linenum, line in enumerate(open('mytsv.tsv'))]

rawDescription: Python: Identify column that has greatest value


rawDescription: Arranging a list by given order in python for dump into json


code:
from django.template import RequestContext
from django.shortcuts import render_to_response
from pygooglechart import PieChart3D

def pytest(request):
    chart = PieChart3D(250, 100)
    chart.add_data([20, 10])
    chart.set_pie_labels(['Hello', 'World'])
    context = RequestContext(request, {
        'url_to_chart': chart.get_url()
    })
    template = 'path/to/template.html'
    return render_to_response(template, context)

rawDescription: How can I display a pygooglechart in a Django view?

description: Display a pygooglechart in a Django view


code:
def index_tag_query(request):
    tag = request.GET.get('tag', None)
    if tag == "Python":
         ...

rawDescription: Django url regex parameter capturing

description: Django url regex parameter capturing


code:
curr_file = open('myfile','a')
curr_file.write('hello world')
curr_file.close()

rawDescription: Appending lines for existing file in python


code:
def morphology_method(in_data=SAMPLE_DATA, person='1', fill_gap_days=31, printit=False):
    date_format_str = "%m/%d/%Y"
    dat = np.array(in_data)
    dat = dat[dat[:, 0] == person, 1:]  # just this person's data

    # for the intervals of this person, get starting and ending years
    # we assume the data is already sorted
    #start_year = datetime.strptime(dat[0, 0], date_format_str)
    #end_year = datetime.strptime(dat[-1, 1], date_format_str)
    start_times = [datetime.strptime(d, date_format_str) for d in dat[:, 0]]
    end_times = [datetime.strptime(d, date_format_str) for d in dat[:, 1]]
    start_year = start_times[0].year
    end_year = end_times[-1].year

    # create the occupancy array, dilated so that each interval
    # is extended by fill_gap_days to 'fill in' the small gaps
    # between intervals
    YD, OCC = make_occupancy_array(start_year, end_year)
    for (s, e) in zip(start_times, end_times):
        set_occupancy(s, e, YD, OCC, fill_gap_days)

    # return the intervals from OCC after having filled gaps,
    # and trim end dates back to original position.
    consolidated_pos = get_occupancy_intervals(OCC, fill_gap_days)

    # map positions back to date-times
    consolidated_ranges = [(map_position_to_date(s, YD), map_position_to_date(e, YD)) for
                           (s, e) in consolidated_pos]

    if printit:
        print_it(person, consolidated_ranges, date_format_str)

    return consolidated_ranges

rawDescription: How to combine records based on date using python connected components?

description: Combine records based on date using python connected components


code:
for replacement, replacables in replacements.iteritems():
    query = 'update foo set value=? where value in ({})'.format(",".join("?"*len(replacables)))
    c.execute(query, [replacement]+replacables)

rawDescription: Python, SQlite and string substitution

description: Python, SQlite and string substitution


rawDescription: How to convert a string that already looks like a list into a list?

description: Convert a string that already looks like a list into a list


code:
def roll_wsum(g,w,p):
    rsum = pd.rolling_apply(g.values,p,lambda x: np.nansum(w*x),min_periods=p)
    return pd.Series(rsum,index=g.index)

weights = np.array([0.1,0.1,0.2,0.6])
df['wsum'] = df.groupby('ID')['VALUE'].apply(roll_wsum,weights,4)

rawDescription: Is there a way to do a weight-average rolling sum over a grouping?


rawDescription: analyzing a txt file in python by jumping the n_th element of a list

description: Analyzing a txt file in python by jumping the n_th element of a list


code:
def dirty_room(room_file):
    rooms = unpickle_dict(room_file)
    room = random.choice(list(clean_rooms))
    clean_rooms[room] += 1
    pickle_dict(clean_rooms, room_file)

rawDescription: save and update a dictionary

description: Save and update a dictionary


code: X

rawDescription: changing numpy array to float

description: Changing numpy array to float


rawDescription: Find all occurrences of integer within text in Python


code:
def C_selection():
    return raw_input("Select a chapter: ")

rawDescription: menu selection with functions

description: Menu selection with functions


code: "Edgebrook Park, Chicago ","Jun-7 A League of Their Own, Jun-9 It's a Mad, Mad, Mad, Mad World","Edgebrook Park, 6525 North Hiawatha Avenue, Chicago, IL 60646, USA",41.9998876,-87.7627672

rawDescription: python ordered dict issue

description: Python ordered dict issue


code:
lis = range(5)
repr(lis.insert(2, 'null')) # returns None
lis                         # But the list is affected.

rawDescription: List comprehension expression showing none value insted of sublist


code:
b = '\n'.join('\t'.join('%0.3f' %x for x in y) for y in a)
print(b)

rawDescription: convert 2d numpy array to string

description: Convert 2d numpy array to string


code:
d = {}
i = 0
values = []
for i, word in enumerate(sentence.split(" ")):
    if not word in d:
        d[word] = i
    values += [d[word]]

rawDescription: Is there a way to place values onto a preset sentence and replace them if there is a repeated word?


code:
def evaluator(object):
    def __init__(self,func=None,params=None):
        self.func = func
        self.params = params

    def eval(self,alternativeparams=None):
        if alternativeparams is not None:
           params = alternativeparams
        else:
           params = self.params

        if params is not None:
           evaluatedparams = (item() if callable(item) else item for item in params)
        else: evaluatedparams = None

        if func is not None:
           return self.func(*(evaluatedparams or ()))
        else: return evaluatedparams
    def __call__(self, *params):
        return self.eval(params if params else None)

rawDescription: return variable name from outside of function, as string inside python function

description: Return variable name from outside of function, as string inside python function


code:
from timeit import default_timer

start = default_timer()

# do stuff

duration = default_timer() - start

rawDescription: How to create a timer on python

description: Create a timer on python


code:
from random import shuffle

L1 = [[1,2], [3,4], [5,6], [7,8], [9,10]]
match = [9,10]
while L1[0]!=match:
    shuffle(L1)
print(L1)

rawDescription: How to reshuffle a shuffled list in Python

description: Reshuffle a shuffled list in Python


code:
import importlib
globals()['b'] = importlib.import_module('b')
b.myfun()

rawDescription: Import files in python with a for loop and a list of names


code: type(b) is Test1

rawDescription: Determine the type of an object?

description: Determine the type of an object


code:
# hold the groupby result along with index (I take groupby field)
# these basically act as the lookup tables
In [8]: total_fwd_size = df.groupby('m_srcaddr').sum()['m_fwd_bytes'] / 1000

In [9]: total_rev_size = df.groupby('m_srcaddr').sum()['m_rev_bytes'] / 1000

# apply to original dataframe locating the value base on m_srcaddr
In [10]: df["total_fwd_size"] = df["m_srcaddr"].apply(lambda x: total_fwd_size.ix[x])

In [11]: df["total_rev_size"] = df["m_srcaddr"].apply(lambda x: total_rev_size.ix[x])

rawDescription: Create New Columns in dataFrame using existing columns in Panda


code: region_name = my_person.region.name  # navigate a 'relationship' and get its 'name' attribute

rawDescription: setup relationship one-to-one in Flask + SQLAlchemy

description: Setup relationship one-to-one in Flask + SQLAlchemy


code:
A = 5
B = 3
total = A + B
x = A
x = total - x    # toggle
x
x = total - x    # toggle
x
x = total - x    # toggle
x

rawDescription: toggle a value in Python

description: Toggle a value in Python


code:
t = ("b", "c")
x = {(1, t):1, (2, t):2, }

yaml.Dumper.ignore_aliases = lambda *args : True

print(yaml.dump(x))

rawDescription: Avoid references in PyYAML

description: Avoid references in PyYAML


rawDescription: Pandas new column from groupby averages

description: Pandas new column from groupby averages


code: df2.loc[:, 'Sales'] = model.predict(new_x)

rawDescription: Predicting out future values using OLS regression (Python, StatsModels, Pandas)


rawDescription: Is there a good way python to compare complex dictionaries with unkonwn depth & level


code:
s = "Hello"
hex_list = ["{:02x}".format(ord(c)) for c in s]

rawDescription: Python: Read hex from file into list?

description: Python: Read hex from file into list


code:
# -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
from django.test import TestCase

from services.fields import WeekdayField

class WeekdayFieldTests(TestCase):

    def test_7_days(self):
        days = range(WeekdayField.MONDAY, len(WeekdayField.DAY_OF_THE_WEEK)+1)
        for day in days:
            field = WeekdayField()
            self.assertEqual(field.clean(day, None), day)

    def test_no_0th_day_in_the_week(self):
        field = WeekdayField()
        with self.assertRaisesMessage(
            ValidationError,
            expected_message=(
                u"Day number should be between 1 and 7"
            )
        ):
            field.clean(0, None)

    def test_no_13th_day_in_the_week(self):
        field = WeekdayField()
        with self.assertRaisesMessage(
            ValidationError,
            expected_message=(
                u"Day number should be between 1 and 7"
            )
        ):
            field.clean(13, None)

rawDescription: How write unittests to Django CustomField with restricted range?


rawDescription: How to form a string from 2 values

description: Form a string from 2 values


rawDescription: How does np.multiply work?

description: How does np.multiply work


rawDescription: How do I parse out the following HTML in python beautifulsoup?

description: Parse out the following HTML in python beautifulsoup


rawDescription: Key to Value to Key in Python Dictionary


code:
class MyList(list):
    def __contains__(self, item):
        return True

rawDescription: Exists a list where every item is a member?


code:
obj, created = Person.objects.update_or_create(
    first_name='John', last_name='Lennon', defaults=updated_values)

rawDescription: Django: Calling .update() on a single model instance retrieved by .get()?


code:
dealt_cards = random.sample(deck_of_cards, 6)
player1_hand, player2_hand = dealt_cards[:3], dealt_cards[3:]

rawDescription: generate two sets of combination with one list in python

description: Generate two sets of combination with one list in python


code: g.vs['foo'] = [[] for _ in range(10)]

rawDescription: How to assign values to individual elements of python igraph list attributes?

description: Assign values to individual elements of python igraph list attributes


code: return result_string + ' and the ' + last_name

rawDescription: Add 'and' before the last item in a string list


code:
from pprint import pprint
pprint(samples[0])
print(y)

rawDescription: handling too many categorical features using scikit-learn

description: Handling too many categorical features using scikit-learn


code:
key,value
a,1
b,2
c,3
d,4

rawDescription: Appending to the end of a certain line

description: Appending to the end of a certain line


code:
from Cipher import Cipher
x = Cipher("this is key")
"a"==x.decrypt(x.encrypt("a"))
"b"==x.decrypt(x.encrypt("b"))
"c"==x.decrypt(x.encrypt("c"))
x.encrypt("a")==x.encrypt("a")

rawDescription: How AES in CTR works for Python with PyCrypto?


code:
import re
from functools import partial

def to_named_groups(match, regexes):
    group_name = re.escape(match.group(0)[1:-1])
    group_regex = regexes.get(group_name, '.*')
    return '(?P<{}>{})'.format(group_name, group_regex)

def make_regex(key_mask, regexes):
    regex = re.sub(r'\{[^}]+\}', partial(to_named_groups, regexes=regexes),
                   key_mask)
    return re.compile(regex)

def find_matches(key_mask, text, regexes=None):
    if regexes is None:
        regexes = {}
    try:
        return make_regex(key_mask, regexes).search(text).groupdict()
    except AttributeError:
        return None

rawDescription: python match regular expression

description: Python match regular expression


rawDescription: Advanced string parsing in python

description: Advanced string parsing in python


rawDescription: python: Right Click on list menu not showing item selected

description: Python: Right Click on list menu not showing item selected


code:
def someview(request):
   objs = Some.object.filter()
   ctx = {}
   ctx['objs'] = []  # hold your objects
   for i in objs:
      ctx['objs'].append((i,i.date_field < someother_obj.date_field))

   return render(request, 'template.html', ctx)

rawDescription: How to find django timesince greater than an integer

description: Find django timesince greater than an integer


code: Pxx[:, np.greater(np.sum(Pxx, axis=0), 2955)] = 0.

rawDescription: Python - Removing specific frequencies between a range


code:
import textwrap

indentation = ';' + ' ' * 11
result = textwrap.fill(
    input_text, width=80,
    initial_indent=indentation, subsequent_indent=indentation)

rawDescription: In Python, is there a way to insert a line break and spaces every 68 characters of a string?


code:
from sympy import I
complex(I)

rawDescription: .eigenvals creates a new variable

description: .eigenvals creates a new variable


rawDescription: pandas dataframe aggregate - why does it return column names?

description: Pandas dataframe aggregate - why does it return column names


code:
from django import forms

class UserForm(forms.Form):
    email_address = forms.EmailField(widget = forms.TextInput(attrs = {'class':'required'}))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(UserForm, self).__init__(*args, **kwargs)

    def clean_email_address(self):
        email = self.cleaned_data.get('email_address')
        if self.user and self.user.email == email:
            return email
        if UserProfile.objects.filter(email=email).count():
            raise forms.ValidationError(u'That email address already exists.')
        return email

rawDescription: get request data in Django form

description: Get request data in Django form


code: from mybottleapp import application

rawDescription: How to replicate a Python 2.7, Bottle, MongoDB OpenShift application locally in Linux Mint 17?

description: Replicate a Python 2.7, Bottle, MongoDB OpenShift application locally in Linux Mint 17


code:
def mapInToOut(inChar, alphFrom, alphTo):
    index = 0
    found = 0
    for char in alphFrom:
        if(char == inChar):
            found = index #remember it in a variable found
            break
        else:
            index +=1
    outChar = alphTo[found]
    return(outChar)

rawDescription: Generalizing two similar functions into one


code:
for eqnSet in symEqns:
  lambdaFuncs = []
  for eqn in eqnSet:
    func = sp.lambdify(['R_0', 'R_1'], eqn, 'numpy')
    lambdaFuncs.append(func)

  # This seems out of place in your example code: whenever a
  # new row of functions is being processed, you lose all the
  # data from outputList, because you're not storing it anywhere.
  outputList = []
  for row in inputArray:
    results = []
    for func in lambdaFuncs:
      results.append(func(*row))
    outputList.append(results)

rawDescription: Improving Performance - Symbolic function applied to each row of numpy array


code:
fullstrings = set(["BREAKFAST", "LUNCH", "DINNER", ...])
prefixes_by_length = {} # dict of length -> prefix string
...
prefixes_by_length[4] = set(["CORN", "DESK", ...])
prefixes_by_length[5] = set(["BREAD", "TABLE", ...])

rawDescription: Efficiently checking if a word matches patterns in set (Python)


code:
sum_columns = [('sum', name) for name in df.columns.levels[1].tolist()]
df[sum_columns] = df.groupby(axis=1, level=1).sum()
df = df.sortlevel(level=1, axis=1)

rawDescription: Using groupby and apply to add column to each group


code: list(get_tuples(3, 2))

rawDescription: How to generate a set of all tuples of given length and sum of elements?

description: Generate a set of all tuples of given length and sum of elements


code:
def sections(fle):
    with open(fle) as f:
        stp = imap(str.strip, f)
        for line in imap(str.strip, stp):
            tmp = []
            if line.startswith(":50:"):
                for line in stp:
                    if line.startswith(":52A:"):
                        yield "".join(tmp)
                        break
                    tmp.append(line)

rawDescription: Python, optimal way of looping through a file, match two lines after a pattern and then join them


code: (r'object/(?P<page>\d+)/$','listing')

rawDescription: How to make Django pagination search engine friendly?

description: Make Django pagination search engine friendly


code: time = [ish[0] for ish in book]

rawDescription: Replacing loop with List Comprehension instead of loop getting a function to return a new array within the list comprehension


code: df.eq(df.iloc[:, 0], axis=0).all(1)

rawDescription: Pandas Dataframe Find Rows Where all Columns Equal


code:
import fbx

# Create an SDK manager
manager = fbx.FbxManager.Create()

# Create a scene
scene = fbx.FbxScene.Create(manager, "")

# Create an importer object
importer = fbx.FbxImporter.Create(manager, "")

# Path to the .obj file
milfalcon = "samples/millenium-falcon/millenium-falcon.obj"

# Specify the path and name of the file to be imported
importstat = importer.Initialize(milfalcon, -1)

importstat = importer.Import(scene)

# Create an exporter object
exporter = fbx.FbxExporter.Create(manager, "")

save_path = "samples/millenium-falcon/millenium-falcon.fbx"

# Specify the path and name of the file to be imported
exportstat = exporter.Initialize(save_path, -1)

exportstat = exporter.Export(scene)

rawDescription: Convert *.obj to *.fbx with Python FBX SDK


rawDescription: Swap two numbers in list of tuples (python)


code:
s = """

Phone Number:

706-878-8888

"""
regex = re.compile(r'.*(Phone Number:).*?([-\d]+).*', re.DOTALL)
regex.sub(r'\1 \2', s)

rawDescription: Regular Expression HTML Tag Exclusion

description: Regular Expression HTML Tag Exclusion


code: lambda x: list(x)[-1]

rawDescription: matching between two columns and taking value from another in pandas

description: Matching between two columns and taking value from another in pandas


rawDescription: Finding the most common pair, trio, etc. in a list of 20 random numbers, played 100 times


rawDescription: Python - partitioning a list of strings using an equivalence relation


rawDescription: Pandas - restructure longitudinal data in a multilevel df to a single-level column


code:
from scipy.sparse.linalg import bicg

def bicg_solve(M, B):
    X, info = zip(*(bicg(M, b) for b in B.T))
    return np.transpose(X), info

rawDescription: Iterative solving of sparse systems of linear equations with (M, N) right-hand size matrix


code:
args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
in_p=', '.join(map(lambda x: '%s', args))
sql = sql % in_p
cursor.execute(sql, args)

rawDescription: Executing "SELECT ... WHERE ... IN ..." using MySQLdb


code:
sam = {
# Each dict has a new key: 'name'.
  'name': 'Sam',
  'food': 'tortas',
  'country': 'Mexico',
  'song': 'Dream On',
  }
dave = {
  'name': 'Dave',
  'food': 'spaghetti',
  'country': 'USA',
  'song': 'Sweet Home Alabama',
  }
people = [sam, dave]

for data in people:
    # Name is a value in the dict.
    print('Name: ' + data['name'])
    for key, value in sorted(data.items()):
        # Have to avoid printing the name again.
        if 'name' != key:
            print('  {0}: {1}'.format(key.title(), value))

rawDescription: How do I work with a nested dictionary's name?

description: Work with a nested dictionary's name


code:
foo = {
    'bar': lambda: 3
}
eval('bar()', globals(), foo)

rawDescription: How do you do a python 'eval' only within an object context?

description: Do a python 'eval' only within an object context


code: comparison > or_expr > xor_expr > and_expr > shift_expr > a_expr > a_expr + m_expr

rawDescription: Is `1 < 2` a `not_test` in Boolean operation even without the keyword `not`?


code:
def is_bijection(seq1, seq2):
    distinct1 = set(seq1)
    distinct2 = set(seq2)
    distinctMappings = set(zip(seq1, seq2))
    return len(distinct1) == len(distinctMappings) and len(distinct2) == len(distinctMappings)

rawDescription: Find possible bijection between characters and digits


code:
import pandas as pd
data = pd.read_csv('Met.csv')

rawDescription: how to find avg of column of csv file

description: Find avg of column of csv file


rawDescription: How to get a list of Xth elements from a list of tuples?

description: Get a list of Xth elements from a list of tuples


code:
import re
long_string = '"Fifty Shades of Grey" shakeup: Kelly Marcel not returning for Sequel'
long_string = re.sub(r'([A-Z][a-z]+(?=\s[A-Z]))(?:\s([A-Z][a-z]+))+', r'\1-\2', long_string)
long_string

rawDescription: Python to Transforming elements in a list when split


code:
def post(self,request, *args, **kwargs):
#Add a AJAX request check. If it is AJAX, redirect to AJAX function
    if self.request.is_ajax():
        return self.ajax(request)

#===========================================================================
# AJAX
#===========================================================================
def ajax(self, request):
    response_dict= {
        'success': True,
    }
    #Your SQL DROP code here...

    return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json')

rawDescription: Calling a function from a template using javascript


code:
for value in exchangeDict2.itervalues():
    writer.writerow(value)

rawDescription: Unpacking list items from a dictionary & writing to a CSV file


code: writer.writerows((title, intro + tagline) for title, intro, tagline in grouped)

rawDescription: Parse a plain text file into a CSV file using Python


code:
alpha
beta
apple
bagel

rawDescription: ZeroMQ and multiple subscribe filters in Python


code:
from flask import request, render_template, jsonify
@catalog.route('/cinema')
@xhr_request_check('cinema.html')
def cinema():
    cinema = Cinema.query.all()
    return {'cinema_scope': cinema}

rawDescription: Efficient way of handling XHR request in Python Flask


rawDescription: Subset of a Pandas DataFrame keeping MultipleIndex with Condition