code:
p = re.compile(r'(tengig.*?(?:\n+)?\bmtu\b.*?(?:\n+)?\bcarrier-delay\b[^\n]+)', re.MULTILINE | re.IGNORECASE)
test_str = "port0 interface GigabitEthernet0/4/0\n\nport1 interface TenGigabitEthernet0/1/0\n\nlogin delay 2\n\nbfd-template single-hop BDI\n\nip ftp source-interface Loopback0\n\nip tftp source-interface Loopback0\n\ninterface Loopback0\n\ninterface Loopback100\n\ninterface Loopback999\n\ndescription * Loopback interface for management *\n\ninterface TenGigabitEthernet0/0/0\n\nmtu 9216\n\ncarrier-delay msec 0\n\ninterface TenGigabitEthernet0/1/0\n\nmtu 9216\n\ncarrier-delay msec 0\n\ninterface GigabitEthernet0/4/0\n\nmtu 9216\n\ninterface GigabitEthernet0/4/1\n"

rawDescription: Python regex to find substring

description: Python regex to find substring


code:
import lxml.etree as etree
import lxml.builder as builder

nsmap = {
    'svg': 'http://www.w3.org/2000/svg',
    'xlink': 'http://www.w3.org/1999/xlink',
}

E = builder.ElementMaker(
    namespace='http://www.w3.org/2000/svg',
    nsmap=nsmap)

root = (
    E.root(
        E.g(
            E.g(
                E.g(id = "route_1_edge" )))))

print(etree.tostring(root, pretty_print=True))
print(root.xpath('./svg:g/svg:g/svg:g[@id="route_1_edge"]', namespaces=nsmap))
print(root.xpath('./svg:g/svg:g/svg:g[starts-with(@id,"route_1")]', namespaces=nsmap))

rawDescription: Python lxml xpath XPathEvalError: Invalid expression -- why?


code: array.append(x * y * 37000.0)

rawDescription: Iterating through multiple arrays

description: Iterating through multiple arrays


rawDescription: append 2dim arrays to one array

description: Append 2dim arrays to one array


rawDescription: How do I print a key without value from a dictionary that has multiple keys

description: Print a key without value from a dictionary that has multiple keys


code: return render(request, 'your_view_file', context_dict)

rawDescription: How can I fill the table? (Python, Django)

description: Fill the table? (Python, Django)


code:
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = [
    os.path.join(PROJECT_ROOT, "templates"),
]

rawDescription: Django settings.py: Separate local and global configuration


code:
pathTuple = tuple(int(x) for x in path2 )
G.add_path([path[:i+1] for i in range(0, len(path))])

rawDescription: Node frequency using networkx

description: Node frequency using networkx


code: patt = Word(alphas)("desc") + OneOrMore(Group(integer*4 + Suppress(',')))("numgroups")

rawDescription: How can I build a regular expression which has options part

description: Build a regular expression which has options part


rawDescription: Create constrained random numbers?

description: Create constrained random numbers


code:
import re

replchars = re.compile(r'[\n\r]')
def replchars_to_hex(match):
    return r'\x{0:02x}'.format(ord(match.group()))

replchars.sub(replchars_to_hex, inputtext)

rawDescription: Show non printable characters in a string


code:
from selenium.webdriver.support.select import Select

adults = Select(driver.find_element_by_id("adults-number"))
adults.select_by_visible_text("4")

rawDescription: How to select a value from a drop down in python

description: Select a value from a drop down in python


code: np.transpose([list1, list2, list3])

rawDescription: Python converting lists into 2D numpy array


code:
def run(self):
    job = None
    while job!='kill':
        job = self.job_queue.get()
        if job!='kill':
            indx_j, x_j = job
            #Note this is the process which really needs access to the X array.
            self.x[indx_j] += x_j
        self.job_queue.task_done()

rawDescription: Assembling Numpy Array in Parallel

description: Assembling Numpy Array in Parallel


rawDescription: using scipy.integrate.odeint with dictionary [Python]

description: Using scipy.integrate.odeint with dictionary [Python]


code: ord('C')

rawDescription: how to represent a number value as a string in python?

description: Represent a number value as a string in python


code:
iface = object_XXObjManager._oleobj_.QueryInterface(pythoncom.IID_IDispatch)
iface_Communications = win32com.client.CastTo(iface,"XXObjCommunications")
connection_XXObjCommunications = win32com.client.Dispatch(iface_Communications)

rawDescription: python port comtypes to win32com

description: Python port comtypes to win32com


code:
import cv2
img  = cv2.imread("image name")
cv2.imshow("window name", img)
cv2.waitKey(0)

rawDescription: No highgui in python

description: No highgui in python


rawDescription: Quickly append value to a list

description: Quickly append value to a list


code:
import subprocess

curl_args = ['curl', '-H', 'Content-Type: application/json', '-u', 'username:password',
             '-d', '{ "name":"something" }', 'https://xxxxxxxx']
curl_output = subprocess.check_output(curl_args)

rawDescription: using testrail api in python script

description: Using testrail api in python script


code:
def apply_function(particle):
    for char, function in char_function_dict.items():
        if char in particle:
            function()

rawDescription: Expressions in a dictionary mapping

description: Expressions in a dictionary mapping


rawDescription: how to set the index page in django like http://127.0.0.1:8000/

description: Set the index page in django like http://127.0.0.1:8000/


code:
#!/usr/bin/env python

from fabric.api import *
import fabric.main

def do():
    local('echo "Hello World"')

if __name__ == '__main__':
    fabric.main.main(fabfile_locations=[__file__])

rawDescription: executing standalone fabric script by calling it by its name, without the .py extension

description: Executing standalone fabric script by calling it by its name, without the .py extension


rawDescription: Multiplying across in a numpy array

description: Multiplying across in a numpy array


rawDescription: Scrapy - get multiple urls from one link


rawDescription: Replacing a string by a string with backslashes


rawDescription: Regular expression to match 3 capital letters followed by a small letter followed by 3 capital letters?


code: Followers:  ['10,623 Followers']

rawDescription: Grabbing a specific value from a webpage using LXML


code: stats = [summ for summ in data['playerStatSummaries']]

rawDescription: Python 3: Iterating over a dictionary

description: Python 3: Iterating over a dictionary


code:
def get_context_data(self, **kwargs):
    #Get the context
    context = super(TeacherCreation, self).get_context_data(**kwargs)
    #Adding the second form
    context['user_form'] = self.second_form_class
    return context

rawDescription: Django User Model one-to-one with other model and Forms


code:
lbl = Label(wind, bg = 'white', text = gravitation(oval1, oval2))
lbl.pack(padx=5, pady=5)
# Put this on its own line so that there are no errors since 'lbl' isn't defined yet
gravitation(oval1, oval2)

rawDescription: Update Tkinter Label

description: Update Tkinter Label


rawDescription: How to put a blank space in a list?

description: Put a blank space in a list


code:
import pygame
from pygame.locals import *

pygame.init()
clock = pygame.time.Clock()
FPS = 30

width = 800
height = 600

screen = pygame.display.set_mode((width, height), 0, 32)

class player:
    def __init__(self, init_pos = (10,10), init_ani_speed = 10):
        self.x = init_pos[0]
        self.y = init_pos[1]

        self.ani_speed_init = init_ani_speed
        self.ani_speed = self.ani_speed_init

        self.ani = []
        # nux-style code here! :)
        # self.ani.append(glob.glob("game\\redplayer_01*.png"))
        # self.ani.append(glob.glob("game\\redplayer_02*.png"))

        self.ani.append("./ani/super_neko_01.png")
        self.ani.append("./ani/super_neko_02.png")

        self.ani_max = len(self.ani)-1
        self.ani_pos = 0

        self.img = []
        for item in self.ani:
            self.img.append(pygame.image.load(item))

        self.update(0)

    def update(self, pos = 0):
        # init: starts at 10, immediately blits self to screen at x,y
        if pos != 0:
            self.ani_speed -= 1
            self.x += pos # move right by pos pixels
            if self.ani_speed == 0:
                self.ani_speed = self.ani_speed_init
                if self.ani_pos < self.ani_max:
                    self.ani_pos += 1
                else:
                    self.ani_pos = 0

        tempSurf = self.img[self.ani_pos]
        screen.blit(tempSurf,(self.x, self.y))

player1 = player()

# Main Game Loop
quit = False
while quit == False:
    for event in pygame.event.get():
        if (event.type == KEYUP):
                    if (event.key == K_q):
                        quit = True

    if quit == False:
        player1.update(1)
        pygame.display.update()
    clock.tick(FPS)

pygame.quit()

rawDescription: My walk animation in pygame isnt working


code: d = dict(zip(array_of_strings, array_of_samples))

rawDescription: convert two different arrays to a dictionary

description: Convert two different arrays to a dictionary


code:
with open('inFile.csv', 'rb') as ids_file:
    reader = csv.reader(ids_file)
    next(reader, None)  # skip the first row
    ids = {r[0] for r in reader}

rawDescription: print columns matching a header value

description: Print columns matching a header value


code:
class PeriodicCallback(object):
    def __init__(self, callback, callback_time, io_loop=None):
        self.callback = callback
        if callback_time <= 0:
            raise ValueError("Periodic callback must have a positive callback_time")
        self.callback_time = callback_time
        self.io_loop = io_loop or IOLoop.current()
        self._running = False
        self._timeout = None

    def start(self):
        """Starts the timer."""
        self._running = True
        self._next_timeout = self.io_loop.time()
        self._schedule_next()

    def _run(self):
        if not self._running:
            return
        try:
            self.callback() # Your function runs here.
        except Exception:
            app_log.error("Error in periodic callback", exc_info=True)
        self._schedule_next()  # Schedule next run after calling self.callback

    def _schedule_next(self):
        if self._running:
            current_time = self.io_loop.time()
            while self._next_timeout <= current_time:
                self._next_timeout += self.callback_time / 1000.0
            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run) # The callback is actually scheduled with the ioloop here.

description: Unexpected tornado.ioloop.PeriodicCallback behavior


code:
text = 'dimension implies direction implies measurement implies the more and the less'
sentence_dict = {}
prev = ''
for word in text.split():
    if word not in sentence_dict:
        sentence_dict[word] = []
    sentence_dict[word].append(prev)
    prev = word

print(sentence_dict)

rawDescription: Python - sentence to a dictionary

description: Python - sentence to a dictionary


code: df['unique_id'] = df.hh_id.astype(str) + '_' + df.pno.astype(str)

rawDescription: Create unique ID from the existing two columns, python


code:
def match_date(abb_wk_dy, day_date, abb_mon):
    dte = "{} {} {}".format(abb_wk_dy.capitalize(), day_date, abb_mon.capitalize())
    start = datetime.strptime(dte, "%a %d %b")
    greatest = None
    while start <= datetime.now():
        start +=  timedelta(days=30)
        start = start.strptime("{} {} {}".format(start.year, start.month, day_date), "%Y %m %d")
        if start.strftime("%a %d %b") == dte:
            greatest = start
    return greatest

rawDescription: string to date in python with the greatest possible year when dow is given

description: String to date in python with the greatest possible year when dow is given


rawDescription: Issue with using the chr() method to add \x to characters in a list


code: datediff = help.data['HL_DATE'] - help.data['help_beg_date']

rawDescription: How to create a binary column a timedelta and a list of bins

description: Create a binary column a timedelta and a list of bins


code:
[i.max(axis=0) for i in l]
[i.max(axis=1) for i in l]

rawDescription: column max with list of matrices

description: Column max with list of matrices


code:
model = hmm.GMMHMM(n_components=3, n_iter=100, init_params="smt")
model.gmms_ = [sklearn.mixture.GMM(),sklearn.mixture.GMM(),sklearn.mixture.GMM()]

rawDescription: HMMlearn Gaussian Mixture: set mean, weight and variance of each mixture component


code:
s = "!MDCNTL\n  !GENERIC .... "
re.findall(r'(!(?!END)\w+)\s+(.*?)\s+(!END)', s, flags=re.DOTALL)

rawDescription: Regular Expression in Python - about a Specific Case


code:
def test_function():
    test_variable = 1
    return test_variable

rawDescription: django - calling functions form one file to another

description: Django - calling functions form one file to another


code: help(sorted)

rawDescription: Sort list containing both lists and scalars


code: assert "www.stackoverflow.com" in driver.current_url

rawDescription: python selenium phantomJS new tab not working

description: Python selenium phantomJS new tab not working


code:
mapped = "".join(map(str, bits))
[int(mapped[i:i+8], 2) for i in range(0, len(mapped), 8)]

rawDescription: Python bit list to byte list

description: Python bit list to byte list


rawDescription: How do I group this list of dicts by the same month?

description: Group this list of dicts by the same month


code:
from collections import namedtuple
Record = namedtuple("Record","IP NoIP IPV LenIP FirstIP SecondIP")
Record._asdict(Record._make(struct.unpack(">LbbbLL",payload[6:])))

rawDescription: Dynamically assign values - python

description: Dynamically assign values - python


code:
class BaseView(TemplateView):
   template_name= None
   role= None
   def get(self, request, *args, **kwargs):
        if request.user is not None and role is "AUTHENTICATE":
            return super(BaseView, self).get(request, *args, **kwargs)
        else:
            raise Exception('user is not logged in')

rawDescription: Django Url group only for Authenticated Users


code: dates = []

rawDescription: Having some problems printing out an array in Python3


code: out.write(datName + "\n")

rawDescription: write to file in python3

description: Write to file in python3


code:
class Member(models.Model):

    name = models.CharField(max_length=30)
    record = models.CharField(max_length=200, blank=True, null=True)
    pub_date = models.DateTimeField('date', blank=True, null=True)

class Data(models.Model):

    member = models.ForeignKey(Member)
    dob = models.CharField(max_length=200, blank=True, null=True)
    event = models.CharField(max_length=200, blank=True, null=True)
    description = models.CharField(max_length=200, blank=True, null=True)
    gender = models.CharField(max_length=200, blank=True, null=True)

    def save(self, *args, **kwargs):

        member, _ = Member.objects.get_or_create(name = self.name)
        # can update member here with other fields that relate to them
        self.member = member
        super(Data, self).save(*args, **kwargs)

rawDescription: Can I use JSON data to add new objects in Django?

description: Use JSON data to add new objects in Django


code:
from collections import defaultdict

filetypecounter = defaultdict(int)
filetypecounter[filetype] += 1

rawDescription: Set value in dictionary if value not there?


code:
def AdjustWindow(self):
  self.move(self.x, self.y)

rawDescription: Passing window name as parameter to a class


code:
str = 1
del str
str(127)

rawDescription: Overloaded or rewritten str() function in Python


code:
pairs = {'A':'T', 'C':'G', 'T':'A', 'G':'C'}
codonsA = ['AAG', 'TAC', 'CGG', 'GAT', 'TTG', 'GTG', 'CAT', 'GGC', 'ATT', 'TCT']
codonsB = ['TAA', 'CTA', 'AAC', 'TTC', 'AGA', 'CCC', 'CCG', 'GTA']
list(codons_pair(pairs, codonsA, codonsB))

rawDescription: Using Dictionary to match codons

description: Using Dictionary to match codons


code:
if version is f:
      APP_VER = 'APP_FREE'
elif version is p:
      APP_VER = 'APP_PAID'

rawDescription: Assign dynamic key string in python

description: Assign dynamic key string in python


rawDescription: Python stdout logging: terminal vs bash file


rawDescription: Signal Compressing

description: Signal Compressing


code:
interger = int((input("Enter a Interger Value")))
Product = int((input("Enter a Product Value")))
intergerValues = [interger,]
productValues = [Product,]
#...

rawDescription: first user input being ignored python

description: First user input being ignored python


code:
data = read_csv('some.csv')
new_list = list(islice(data, LIMIT))
# call a func to create xml file with data
# do something with remaining `data`

rawDescription: take next n lines from a file until EOF reached

description: Take next n lines from a file until EOF reached


rawDescription: How do I do variable variables in Python?

description: Do variable variables in Python


code:
d = {}
d.setdefault('1', []).append('x')
d.setdefault('1', []).append('y')
d.setdefault('1', []).append('z')
d

rawDescription: python dictionary adding to an existing key

description: Python dictionary adding to an existing key


rawDescription: Pythonic way to append multiple values to a list


code:
def f(values, x):
    return {i % x for i in values}

rawDescription: Most idiomatic way of applying modulo to list in python


code:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2016)

C0 = list('ABCDEF')
C2 = np.random.randint(20000, size=(len(C0), 3))
width = 1.0
C1 = ['foo', 'bar', 'baz']
ind = np.linspace(-width, width, len(C1))

colorsArr = plt.cm.BuPu(np.linspace(0, 0.5, len(C2)))
fig = plt.figure(figsize=(11,11))
ax = fig.add_subplot(1, 1, 1)

prevBar = 0
for height, color, label in zip(C2, colorsArr, C0):
    h = ax.bar(ind, height, width, bottom=prevBar, color=color, label=label)
    prevBar = prevBar + height

plt.ylabel('Home Category')
plt.title('Affinity - Retail Details(Home category)')

# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(width/2.0) for i in ind]
# set the x ticks with names
plt.xticks(tick_pos, C1)
plt.yticks(np.arange(0,70000,3000))

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')

plt.show()

rawDescription: Reverse the order of legend

description: Reverse the order of legend


code:
def log_add2(logA, logB):
    if logA < logB:
        return log_add2(logB, logA)
    return numpy.logaddexp(0,logB-logA)+logA

rawDescription: Numeric function for log of sum in Python


code:
from django.conf import settings
admin_emails = [v for k,v in settings.ADMINS]

rawDescription: E-Mail Site Admins in Django without using mail_admins()


code:
dict(freq)
sorted(freq.keys(), key=lambda k: (-freq[k], text.index(k)))
dict(zip(ranks, range(1, len(ranks)+1)))

rawDescription: Bigrams and ranks of words

description: Bigrams and ranks of words


rawDescription: Python 3 - A Specific Operation on a List


code:
class One(...):
    ...
    self.lb1.bind('<<ListboxSelect>>', self.other_class.lookup)

rawDescription: python / tk - affecting widget in other class

description: Python / tk - affecting widget in other class


code:
translations = elems[1].strip().strip('/').split('/')
#strip the spaces, then the first and last slash,
#then split on the slashes

rawDescription: python regex unicode - extracting data from an utf-8 file

description: Python regex unicode - extracting data from an utf-8 file


rawDescription: Spawn processes using host file with mpi4py


rawDescription: How to scrape XML with Python?

description: Scrape XML with Python


code:
from datetime import date

# date() takes in year, month, day args
date_lst = [(date(int(q[3:]), 3 * int(q[1]) - 2, 1), v)
            for q, v in lst]

rawDescription: Sorting list of tuples by first element of each tuple - Python 2.7


code:
from collections import defaultdict

class mydefaultdict(defaultdict):
    def __missing__(self, key):
        self[key] = value = self.default_factory(key)
        return value

# pass 'name' to the dictionary
value = mydefaultdict(lambda name: {'name': name, 'data': []})
key = []

for x in l:
    key.append(x[0])
    for k, v in x[1].items():
        value[k]['data'].append(v)

rawDescription: Get data from dict by using for-loop in Python


code:
def run_tests(self, url, outqueue):
    outqueue.put("Running test #1...")
    self.webtester.urlopen(url)
    outqueue.put("Running test #2")
    self.webtester.test2()
    outqueue.put(sentinel)

rawDescription: Run thread from Tkinter and wait until it's finished


code:
import scipy.optimize as optimize

def func(x):
    return -x**3+1

# This finds the value of x such that func(x) = x, that is, where
# -x**3 + 1 = x
print(optimize.fixed_point(func,0))
# 0.682327803828

rawDescription: Solve this equation with fixed point iteration


rawDescription: Python: How to remove string from string


code:
env = Environment()

def h(env):
    x = env.Program("hello1", "hello1.c")
    y = env.Program("hello2", "hello2.c")
    return x,y

def h3(env):
    return env.Program("hello3", "hello3.c")

env.Alias("h", h(env))
env.Alias("h3", h3(env))
Default(None)

rawDescription: Dividing SConstruct code into set of aliases; no code called by default


code:
import os

def filter_dirs(dirs=[]):
    result = []
    for dir in dirs:
        files = os.listdir(dir)
        file_a = 'a.shp' in files
        file_b = 'b.shp' in files
        if file_a or file_b:
            result.append({'dir':dir, 'file_a':file_a, 'file_b':file_b})
    return result

rawDescription: Locating files conditional on file names in python


code: d = dict([item.split('=', 1) for item in a])

rawDescription: Can I avoid such cumbersome list comprehension

description: Avoid such cumbersome list comprehension


code: (name, view, id), tokens = k[:3], k[3:]

rawDescription: How do I unpack a list with fewer variables?

description: Unpack a list with fewer variables


code: value = [x/divisor for x in numberstuple]

rawDescription: how do you divide each element in a tuple by an int

description: Divide each element in a tuple by an int


code:
import re

def version_from(filename, pattern=r'(\d+[\-\.]?)*\d+'):
    match = re.search(pattern, filename)
    if match:
        return match.group(0)
    else:
        return None

rawDescription: extract a pattern from different string in Python

description: Extract a pattern from different string in Python


code: t = Task("Task_{0}".format(i), "FUNCTION", id2, "task{0}_types".format(i), None)

rawDescription: Passing formatted strings to functions as arguments


code: avg_V = V.mean()

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


code:
count = range(0,6)
count

rawDescription: Python: Append values to list without for-loop


code:
def next(value, arg):
    try:
        return value[int(arg)+1]
    except:
        return None

rawDescription: Django templates: accessing the previous and the following element of the list


rawDescription: Flipped an array and reversing every second row


code:
res = np.vstack(a)
res3d = res[None, ...]            # option 1 - ellipsis
res3d = res[None, :, :]           # option 2
res3d = np.expand_dims(res, 0)    # option 3 - using np.expand_dims

rawDescription: How to convert a array of dimension 3 * 200 * 120 into a 1*600 *120 in python?

description: Convert a array of dimension 3 * 200 * 120 into a 1*600 *120 in python


code:
import numpy
a = numpy.linspace(-1,1,20)
a.shape
a[None,:,None].shape
b = a[None,:,None] # this is a 3D array, but with the first and third dimension being "empty"
c = a[:,None,None] # same, but last two dimensions are "empty" here
d=b*c
d.shape # only the last dimension is "empty" here

rawDescription: numpy - evaluate function on a grid of points

description: Numpy - evaluate function on a grid of points


code:
def fib(n):
  def fib_help(a, b, n):
    return fib_help(b, a+b, n-1) if n > 0 else a
  return fib_help(0, 1, n)

rawDescription: Tail Recursion Fibonacci

description: Tail Recursion Fibonacci


code:
def withdraw(self, amount):

    if self.money - amount < 0:
        self.penalty += 5

rawDescription: Bank account Classes. How to make it more powerful/efficient? (OOP)


code: session.query(*[c for c in User.__table__.c if c.name != 'password'])

rawDescription: Retrieving all columns but some with SQLAlchemy


rawDescription: Explain the code function in call by object


code:
class MyForm(forms.Form):
    def __getitem__(self, name):
        boundfield = super(forms.Form,self).__getitem__(name)
        boundfield.foo = "bar"
        return boundfield

rawDescription: Attaching additional information to form fields


rawDescription: Django if value is in list

description: Django if value is in list


code:
# our matrix must be n x n with n even.
n = 6

# Create n x n matrix.
head = [i for i in xrange(1, n + 1)]   # contains values from 1 to n.
zeros = [0 for i in xrange(1, n-1)]    # zeros
tail = [i for i in xrange(n, 0, -1)]   # contains values from n to 1.

# Add head and zeros until tail.
MATRIX = [([j] + zeros + [(n+1)-j]) if j != 1 else head for j in xrange(1, n)]
# Add tail
MATRIX.append(tail)

rawDescription: Numbers in a Matrix

description: Numbers in a Matrix


code:
import numpy as np
np.setdiff1d(lst1,lst2) # Output as an array
np.setdiff1d(lst1,lst2).tolist() # Output as list

rawDescription: What is the Matlab equivalent to Python's `not in`?


code: [my_tuple[isinstance(x,basestring)].append(x) for x in a_list]

rawDescription: How to divide a tuple into two in pythonic way

description: Divide a tuple into two in pythonic way


code:
from django import forms

from .models import Model1, Model2

class MultipleModelChoiceForm(forms.Form):
    select = forms.ChoiceField(choices=[])

    def __init__(self, *args, **kwargs):
        super(MultipleModelChoiceForm, self).__init__(*args, **kwargs)
        choices = []
        for obj1 in Model1.objects.all():
            choices.append((obj1.name, obj1.description))
        for obj2 in Model2.objects.all():
            choices.append((obj2.name, obj2.description))
        self.fields['select'].choices = choices

rawDescription: How do I populate a ModelChoiceField from two Models

description: Populate a ModelChoiceField from two Models


code:
lst1 = MyList(list)
lst2 = MyList(int)

rawDescription: How to make an iterable class in Python in which only a specific type is allowed to be the element?

description: Make an iterable class in Python in which only a specific type is allowed to be the element


code:
my_team = Team("Monty Python")
p_info = [("Adam", 10e5), ("Joe-bob", -1)]
participants = [Participant(name, level) for name, level in p_info]

for participant in participants:
    my_team.add_participant(participant)
    # say that 10 times fast....

In [1]: [p.name for p in my_team.participants]
Out[1]: ["Adam", "Joe-bob"]

rawDescription: Add an object of one class to an object of another class in python


rawDescription: Switch between assignments to different variables in python? With ternary operator?


code: len(string)

rawDescription: Count letters in string python

description: Count letters in string python


code:
import ast

thelist = [ast.literal_eval(line) for line in open('file.txt', 'r')]

rawDescription: Strip outside quotes from text when writing to list in Python


code:
class Foo(object):
    pass

def foo_singleton_factory(_singlton = Foo()):
    return _singleton

a = foo_singleton_factory()
b = foo_singleton_factory()
print (a is b)

rawDescription: issue with singleton python call two times __init__

description: Issue with singleton python call two times __init__


code:
engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
session = sessionmaker(bind=engine)

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    street = Column(String, nullable=False)
    city = Column(String, nullable=False)
    # you are missing some fields you'll need eventually
    state = Column(String, nullable=False)
    zip_code = Column(String, nullable=False)  # this can be an int if you don't have to worry about Canadian zips which have letters in them
    user = relationship('User', back_populates="address")

    def __init__(self, street, city, state, zip_code, user):
        self.street = street
        self.city = city
        self.state = state
        self.zip_code = zip_code
        self.user = user

    def insert(self, session):
        #   INSERT
        session.add(self)
        session.commit()

rawDescription: Python: define object variable without initialization


rawDescription: Transform string into dictionary (with additional constraints)


code:
#!/usr/bin/env python
import sys; print(sys.version_info)

rawDescription: The Python Windows launcher isn't reading `py.ini`


code: return self.insert(key, root=tmp.left)

rawDescription: Python recursion and return statements

description: Python recursion and return statements


code:
for key,val in get_args.items():
    do_something(val)

rawDescription: How can i grab all url patrameters in django

description: Grab all url patrameters in django


code: my_turtles = [Turtle(..., ..., ...) for i in range(num_turtles)]

rawDescription: How can I name my objects in Python?

description: Name my objects in Python


code:
import numpy as np

A = np.array([[1, 2 ],[2, 3]])   # Input
A_new = np.lib.pad(A, ((0,1),(0,2)), 'constant', constant_values=(0)) # Output

rawDescription: python - increase array size and initialize new elements to zero

description: Python - increase array size and initialize new elements to zero


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--aaa', default=1, dest='first_entry')
parser.add_argument('command', nargs=argparse.REMAINDER)
parser.parse_args(['-a', '3', 'someApplication', '-ab', '4'])

rawDescription: Argparse to match the first option entry only


code:
def strange_sort(seq):
    """
    Sorts digitstrings (by integer value) and non-digitstrings in a
    sequence among themselves, preserving the original ds/non-ds
    signature.
    """
    numbers = iter(sorted((elem for elem in seq if elem.isdigit()), key=int))
    words = iter(sorted(elem for elem in seq if not elem.isdigit()))
    final = [next(numbers if elem.isdigit() else words) for elem in seq]
    return final

rawDescription: How to sort and keep the integrity of the list?

description: Sort and keep the integrity of the list


code:
plt.scatter(x, y, c=t, cmap='viridis')
plt.colorbar()
plt.show()

rawDescription: Scatter plot and Color mapping in Python


code:
tree = etree.XML('<c/>TAIL<d><e><f/></e></d>')
node_b = tree.xpath('/a/b')[0]
node_d = tree.xpath('/a/d')[0]
node_a = tree.xpath('/a')[0]
# Manually move text
node_a.text = node_b.tail
node_b.tail = None
node_d.append(node_b)
etree.tostring(tree)
# Now TAIL text stays within its old place

rawDescription: Move an entire element in with lxml.etree


code:
fname = raw_input()
if hasattr(shell, fname):
    func = getattr(shell, fname)
    result = func()
else:
    print('That function is not defined.')

rawDescription: exposing the inner methods of a class, and using them

description: Exposing the inner methods of a class, and using them


code:
import uuid
import base64
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
from userena.models import UserenaLanguageBaseProfile
from userena.utils import user_model_label

class Profile(UserenaLanguageBaseProfile):
    """ Default profile """

    user = models.OneToOneField(User,
                                unique=True,
                                verbose_name=_('user'),
                                related_name='profile')
    referral_code = models.CharField(max_length=300, blank=True, null=True)

    def get_absolute_url(self):
        return u'/profile/show/%d' % self.id
    def generate_verification_code(self):
        # Generate user's verification code
        # TODO: Move this to the model
        return base64.urlsafe_b64encode(uuid.uuid1().bytes.encode("base64").rstrip())[:25]

    def save(self, *args, **kwargs):
        """
        If this is a new user, generate code.
        Otherwise leave as is
        """
        if not self.pk:
            self.referral_code = self.generate_verification_code()
        elif not self.verification_code:
            self.referral_code = self.generate_verification_code()

        return super(Profile, self).save(*args, **kwargs)

rawDescription: Unique referral code generate in django

description: Unique referral code generate in django


rawDescription: How to determine 'word' size in Python

description: Determine 'word' size in Python


code:
dic = {'general':
        {'pH_1': False,
        'pH_2': False,
        'pH_3': False,
        'pH_4': False,
        'response_time': 10,
        'base_concentration': 5000,
        'data_path': '/home/moritz/data/'
        }}
[dic['general'][val] for val in sorted([value for value in dic["general"] if value.startswith("pH")],key = lambda x:int(x[3:]) )]

rawDescription: kivy settings: pythonic way of dealing with list of values

description: Kivy settings: pythonic way of dealing with list of values


code: string.replace("bla", "a", "b")

rawDescription: Python 2.7: replace method of string object deprecated


code:
messages = zip(message, newkeyword)
positions = [(alphabet.find(m), alphabet.find(n)) for m, n in messages]
sums = [(a, b, a + b, "{}+{}".format(a,b)) for a, b in positions]

rawDescription: How to store multiple numbers and then add to each individual one

description: Store multiple numbers and then add to each individual one


code:
links = soup.find_all('a', {'class': ['btn', 'btn-gray']})
results = [link['href'] for link in links if 'More Info' in link.text]

rawDescription: Beautiful soup - capture all links with a certain class or text


code:
def count_prime_terms(n):
    ''' Count the number of primes terms in a Collatz sequence '''
    if n not in lookup:
        if n % 2:
            next_n = n * 3 + 1
        else:
            next_n = n // 2

        lookup[n] = count_prime_terms(next_n) + is_prime(n)
    return lookup[n]

rawDescription: finding the lowest collatz sequence that gives more that 65 primes

description: Finding the lowest collatz sequence that gives more that 65 primes


code:
from google.appengine.api.app_identity import get_application_id
appname = get_application_id()

rawDescription: Name of Current App in Google App Engine (Python)


code:
from itertools import chain,izip_longest
words = ('janice','tanice','practice')
''.join(chain.from_iterable(izip_longest(*words,fillvalue='')))

rawDescription: Python: Unpack individual strings from tuple using Unpacking asterisk argument


code:
z = y.header
z._parent = y

rawDescription: Reference counting for SWIG-ed C structs containing complex types doesn't seem to work as expected


code: PrintFrom("x","abcxdef")

rawDescription: Python - Print all items in a string from first instance of item onwards


code: result = 2 + 2 # Adding 2 + 2

rawDescription: Proper styling for long If statements

description: Proper styling for long If statements


code:
unicode_text = bytestring.decode(character_encoding)
bytestring = unicode_text.encode(character_encoding)

rawDescription: Python - How can I change bytes in a file


code: [(sl.start, sl.stop) for sl in my_slice]

rawDescription: How to get coordinates from a numpy slice object

description: Get coordinates from a numpy slice object


code:
from django.contrib import admin

from .models import *

def run(self, request, queryset):
    id=request.POST.get('_selected_action')
    siteObj=self.model.objects.get(pk=id)
    self.message_user(request, "Running: " + siteObj.script)
    execfile(siteObj.script)
run.short_description = "Run the script"

class SiteAdmin(admin.ModelAdmin):
    actions = [run]
    model = Site

# Register your models here.
admin.site.register(Site, SiteAdmin)

rawDescription: Django 1.9: Add a custom button to run a python script on clicking in admin site of a app/model


code:
results = dictfetchall(cursor)
json_results = json.dumps(results)

rawDescription: how to get all mysql tuple result and convert to json

description: Get all mysql tuple result and convert to json


cmd:
python
-u
/path/to/convert.py $file

rawDescription: Sublime Text Markdown-to-HTML-email

description: Sublime Text Markdown-to-HTML-email


code:
from functools import partial

import pyximport; pyximport.install() # pip install cython
from bpp8to10 import convert # bpp8to10.pyx

f_in = 'foreman_cif.yuv'
f_out = 'py_10bpp.yuv'

def main():
    with open(f_in, 'rb') as fd_in, open(f_out, 'wb') as fd_out:
        for chunk in iter(partial(fd_in.read, 8192), b''):
            fd_out.write(convert(chunk))
main()

rawDescription: python performance dealing with binary files

description: Python performance dealing with binary files


code:
import timeit
print("chain, list",timeit.timeit(r"""
with open('file.txt') as f:
    lines = chain.from_iterable([l.replace(r'"','').rstrip('\n').split('\t',1) for l in f])""",setup="from itertools import chain",number=1000))
print("flat       ",timeit.timeit(r"""
with open('file.txt') as f:
    lines = [l.replace(r'"','').rstrip('\n').split('\t',1) for l in f]""",setup="from itertools import chain",number=1000))
print("op's       ",timeit.timeit(r"""temp = []
fp = open('file.txt', "r")
for line in fp:
    temp.append(line.replace("\"","").rstrip("\n").split("\t"))
""",number=1000))
print("jamlyks    ",timeit.timeit(r"""
with open('file.txt', 'rb') as f:
    r = csv.reader(f, delimiter=' ', skipinitialspace=True)
    list(chain.from_iterable(r))""",setup="from itertools import chain; import csv",number=1000))
print("lennart    ",timeit.timeit(r"""
    list(csv.reader(open('file.txt'), delimiter='\t', quotechar='"'))""",setup="from itertools import chain; import csv",number=1000))

rawDescription: Python: What's a fast way to read and split a file?


code:
import mock   # or from unittest import mock

mock_socket = mock.Mock()
mock_socket.recv.return_value = data

rawDescription: How to mock a socket object via the mock library

description: Mock a socket object via the mock library


code:
# determine per-pixel variablility, std() over all images
variability = sample_images.std(axis=0).sum(axis=2)

# show image of these variabilities
plt.figure(2)
plt.imshow(variability, cmap=plt.cm.gray, interpolation="nearest", origin="lower")

rawDescription: How to detect object on images?

description: Detect object on images


code:
N = len(my_data2)//2
learning_sample, test_sample = my_data2[:N], my_data2[N:]

rawDescription: How can I divide my data table called (my_data2) in two samples

description: Divide my data table called (my_data2) in two samples


code:
M = zeros((4,4))
M.flat[:4] = 1
print(M)

rawDescription: Numpy: Assignment and Indexing as Matlab


code:
elements = tree.xpath(
    '//AdditionalAttribute[@name="Internal Version Identifier"]/@value')

assert len(elements) == 1
assert elements[0] == 'UCV261KSBQGBPYF6'

rawDescription: lxml - Access value of meta tag on element

description: Lxml - Access value of meta tag on element


code:
def get_contact_conditions(kwds):
    contact = session.query(Contact).filter_by(**kwds).all()
    return contact

rawDescription: how to deal with multiple arguments in a dictionary construct when query in sqlalchemy?

description: Deal with multiple arguments in a dictionary construct when query in sqlalchemy


code:
import re
line = 'blah blah ValueName: 1234 blah blah ValueName: 5678'
m = re.findall(r'ValueName:\s+([0-9]+)',line)
m

rawDescription: Python Extract Values of varying length from Text Files


code:
from array import array

arr = array('L')
with open(filename, 'rb') as fileobj:
    arr.fromfile(fileobj, number_of_integers_to_read)

rawDescription: Reading 4 byte integers from binary file in Python


code:
proc = subprocess.Popen(['pdflatex', 'cover.tex'])
proc.communicate()

rawDescription: Generating pdf-latex with python script

description: Generating pdf-latex with python script


code:
location = lambda x: os.path.join(
os.path.dirname(os.path.realpath(__file__)), x)

TEMPLATE_DIRS = (
    location('templates'),
    OSCAR_MAIN_TEMPLATE_DIR,
)
STATIC_URL = '/static/'
STATIC_ROOT = location('static')
MEDIA_URL = '/media/'
MEDIA_ROOT = location('media')
THUMBNAIL_DEBUG = True
THUMBNAIL_KEY_PREFIX = 'oscar-sandbox'

rawDescription: Django-Oscar Images Error

description: Django-Oscar Images Error


rawDescription: ast.literal_eval not working (python string of list to list)

description: Ast.literal_eval not working (python string of list to list)


rawDescription: Generating products of lists that sum to a parameter N


rawDescription: pygame error: TypeError: must be 2-item sequence

description: Pygame error: TypeError: must be 2-item sequence


code:
# wrong
user.check_password(user.password)
# should be
user.check_password(passwd)

rawDescription: Why is check_password_hash always returning False in this login view?


rawDescription: Python 3.5 csv parsing with special characters


code:
def find_instance(fn, objs):
    all_matches = filter(fn, objs)
    if len(all_matches) == 0:
        return False # no matches
    else:
        return all_matches[0]

rawDescription: Get class instance where a certain property has a certain value


code: search('aabbccdcabcbbacdaaa', {'aaa', 'acd', 'adb', 'bccd', 'cbbb', 'abc'})

rawDescription: Fastest way to match substring from large dict


code:
import urllib.parse

u = "http://java.dzone.com/articles/python-201-decorators?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+zones%2Fpython+%28Python+Zone%29"
p = urllib.parse.urlparse(u)
q = urllib.parse.parse_qs(p.query)
print(q)

rawDescription: Handling HTTP Query Parameters

description: Handling HTTP Query Parameters


code:
s2 = s.shift(1).fillna(set([]))
s2

rawDescription: Count size of rolling intersection in pandas


rawDescription: Print data-structure/ Data-type hierarchy


rawDescription: How to stop a Python program after some arbitrary timeout

description: Stop a Python program after some arbitrary timeout


code:
from itertools import product
import string

pools = [string.ascii_uppercase]*3 + [string.digits]*2
names = (''.join(c) for c in product(*pools) if c[-2:] != ('0', '0'))
# next(names) will give you the next unused name

rawDescription: How would i go about automatic name generation


code: re.findall('Full Path.*', data)

rawDescription: Python 3.5 Regular expressions cannot read text file


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

# create normally distributed random data
n = 10000
data = np.random.normal(0, 1, n)
bins = np.linspace(-data.max(), data.max(), 20)
hist = np.histogram(data, bins=bins)[0]
bincenters = 0.5 * (bins[1:] + bins[:-1])

# create interpolation function and dense x-axis to interpolate over
f = interp1d(bincenters, hist, kind='cubic')
x = np.linspace(bincenters.min(), bincenters.max(), n)

plt.plot(bincenters, hist, '-o')
# calculate greatest bincenter < 10th percentile
bincenter_under10thPerc = bincenters[bincenters < np.percentile(bincenters, 10)].max()
bincenter_10thPerc = np.percentile(bincenters, 10)

bincenter_90thPerc = np.percentile(bincenters, 90)
# calculate smallest bincenter > 90th percentile
bincenter_above90thPerc = bincenters[bincenters > np.percentile(bincenters, 90)].min()

# fill between 10th percentile region using dense x-axis array, x
plt.fill_between(x, 0, f(x), interpolate=True,
                 where=((x>=bincenter_under10thPerc) &
                        (x<=bincenter_10thPerc)))

# fill between 90th percentile region using dense x-axis array, x
plt.fill_between(x, 0, f(x), interpolate=True,
                 where=((x>=bincenter_90thPerc) &
                        (x<=bincenter_above90thPerc)))

rawDescription: Filling under histogram until exact point with fill_between python


code:
import matplotlib
matplotlib.use('tkagg')
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4, 5))
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.imshow(plt.imread('test.png'), aspect='auto')

# Tk specific!
fig.canvas.toolbar.pack_forget()

plt.show()

rawDescription: How can I display a matplotlib interactive window without any of the controls visible?

description: Display a matplotlib interactive window without any of the controls visible


code:
from mpmath import polylog, exp
from scipy.optimize import newton

def root(A,B,t):
    return abs(newton(lambda x: (x - A*polylog(1.5, B*exp(-t*x))), 0.0))

rawDescription: Call Python function from Fortran/C

description: Call Python function from Fortran/C


code:
n1 = Note(memo="I love chemistry")
n2 = Note(memo="I hate chemistry")
n3 = Note(memo="Inorganic")

rawDescription: python for loop is not working as it should

description: Python for loop is not working as it should


code: Q = np.empty(len(T))

rawDescription: python for loop for creating a 2D array form 2 1D array

description: Python for loop for creating a 2D array form 2 1D array


code:
from scipy.integrate import quad
from scipy.special import jn as besselj
from scipy import exp, zeros, linspace
from scipy.linalg import norm
import numpy as np

def complicated_func(lmbd, a, n, k):
    u,v,w = 5, 3, 2
    x = a*lmbd
    fac = exp(2*x)
    comm = (2*w + x)
    part1 = ((v**2 + 4*w*(w + 2*x) + 2*x*(x - 1))*fac**5
        + 2*u*fac**4
        + (-v**2 - 4*(w*(3*w + 4*x + 1) + x*(x-2)) + 1)*fac**3
        + (-8*(w + x) + 2)*fac**2
        + (2*comm*(comm + 1) - 1)*fac)
    return part1/lmbd *besselj(n+1, lmbd) * besselj(k+1, lmbd)

def perform_quad(n, k, a):
    return quad(complicated_func, 0, np.inf, args=(a,n,k))[0]

def improved_main():
    sz = 20
    amatrix = np.zeros((sz,sz))
    ls = -np.linspace(1, 10, 20)/2
    inds = np.tril_indices(sz)
    myv3 = np.vectorize(perform_quad)
    res = myv3(inds[0], inds[1], ls.reshape(-1,1))
    results = np.empty(res.shape[0])
    for rowind, row in enumerate(res):
        amatrix[inds] = row
        symm_matrix = amatrix + amatrix.T - np.diag(amatrix.diagonal())
        results[rowind] = norm(symm_matrix)
    return results

rawDescription: Speed up function evaluation for integration in scipy


code:
foo = [[], []]
bar = foo[:]
bar is foo
bar[0] is foo[0]
bar[0].append(1)
foo

rawDescription: Different slicing behaviors on left/right hand side of assignment operator


rawDescription: Embed list into python file

description: Embed list into python file


code:
df['score_indicator'] = df.Score.apply(lambda x: 1 if x >=0 else 0)
df['Site%'] = df.groupby('Site')['score_indicator'].transform(lambda x: x.sum() / x.count())
df['Group%'] = df.groupby(['Site','Group'])['score_indicator'].transform(lambda x: x.sum() / x.count())

rawDescription: Percentage by Group

description: Percentage by Group


code: df.index = pd.DatetimeIndex(df[1])

rawDescription: Grouping pandas data frame by time intervals


code:
def lop_triangle(points):
    triangle = [points[0], points[-1], points[-2]]
    polygon = points[:-1]
    return triangle, polygon

rawDescription: Area of a polygon (Recursively using Python)


code:
from PyQt4 import QtGui

app = QtGui.QApplication([])

w = QtGui.QMainWindow()
menu = QtGui.QMenu("menu", w)

menu.addAction(QtGui.QAction('50%', menu, checkable=True))
menu.addAction(QtGui.QAction('100%', menu, checkable=True))
menu.addAction(QtGui.QAction('200%', menu, checkable=True))
menu.addAction(QtGui.QAction('300%', menu, checkable=True))
menu.addAction(QtGui.QAction('400%', menu, checkable=True))

w.menuBar().addMenu(menu)
w.show()
app.exec_()

rawDescription: how to make qmenu item checkable pyqt4 python

description: Make qmenu item checkable pyqt4 python


code:
xtick.direction      : out     # direction: in or out
ytick.direction      : out     # direction: in or out

rawDescription: In matplotlib, how do you draw R-style axis ticks that point outward from the axes?


code:
x = rng[rng.indexer_between_time('9:30','16:00')]
x

rawDescription: Python Pandas business day range bdate_range doesn't take 1min freq?


rawDescription: Something about python class

description: Something about python class


rawDescription: Python logic - how do I code the maximum weight for two roads that have a variety of maximum weight values?


code:
import array
array.array('B', [0xc0, 0x04, 0x00]).tostring()

rawDescription: Binary data with pyserial(python serial port)


code:
import pandas as pd
day_names = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

rawDescription: Pandas - How do I subset a column composed of list objects?


code:
from subprocess import check_output

out = check_output("your command goes here", shell=true)

rawDescription: Handle result of os.system

description: Handle result of os.system


code:
from scipy.optimize import minimize
import numpy as np

def f(coord,x,y,r):
    return np.sum( ((coord[0] - x)**2) + ((coord[1] - y)**2) - (r**2) )

x = np.array([0,   2,  0])
y = np.array([0,   0,  2])
r = np.array([.88, 1, .75])

# initial (bad) guess at (x,y) values
initial_guess = np.array([100,100])

res = minimize(f,initial_guess,args = [x,y,r])

rawDescription: How to perform non-linear optimization with scipy/numpy or sympy?

description: Perform non-linear optimization with scipy/numpy or sympy


code:
class Something(unittest.TestCase):
    ...

rawDescription: Python nose test inheritance: load unit test fixtures from subclasses


code:
with open("my_dict.py", "w") as f:
    print("dict2 = " + literal, file=f)

rawDescription: Outputting a dictionary to file exactly as defined in variable


code: c_tilde = SR.var('c_tilde', latex_name=r'\tilde c')

rawDescription: How to render a variable with a tilde on Latex with Sagetex

description: Render a variable with a tilde on Latex with Sagetex


rawDescription: Python equivalent for PHP's usort()?

description: Python equivalent for PHP's usort()


code:
import re
file = open('test.txt')
fi = file.readlines()

for line in fi:
    match = re.match('.*id (\d+).*',line)
    if match:
        print("************ %s" % match.group(1))
    match = re.match('.*192\.168\.45\.28\.(\d+).*',line)
    if match:
        print(match.group(1))

rawDescription: Locate multiple keywords in lines using Python


code:
def lucas_kanade_op(im1, im2, win=2) :
    ...
    return np.array(opfl)

rawDescription: Lucas Kanade python numpy implementation uses enormous amount of memory


rawDescription: Python Classes: adding dynamic attributes to methods


code:
import pandas as pd
import numpy as np

# use a DataFrame df with some sample data
df = pd.DataFrame(np.random.random((5, 5)))

# get latex string via `.to_latex()`
latex = df.to_latex()

# split lines into a list
latex_list = latex.splitlines()

# insert a `\midrule` at third last position in list (which will be the fourth last line in latex output)
latex_list.insert(len(latex_list)-3, '\midrule')

# join split lines to get the modified latex output string
latex_new = '\n'.join(latex_list)

rawDescription: Midrule in LaTeX output of Python Pandas


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
plt.show()

rawDescription: Matplotlib - change automatic axis range


code:
def listEventsSummary(request):
    listEventsSummary = Event.objects.all().order_by('-id')[:20]
    return render_to_response('stuff.html',{'events':listEventsSummary})

rawDescription: Django, displaying a view in an another view?


rawDescription: Convert Pandas DatetimeIndex to fractional day of year


code: df['group'] = (df['Time'].diff() > np.timedelta64(60,'s')).cumsum()

rawDescription: pandas quick way to break dataframe by timeindex

description: Pandas quick way to break dataframe by timeindex


code: voto = controlla_voto(voto_lett)

rawDescription: Variables change values inside while cycle


code:
import numpy as np
import scipy.special as special

expr='(1+p[1])**(1+p[1])/special.gamma(1+p[1]) * x**p[1]/p[0]**(1+p[1]) * np.exp(-(1+p[1])*x/p[0])'

def make_func(expr):
    funcstr='''\
def f(x,p):
    return {e}
    '''.format(e=expr)
    exec(funcstr)
    return f

f=make_func(expr)
print(f(1,[2,3]))

rawDescription: Python/Numpy/Scipy - Converting string to mathematical function


code:
regex = re.compile(r'(\b(iphone|games|mac)\b(\s*(iphone|games|mac)\b)*)', re.I)
regex.sub(r'\1', 'I love downloading iPhone games from my mac')
regex.sub(r'\1', 'I love downloading iPhone gameses from my mac')
regex.sub(r'\1', 'I love downloading iPhoney games from my mac')
regex.sub(r'\1', 'I love downloading iPhoney gameses from my mac')
regex.sub(r'\1', 'I love downloading miPhone gameses from my mac')
regex.sub(r'\1', 'I love downloading miPhone games from my mac')
regex.sub(r'\1', 'I love downloading iPhone igames from my mac')

rawDescription: How do I add tags to certain strings in python using re.sub?

description: Add tags to certain strings in python using re.sub


code:
new_index = pd.MultiIndex.from_product([df2.index.get_level_values(0).unique(), range(31)])
df2 = df2.reindex(new_index, fill_value=0)

rawDescription: computing rolling averages by integer days in pandas

description: Computing rolling averages by integer days in pandas


code:
#Create an instance of tool_swoe_iv
my_tool = tool_swoe_iv(5)

#Execute calculations
my_tool.swoe_iv(param1, param2)

#Now there exists a new dataframe called param1

rawDescription: re-naming data frame output given input parameter to class in python

description: Re-naming data frame output given input parameter to class in python


code:
def do_print(label):
    print("%s: python print" % label)
    s = ("%s: libc _write\n" % label).encode('ascii')
    libc._write(1, s, len(s))
    s = ("%s: libc printf\n" % label).encode('ascii')
    libc.printf(s)
    libc.fflush(None) # flush all C streams

if __name__ == '__main__':
    # save POSIX stdout and Windows StandardOutput
    fd_stdout = os.dup(1)
    hStandardOutput = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

    do_print("begin")

    # redirect POSIX and Windows
    with open("TEST.TXT", "w") as test:
        os.dup2(test.fileno(), 1)
        kernel32.SetStdHandle(STD_OUTPUT_HANDLE, libc._get_osfhandle(1))

    do_print("redirected")

    # restore POSIX and Windows
    os.dup2(fd_stdout, 1)
    kernel32.SetStdHandle(STD_OUTPUT_HANDLE, hStandardOutput)

    do_print("end")

rawDescription: stdout redirection with ctypes and Python

description: Stdout redirection with ctypes and Python


code:
lst = [1,7,3,4]
prod = 1
for i in l:
    prod *= i
newlst = [prod//i for i in lst]
newlst

rawDescription: Product of integer in the list except the integer at that index


code:
r = requests.get(url1)
files = {'image': r.content}
r = requests.post(url2, files=files)

rawDescription: How to post an image in Python just like byte array in Java?

description: Post an image in Python just like byte array in Java


code:
def Submit_Code(request):
     #Create MyModel using POST data
     process_input_file(NEWLY_CREATED_MODEL_NAME)
     return HttpResponse("Upload Successful")

def process_input_file(modelName):
     #assuming unique name. Use "id=" instead if needed.
     mm = MyModel.objects.get(name=modelName)
     if passes_security_checks(mm.code):
          f = open(mm.name, "r")
          f.write(mm.code)
          f.close()

rawDescription: Django FileField: how to set default value (auto-create empty file)?


rawDescription: Python select ith element in OrderedDict


code:
#Assuming that the keyvalue pairs is in a dictionary,
import operator
from django.db.models import Q

k_v_pairs = (Q(metadata__key=key, metadata__value=value) for key, value in k_v_dictionary)
tests = Test.objects.filter(reduce(operator.or_, k_v_pairs)).distinct()

rawDescription: Django Filter by Multiple Foreign Key Properties


code:
import numpy as np
arr
hpairs = (arr[:, :-1] == arr[:, 1:])
hpairs
arr[hpairs]
np.argwhere(hpairs)

rawDescription: Comparing elements in a numpy array, finding pairs, how to deal with edges/corners


code:
import subprocess
cmd = "unichars '\p{Open_Punctuation}' | cut -f2 -d' ' | tr -d '\n'"
open_punct = subprocess.check_output(cmd, shell=True).decode('utf8')
print (open_punct)

rawDescription: What is the equivalence of perluniprops in python?


code:
import pystache
import os
pystache.render('{{PATH}}', dict(os.environ))

rawDescription: how do i parse environment variables with pystache?

description: Parse environment variables with pystache


code:
import Image
imag = Image.open("yourimage.yourextension")
#Convert the image te RGB if it is a .gif for example
imag = imag.convert ('RGB')
#coordinates of the pixel
X,Y = 0,0
#Get RGB
pixelRGB = imag.getpixel((X,Y))
R,G,B = pixelRGB

rawDescription: python -- measuring pixel brightness

description: Python -- measuring pixel brightness


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

rawDescription: Python Counter: print key whose count is x


code:
for item in [1, 2, 3]:
   add(item, 10)

rawDescription: How to specify arguments in map in Python?

description: Specify arguments in map in Python


rawDescription: Reshaping a numpy array in python

description: Reshaping a numpy array in python


rawDescription: Get name of QPushButton

description: Get name of QPushButton


code: conditions = [{field: {"$regex": value.lower()}} for field, value in args.items()]

rawDescription: Dynamically build query with regex in PyMongo


rawDescription: How to avoid getting imaginary/complex number python

description: Avoid getting imaginary/complex number python


code:
import sys
import os
if not os.isatty(0):
    cmd = sys.stdin.read()
    print(cmd)
else:
    print("standard behavior")

rawDescription: Is there a way for a python script to "know" if it is being piped to?


code: url = reverse('my_api.actor_resource', args={'id': actor.id})

rawDescription: Django REST Framework: how to properly use the HyperlinkedModelSerializer url field in unit tests


code:
def GetInterpolatedZ(triangle, u, v):
    z0 = 1.0 / triangle[0].z
    z1 = 1.0 / triangle[1].z
    z2 = 1.0 / triangle[2].z
    z = z0 + u * (z1-z0) + v * (z2-z0)
    return 1.0/z

rawDescription: Retrieving the actual 3D coordinates of a point on a triangle that has been flattened to 2 dimensions


rawDescription: How to remove items from a list if they match any items in another list in Python

description: Remove items from a list if they match any items in another list in Python


code:
# File: urls.py
urlpatterns = [
    url(r'^invoices/$', views.invoice_list, name='invoice-list'),
    url(r'^invoice/(?P<id>\d+)/$', views.invoice_detail, name='invoice-detail'),
]

rawDescription: Django, splitting a filter into separate links


rawDescription: Isolating/manipulating data in a pandas Dataframe


code:
# foo.py
class Foo(object):
    pass # same code as before, plus foo_func

try:
   import whatever
   _singleton = Foo(whatever)
except ImportError:
   _singleton = Foo(something_else)

def foo_func():
   return _singleton.foo_func()

rawDescription: Python: Mock a module without importing it or needing it to exist


code:
from lxml import html
t = html.fromstring(text)
t.xpath("table/tbody/tr[2]/td/div")[0].text

rawDescription: Python: how to extract the content of a column in a table


code:
for idx, c in enumerate(colors):
        plt.bar(idx, c[0], color=hexencode(c[1]),edgecolor=hexencode(c[1]))

rawDescription: Plot image color histogram using matplotlib


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

class MobiItem(Item):
    brand = Field()
    title = Field()
    price = Field()

class MobiSpider(BaseSpider):
    name = "mobi"
    allowed_domains = ["mobi.ge"]
    start_urls = [
        "http://mobi.ge/?page=products&category=60"
    ]

    def parse(self, response):
        sel = Selector(response)
        blocks = sel.xpath('//table[@class="m_product_previews"]/tr/td/a')
        for block in blocks:
            item = MobiItem()
            try:
                item["brand"] = block.xpath(".//div[@class='m_product_title_div']/span/text()").extract()[0].strip()
                item["title"] = block.xpath(".//div[@class='m_product_title_div']/span/following-sibling::text()").extract()[0].strip()
                item["price"] = block.xpath(".//div[@id='m_product_price_div']/text()").extract()[0].strip()
                yield item
            except:
                continue

rawDescription: struggling on xpath establishment

description: Struggling on xpath establishment


code:
from scipy.spatial import cKDTree

tree = cKDTree(data)
# where data is (nshops, ndim) containing the Euclidean coordinates of each shop
# in units of km

pairs = tree.query_pairs(50, p=2)   # 50km radius, L2 (Euclidean) norm

rawDescription: Python calculate lots of distances quickly


code: j = bisect.bisect(L, max, i)

rawDescription: Using ternary search to find all elements within a range?


code:
from collections import OrderedDict
D=OrderedDict()
for k,v in sorted(((inp+' '+i,len(inp+i)) for i in a),key=lambda x:x[1]):
  D[k]=v

D

rawDescription: finding string length and storing in dict

description: Finding string length and storing in dict


code:
import some_helper_module

db = some_helper_module.db_util.connect() # or whatever the real API is

#...

rawDescription: Python import as global name not defined


rawDescription: How to present a class as a function?

description: Present a class as a function


code:
re.search(r'"(?=(?P<tmp>[A-Za-z]*))(?P=tmp)"', '"Quote"').groupdict()
# => {'tmp': 'Quote'}

rawDescription: Do Python regular expressions have an equivalent to Ruby's atomic grouping?


code: np.linalg.solve(A_list, B_list)

rawDescription: How to map np.linalg.solve to an array of matrice and keep speed?

description: Map np.linalg.solve to an array of matrice and keep speed


code:
def parser():
    header = Group(...)
    inputsummary = Group(...)
    jobstats = Group(...)
    measurements = Group(...)
    return header("hdr") + inputsummary("inputs") + jobstats("stats") + measurements("meas")

rawDescription: How should I organise my functions with pyparsing?


rawDescription: NLTK: how can I list all pairs of adjacent subtrees (rooted in specific nonterminal) of a parse tree


code:
for row in table.find_all("tr")[2:]:
    print([cell.get_text(strip=True) for cell in row.find_all("td")])

rawDescription: Python+BeautifulSoup: scraping a particular table from a webpage


code:
from gadjo.requestprovider.signals import get_request

http_request = get_request()

rawDescription: How to do result post-processing before rendering with django endless-pagination?

description: Do result post-processing before rendering with django endless-pagination


code:
import os

root_path = r'C:\Tasks\\'
total_lines = 0
file_indices = dict()

# Based on http://stackoverflow.com/q/845058, bufcount function
def linecount(filename, buf_size=1024*1024):
    with open(filename) as f:
        return sum(buf.count('\n') for buf in iter(lambda: f.read(buf_size), ''))

for dirpath, dirnames, filenames in os.walk(root_path):
    for filename in filenames:
         if not filename.endswith('.txt'):
             continue
         path = os.path.join(dirpath, filename)
         file_indices[total_lines] = path
         total_lines += linecount(path)

offsets = list(file_indices.keys())
offsets.sort()

rawDescription: Python random lines from subfolders

description: Python random lines from subfolders


code:
from itertools import repeat, chain, imap
list(chain.from_iterable(imap(repeat, a, s)))

rawDescription: Repeat each values of an array different times


code: row += 1

rawDescription: Converting for loops to while loops in python


code:
class NonDataProperty(object):
    def __init__(self, fget):
        self.fget = fget

    def __get__(self, obj, type):
        if obj:
            return self.fget(obj)
        else:
            return self

    # don't define a __set__ method!

rawDescription: How to let inheritance take precedence over class properties when using a metaclass?

description: Let inheritance take precedence over class properties when using a metaclass


code:
class MyInt(int):
    def __new__(cls, value):
        new_myint = super(MyInt, cls).__new__(cls, value)
        return new_myint

rawDescription: Inheriting from immutable types

description: Inheriting from immutable types


code:
df = pd.DataFrame([1,1,1,1], index=pd.date_range('1/1/2013',periods=4))
target_zero_row = df.index.get_loc('2013-01-04')
df.index = pd.np.arange(df.shape[0]) - target_zero_row
df

rawDescription: How to reindex a dataframe specifying center

description: Reindex a dataframe specifying center


code: x, y, z = load_variables(...)

rawDescription: Function that intentionally bleeds variables into caller's scope


code:
class Day:
    def __init__(self, day):
        self.day = day
        self.jobs = {}
        self.no_jobs = 0
    def getjobs(self):
        """populates a dictionary with the information from an excel sheet"""
        for i in range(start_row, self.day.nrows): # note self.day
            ... # use self.jobs here
        self.no_jobs = len(self.jobs)

rawDescription: Python Class not working as expected?

description: Python Class not working as expected


code:
with open('another_file', 'wb') as output:
    subprocess.check_call(['awk', '{print $0}', file], stdout=output)

rawDescription: python variables in awk

description: Python variables in awk


code:
import re
s = '<@ """@$ FSDF >something something <more noise>'
re.sub('<[^>]+>', '', s)

rawDescription: Python: delete the words between two delimeters


code:
import pandas as pd
import numpy as np
drg = pd.date_range('2000-07-31', '2015-08-05', freq='B')
timestamp = pd.Timestamp('2015-08-05', 'B')

def using_astype(drg, timestamp):
    A = drg.values.astype('<M8[D]')
    B = timestamp.asm8.astype('<M8[D]')
    return np.busday_count(A, B)

def using_datetimes(drg, timestamp):
    A = [d.date() for d in drg]
    B = pd.Timestamp('2015-08-05', 'B').date()
    return np.busday_count(A, B)

rawDescription: Pandas number of business days between a DatetimeIndex and a Timestamp


code:
print("What do you wanna do?")

input1 = input()

complex_inputs = ["stab this guy", "punch this guy"]

actions_list = [action for actions in complex_inputs for action in actions.split()]

while input1.lower() not in (actions_list or complex_inputs):
    print("Sorry didn't catch that")
    print("What do you wanna do?")
    input1 = input()

if input1.lower() in "stab this guy":
    print("You stabbed that guy and killed him.")

elif (input1.lower() in "punch this guy"):
    print("You punched him...")

rawDescription: I would like to implement a loop but I don't know how to go about it


code: {i.pop('name'): i for i in listofdict}

rawDescription: Elegant way to transform a list of dict into a dict of dicts


code: delta = datetime.datetime.now() - previousTime

rawDescription: Converting a datetime into a string and back again


code:
class DefaultAttribute(Attribute):
  __handler = None

  def __call__(self, func):
    self.__handler = func
    return super().__call__(func)

  @property
  def Handler(self):
    return self.__handler

class CommandAttribute(Attribute):
  __command = ""
  __handler = None
  __kwargs =  None

  def __init__(self, command, **kwargs):
    super().__init__()
    self.__command =  command
    self.__kwargs =   kwargs

  def __call__(self, func):
    self.__handler = func
    return super().__call__(func)

  @property
  def Command(self):
    return self.__command

  @property
  def Handler(self):
    return self.__handler

  @property
  def KWArgs(self):
    return self.__kwargs

class ArgumentAttribute(Attribute):
  __args =   None
  __kwargs = None

  def __init__(self, *args, **kwargs):
    super().__init__()
    self.__args =   args
    self.__kwargs = kwargs

  @property
  def Args(self):
    return self.__args

  @property
  def KWArgs(self):
    return self.__kwargs

rawDescription: Is it possible to implement .NET-like attributes in Python?


code:
if word == "banana":
    print("word is banana")
elif word == "apple":
    print("word is not banana, but it is apple")
else:
    print("word is neither banana, nor apple, but something else")

rawDescription: Python 3 else for all previous ifs

description: Python 3 else for all previous ifs


code: c = a.astype('U')

rawDescription: How to convert numpy object array into str/unicode array?

description: Convert numpy object array into str/unicode array


code:
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

rawDescription: How can i make django-rest-framework-jwt return token on registration?

description: Make django-rest-framework-jwt return token on registration


code: pd.DataFrame(np.outer(a, b), columns=b.index, index=a.index)

rawDescription: How to broadcast pandas series with different indices?

description: Broadcast pandas series with different indices


code:
find_all("dark", File_Path)

find_all("lie", File_Path)

rawDescription: Display 'word' results on seperate line and print first word of sentences which contain the word (Python)


code:
s = '''Security/Microsoft-Windows-Security-Auditing ID [4624] :EventData/Data -> SubjectUserSid = S-1-0-0 SubjectUserName = - SubjectDomainName = - SubjectLogonId = 0x0000000000000000 TargetUserSid = S-1-1-11-1111111111-1111111111-1111111111-1111 TargetUserName = johndoe TargetDomainName = TestDomain TargetLogonId = 0x0000000001111111 LogonType = 3 LogonProcessName = NtLmSsp  AuthenticationPackageName = NTLM WorkstationName = TestWorkstation LogonGuid = {00000000-0000-0000-0000-000000000000} TransmittedServices = - LmPackageName = NTLM V2 KeyLength = 128 ProcessId = 0x0000000000000000 ProcessName = - IpAddress = 1.1.1.1 IpPort = 11111 '''
import re
for item in re.findall(r'([A-Za-z]+) = (\S+)', s):
    print('{} = {}'.format(*item))

rawDescription: Python - Searching file lines for multiple patterns efficiently


code:
text = "This is a word. This is another word. H.E. Stein"
re.sub(r'(\w{2})\.', r'\1', text)

rawDescription: Python Regex sub on single character

description: Python Regex sub on single character


code:
def check_rule(rule, o, p):
    # o = original, p = pattern
    if rule == 'any':
        return True
    elif rule == 'any-but-or':
        return not bool(set(p)-set(o))
    elif rule == 'any-but-and':
        return len(set(p)-set(o)) != 0

check_rule('any-but-and', lang_list, ['english','chinese'])

rawDescription: Checking a list against different criteria rules


code:
import pygame, sys, time, random
from pygame.locals import *
from time import *

pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption("Bounce")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

info = pygame.display.Info()
sw = info.current_w
sh = info.current_h
y = 0

# Initial direction is down
direction = 1

while True:
    windowSurface.fill(BLACK)
    pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)
    #print "Drawing at 250,", y
    sleep(.006)
    y += direction
    if y >= sh:
        # Changes the direction from down to up
        direction = -1
    elif y <= 0:
        # Changes the direction from up to down
        direction = 1

    pygame.display.update()

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

rawDescription: animation in pygame

description: Animation in pygame


code:
from pyspark.sql import Row

df = sc.parallelize([
    Row(sentence_id=1, sentence=u'the dog ran the fastest.'),
     Row(sentence_id=2, sentence=u'the cat sat down.')
]).toDF()

rawDescription: "normalize" dataframe of sentences into larger dataframe of words


code:
from itertools import groupby
from operator import itemgetter
sorted_keys = sorted(original_dict, key=lambda key: (key[0], -original_dict[key]))
for primary_key, key_group in groupby(sorted_keys, key=itemgetter(0)):
    print(primary_key, [key[1] for key in key_group])

rawDescription: How to sort and subset a python dictionary with compound key?

description: Sort and subset a python dictionary with compound key


code:
from selenium import webdriver

def main():
    browser = webdriver.Chrome()
    browser.set_window_size(1000, 1000)
    browser.get("http://yoursite.com")
    browser.execute_script("$('#values').css('zoom', 5);")

if __name__ == '__main__':
    main()

rawDescription: How to zoom out of page using python selenium

description: Zoom out of page using python selenium


code:
import seaborn as sns  # for nice plot styles (optional)

daily = data.set_index('TIMESTAMP').groupby(pd.TimeGrouper(freq='D'))['TYPE'].count()
monthly = daily.groupby(pd.TimeGrouper(freq='M')).mean()
ax = monthly.plot(kind='bar')

rawDescription: Average of daily count of records per month in a Pandas DataFrame


code: np.ma.masked_where(x <= 75, x)

rawDescription: How to delete a set of meshgrid points inside a circle?

description: Delete a set of meshgrid points inside a circle


rawDescription: How to find hidden properties/methods in Javascript objects?

description: Find hidden properties/methods in Javascript objects


rawDescription: Converting between datetime, Timestamp and datetime64


code:
import json
d = {'foo': 'bar'}
new_d = json.loads(json.dumps(d))
new_d
new_d['foo']

rawDescription: How do you save a complex dictionary in JSON file, and then load it back as dictionary?

description: Save a complex dictionary in JSON file, and then load it back as dictionary


code:
my_data = np.random.random((210,8)) #recfromcsv('LIAB.ST.csv', delimiter='\t')
new_col = my_data.sum(1)[...,None] # None keeps (n, 1) shape
new_col.shape
#(210,1)
all_data = np.append(my_data, new_col, 1)
all_data.shape
#(210,9)

rawDescription: How to add column to numpy array

description: Add column to numpy array


code:
temp_df = ga.read_ga(metrics,
              dimensions=dimensions,
              start_date=start_date,
              end_date=end_date,
              index_col=0,
              filters=filters,
              account_id=gc['site1']['acct'],
              property_id=gc['site1']['prop'],
              profile_id=gc['site1']['view'],
              start_index=start_index)

rawDescription: Pandas google analytics API - how to switch account?


code:
class Bar:
    def __init__(self, arr):
        self.items = arr
    def __repr__(self):
        return "Bar("+str(self.items)+")"
    def __add__(self, new):
        newlst = [];
        for i, j in zip(self.items, new.items):
            newlst.append(i+j)
        return Bar(newlst)

rawDescription: Add two instances of my class

description: Add two instances of my class


code: {x: func(y) for x, y in l if isinstance(func(y), int)}

rawDescription: Is comprehension possible here?

description: Is comprehension possible here


code:
def get_resolution(self):
    return "%sx%s" % (self.width, self.height)

rawDescription: Help with validation in Models and Forms


code:
a = np.array(['a', 'b', 'b', 'c', 'a'])
u, indices = np.unique(a, return_index=True)
u
indices
a[indices]

rawDescription: finding the number of grey levels

description: Finding the number of grey levels


rawDescription: How to evaluate the sum of values within array blocks

description: Evaluate the sum of values within array blocks


rawDescription: Deleting equal elements from a list

description: Deleting equal elements from a list


code:
def index(request):
    posts = Post.objects.filter(active=True)
    return render(request, 'blog/index.html', {'posts': posts})

rawDescription: Django: Querying Multiple Foreign Keys

description: Django: Querying Multiple Foreign Keys


code: action = visit[room]

rawDescription: Having trouble with functions calling other functions through dictionaries: could someone please explain this code to me?


rawDescription: Django: Count users used in model's ManyToMany


code: pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))

rawDescription: Python pi calculation?

description: Python pi calculation


code:
data=np.random.uniform(1,1000,3000)
@np.vectorize
def plotting(i):
    ax.plot(i,data[i],color=colors[cIdx[i]],marker=mark[cIdx[i]])

mark=['>','o','^']
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plotting(range(len(data)))
ax.set_xlabel('index')
ax.set_ylabel('Data')
plt.show()

rawDescription: Ordered colored plot after clustering using python


code: averages = dict((k, map(avg, zip(*v))) for k, v in groupings.iteritems())

rawDescription: Averaging along DataFrame columns with some missing rows


code:
import inspect
def function_that_has_site(f):
    return inspect.isfunction(f) and f.__name__.startswith('site_')

rawDescription: Go through a number of functions in Python


code:
def post(self):
    imageurl = self.request.POST.get("imageurl")
    logging.info(imageurl)

rawDescription: Getting file location from an html form

description: Getting file location from an html form


rawDescription: What is the quickest way to HTTP GET in Python?


code:
if not os.path.isdir("{0}.{1}".format(homedir,projectname)):
    os.mkdir("{0}.{1}".format(homedir,projectname))

rawDescription: How to store variables/preferences in Python for later use

description: Store variables/preferences in Python for later use


code: wind = MyCustomWindow(self)

rawDescription: Easiest way to create a scrollable area using wxPython?


code: url.append(base_url + link['href'])

rawDescription: Making a vector from unformatted elements in Python


code:
if toTest == toTest[::-1]:
    print("It's a palindrome!")

rawDescription: for loop nested inside the expression from an if statement

description: For loop nested inside the expression from an if statement


rawDescription: Extracting data from a GML file

description: Extracting data from a GML file


code: table.Cell(Row =1, Column =1).Range.Text

rawDescription: How to read contents of an Table in MS-Word file Using Python?

description: Read contents of an Table in MS-Word file Using Python


code: df.loc[df['label'] == 1].sum()

rawDescription: Iterate over pandas columns with row-wise comparisons


code: [list(map(list, zip(a,b))) for a,b in zip(L2, L1)]

rawDescription: Merging lists of lists

description: Merging lists of lists


code:
content = bytearray(content)
old2new={b'SDV2':b'work'} # add more renaming patterns as you need
for oldn, newn in old2new.items():
  i = content.find(oldn)
  # or using regex pattern:
  # re.search(oldn, content).start()
  content[i:i+len(newn)] = newn

rawDescription: Replacing State variable names in odb with python


code:
import pypyodbc
import csv

# MS ACCESS DB CONNECTION
pypyodbc.lowercase = False
conn = pypyodbc.connect(
    r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
    r"Dbq=C:\temp\Temp_DB.accdb;")

# OPEN CURSOR AND EXECUTE SQL
cur = conn.cursor()
cur.execute("SELECT Column1, Column2, FROM Table1");

# OPEN CSV AND ITERATE THROUGH RESULTS
with open('Output.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    for row in cur.fetchall() :
        writer.writerow(row)

cur.close()
conn.close()

rawDescription: How to export MS Access table into a csv file in Python using e.g. pypyodbc

description: Export MS Access table into a csv file in Python using e.g. pypyodbc


rawDescription: Dynamic FormWizard

description: Dynamic FormWizard


code:
def professor(x):
    employees2 = []
    for line in x:
       if line[1] == "Professor":
          employees2.append(line)
    return employees2

rawDescription: Trying to filter a list to bring back lines with a specific word


code:
### app1/urls.py ###
urlpatterns = (
        url(r'^recents/$', RecentBookmarks.as_view()),
       # Samefor all the urls
    )

rawDescription: URL hashing in django web application

description: URL hashing in django web application


rawDescription: Grouping Pandas DataFrame by date

description: Grouping Pandas DataFrame by date


code: --user

rawDescription: Emacs elpy Flymake can't find pyflakes even though pyflake has been installed by pip


code:
from contextlib import contextmanager
import time

@contextmanager
def msg(m):
    print(m + "... ", end='', flush=True)
    t_start = time.time()
    yield
    t_duration_ms = 1000 * (time.time() - t_start)
    print("done. [{:.0f} ms]".format(t_duration_ms))

rawDescription: python contextmanager newline issue

description: Python contextmanager newline issue


rawDescription: Sum one number to every element in a list (or array) in Python


code: "hello there my name is dominic and >my< name is very special"

rawDescription: Implementing Basic Efficient "Search" Algorithm: Python


code:
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

rawDescription: Structure of a Flask app with more than one models.py


code:
os.rename('FakeAPData.csv', 'FakeAPData.csv.bak')

csv_in = open('FakeAPData.csv.bak', 'rb')
csv_out = open('FakeAPData.csv', 'wb')

writer = csv.writer(csv_out)

for row in csv.reader(csv_in):
    date = datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
    datet = unicode(datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S'))
    datett = tuple(int(v) for v in re.findall("[0-9]+", datet))
    y = calendar.timegm(datett)
    row[0] = y
    writer.writerow(row)

rawDescription: Overwrite a specific column in a csv file using Python csv module


code:
def getwebsafe(colour):
  return [51*((int(c)+25)//51) for c in colour]

rawDescription: How to round an RGB value to the closest web safe value with PIL (Python Imaging Library)?

description: Round an RGB value to the closest web safe value with PIL (Python Imaging Library)


code:
from BeautifulSoup import BeautifulSoup
example = u'
\n<A href="/pic/93/b67793.jpg" target="_blank" title="
'
soup = BeautifulSoup(example)
soup.findAll('a', title=u'\u67e5\u770b\u5927\u56fe')

rawDescription: how to get tags when attribute is chinese in beautifulsoup

description: Get tags when attribute is chinese in beautifulsoup


code:
pdf = StringIO()

doc = SimpleDocTemplate(pdf, pagesize=letter)
doc.build(story)

#get content of generated pdf
content = pdf.getvalue()

#save to db
pdfStorage = PdfStorage(pdfContent = content);
pdfStorage.put()

#output to browser
handler.response.write(content)

rawDescription: How to save generated PDF with Reportlab to Datastore in App Engine Python

description: Save generated PDF with Reportlab to Datastore in App Engine Python


code: [list(t) for t in zip(list1, list2)]

rawDescription: How to combine lists? (Python)

description: Combine lists? (Python)


code:
from itertools import islice, imap
import csv
with open("in.txt") as f,open("numbers.txt") as nums:
    # make a set of all winning nums
    nums = set(imap(str.rstrip, nums))
    r = csv.reader(f)
    # iterate over each row and sum how many matches we get
    for row in r:
        print("{} matched {}".format(row[0], sum(n in nums
                                                 for n in islice(row, 1, None))))

rawDescription: Comparing two CSV files in Python when rows have multiple values


code:
d = {}
with open("in.txt") as f:
    f_csv = csv.reader(f, delimiter='\t')
    headers = next(f_csv)
    tuple_attr = tuple(headers)
    for ele in f_csv:
        d.setdefault(ele[-1],[])
        d[ele[-1]].append(ele[:-1])

rawDescription: Creating python dictionary with a particular column value as key and removing that column from value


code:
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as pool:
    jobs = []

    for i in range(njobs * 10):
        bounds = (ceil(i * data.shape[0] / float(njobs * 10)),
                  ceil((i + 1) * data.shape[0] / float(njobs * 10)))

        jobs.append(pool.submit(
            df[bounds[0]:bounds[1]].apply,
            some_func_returning_tuple_of_two,
            axis=1))

    result = pandas.DataFrame(
        list(itertools.chain.from_iterable([job.result() for job in jobs])),
        index=data.index,
        columns=('result', 'meta') if has_meta else ('result'))

rawDescription: Getting specific list element from a series


code:
result = function_call(params)
print(result) if result else None

rawDescription: Alternatives for 3 lines of java-like code?


code:
for extra in extras:
    d.update(extra)

rawDescription: Python 3 map dictionary update method to a list of other dictionaries


code:
for i in range(1, 10):
    self.outerLabels[i] = ttk.Label(self.Shape).grid(row=i)
    self.upperLabels[i] = ttk.Label(self.outerLabels[i]).grid(row=0)
    ttk.Radiobutton(self.upperLabels[i]).grid(column=0)
    ttk.Radiobutton(self.upperLabels[i]).grid(column=1)
    ttk.Radiobutton(self.upperLabels[i]).grid(column=2)
    ttk.Radiobutton(self.upperLabels[i]).grid(column=3)
    ttk.Entry(self.upperLabels[i]).grid(column=4)
    ttk.Scale(self.upperLabels[i]).grid(column=5)
    self.lowerLabels[i] = ttk.Label(self.outerLabels[i]).grid(row=1)
    ttk.Entry(self.lowerLabels[i]).grid(column=0)
    ttk.Scale(self.lowerLabels[i]).grid(column=1)
    self.lowerLabels[i].configure(state=DISABLED)

rawDescription: Declaring callable variables in a for loop in python


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

# lowercase variables are 1D arrays
x = np.array([1,2,3,4,5])
y = np.array([3,1,5,1,3])
u = np.array([1,1,0,-1,-1])
v = np.array([-0.5,1,-1,1,-0.5])

# capitalized variables are 2D arrays
xi = np.linspace(x.min(), x.max(), 100)
yi = np.linspace(y.min(), y.max(), 100)
X, Y = np.meshgrid(xi, yi)
U = interpolate.griddata((x, y), u, (X, Y), method='nearest')
V = interpolate.griddata((x, y), v, (X, Y), method='nearest')

plt.figure()
plt.quiver(x, y, u, v, scale_units='xy', angles='xy', scale=1.5)
plt.streamplot(X, Y, U, V, color=U**2+V**2, linewidth=2, cmap=plt.cm.autumn)
plt.show()

rawDescription: Matplotlib - Using 1-D arrays in streamplot()


code:
w = df['Time']
w /= 3600000 # Convert milliseconds to hours

rawDescription: Matplotlib axis tickmarker alteration

description: Matplotlib axis tickmarker alteration


code:
def forward():
    turt.forward(30)

def left():
    turt.left(90)

def right():
    turt.right(90)

rawDescription: Assigning turtle commands to variables and recalling them on python


code:
[
    line.strip().split()
    for line in z if line.endswith('c') and not line.startswith(('a', 'b'))
]

rawDescription: Python - ignore lines in a file

description: Python - ignore lines in a file


code:
from collections import Counter

# generate 10,000 items
test = Counter(make_treasure() for i in range(10000))

# check number of each item generated
print(test.most_common())

rawDescription: Pythonic way of percentagechance

description: Pythonic way of percentagechance


code:
def make_subtract(fn, val):
    def wrapper(x):
        return fn(x) - val
    return wrapper

rawDescription: Adding a constant to a closure expression


code: encrypt = Button(master, text='Encrypt')

rawDescription: Implement a dynamic dropdown menu based on on the number of lines of text file


code:
x = re.sub(exp, 'hello', s)
print(x)

rawDescription: replacing appointed characters in a string in txt file

description: Replacing appointed characters in a string in txt file


code:
def string(x):
    if x=="1":
        word = "one"
    elif x=="2":
        word = "two"
    elif x=="3":
        word = "three"
    elif x=="4":
        word = "four"
    elif x=="5":
        word = "five"
    elif x=="6":
        word = "six"
    elif x=="7":
        word = "seven"
    else:
        word = "Try again"
    return word

def main():
  y = input("Please enter a number between 1 and 7: ")
  z = string(y)
  print(z)

main()

rawDescription: How to use IF or ELSE statements in Python? BTW, How is my username and profile picture?

description: Use IF or ELSE statements in Python? BTW, How is my username and profile picture


code:
for i in range(0, self.rows):
    item = MyTableWidgetItem("Row: %s" %(i), i)
    self.ui.tableWidget.setItem(i, 1, item)

rawDescription: Python: numerical sorting in QTableWidget


rawDescription: Discuss the "sorted" function in Python

description: Discuss the "sorted" function in Python


code:
left, width = 0.1, 0.6
bottom, height = 0.1, 0.8
left_table = left+width+0.1
table_width = 0.15
table_height = width/2.

rect_main = [left, bottom, width, height]
rect_table1 = [left_table, table_height+bottom , table_width, table_height]
rect_table2 = [left_table, bottom, table_width, table_height]

axMain = plt.axes(rect_main)
axTable1 = plt.axes(rect_table1, frameon =False)
axTable2 = plt.axes(rect_table2, frameon =False)
axTable1.axes.get_xaxis().set_visible(False)
axTable2.axes.get_xaxis().set_visible(False)
axTable1.axes.get_yaxis().set_visible(False)
axTable2.axes.get_yaxis().set_visible(False)

axMain.plot([1,2,3])
axTable1.table(cellText=[[1,1],[2,2]], loc='upper center',
               rowLabels=['row1','row2'], colLabels=['col1','col2'])
axTable2.table(cellText=[[3,3],[4,4]], loc='upper center',
               rowLabels=['row1','row2'], colLabels=['col1','col2'])

rawDescription: two tables in matplotlib

description: Two tables in matplotlib


code: #!/usr/bin/env python

rawDescription: How transform a python program .py in an executable program in Ubuntu?


code: c.SSHEngineSetLauncher.engine_cmd = ['/path/to/your/python', '-c', 'from IPython.parallel.apps.ipengineapp import launch_new_instance; launch_new_instance()']

rawDescription: Using ipcluster to connect to an OS X server w/ EPD from Linux?


code:
from celery.decorators import task

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

rawDescription: Django, Python calling Python code without waiting for response?


code:
def _set_ndb_cache_policy():
  """Tell NDB to never cache anything in memcache or in-process.

  This ensures that entities fetched from Datastore input_readers via NDB
  will not bloat up the request memory size and Datastore Puts will avoid
  doing calls to memcache. Without this you get soft memory limit exits,
  which hurts overall throughput.
  """
  ndb_ctx = ndb.get_context()
  ndb_ctx.set_cache_policy(lambda key: False)
  ndb_ctx.set_memcache_policy(lambda key: False)

rawDescription: ndb Models are not saved in memcache when using MapReduce

description: Ndb Models are not saved in memcache when using MapReduce


code:
{'Hardness': 'Hard',
 'Hardy': 'Hard',
 'Hardy Boys': 'Hard',
 'Johnny': 'John',
 'Ron': 'Ron',
 'Ronald': 'Ron',
 'Ronaldo': 'Ron',
 'Ronny': 'Ron',
 'john': 'John',
 'johnny Bravo': 'John'}

rawDescription: Comparing multiple dictionaries and generating another dictionary using python


code:
wanted_scaffs  = set(['scaffold126', 'scaffold5112'])
files = {name: open(name+'.txt', 'w') for name in wanted_scaffs}
for line in big_file:
    curr_scaff = line.split(' ', 1)[0] # minimal splitting
    if curr_scaff in wanted_scaffs:
        files[key].write(line)
for f in files.values():
    f.close()

rawDescription: Python large files, how to find specific lines with a particular string


code:
import win32gui, win32ui, win32con, win32api
hwin = win32gui.GetDesktopWindow()
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
hwindc = win32gui.GetWindowDC(hwin)
srcdc = win32ui.CreateDCFromHandle(hwindc)
memdc = srcdc.CreateCompatibleDC()
bmp = win32ui.CreateBitmap()
bmp.CreateCompatibleBitmap(srcdc, width, height)
memdc.SelectObject(bmp)
memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
bmp.SaveBitmapFile(memdc, 'screenshot.bmp')

rawDescription: Is there any better way to capture the screen than PIL.ImageGrab.grab()?


code:
idx = random.randint(0, n)
for k, v in D.items():
    if idx < len(v):
        do_something_with_val(k, v[idx])
        break
    else:
        idx -= len(v)

rawDescription: Select random element from "non uniform" python dictionary


code: any(value in dictionary[key] for key in dictionary)

rawDescription: Using 'if in' with a dictionary

description: Using 'if in' with a dictionary


code:
if not available_bikes:
    bikestoshow = None
else:
    bikestoshow = available_bikes[0].id #list of bike IDs

rawDescription: What is efficient way of detecting if date range of object is occupied?


code:
current_level = Tkinter.StringVar()
Tkinter.Label(master, textvariable=current_level)

rawDescription: Tkinter - Configuring a Label

description: Tkinter - Configuring a Label


code:
class Power_calc():
    def calculate(self, exp):
        methods = {
            '+': self.summ,
            '-': self.minus,
        }

        self.srt = exp.split(" ")
        self.x = float(self.srt[0])
        self.y = float(self.srt[2])
        operand = self.srt[1]
        return methods[operand](self.x, self.y)

    def summ(self, a, b):
        return a + b

    def minus(self, a, b):
        return a - b

rawDescription: Is there any idiomatic way to add methods to object in Python?


code:
class Connection_XML(XML_Element_Class):
    ### members
    name = None
    type = None
    ID = None
    max_size = None
    queue_size = None
    direction = None
    def do_something(self):
        pass

rawDescription: python how to save new objects into a list without duplication

description: Python how to save new objects into a list without duplication


code: [r for r in result if 10 < r.cost < 20 and 0 < r.risk < 10]

rawDescription: Is there an elegant alternative to filtering these results without using lots of if statements?


code: con.execute("insert into person(firstname) values (?)", (firstname_from_client,))

rawDescription: Protecting against SQL injection in python


code:
class Weapon:
    def __init__(self, finesse=False, light=False, thrown=False, two_handed=False,
                 versatile=False):
        props = locals()
        props.pop('self')
        for prop, value in props.items():
            if value:
                setattr(self, prop, value)

rawDescription: Creating a variable inside of a for loop


code:
@weapon_size.setter
def weapon_size(self, value):
    # custom code here
    self._weapon_size = value

rawDescription: Perform method when an attribute is added to a class in Python


rawDescription: Regex in Python: "\d+" and "[0-9]+ do NOT only recognize numbers&Digits but also Operators?


code:
#!/usr/bin/env python

# After registering your app you should be able to
# find these values on your application page.
# https://dev.twitter.com/apps/{your_app_id}/show
# Make sure your app's access level is "Read and Write",
# or you won't be able to post.
consumer_key=""
consumer_secret=""
access_token=""
access_token_secret=""

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

api.update_status('Maybe you should try Googling next time!')

rawDescription: After authorizing the oauth how can i send a tweet from Python shell?


code:
import numpy as np
data = np.genfromtxt('UK.txt',skiprows=8,delimiter=(4,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,7,8))

rawDescription: Handling empty space in reading table from text file python


code: df['datetime'] = pd.to_datetime(df['epochtime'], unit='s')

rawDescription: Python convert a series of seconds since epoch time to datetime series


code:
def filtre(list):
    for i,item in enumerate(list):
        matchObject=re.search(r"(^.*?\/(?:Accept|Integrate))(?!$).*", item)
        if matchObject :
            list.remove(item)
        else:
            i=i+1
    return list

rawDescription: generating a regex for path

description: Generating a regex for path


code: 'Diesel' and ('Hatchback' in mydict.get('Bri'))

rawDescription: Make sure that there are two values in a Dictionaries Key Python


rawDescription: Slicing pandas dataframe by column numbers I don't want


code:
numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} # expand as needed
for key, c in sorted(count.items(), key=lambda i: numbers[i[0].lower()]):
    print("{}: {}".format(key, c))

rawDescription: Display 'Counter' results on seperate line (Python)


rawDescription: How can you adjust xmlrpclib to interpret custom types?

description: Adjust xmlrpclib to interpret custom types


code:
class AutoVivify(dict):
    """Implementation of perl's autovivification feature."""
    def __missing__(self, item):
        value = self[item] = type(self)()
        return value

rates=AutoVivify()
with open(ur_file) as f:
    for line in csv.reader(f, skipinitialspace=True, quotechar="'"):
        state=line[0]
        k1,k2=line[1].split()
        rates[state][k1][k2]=[float(e) for e in line[2:]]

print(rates)

rawDescription: Efficiently Searching Nested Lists

description: Efficiently Searching Nested Lists


rawDescription: Django Annotate with select_related

description: Django Annotate with select_related


code: b in cycles(a)

description: Clean way to accomplish -- if x in [(0, 1, 2), (2, 0, 1), (1, 2, 0)]:


code:
conn = engine.connect()
conn.execute("INSERT INTO users VALUES (1, 'john')")  # autocommits

rawDescription: how to set autocommit = 1 in a sqlalchemy.engine.Connection

description: Set autocommit = 1 in a sqlalchemy.engine.Connection


rawDescription: Converting letters to numbers and performing sequence of operations along the length in Python


code: subprocess.call(['ls', '-l', dir], shell=True)

rawDescription: Subprocess– showing X lines of output

description: Subprocess– showing X lines of output