code:
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Rect(object):
    def __init__(self, p1, p2):
        '''Store the top, bottom, left and right values for points
               p1 and p2 are the (corners) in either order
        '''
        self.left   = min(p1.x, p2.x)
        self.right  = max(p1.x, p2.x)
        self.bottom = min(p1.y, p2.y)
        self.top    = max(p1.y, p2.y)

    def __str__(self):
         return "Rect[%d, %d, %d, %d]" % ( self.left, self.top, self.right, self.bottom )

def range_overlap(a_min, a_max, b_min, b_max):
    '''Neither range is completely greater than the other
    '''
    return (a_min <= b_max) and (b_min <= a_max)

def rect_overlaps(r1,r2):
    return range_overlap(r1.left, r1.right, r2.left, r2.right) and range_overlap(r1.bottom, r1.top, r2.bottom, r2.top)

rawDescription: Combining rectangle/square areas into bigger ones - imshow/python


rawDescription: Pandas group by several values in a single column


code: import somemodule

rawDescription: Replacing an imported module dependency

description: Replacing an imported module dependency


code:
f = open('really_big_file.dat')
def read1k():
    return f.read(1024)

for piece in iter(read1k, ''):
    process_data(piece)

rawDescription: Lazy Method for Reading Big File in Python?


code:
def stars_and_bars(star='*', bar='|', star_count=8, bar_count=2):
    if star_count == 0:
        yield (bar,) * bar_count
        return
    if bar_count == 0:
        yield (star,) * star_count
        return
    for left in range(star_count + 1):
        right = star_count - left
        assert right >= 0
        assert left + right == star_count
        for partial in stars_and_bars(star, bar, left, bar_count - 1):
            yield partial + (bar,) + (star,) * right

rawDescription: How can i create a permutation with a limit on specific characters efficently?

description: Create a permutation with a limit on specific characters efficently


code:
import copy
new_list = copy.deepcopy(old_list)

rawDescription: How to clone or copy a list in Python?

description: Clone or copy a list in Python


code:
def Add(self, *args):
    for card in args:
        self.cards.insert(0, card)

rawDescription: Two functions same name python

description: Two functions same name python


code: {{ postone.user|make_list|first }}

rawDescription: Want to display the first character of word in django templates


rawDescription: Biopython PDB: calculate distance between an atom and a point


code:
def scatter_dict(view, name, d):
    """partition a dictionary across the engines of a view"""
    ntargets = len(view)
    keys = d.keys() # list(d.keys()) in Python 3
    for i, target in enumerate(view.targets):
        subd = {}
        for key in keys[i::ntargets]:
            subd[key] = d[key]
        view.client[target][name] = subd

scatter_dict(dview, 'test', test_dict)

rawDescription: Parallelize function on dictionary in IPython


code:
df
df.pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')  # desired?
df1 = df.set_index([0, 1, 2])
df1
df1.unstack(2)

rawDescription: Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape


code:
from contextlib import closing

def process_chunks():
    while True:
        try:
            chunk = yield
        except GeneratorExit:
            finish_up()
            return
        else:
            do_whatever_with(chunk)

with closing(process_chunks()) as coroutine:

    # Get the coroutine to the first yield
    coroutine.next()

    FTP.retrbinary(command, callback=coroutine.send)
# coroutine.close() #  called by exiting the block

rawDescription: Python FTP "chunk" iterator (without loading entire file into memory)


code:
# python test_me.py - Ran 1 test in 0.000s
# python test_other.py - Ran 1 test in 0.000s

rawDescription: Run unittests from a different file

description: Run unittests from a different file


code:
# 1. Plot in same line, this would work
fig = plt.figure(figsize = (15,8))
ax1 = fig.add_subplot(1,2,1, projection = '3d')
custom_plot1(ax1)
ax2 = fig.add_subplot(1,2,2)
custom_plot2(ax2)

# 2. Plot in same line, on two rows
fig = plt.figure(figsize = (8,15))                  # Changed the size of the figure, just aesthetic
ax1 = fig.add_subplot(2,1,1, projection = '3d')     # Change the subplot arguments
custom_plot1(ax1)
ax2 = fig.add_subplot(2,1,2)                        # Change the subplot arguments
custom_plot2(ax2)

rawDescription: Python & Matplotlib: Plot multiple figure in the same line


rawDescription: Write data to file

description: Write data to file


rawDescription: Call GUID function more than once in print formatting in python


code:
import re
from datetime import datetime

# test data
link = '"Something":"foo","Date":"1448204858","Otherthing":"bar"'

match=re.compile('"Date":"(.+?)"').findall(link)
dt = datetime.fromtimestamp(float(match[0]))

print(repr(dt))
print(dt.strftime('%Y-%m-%d %H:%M:%S'))

rawDescription: Get Unix date (numeric) from string and convert to Python date


code:
for i in range(len(a)):
    print(a[i][0])

rawDescription: Python: Picking a certain element from an array


code:
for row, data in enumerate(fileData):
    if row > row_elements: # below `top_row`
        try:
            int(data[0])
        except ValueError:
            break # not an int value, `bottom_row` found

        # if we get here, we’re between the top- and bottom row.
        elements.append(data)

rawDescription: Loop thru a list and stop when the first string is found


code:
class A():
    number = 0

rawDescription: Fastest and pythonic way of deletion of objects in this code


code: filtered_dict = {k:v for k,v in d.iteritems() if filter_string in k}

rawDescription: filter items in a python dictionary where keys contain a specific string

description: Filter items in a python dictionary where keys contain a specific string


code:
import sys
import os
import time
import itertools
import multiprocessing as mp
import numpy as np
import matplotlib.nxutils as nx
import liblas
import shapefile

clock = time.clock if sys.platform == 'win32' else time.time

def LAS2TXTClipSplitbyChunk(inFile, poly, chunkSize = 1, MinPoints = 1):
    sf = shapefile.Reader(poly) #open shpfile
    sr = sf.shapeRecords()
    poly_filename, ext = os.path.splitext(poly)
    for record in sr:
        inFile_filename = os.path.splitext(os.path.basename(inFile))[0]
        record_num = record.record[0]
        out_filename = '{0}_{1}_{2}.txt'.format(
            poly_filename, inFile_filename, record_num)
        pool.apply_async(pointinside,
                         args = (record, out_filename, inFile, chunkSize, MinPoints),
                         callback = update)

def pointinside(record, out_filename, inFile, chunkSize, MinPoints):
    start = clock()
    record_num = record.record[0]
    verts = np.array(record.shape.points, float)
    f = iter(liblas.file.File(inFile, None, 'rb'))
    result = []
    worth_writing = False
    for chunk in iter(lambda: list(itertools.islice(f, chunkSize)), []):
        points = [(p.x, p.y) for p in chunk]
        index = nx.points_inside_poly(points, verts)
        chunk = [p for inside, p in itertools.izip(index,chunk) if inside]
        for p in chunk:
            fields = (p.x, p.y, p.z, p.intensity, p.return_number,
                      p.number_of_returns, p.scan_direction, p.flightline_edge,
                      p.classification, p.scan_angle, record_num)
            result.append(' '.join(map(str, fields)))
        if len(result) >= bufferSize:
            # Writing to disk is slow. Doing it once for every iteration is
            # inefficient.  So instead build up bufferSize number of lines
            # before writing them all to disk.
            worth_writing = True
            with open(out_filename, 'a') as file_out:
                file_out.write('\n'.join(result)+'\n')
            result = []
    # In case there were some results (less than bufferSize lines), we
    # dump them to disk here.
    if (len(result) >= MinPoints) or worth_writing:
        with open(out_filename, 'a') as file_out:
            file_out.write('\n'.join(result)+'\n')
    f.close()
    end = clock()
    return end-start

def update(result):
    with open(debug_filename, 'a') as f:
        f.write('{r}\n'.format(r = result))

if __name__ == '__main__':
    workdir = 'C://04-las_clip_inside_area//prova//'
    # workdir = os.path.expanduser('~/tmp/tmp')
    os.chdir(workdir)
    inFile = 'Ku_115_class_Notground_normalize.las'
    poly = 'ku_115_plot_clip.shp'
    debug_filename = 'debug.dat'
    chunkSize = None
    MinPoints = 1
    bufferSize = max(MinPoints, 100)

    pool = mp.Pool()
    LAS2TXTClipSplitbyChunk(inFile, poly, chunkSize, MinPoints)
    pool.close()
    pool.join()

rawDescription: Python: memory problems in a script

description: Python: memory problems in a script


rawDescription: How to set first column to a constant value of an empty np.zeros numPy matrix?

description: Set first column to a constant value of an empty np.zeros numPy matrix


code:
def set(self, key, value, callback=None):
    self.execute_command('SET', key, value, callback=callback)

rawDescription: how to do asynchronous writes to redis in tornado

description: Do asynchronous writes to redis in tornado


code:
def read_date(date_str: str) -> datetime:
    return datetime.strptime(date_str, 'date(%m-%d-%Y)').date()

# The read_date helper imports the date(...) strings as Python date objects
data_clan = import_csv(StringIO(mycsvfile), {'col1': int, 'col2': read_date})

rawDescription: Comparing date object in a Couplet between two dates


rawDescription: Table with missing <tr> around a row: can I parse it?


code: decreasing_pixels = (myArray[0] >= myArray[1]) * (myArray[1] >= myArray[2])

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

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


code:
def eliminate_consonants(x):
        vowels= ['a','e','i','o','u']
        for char in x:
            if char in vowels:
                print(char,end = "")

eliminate_consonants('mississippi')

rawDescription: Deleting consonants from a string in Python


code: filename = cmd[6:]

rawDescription: Using part of input as a filename

description: Using part of input as a filename


code:
my_list = [(v, k[0], k[1]) for k,v in dd.iteritems()]
my_list
# If you need the output sorted:
sorted_my_list = sorted(my_list, key = lambda k : len(k[0]), reverse=True)
sorted_my_list

rawDescription: Summarize a list of dictionaries based on common key values


code: today = pd.datetime.today()

rawDescription: return pandas DF column with the number of days elapsed between index and today's date

description: Return pandas DF column with the number of days elapsed between index and today's date


code: reduce(lambda x,y : x^y, [hash(item) for item in d.items()])

rawDescription: Python, checksum of a dict

description: Python, checksum of a dict


rawDescription: how to sort lists within list in user defined order?

description: Sort lists within list in user defined order


code: from django.core import management

rawDescription: Can I combine custom django-admin commands?

description: Combine custom django-admin commands


code:
text = "header1svdijfooter1ccsdheader2cdijhfooter2"
headers = ["header1", "header2"]
footers = ["footer1", "footer2"]

import re

matches = [re.search(r"{}\w+?{}".format(header,footer),text).group() for header,footer in zip(headers,footers) if re.search(r"{}\w+?{}".format(header,footer),text)]

rawDescription: How to cut out matched string

description: Cut out matched string


code: url = "http://{0}:8080/api/{1}/{2}.get?query=(name LIKE '%{3}%')".format(servername, environment, component, componentname)

rawDescription: python - replace values in url

description: Python - replace values in url


code:
dis.dis(first)
dis.dis(second)

rawDescription: Python: Efficient way to call inbuilt function multiple times?


rawDescription: Python - Addings nulls

description: Python - Addings nulls


code:
import itertools
indices = list(itertools.product(range(N), range(N)))

rawDescription: Matrix with given numbers in random places in python/numpy


code: diff - s1

rawDescription: Why does timedelta function return 0 seconds when datetimes are perfect number of days apart?


code:
most_recent = {}
for user, date in myList:
    most_recent[user] = max(most_recent.get(user, date), date)

newList = [(user, most_recent[user]) for user, _ in myList]

rawDescription: Complex python list processing

description: Complex python list processing


rawDescription: Theano scan for fast computations on an array


code:
fasta_data = {} # creates an empty dictionary
with open( fasta_file, 'r' ) as fh:
    for line in fh:
        if line[0] == '>':
            seq_id = line.rstrip()[1:] # strip newline character and remove leading '>' character
            fasta_data[seq_id] = ''
        else:
            fasta_data[seq_id] += line.rstrip()

# return substring from chromosome 'chrI' with a first character at amino_start up to but not including amino_end
sequence_string1 = fasta_data['chrI'][amino_start:amino_end]
# return substring from chromosome 'chrII' with a first character at amino_start up to and including amino_end
sequence_string2 = fasta_data['chrII'][amino_start:amino_end+1]

rawDescription: complex regex matches in python

description: Complex regex matches in python


code:
def col_avg2(df, col_ids):
    means = df.iloc[:, col_ids].mean(axis=1)
    for i in col_ids:
        df.iloc[:, i] -= means

rawDescription: Pandas: how to concisely detrend subset of columns


rawDescription: Find same elements in a list, and then change these elemens to tuple (f.e. 2 to (2,1))


code:
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

from hbase import Hbase
from hbase.ttypes import *

from random import randrange
from pprint import pprint

socket = TSocket.TSocket('localhost', 9090)
transport = TTransport.TBufferedTransport(socket)
transport.open()
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Hbase.Client(protocol)

table_name = 'test_table'
row_key = 'test_row1'
colfamily1 = 'test_colfamily1'
column1 = 'test_col1'
fullcol1 = ('%s:%s' % (colfamily1, column1))
value = ('%d' % randrange(1000, 9999))

num_versions = 3

try:
    desc = ColumnDescriptor(colfamily1)
    client.createTable(table_name, [desc])
except AlreadyExists:
    pass

client.mutateRow(table_name, row_key, [Mutation(column=fullcol1, value=value)], {})
results = client.getVer(table_name, row_key, fullcol1, num_versions, {})

pprint(results)

rawDescription: mutateRow() in HBase through Thrift requires undocumented fourth argument

description: MutateRow() in HBase through Thrift requires undocumented fourth argument


code:
RunnerList = A()
RunnerList.Runner(number)
the_list_you_need=RunnerList.NumofLaps

rawDescription: Accessing a list on a separate method in a separate class in python


code: simple()

rawDescription: A simple looping command In Python

description: A simple looping command In Python


code:
accuracy = (tp + tn) / (tp + tn + fp + fn)
precision = tp / tp + fp

rawDescription: IOB Accuracy on NLTK named entity recognition


code: parameter = input('Parameter you want to change: ')

rawDescription: How to exchange parameter in list in file by new input

description: Exchange parameter in list in file by new input


group_name: Ilgauskas,Zydrunas - James,LeBron - Wallace,Ben - West,Delonte - Williams,Mo

group_set: Lineups

rawDescription: crawl dynamic webpage for data using scrapy

description: Crawl dynamic webpage for data using scrapy


code:
from bs4 import BeautifulSoup
import re

html = ... # your html goes here
soup = BeautifulSoup(html)

telephone_p = soup.find_all(text=re.compile(r'Tel:'))
telephone = telephone_p[0].replace('Tel:', '').strip()
fax_p = soup.find_all(text=re.compile(r'Fax:'))
fax = fax_p[0].replace('Fax:', '').strip()
address_ps = soup.find_all('p')[:2]
address = '\n'.join([p.text for p in address_ps])

print(telephone)
print(fax)
print(address)

rawDescription: Parse HTML, set datas to variables

description: Parse HTML, set datas to variables


code:
('Difensori dei diritti umani', 'Human rights defenders')
('libertà di espressione', 'freedom of expression')

rawDescription: Creation of bigrams in python

description: Creation of bigrams in python


code:
dbCursor.execute("""
PREPARE cms_lib_insert (bigint, text, text) AS
INSERT INTO cms_libraries (cms_library_ident, cms_library_name, cms_library_type_id, cms_library_status_id)
VALUES ($1, $2,
    (select id from cms_library_types where cms_library_type_name = $3),
    (select id from cms_library_status where cms_library_status_name = 'active')
)
RETURNING cms_library.id
""")

rawDescription: Python with postgres using named variables and bulk inserts


rawDescription: Create a list of lists using Python

description: Create a list of lists using Python


code: dict((k, mydict[k]) for k in keys_to_select if k in mydict)

rawDescription: Selecting dictionary items by key efficiently in Python


rawDescription: Python - reference object in memory by address


code: map(tuple, a)

rawDescription: What is the easiest way to make tuples of the rows in an array?


code:
import pymunk
pymunk.init_pymunk()
space = pymunk.Space()
space.gravity = (0.0, -100.0)

rawDescription: Simulating a simple physics related scenario


rawDescription: Can I add arguments to python code when I submit spark job?

description: Add arguments to python code when I submit spark job


rawDescription: Match the folder list by using regex in python


code:
def __str__(self):
    ret = ""
    for i in vars(self).values():
        if isinstance(i, A):
            ret += str(i)
    return ret

rawDescription: Filter attributes of a class based on the type


code:
class AlchemyEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, tuple):
            data = {}
            for obj in o:
                data.update(self.parse_sqlalchemy_object(obj))
            return data
        if isinstance(o.__class__, DeclarativeMeta):
            return self.parse_sqlalchemy_object(o)
        return json.JSONEncoder.default(self, o)

    def parse_sqlalchemy_object(self, o):
        data = {}
        fields = o.__json__() if hasattr(o, '__json__') else dir(o)
        for field in [f for f in fields if not f.startswith('_') and f not in ['metadata', 'query', 'query_class']]:
            value = o.__getattribute__(field)
            try:
                json.dumps(value)
                data[field] = value
            except TypeError:
                data[field] = None
        return data

rawDescription: How to serialize SqlAlchemy join query to JSON?

description: Serialize SqlAlchemy join query to JSON


code:
f = os.fdopen(tup[0], "w")
f.write("foo")

rawDescription: Python - How do I convert "an OS-level handle to an open file" to a file object?


code:
#!/usr/bin/env python
import sys
from functools import partial
from itertools import takewhile

def get_tokens(stream=sys.stdin):
    token = []
    for char in iter(partial(stream.read, 1), ''):
        if char.isspace(): # use any space as a separator
            if token:
                yield ''.join(token)
                del token[:]
        else:
            token.append(char)
    if token:
        yield ''.join(token)

print(' '.join(takewhile(lambda s: s != '-1', get_tokens())))

rawDescription: How to stop reading input from user after a certain char using raw_input() in Python?

description: Stop reading input from user after a certain char using raw_input() in Python


code:
sample, value = strs.split(':')
sample
value

rawDescription: Replace character in line inside a file

description: Replace character in line inside a file


code:
numbers = itertools.count(1) # all positive integers
squares = (x**2 for x in numbers) # all squares of positive integers
totals = itertools.accumulate(squares) # all running totals of squares of ...
bigtotals = itertools.dropwhile(lambda total: total < n, totals) # all ... starting >= n
total = next(bigtotals) # first ... starting >= n

rawDescription: How to calculate the value of the sum of squares defined as 1^2 + 2^2 + 3^2 + ... +n2 until a user specified sum has been reached

description: Calculate the value of the sum of squares defined as 1^2 + 2^2 + 3^2 + ... +n2 until a user specified sum has been reached


code:
from xml.etree import ElementTree as ET
sample = '''\
<visu>
    <time>12:34</time>
    <name>my_visu</name>
    <language>english</language>
    <vars>
        <var name="input1">2</var>
        <var name="input2">45.6</var>
        <var name="input3">"hello"</var>
    </vars>
</visu>
'''
root = ET.fromstring(sample)
name = 'input2'
root.find('.//vars/var[@name="{}"]'.format(name)).text

rawDescription: How to get the child of child using Python's ElementTree

description: Get the child of child using Python's ElementTree


code:
import pickle
class Character():
    def __init__(self):
        self.name = None
        self.hp = None
        self.mp = None

class Race(Character):
    def __init__(self):
        super().__init__()
        self.race = None

name_game = input('Name your game: ')

cur_save=open('saves/' + name_game + '.p', 'wb')
player = Character()
player_name = input('Name your character: ')
player.name = player_name
player_race = input('What is your race? ')
player.race = player_race
pickle.dump(player, cur_save, -1)
cur_save.close()

cur_save=open('saves/' + name_game + '.p', 'rb')
player = pickle.load(cur_save)
print(player.name)

rawDescription: Saving and Loading a Class Instance

description: Saving and Loading a Class Instance


code: field.widget = field.hidden_widget()

rawDescription: How do you dynamically hide form fields in Django?

description: Dynamically hide form fields in Django


code:
import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')

def openExcel(makeExcelVisible=True):
    excel.Visible = makeExcelVisible

def closeExcel():
    excel.Application.Quit()

class ExcelFile(object):
# opens up a workbook to work on, not selecting a file name creates a new one
    def __init__(self, fileName=None):
        if fileName == None:
            self.wb = excel.Workbooks.Add()
        else:
            self.wb = excel.Workbooks.Open(fileName)
        self.ws = None

    def addWorksheet(self):
    # adds a new worksheet to the workbook and makes it the current worksheet
        self.ws = self.wb.Worksheets.Add()

    def selectWorksheet(self, worksheetName):
    # selects a worksheet to work on
        self.ws = self.wb.Worksheets(worksheetName)

    def renameWorksheet(self, worksheetName):
    # renames current worksheet
        self.ws.Name = worksheetName

    def save(self):
    # saves the workbook
        self.wb.Save()

    def saveAs(self, fileName):
    # saves the workbook with the file name
        self.wb.SaveAs(fileName)

    def close(self):
    # closes the workbook
        self.wb.Close()

    def insertIntoCell(self, cellRow, cellCol, data):
        self.ws.Cells(cellRow,cellCol).Value = data

    def clearCell(self, cellRow, cellCol):
        self.ws.Cells(cellRow,cellCol).Value = None

rawDescription: python write to EXCEL cell range (NumPy?)

description: Python write to EXCEL cell range (NumPy?)


rawDescription: What is the best escape character strategy for Python/MySQL combo?


code:
from scipy.spatial import distance

positions = np.random.rand(10, 2)
counts = np.random.randint(1, 5, len(positions))

distances = distance.pdist(positions)
i, j = np.triu_indices(len(positions), 1)

bins = np.linspace(0, 1, 10)
h, b = np.histogram(distances, bins=bins, weights=counts[i]*counts[j])

rawDescription: Multiply number of distances in distance matrix prior to histogram binning


code:
import numpy as np
import scipy as sp
from scipy.optimize import curve_fit

def lorentzian(x, a, x0):
    return a / ((x-x0)**2 + a**2) / np.pi

# Obtain xdata and ydata
...

# Initial guess of the parameters (you must find them some way!)
pguess = [a_guess, x0_guess]

# Fit the data
popt, pcov = curve_fit(lorentzian, xdata, ydata, p0 = pguess)

# Results
a, x0 = popt[0], popt[1]

rawDescription: Fit points to a Lorentzian curve and find center and half maximum bandwidth in Python


code: norm = [float(i)/sum(raw) for i in raw]

rawDescription: Normalizing a list of numbers in Python

description: Normalizing a list of numbers in Python


code:
ircsock.send(bytes("NICK " + nick + "\r\n", 'UTF-8'))
ircsock.send(bytes("USER " + nick + " " + nick + " " + nick + " :" + nick + "\r\n", 'UTF-8'))

rawDescription: Creating a simple IRC bot in python. Having trouble


rawDescription: How to decide if an string is in hh:mm format in python?

description: Decide if an string is in hh:mm format in python


code:
# Assumption: question_list has tuples (<question_no>,<learning_obj>,<exam_date>)
learning_dict = {}
for question in question_list:
  question_no = question[0]
  learning_obj = question[1]
  if learning_obj in learning_dict:
    learning_dict[learning_obj].append(question_no)
  else:
    learning_dict[learning_obj] = [question_no]

rawDescription: Randomly Generating Exam Questions. Numbers based on Number + Letter associated with Questions


rawDescription: How do I create this object with the models I have set up?

description: Create this object with the models I have set up


code:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

rawDescription: Update new Django and Python 2.7.* with virtualenv on Dreamhost (with passenger)


code: [x.strip(string.punctuation) for x in punc]

rawDescription: Stripping punctuation from a list of lists of words


rawDescription: Retrieve indices of NaN values in a pandas dataframe


rawDescription: All possible random tiles in 2048(Stupid issue)


rawDescription: Unicode character render

description: Unicode character render


code: weights_h = [[random.random() for e in inputs[0]] for e in range(hiden_neurons)]

rawDescription: Simple way to create matrix of random numbers


code:
def getDollarFormatText(dolAndCent):

    separateDolCent = [int(x) for x in str(dolAndCent).split('.')]

    return separateDolCent

rawDescription: Beginner Python: Extract List to integer


code:
def tryconvert(value, *types):
    for t in types:
        try:
            return t(value)
        except (ValueError, TypeError):
            continue
    return value

for line in infile:
    data = [tryconvert(x, int, float) for x in line.split()]

rawDescription: Python: How can I read in the characters from a line in a file and convert them to floats and strs, depending on if they are numbers or letters?


code:
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse

class KeyAuthMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        login_url = reverse('key_auth_login') # your custom named view

        # Exceptional pages
        login_page = request.path.find(login_url) == 0
        logout_page = request.path.find(reverse('logout')) == 0
        admin_page = request.path.find(reverse('admin:index')) == 0 # I've excluded Admin Site urls

        if not login_page and not logout_page and not admin_page:
            view_func = login_required(view_func, login_url=login_url)

        return view_func(request, *view_args, **view_kwargs)

rawDescription: Security issues with a middleware screener page


code:
import xml.etree.ElementTree as ET

def find_rec(node, element, result):
    for item in node.findall('saybye'):
        result.append(item)
        find_rec(item, element, result)
    return result

find_rec(ET.parse("h.xml"), 'saybye', [])

rawDescription: ElementTree - findall to recursively select all child elements


code:
class PermissionList(models.Model):
    setter = models.ManyToManyField(User)
    email = models.EmailField(unique=True) #don't want conflicting results
    permission = models.BooleanField()

rawDescription: email whitelist/blacklist in python/django

description: Email whitelist/blacklist in python/django


code:
class Player(object):
    # has self.card1, self.card2

    def __str__(self):
        return "Player's Cards %s %s (Total %d)" % (
            self.card1, self.card2, self.__sum_of_cards()
        )

rawDescription: Python - __str__ returning elements of a list


rawDescription: Python, using Selenium how to clean page_source from char like /a0:


code:
x = 1.5
y = 1.5
items = [x-1, x, x+1]
cp = []
for i in items:
    for j in items:
        if i != x or j != y:
            cp.append([i, j])

items = cp
items

rawDescription: Creating a list with two different numbers


code:
if __name__ == '__main__':
    dict_filename = 'dictionary.txt'
    print("part 4")
    part4(dict_filename)

rawDescription: This code isn't displaying the correct answer


code:
dbengine.echo = True
session.query(MyTable).filter_by(specified_field = 'some_value').all()

rawDescription: Persistent where clause SQLAlchemy

description: Persistent where clause SQLAlchemy


code:
import pygame
from pygame.locals import *

pygame.init()
screen=pygame.display.set_mode((640,480))

class Block(object):
    sprite = pygame.image.load("dirt.png").convert_alpha()
    def __init__(self, x, y):
        # since x and y will be the mouse position,
        # let x and y be the center of the block
        self.rect = self.sprite.get_rect(centery=y, centerx=x)

blocklist = []

while True:
    # don't forget to clear the screen
    screen.fill((0, 0, 0))
    mouse_pos = pygame.mouse.get_pos()

    for event in pygame.event.get():
        if event.type == QUIT: exit()
        if event.type == pygame.MOUSEBUTTONUP:
            # get all blocks that "collide" with the current mouse position
            to_remove = [b for b in blocklist if b.rect.collidepoint(mouse_pos)]
            for b in to_remove:
                blocklist.remove(b)

            # if we didn't remove a block, we create a new one
            if not to_remove:
                blocklist.append(Block(*mouse_pos))

    for b in blocklist:
        screen.blit(b.sprite, b.rect)

    pygame.display.update()

rawDescription: Pygame: Removing an entity from a list

description: Pygame: Removing an entity from a list


code:
class C(P):
    def __init__(self, a, b, c):
        super(C, self).__init__(a, b)
        self.c = c

rawDescription: Passing arguments to superclass constructor without repeating them in childclass constructor


code:
import pandas as pd

df = pd.DataFrame({'Name': ['Curly', 'Moe', 'Larry'],
                   'Fruit': [['Apple'], ['Orange'], ['Apple', 'Banana']]},
                  columns=['Name', 'Fruit'])

# a one-liner... that's pretty long
dummies_df = pd.get_dummies(
  df.join(pd.Series(df['Fruit'].apply(pd.Series).stack().reset_index(1, drop=True),
                    name='Fruit1')).drop('Fruit', axis=1).rename(columns={'Fruit1': 'Fruit'}),
  columns=['Fruit']).groupby('Name', as_index=False).sum()

print(dummies_df)

rawDescription: get_dummies for Pandas column containing list

description: Get_dummies for Pandas column containing list


code:
['CLUB TENIS DE MESA PORTOBAIL', 'C.T.M. PORTOBAIL', '63097005534']
[u'Club', u'Nombre Equipo', u'Telefono fijo']

rawDescription: Extracting table data from html with python and BeautifulSoup


code:
def recursive_appending(dict, list,e,inittext):
  if not e in dict:
    list.append(inittext + "." + e)
  else:
    for z in dict[e]:
      recursive_appending(dict, list,z,inittext + "." + e)

def rearrange_dict(dict_1, root):
    dict_2 = {root: []}
    for x in dict_1[root]:
        if x in dict_1:
            for z in dict_1[x]:
                recursive_appending(dict_1, dict_2[root],z,x)
        else:
          dict_2[root].append(x)
    return dict_2

dict_1 ={'a' : ['X1', 'X2'] , 'X2' : ['Y1','Y2'] , 'Y1':['Z1','Z2','Z3'], 'Z1':['A1','A2']}
root = 'a'
print(rearrange_dict(dict_1, root))

rawDescription: How to rearrange the elements contained in lists in a dictionary

description: Rearrange the elements contained in lists in a dictionary


code:
class Element(object):
    def __init__(self, name, children=None):
        self.name = name
        self.children = [] if children is None else children
    def to_dict(self):
        d = {'name': self.name}
        if self.children:
            d['children'] = [c.to_dict() for c in self.children]
        return d

def add_items(children, items):
    head, *tail = items
    for child in children:
        if child.name == head:
            break
    else:
        child = Element(head)
        children.append(child)
    if tail:
        add_items(child.children, tail)

root = Element('root')

with open('commands.txt') as f:
    for line in f:
        items = line.strip().split()
        add_items(root.children, items)

rawDescription: Text file with repeated elements to JSON


code:
result = {}
for k1, k2, v1, v2 in data:
    for k in (k1, k2):
        result[k] = v

rawDescription: Python: dict comprehension with multiple key-value pairs in the same time


rawDescription: Sorting lists in dictionary

description: Sorting lists in dictionary


rawDescription: How to calculate longitude using PyEphem

description: Calculate longitude using PyEphem


code: filenames = sys.argv[1:]

rawDescription: Merge tab-delimited files horizontally with files of different row lengths


code:
import glumpy
import numpy as np

# Generate some data...
x, y = np.meshgrid(np.linspace(-2,2,200), np.linspace(-2,2,200))
x, y = x - x.mean(), y - y.mean()
z = x * np.exp(-x**2 - y**2)

window = glumpy.Window(512, 512)
im = glumpy.Image(z.astype(np.float32), cmap=glumpy.colormap.Grey)

@window.event
def on_draw():
    im.blit(0, 0, window.width, window.height)
window.mainloop()

rawDescription: Display array as raster image in python

description: Display array as raster image in python


code: splitter.setSizes([self.width(), 0])

rawDescription: Removing a widget by invoking from a button which is set using QSplitter() in PyQt4


code: output = [ (kl(line),line.rstrip()) for line in output]

rawDescription: How to merge only the unique lines from file_a to file_b?

description: Merge only the unique lines from file_a to file_b


code:
def primesum2(xs, ys):
    sum_limit = max(xs) + max(ys)  # largest possible sum
    count = 0
    primes = set(gen_primes_through(sum_limit))
    for i in xs:
        for j in ys:
            if i+j in primes:
                # print("%s + %s = prime %s" % (i, j, i+j))
                count += 1
    return count

rawDescription: Python 2 lists of positive integers finding prime number


code:
current_word = ''
current_longest = ''
for c in mystring:
    if c in string.ascii_letters:
        current_word += c
    else:
        if len(current_word)>len(current_longest):
            current_longest = current_word
            current_word = ''
else:
    if len(current_word)>len(current_longest):
        current_longest = current_word

rawDescription: Python: Find the longest word in a string


rawDescription: Swap columns in a nested list (Python 3)


code:
match = pattern.findall('this is the message. review: http://url.com/123 http://url.com/456')
match

rawDescription: Python regex to match multiple times

description: Python regex to match multiple times


code:
import mod
...
mod.fn()

rawDescription: personal libraries C-like in Python

description: Personal libraries C-like in Python


code:
from itertools import product
for y, x in product(range(1, 9), range(4)):
    base = 20 if y % 2 == 0 else 10
    print (base + (x * 20), y * 10)

rawDescription: Graphics window that creates a checkerboard with 64 squares,python


code:
class my_label(tk.Frame):
    def __init__(self,parent):
        tk.Frame.__init__(self,parent)
        self.l = tk.Label(self,text="some text")
        self.l.grid()
        self.grid()

    # my_update.ButtonPushed will call this method.
    def ButtonPushed(self):
        self.l['text'] = 'pushed'

rawDescription: tkinter : how to call a method of a child from another child

description: Tkinter : how to call a method of a child from another child


rawDescription: Logical OR of 2 indicator columns in pandas


code:
soup.find_all('p')[1]
text = soup.find_all('p')[1].get_text()
text.partition('.')[0] + '.'

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


code:
idx1[idx2] == np.arange(len(X))
idx2[idx1] == np.arange(len(Y))

rawDescription: Interleave two numpy arrays based on element distances (python)


code:
l = ['3445 3332r IT Ron Mose Don Simpson',
     '3446 2334f Teacher Hezen Mike Rob',
     '3447 2344g Writer Mike Robert']
result = [(a, b, c, ' '.join(d), e) for a, b, c, *d, e in (item.split() for item in l)]

rawDescription: Parsing regular strings into a tuple

description: Parsing regular strings into a tuple


rawDescription: combine multiple lists horizontally into a single list

description: Combine multiple lists horizontally into a single list


code:
TextArea = Text()
TextArea.pack(expand=YES, fill=BOTH)

rawDescription: Multiple line text entry box in python

description: Multiple line text entry box in python


code: counts = Counter(d["date"] for d in mylist)

rawDescription: Best way to aggregate a simple dict in Python

description: Aggregate a simple dict in Python


code: self.textField = Entry(self.top)

rawDescription: Python Tkinter - Close dialog without closing main window


rawDescription: Python list check if 2 largest values are the same


rawDescription: How do I multiply more the one variable by a number simultaneously

description: Multiply more the one variable by a number simultaneously


code:
from flask import Flask, request, redirect, url_for
from flask_wtf import Form
from wtforms.fields import PasswordField
from wtforms.validators import InputRequired

app = Flask(__name__)

class WifiForm(Form):
    password = PasswordField(validators=[InputRequired()])

@app.route('/wifi-password', methods=['GET', 'POST'])
def wifi_password():
    form = WifiForm()

    if form.validate_on_submit():
        password = form.password.data

        with open('/boot/wpa_supplicant.conf', 'w') as f:
            f.write('valid conf file with password')

        return redirect(url_for('index'))

    return render_template('wifi_password.html', form=form)

rawDescription: Python Flask WTForms - appending files based on user input


code: c

rawDescription: Assigning values to two dimensional array from two one dimensional ones


rawDescription: Numpy/Scipy Sparse vs dense multiplication


code:
import string
import random
string.ascii_letters[:random.randint(1, 50)].title()
string.ascii_letters[:random.randint(1, 50)].title()
string.ascii_letters[:random.randint(1, 50)].title()

rawDescription: Generate in flight string from [A-z]

description: Generate in flight string from [A-z]


code:
import glob
from pydub import AudioSegment

combined_sound = AudioSegment.empty()
for filename in glob.glob('*.wav'):
    combined_sound += AudioSegment.from_wav(filename)

outfile = "sounds.wav"
combined_sound.export(outfile, format='wav')

rawDescription: Concating a list of objects in Python for Pydub module


code:
from datetime import datetime

def get_dates_approved(request):
    user = request.user
    alreadyRated = [x.date.id for x in Ratings.objects.filter(rator=user)]
    dates = Dating.objects.filter((Q(creator=user) | Q(assignee=user)) & Q(accepted=True)) \
                      .exclude(id__in=alreadyRated, finalDate__lt=datetime.today())

rawDescription: Discard older elements in Django queryset


code:
import weakref

class LINK(object):
    pass

class PORT(object):

    def __init__(self, link=None):
        if link is not None:
            self.link = weakref.ref(link)
        else:
            self.link = None

    def __repr__(self):
        if self.link is None:
            return 'None'
        o = self.link()
        return 'None' if o is None else str(id(o))

link = LINK()

port1 = PORT()
port2 = PORT()
port1.link = port2.link = weakref.ref(link)

print(id(link), port1, port2)
del link
print(port1, port2)

rawDescription: How to remove memory location that is referenced objects in python?

description: Remove memory location that is referenced objects in python


code: productlist = [reduce(mul,t) for t in product(*[[i**j for j in range(n)] for i in primes])]

rawDescription: Pythonic way to compute all combinations of products


code:
y, x = np.mgrid[0:a.shape[0]/size, 0:a.shape[1]/size]
y_coords = y[..., np.newaxis] * size + base
x_coords = x[..., np.newaxis] * size + base

rawDescription: Indexes of fixed size sub-matrices of numpy array


code:
def get_time_deltas(infile):
    entries = (line.split() for line in open(INFILE, "r"))
    ts = {}
    for e in entries:
        if len(e) == 11 and " ".join(e[2:5]) == "TMsg out: [O]":
            ts[e[8]] = e[0]   # store timestamp for id
        elif len(e) == 10 and " ".join(e[2:5]) == "TMsg in: [A]":
            in_ts, ref_id = e[0], e[9]
            # Raises KeyError if out msg not seen yet. Handle if required.
            out_ts = ts.pop(ref_id)   # get ts for this id
            yield (ref_id[1:-1], float(in_ts) - float(out_ts))

rawDescription: How do I create a list of timedeltas in python?

description: Create a list of timedeltas in python


code:
#Assuming words is a list of words you wish to query for
import urllib

# replace en.wikipedia.org with the address of the wiki you want to access
query = "http://en.wikipedia.org/w/api?action=query&titles=%s&format=xml" % "|".join(words)
pages = urllib.urlopen(query)

rawDescription: Check if a MediaWiki page exists (Python)


code:
import random
import time
from time import sleep

outcomes = ["TT", "Tt", "Tt", "tt"]
outcomesCount = {"TT":0, "Tt":0, "tt":0}

for x in range(0,5):
    b = "LOADING OUTCOMES" + "." * x
    print(b, end="\r")
    time.sleep(0.5)
print("4 Possible Genetic Outcomes Will Be Shown. . . ")
sleep(1)

for x in range(0,10000):
    choice = (random.choice(outcomes))
    time.sleep(0.001)
    outcomesCount[choice] += 1
    print(choice) #This is something you were doing in original code. I would not do this because there are too many print statements, and will cause the program to run for a while.

print("The number of times each outcome appeared was: ")
print("TT : %s" %(outcomesCount["TT"]))
print("Tt : %s" %(outcomesCount["Tt"]))
print("tt : %s" %(outcomesCount["tt"]))
x = input("Done determining outcomes!! Press enter to close")

rawDescription: Count # of times a certain outcome appears when randomly selecting from a list of possible outcomes


code:
display_s = space_ship # default value at start when ship wasn't rotate

while True:
    clock.tick(60)
    screen.blit(bk, (0, 0))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN and event.button == 3:
            pressed_down = 1
        elif event.type == MOUSEBUTTONUP:
            pressed_down = 0
        if pressed_down == 1:
            x, y = pygame.mouse.get_pos()
            x1, y1 = x - space_ship_rect.x, y - space_ship_rect.y
            angle = math.atan2(y1, x1)
            dx = speed*math.cos(angle)
            dy = speed*math.sin(angle)
            movex = space_ship_rect.centerx = space_ship_rect.centerx + dx#ship x
            movey = space_ship_rect.centery = space_ship_rect.centery + dy#ship y
        if event.type == MOUSEMOTION:
            x1, y1 = pygame.mouse.get_pos()
            x2, y2 = space_ship_rect.centerx, space_ship_rect.centery
            dx, dy = x2 - x1, y2 - y1
            rads = math.atan2(dx, dy)
            degs = math.degrees(rads)

            display_s = pygame.transform.rotate(space_ship, (degs))#rotation of ship
            display_s_rect = display_s.get_rect(center = space_ship_rect.center)

        if event.type == MOUSEBUTTONDOWN and event.button == 1:
            #Is it possible for me to get the degree rotation of the space_ship and apply it to here so the beam will travel in the direction it was shot in?
            pass

    screen.blit(display_s, display_s_rect)
    #screen.blit(display_s, space_ship_rect)

    pos = pygame.mouse.get_pos()
    mousec_rect = mousec.get_rect(centerx=pos[0], centery=pos[1])

    screen.blit(mousec, mousec_rect )

    pygame.display.update()

rawDescription: Python - Pygame bullet movements

description: Python - Pygame bullet movements


code:
class MyClass(object):

    def do_something_periodically(self, delay, repeats, i=0):
        while i < repeats:
            # do something useful
            if not self._sleep(delay, repeats, i):
                break
            i+= 1
        return i

    def _sleep(self, delay, repeats, i):
        time.sleep(delay)
        return True

class MyAsyncioClass(MyClass):

    def do_something_periodically(self, delay, repeats, i=0):
        out = super().do_something_periodically(delay, repeats, i)
        if out == repeats:
            asyncio.get_event_loop().stop()

    def _sleep(self, delay, repeats, i):
        i+=1
        asyncio.get_event_loop().call_later(delay,
                                            self.do_something_periodically,
                                            delay, repeats, i)
        return False

rawDescription: asyncio: Is it possible to release control of the event loop without using yield from?

description: Asyncio: Is it possible to release control of the event loop without using yield from


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

images = np.random.uniform(0, 255, size=(40, 50, 50))

fig, ax = plt.subplots()

fig.show()
for image in images:
    ax.imshow(image)
    fig.canvas.draw()
    ax.cla()

rawDescription: Why does my pylab animation slow down with each update?


code:
import threading
my_thread = threading.Thread(target=func, args=(), kwargs={})
my_thread.daemon = True
my_thread.start()

rawDescription: Parent Thread exiting before Child Threads [python]


code:
tmp = np.zeros((1024,768,3),np.uint_8)

img[y1:y2, x1:x2] = tmp[y3:y4, x3:x4] # given that (y2-y1) = (y4 - y3) and same for x

rawDescription: Filling a blank image with another with opencv


code:
from example import Spam
x = 42
assert(Spam.getX() != x)
assert(not Spam.checkX(x))
Spam.setX(x)
assert(Spam.getX() == x)
assert(Spam.checkX(x))
x = 43
assert(Spam.getX() != x)
assert(not Spam.checkX(x))

rawDescription: C++ statics in Boost.Python

description: C++ statics in Boost.Python


code:
import re

results = {}
with open('example.txt', 'r') as f:
    for line in f.readlines():
        m = re.match(r'([^\d]+)(.*)', line.strip())
        if m and m.group(2):
            results[m.group(1).strip()] = [float(n) for n in m.group(2).split()]

rawDescription: Regexp for matching names followed by optional spaces, but ignoring comments


rawDescription: How to split string at a specific char(set of chars, actually), but with specified length

description: Split string at a specific char(set of chars, actually), but with specified length


rawDescription: Extracting certain range of values from an array


code:
#!/usr/bin/env python

import curses

screen = curses.initscr()
screen.immedok(True)

try:
    screen.border(0)

    box1 = curses.newwin(20, 20, 5, 5)
    box1.immedok(True)

    box1.box()
    box1.addstr("Hello World of Curses!")

    screen.getch()

finally:
    curses.endwin()

rawDescription: Why won't my curses box draw?

description: Why won't my curses box draw


code:
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600)
a = ser.read()
t0 = time.time()

while(a == ser.read()):
    t1 = time.time()
    try:
        print(1 / ((t1-t0)/60))
    except ZeroDivisionError:
        pass
    t0 = t1

rawDescription: Calculating revolutions per minute in Python from an Arduino


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

data = np.random.random((10, 10))

fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='nearest', cmap='gist_earth', aspect='auto',
               extent=[220, 2000, 3000, 330])

ax.invert_yaxis()
ax.set(xlabel='Easting (m)', ylabel='Northing (m)', title='This is a title')
fig.colorbar(im, orientation='horizontal').set_label('Water Depth (m)')

# Now let's add your additional information
ax.annotate('...Additional information...',
            xy=(0.5, 0), xytext=(0, 10),
            xycoords=('axes fraction', 'figure fraction'),
            textcoords='offset points',
            size=14, ha='center', va='bottom')

plt.show()

rawDescription: Python: displaying a line of text outside a matplotlib chart


code: data = data.decode('utf-16le')

rawDescription: how to handle this string in python

description: Handle this string in python


code: test = requests.get('https://utas.s2.fut.ea.com/ut/game/fifa16/trade/{playerNumber}/bid'.format(playerNumber=playerNumber), headers=headers, cookies=cookies)

rawDescription: Adding a param to a URL in Python

description: Adding a param to a URL in Python


rawDescription: rolling_sum on business day and return new dataframe with date as index

description: Rolling_sum on business day and return new dataframe with date as index


code:
from collections import Counter
lst = [1, 3, 5, 7, 9, 5, 3, 5, 3]
def duplicates(list_of_numbers):
   counter = Counter(list_of_numbers)
   return [y for y in counter if counter[y] > 1]

duplicates(lst)

rawDescription: return duplicates in a list

description: Return duplicates in a list


code:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.axis3d import Axis
import matplotlib.pyplot as plt
import matplotlib.projections as proj
from matplotlib.colors import colorConverter

class axis3d_custom(Axis):
    def __init__(self, adir, v_intervalx, d_intervalx, axes, *args, **kwargs):
        Axis.__init__(self, adir, v_intervalx, d_intervalx, axes, *args, **kwargs)
        self.gridline_colors = []
    def set_gridline_color(self, *gridline_info):
        '''Gridline_info is a tuple containing the value of the gridline to change
        and the color to change it to. A list of tuples may be used with the * operator.'''
        self.gridline_colors.extend(gridline_info)
    def draw(self, renderer):
        # filter locations here so that no extra grid lines are drawn
        Axis.draw(self, renderer)
        which_gridlines = []
        if self.gridline_colors:
            locmin, locmax = self.get_view_interval()
            if locmin > locmax:
                locmin, locmax = locmax, locmin

            # Rudimentary clipping
            majorLocs = [loc for loc in self.major.locator() if
                         locmin <= loc <= locmax]
            for i, val in enumerate(majorLocs):
                for colored_val, color in self.gridline_colors:
                    if val == colored_val:
                        which_gridlines.append((i, color))
            colors = self.gridlines.get_colors()
            for val, color in which_gridlines:
                colors[val] = colorConverter.to_rgba(color)
            self.gridlines.set_color(colors)
            self.gridlines.draw(renderer, project=True)

class XAxis(axis3d_custom):
    def get_data_interval(self):
        'return the Interval instance for this axis data limits'
        return self.axes.xy_dataLim.intervalx

class YAxis(axis3d_custom):
    def get_data_interval(self):
        'return the Interval instance for this axis data limits'
        return self.axes.xy_dataLim.intervaly

class ZAxis(axis3d_custom):
    def get_data_interval(self):
        'return the Interval instance for this axis data limits'
        return self.axes.zz_dataLim.intervalx

class Axes3D_custom(Axes3D):
    """
    3D axes object.
    """
    name = '3d_custom'

    def _init_axis(self):
        '''Init 3D axes; overrides creation of regular X/Y axes'''
        self.w_xaxis = XAxis('x', self.xy_viewLim.intervalx,
                            self.xy_dataLim.intervalx, self)
        self.xaxis = self.w_xaxis
        self.w_yaxis = YAxis('y', self.xy_viewLim.intervaly,
                            self.xy_dataLim.intervaly, self)
        self.yaxis = self.w_yaxis
        self.w_zaxis = ZAxis('z', self.zz_viewLim.intervalx,
                            self.zz_dataLim.intervalx, self)
        self.zaxis = self.w_zaxis

        for ax in self.xaxis, self.yaxis, self.zaxis:
            ax.init3d()
proj.projection_registry.register(Axes3D_custom)

rawDescription: How to color a specific gridline/tickline in 3D Matplotlib Scatter Plot figure?

description: Color a specific gridline/tickline in 3D Matplotlib Scatter Plot figure


code:
def hexencode(s):
   return s.encode("hex")
mapping = {'encode_b64': base64.encodestring, 'encode_url': urllib.quote_plus, 'encode_hex': hexencode}

rawDescription: Execute var python

description: Execute var python


code:
from django.db.models.lookups import BuiltinLookup
from django.db.models.fields import Field

class Any(BuiltinLookup):
    lookup_name = 'any'

    def get_rhs_op(self, connection, rhs):
       return " = ANY(%s)" % (rhs,)

Field.register_lookup(Any)

rawDescription: How to avoid brackets in SQL around Django custom database function call?

description: Avoid brackets in SQL around Django custom database function call


code:
def worker(V, element):
    element *= V.value

rawDescription: PySpark broadcast variables from local functions


code: board = [['O' for i in range(5)] for j in range(5)]

rawDescription: Сodecademy 18/19 Battleship

description: Сodecademy 18/19 Battleship


rawDescription: Python convert comma separated list to pandas dataframe


code:
def taskkill(self, pid):
    """
    Kill task and entire process tree for this process
    """
    print('Task kill for PID {0}'.format(pid))
    cmd = 'taskkill /f /t /pid {0}'.format(pid)
    subprocess.call(cmd.split())

rawDescription: How to launch crashing (rarely) application in subprocess

description: Launch crashing (rarely) application in subprocess


code:
class Player(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    avatar = db.Column(db.String(120))
    skill = db.Column(db.Integer)

class Participant(db.Model):
    player_id = db.Column(db.Integer, db.ForeignKey('player.id'),
                          primary_key=True)
    game_id = db.Column(db.Integer, db.ForeignKey('game.id'), primary_key=True)
    winner = db.Column(db.Boolean)

    # relationships
    player = db.relationship('Player')

class Game(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    loser_score = db.Column(db.Integer)

    # relationships
    game_players = db.relationship(
        'Participant',
        collection_class=attribute_mapped_collection("winner"),
        cascade="all, delete-orphan",
        backref="game",
    )

    # this allows usage like: my_game.player[True/False] = my_player
    players = association_proxy(
        'game_players', 'player',
        creator=lambda win, pla: Participant(winner=win, player=pla),
    )

    # winner: an alias to self.players[True]
    @property
    def winner(self):
        return self.players.get(True)

    @winner.setter
    def winner(self, value):
        self.players[True] = value

    @winner.deleter
    def winner(self):
        del self.players[True]

    # loser: an alias to self.players[False]
    @property
    def loser(self):
        return self.players.get(False)

    @loser.setter
    def loser(self, value):
        self.players[False] = value

    @loser.deleter
    def loser(self):
        del self.players[False]

rawDescription: Secondary Join Condition Ignored in Insert SQL Alchemy


rawDescription: Sorting variable number of columns/rows

description: Sorting variable number of columns/rows


code:
import requests
from bs4 import BeautifulSoup

with open('data.txt', 'r') as data:
    for line in data:
        res = requests.get(line.strip()).content
        soup = BeautifulSoup(res, 'html.parser')
        with open('result.txt', 'a') as result_file:
            if soup.find_all('form'):
                result_file.write('{} y\n'.format(line.strip()))
            else:
                result_file.write('{} n\n'.format(line.strip()))

rawDescription: urllib2 and BeautifulSoup - loop through urls and return whether html contains "<form" tag

description: Urllib2 and BeautifulSoup - loop through urls and return whether html contains "<form" tag


code:
f = open("test.dat", "rb")
f.seek(header_size)
b = np.fromfile(f, dtype=dtype)
f.close()

rawDescription: Reading a binary file with numpy structured array


code:
teststring = "Coca-Cola - A History.pdf"
re.sub(r'(\W)-(\W)',r'\1\2',teststring)

rawDescription: Renaming files according to a set of rules


code:
import collections
import psycopg2
import psycopg2.extras

pg = psycopg2.connect(...)
psycopg2.extras.register_hstore(pg)
cursor = pg.cursor()

cursor.execute("""
    SELECT hstore_to_matrix('a=>1,b=>2,c=>3'::hstore);
""")
pairs = cursor.fetchone()[0]
ordered = collections.OrderedDict(pairs)

print(pairs)
# [['a', '1'], ['b', '2'], ['c', '3']]
print(ordered)
# OrderedDict([('a', '1'), ('b', '2'), ('c', '3')])

rawDescription: Return PostgreSQL hstore as OrderedDict using psycopg2 in Python


code:
array([[False, False,  True,  True, False],
       [False, False,  True,  True, False],
       [ True,  True, False, False, False]], dtype=bool)

rawDescription: Find adjacent elements in a 2D numpy grid


code:
file_save_path = os.path.join(config.images_dir, request.POST['image'].filename)
file_contents = request.POST['image'].file.read()

# insert sanity checks here...

save_file = open(file_save_path, 'wb')
save_file.write(file_contents)
save_file.close()

rawDescription: Pylons Uploading Distorted Images on Windows


code: cs = np.zeros(len(amp-1))

rawDescription: Python: Speeding up a slow for-loop calculation (np.append)


code: from PyQt4 import QtCore

rawDescription: how to disable the window maximize icon using PyQt4?

description: Disable the window maximize icon using PyQt4


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

rawDescription: Doing mapping from range of numbers to words


code:
for row_idx, row in enumerate(data):
    for col_idx, element in enumerate(row):
        if row_idx == col_idx:
            continue

rawDescription: Optimizing Very Large Distance Matrix Processing Workflow


code:
from azure.storage import TableService,Entity

ts=TableService(account_name='user',account_key='key')

tasks=ts.query_entities('Events', filter=None, select=None, top=10,next_partition_key=None, next_row_key=None)

task = tasks[0]

columns = [ column for column in task.__dir__() if not str.startwith(column, '__')]

rawDescription: How to get all columns in azure table using python?

description: Get all columns in azure table using python


code:
class Feature( models.Model ):
    feature_name = models.CharField( max_length=128 )
    feature_value = models.TextField()
    part_of = models.ForeignKey( Product )

rawDescription: Django - designing models with virtual fields?


code:
fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax4=fig.add_subplot(2,2,4,projection='3d')

rawDescription: Can I turn an existing ax object into a 3d projection?

description: Turn an existing ax object into a 3d projection


code:
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

rawDescription: How can I use Bootstrap with Django?

description: Use Bootstrap with Django


code: return (modelist, countdict)

rawDescription: Why I cannot pass my parameter python

description: Why I cannot pass my parameter python


code:
map(A, range(3)+range(3))
set(map(A, range(3)+range(3)))
np.unique(map(A, range(3)+range(3)))

rawDescription: numpy.unique generates a list unique in what regard?

description: Numpy.unique generates a list unique in what regard


rawDescription: Splitting a CSV file by range of datetimes


code:
a = np.array(j)
a.sum(axis=0)

rawDescription: Quick way to sum the ith item of a list of lists in python


code:
all_divs = driver.find_elements_by_xpath("//table/tr/td/div") # all_divs should have 10 elements
second_div = all_divs[1] # zero-based index

rawDescription: my xpath is not working

description: My xpath is not working


rawDescription: Cut a Substring of a String which was read by serial in Python


code:
article = ('The computer code has a little bug'
           'im learning python'
           'thanks for helping me'
           'this is trouble'
           'this is a sample sentence'
           'cat in the hat')

rawDescription: Removing stopwords from list using python3


code:
repr(u'Cristina Fern\xe1ndez de Kirchner')
print(u'Cristina Fern\xe1ndez de Kirchner')

rawDescription: Pandas dataframe and character encoding when reading excel file


rawDescription: Splitting string by comma in python

description: Splitting string by comma in python


rawDescription: Extracting rows from a table

description: Extracting rows from a table


code:
#your original code

#declare global variables is_Left and is_Right
is_Left = False
is_Right = False

while not stop:
    #draw controls, boat and water
    #increment WaterLevel and Depth

    #event loop
    for event in pygame.event.get():
        #detect MOUSEBUTTONDOWN event and collision
        if event.type == pygame.MOUSEBUTTONDOWN:
            is_Left = Left_Rect.collidepoint(pygame.mouse.get_pos())
            is_Right = Right_Rect.collidepoint(pygame.mouse.get_pos())

        if event.type == pygame.MOUSEBUTTONUP:
            #reset is_Left and is_Right
            is_Left = False
            is_Right = False

        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    #change Location
    if is_Left:
        Location -= 5
    elif is_Right:
        Location += 5

    CLOCK.tick(FPS)

    pygame.display.update()

rawDescription: How can I get continuous motion in pygame?

description: Get continuous motion in pygame


code: {k: l[v] for k, v in exist.items()}

rawDescription: What's an elegant way to create a dictionary from another dictionary's keys and an array of values?


code:
id(longdat[0])
id(longdat[1])
id(longdat[2])
itemgetter('id')(longdat[1])
itemgetter('id')(longdat[2])
itemgetter('id')(longdat[3])

rawDescription: iterative long-to-wide python one-liner (or two) using groupby

description: Iterative long-to-wide python one-liner (or two) using groupby


rawDescription: Does Dividing by Zero in Python Crash Windows 98, et al?


rawDescription: Python sort 2-D list by time string

description: Python sort 2-D list by time string


code:
cust = QtGui.QLabel(' - Customer - ')
qty = QtGui.QLabel('1234')
qty.setAlignment(QtCore.Qt.AlignRight)
self.topFive.append([cust, qty])
ov_custs.addRow(cust, qty)

rawDescription: How can I right-align the second column in a QFormLayout?

description: Right-align the second column in a QFormLayout


rawDescription: Extract text from an extracted new page from main page


code:
choices = []
for item, weight in loot:
    choices.extend( [item]*weight )

rawDescription: How to make a selective RNG for a game in Python?

description: Make a selective RNG for a game in Python


code:
def collatz_sequence(x):
    seq = [x]
    if x < 1:
       return []
    while x > 1:
       if x % 2 == 0:
         x = x / 2
       else:
         x = 3 * x + 1
       seq.append(x)    # Added line
    return seq

rawDescription: Collatz conjecture sequence

description: Collatz conjecture sequence


rawDescription: Getting 2-d array pattern from user inputs in python


code:
# Explanation

RE = r"""(?:        # Begins the group so we can repeat it
        [A-Z][a-z]+ # Matches one cap letter then any number of lowercase
        -?          # Allows a hyphen at the end of the word w/o requiring it
    ){2,3}          # Ends the group and requires the group match 2 or 3 times in a row
    \s\w+           # Matches a space and the next word
    \s\w+           # Does so again
    # those last two lines could just as easily be (?:\s\w+){2}
"""
RE = re.compile(RE,re.verbose) # will compile the expression as written

rawDescription: regex continue only if positive lookahead has been matched at least once

description: Regex continue only if positive lookahead has been matched at least once


code:
lis = [ '1', '2', '3', '4' ]
def func(x):
    return int(x)

min(lis, key=func) # each value from list is passed to `func`(one at a time)

rawDescription: max() function: how to get the item being iterated and pass to key=func()

description: Max() function: how to get the item being iterated and pass to key=func()


rawDescription: I'm working with a color conversion in python and get 'False' back


code: plt.plot(range(10), '--bo')

rawDescription: matplotlib: Set markers for individual points on a line

description: Matplotlib: Set markers for individual points on a line


code:
instance = conn.run_instances( ami.ami_id, key_name=ami.sshkey.name,
     instance_type=server.game.instance_type,
     security_groups=[server.game.security_group] )
instance = instance.instances[0]

while instance.update() == "pending":
    time.sleep( 5 )

rawDescription: How can I write a python script that can start new EC2 instances?

description: Write a python script that can start new EC2 instances


rawDescription: Split numpy recarray based on value in one column


code:
def GetMaxFlow(flows):
    maks=max(flows, key=lambda k: len(flows[k]))
    return flows[maks],maks

rawDescription: Get longest element in Dict

description: Get longest element in Dict


code:
class Juice:

    def __init__(self, fruits):
        self.fruits = fruits

    @property
    def sugar_content(self):
        return sum(fruit.sugar_content for fruit in self.fruits)

rawDescription: Pythonic way of inheriting many classes?

description: Pythonic way of inheriting many classes


code:
def call_delay(delay, repetitions, func, *args, **kwargs):
    for i in range(repetitions):
        sleep(delay)
        func(*args, *kwargs)

rawDescription: Postponing functions in python

description: Postponing functions in python


code:
from pprint import pprint

import requests
from bs4 import BeautifulSoup

url = "https://developers.google.com/android/nexus/images"
response = requests.get(url)

soup = BeautifulSoup(response.content, "lxml")

data = {}
for device in soup.find_all("h2", id=True)[1:]:
    device_name = device.get_text(strip=True)

    data[device_name] = [version.find("td").get_text(strip=True)
                         for version in device.find_next("table").find_all("tr", id=True)]

pprint(data)

rawDescription: Scraping for bottom row of table

description: Scraping for bottom row of table


code:
{'file3.txt': 'content3',
 'test': {'file1.txt': 'content1', 'file2.txt': 'content2'},
 'test1': {'test2': {'test3': {'file5.txt': 'content5'}}},
 'test2': {'file4.txt': 'content4'}}

rawDescription: Map path list to files structure

description: Map path list to files structure


code: cursor.execute("... WHERE name = ?", (n[1],))

rawDescription: Calculation using a sqlite db in python

description: Calculation using a sqlite db in python


code:
def big(func, args):
    func(*args)

rawDescription: Python: passing a function with parameters as parameter


code: connection.request('POST', '/markdown', json_foo, headers)

rawDescription: Python http.client json request and response. How?


rawDescription: Subclassing datatypes that have views in Python2.7 and Python3


rawDescription: How to keep track of status with multiprocessing and pool.map?

description: Keep track of status with multiprocessing and pool.map


code:
import types

class number(object):
    def __init__(self, value):
        self.value = value

def replace_int(x):
    if isinstance(x, int):
        return number(x)
    else:
        return x

def custom_numbers(f):
    code = f.func_code
    consts = tuple(map(replace_int, code.co_consts))
    new_code = types.CodeType(code.co_argcount, code.co_nlocals,
                              code.co_stacksize, code.co_flags,
                              code.co_code, consts, code.co_names,
                              code.co_varnames, code.co_filename,
                              code.co_name, code.co_firstlineno,
                              code.co_lnotab)
    return types.FunctionType(new_code, f.func_globals, f.func_name)

rawDescription: Python automatic class assignment

description: Python automatic class assignment


rawDescription: Seperate words/numbers from symbols in Python


rawDescription: Google App Engine passing template variables into view with arrays


code:
def nestprint(lst, level=0):
    print('{} is at nesting level {}'.format(lst, level))
    for item in lst:
        if isinstance(item, list):
            nestprint(item, level+1)

rawDescription: Understanding nested lists in Python

description: Understanding nested lists in Python


code:
f.func_closure[2].cell_contents
import inspect
inspect.getsource(_)

rawDescription: How to debug dynamically defined functions in Python?

description: Debug dynamically defined functions in Python


rawDescription: Dot product sparse matrices

description: Dot product sparse matrices


code:
def recurse(i):
    if i > 0:
        recurse(i-1)

rawDescription: Recursive definitions in Python

description: Recursive definitions in Python


code:
def luhn_residue(digits):
    return sum(sum(divmod(int(d)*(1 + i%2), 10))
                 for i, d in enumerate(digits[::-1])) % 10

rawDescription: Generate IMEI in python

description: Generate IMEI in python


code:
df[['page', 'event']] = df['event'].str.extract('page (?P<page>\d+) (?P<event>\w+)')
df

rawDescription: validate rows before computing values using python/pandas DataFrame

description: Validate rows before computing values using python/pandas DataFrame


foo: bar

rawDescription: tornado write a Jsonp object

description: Tornado write a Jsonp object


rawDescription: PyQT - modifying main window widgets from other functions


code: return all((recursively_empty(c) for c in e.getchildren()))

rawDescription: Python lxml - How to remove empty repeated tags


rawDescription: Remove border around image in Pygame

description: Remove border around image in Pygame


code:
class Association(Base):
    __tablename__ = 'associations'

    a_id = Column(Integer, ForeignKey('table_a.id'), primary_key=True)
    b_id = Column(Integer, ForeignKey('table_b.id'), primary_key=True)

    association_property_1 = Column(Float)

    @hybrid.hybrid_property
    def a_property_special(self):
        return self.a.a_property_special

    @a_property_special.expression
    def a_property_special(cls):
        return select([A.a_property_special]).where(A.id==cls.a_id).as_scalar()

    @hybrid.hybrid_property
    def b_a_property_special(self):
        return self.b.a.a_property_special

    @b_a_property_special.expression
    def b_a_property_special(cls):
        return select([A.a_property_special]).where(A.id==B.a_id).where(B.id==cls.b_id).as_scalar()

session.query(
  Association.association_property_1,
  func.abs(Association.a_property_special - Association.b_a_property_special)
 )

rawDescription: In SQLAlchemy, how to access a referenced property in a query when having multiple relationships?


code:
import numpy as np
import matplotlib.pyplot as plt
a = np.random.random_integers(0,1, (3,3))  # generate some fake data
a
mask = a == 0
b = np.random.random_integers(0,9, a.shape) # more fake data
c = np.random.random_integers(1,9, a.shape) # more fake data
b
c
B = np.ma.masked_array(b, mask=mask)  # initialize a masked array
C = np.ma.masked_array(c, mask=mask)
B
C
B/C  # you can divide these 2D matrices element-wise, the mask is retained
(b/c)[~mask]

rawDescription: Get 2D array after mask condition

description: Get 2D array after mask condition


code:
# paying $63.51
x = 6351 // 1000      # == 6    maximum number of $10.00 bills
y = 6351 % 1000       # == 351  $3.51 not payable in 10s.

# you could instead do
y = 6351 - (6351 // 1000) * 1000

# this would give the same result,
# but you've got to admit it's a lot
# less readable.

rawDescription: Can someone please explain to me the way to calculate the number of bills and coins of change in python?


code:
def test_reg():
    good_tests = ["br'", "'", 'r"""', "Ur'", 'B"', '"']
    for t in good_tests:
        assert reg.match(t).group(0) == t, "Failed good test {}".format(t)

    bad_tests  = ["bU'", "bb'", 'Uru"']
    for t in bad_tests:
        assert reg.match(t) is None, "Failed bad test {}".format(t)

rawDescription: Regular expression to find string prefix in Python grammar


code: [float('nan'), float('inf')]

rawDescription: Check if dictionary key is filled with list of 2 numbers


code:
teacher = Teacher.objects.create(name='Susan') # create a teacher object
student1 = Student.objects.create(name='Alan') # create 1st student
student2 = Student.objects.create(name='Mike') # create 2nd student
parent1 = Parent.objects.create(name='George') # create parent object
parent2 = Parent.objects.create(name='John Doe') # create parent object

teacher.student.add(student1) # associate teacher with 1st student
teacher.student.add(student2) # associate teacher with 2nd student

student1.parents.add(parent1) # associate 1st student with parent1
student2.parents.add(parent2) # associate 2nd student with parent2

rawDescription: How do I fill in nested ManyToMany fields in Django with Shell?

description: Fill in nested ManyToMany fields in Django with Shell


code:
son_value = family['son']
family.clear()
family['son'] = son_value

rawDescription: How to delete all other keys but keep 1 key in the dictionary

description: Delete all other keys but keep 1 key in the dictionary


code:
class Test:
    # note that this is only called if the attr does not exist
    def __getattr__(self, name):
        try:
            with open(".matrix/{0}.csv".format(name)) as f:
                return f.read()
        except IOError:
            raise AttributeError("{0} does not exist".format(name))

rawDescription: Using eval in defing Python class data attributs


code: a = Phrase("content", u"the first")

rawDescription: whoosh exact match for a phrase

description: Whoosh exact match for a phrase


rawDescription: Access to widget in GTK+

description: Access to widget in GTK+


code:
response = requests.head('http://www.google.com', allow_redirects=True)
response.url
response.history
response.history[0].url
response.request.method

rawDescription: Why am I able to read a HEAD http request in python 3 urllib.request?


code:
np.argwhere(image[:,:,0] > threshold)
image[0,0]
image[1,3]

rawDescription: Thresholded pixel indices of a NumPy array


code:
totals_frame = pd.DataFrame(totals).T
totals_frame.index = ['totalCount']

pivot.index = ['city%i' % item for item in pivot.index]
final_result = pivot.append(totals_frame)
final_result.columns  = ['state-%i' % item for item in final_result.columns]

rawDescription: Make pivot tables in sql like in spss

description: Make pivot tables in sql like in spss


code:
import requests
from http.cookiejar import LWPCookieJar
session = requests.Session()
session.cookies = LWPCookieJar("storage.jar")
session.cookies.load()

rawDescription: Do requests sessions end when the program is killed?


code:
def f(x):
    return x**2

rawDescription: Is there a simple process-based parallel map for python?


code: modified_list = [1 for ignored in [1, 2, 3, 4, 5]]

rawDescription: constant lambda function in python

description: Constant lambda function in python


code:
curses.setsyx(y, 0)   # beginning of the correct line
# stdscr.move(y, 0)   # alternative
stdscr.clrtoeol()    # clears the current line

rawDescription: How to move character string in ncurses screen?

description: Move character string in ncurses screen


code: ':'.join('%02x' % ord(ch) for ch in '\x01\xfa')

rawDescription: How to reformat a string that represents a big-endian into a MAC-Address format?

description: Reformat a string that represents a big-endian into a MAC-Address format


code:
for i in content:
   s=i.split()
   name,scores=s[0],s[1:]

rawDescription: String split in python

description: String split in python


code:
if problem in problems:
    solution = problems[problem]

rawDescription: Python - Searching a dictionary for strings


code:
f = pow(x[-1]/x[0], 1.0/(x.size-1) )
xnew[0] = x[0]
for i in range(1,x.size):
    xnew[i] = xnew[i-1] * f

rawDescription: Interpolate on a logarithmic scale in python


code:
n=10
for a in range(1,n):
    val = ""
    for b in range(1,n):
        val = val + str(a*b) + " "
        print(val)

rawDescription: how to make a multiplication table in python

description: Make a multiplication table in python


rawDescription: Sorting a list of strings by their components


code:
with open("old.txt") as f_old, open("new.txt", "w") as f_new:
    for line in f_old:
        f_new.write(line)
        if 'identifier' in line:
            f_new.write("extra stuff\n")

rawDescription: Insert text into a text file following specific text using Python


code:
class Piece():
    d = {'R':4, 'L':5, 'W':7, 'K':9}

Ask=input("Which value do you want:")
Value = Piece.d[Ask]

rawDescription: Python - Enumerated types

description: Python - Enumerated types


code: s.rank(pct=True, numeric_only=True)

rawDescription: why aren't pandas "rank" percentiles bounded between 0 and 1?

description: Why aren't pandas "rank" percentiles bounded between 0 and 1


code: graphicsView.setStyleSheet("border-width: 0px; border-style: solid")

rawDescription: Unable to fully remove border of PyQt QGraphicsView


code:
emails = modelB.objects.values_list('email', flat=True)
a_models = modelA.objects.exclude(email__in=emails)

rawDescription: Django ORM - partial match of rows in different tables


code: m_angle = math.degrees(math.atan(float(thing.position()[1]-stuff.position()[1]) / float(thing.position()[0]-stuff.position()[0])))

rawDescription: Odd behavior with division in Python

description: Odd behavior with division in Python


code:
from numpy import concatenate, zeros
from scipy.linalg import toeplitz

toeplitz(concatenate([[1., -.25], zeros(20)]))

rawDescription: Toeplitz matrix using numpy/scipy

description: Toeplitz matrix using numpy/scipy


code:
import re
strValue.setParseAction(lambda t: re.sub(r'\\(.)', r'\g<1>', t[0]))

rawDescription: With pyparsing, how do you parse a quoted string that ends with a backslash


code:
import wmi
c = wmi.WMI()
c.Win32_Product(Name = 'ProductName')[0].Uninstall()

rawDescription: msiexec scripting in python

description: Msiexec scripting in python


rawDescription: Python some special products of a given list


code:
def matches(string, words, start=-1):
    result= []
    for word in words: # for each word
        pos= start
        while True:
            pos= string.find(word, pos+1) # find the next occurence of the word
            if pos==-1: # if there are no more occurences, continue with the next word
                break

            if [word] not in result: # add the word to the result
                result.append([word])

            # recursively scan the rest of the string
            for match in matches(string, words, pos+len(word)-1):
                match= [word]+match
                if match not in result:
                    result.append(match)
    return result

rawDescription: Python: comparing list to a string

description: Python: comparing list to a string


code:
for procElement in procedureList:
    ListOfData2 = procElement.getElementsByTagName('Data2')
    for Data2 in ListOfData2:
        varElements = Data2.getElementsByTagName('Variable')
        for varElemTmp in varElements:
            varName.append(varElemTmp.getAttribute('name'))
            varType.append(varElemTmp.getAttribute('type'))

rawDescription: Issue Getting Nested Elements in xml File using minidom


code: df

rawDescription: Add specific amount to each column in pandas


code:
class MyFunction:
  def __init__(self, v):
    self.v = v
  def __call__(self):
    return self.v

l = [MyFunction(i) for i in range(2)]

l[0]() # 0
l[1]() # 1

rawDescription: Python dynamic function attribute

description: Python dynamic function attribute


code:
with open('my_file2.txt', 'w+') as out_file:
  for line in a:
    out_file.write(line)

rawDescription: Filling tabs until the maximum length of column


code:
sqlContext.registerFunction("day", lambda x: x.day)
sqlContext.registerDataFrameAsTable(df, "df")
sqlContext.sql("SELECT *, day(date_time) as day FROM df")

rawDescription: PySpark add a column to a DataFrame from a TimeStampType column


code: my_func(a, b)

rawDescription: Is there a way to use more than 1 variable length arguments (*args) in a Python function?


rawDescription: Python: How to sort a list by the max of each element?


code:
sequence = 'abcdefghijklmnopqrstuvwxyz'
query = 'jklmnop'
'(\w+)({})(\w+)'.format(query)
re.search('(\w+)({})(\w+)'.format(query),sequence).group(1)
re.search('(\w+)({})(\w+)'.format(query),sequence).group(3)

rawDescription: Regex search find before and after query. Python


code:
r = range(n)
it = ControllableIterator(r)
for i in it:
    foo(i)

rawDescription: Can you jump to the nth iteration in a loop?

description: Jump to the nth iteration in a loop


code:
@register.filter()
def user_may_see_full_version(article, user):
    return article.user_may_see_full_version(user)

rawDescription: What is the Django way to do this?

description: What is the Django way to do this


code:
parse(['test.py', 'executeBuild', '--name', 'foobar1', 'executeBuild', '--name', 'foobar2'],
    ('executeBuild',))

rawDescription: Multiple invocation of the same subcommand in a single command line


code: getattr(all_models, m)

rawDescription: How to access dir() Python attributes on a module object?

description: Access dir() Python attributes on a module object


code: palette1.description = "This is palette 1."

rawDescription: How can a class that inherits from list and uses keyword arguments be made to work in both Python 2 and Python 3?


code: str(int(f))

rawDescription: Change float to string without decimal places


code:
from collections import Counter

combos = [['a', 'b', 'c'], ['c', 'b', 'a'], ['d', 'e', 'f'], ['c', 'a', 'b'], ['c', 'f', 'b']]
combos = Counter(tuple(sorted(item)) for item in combos)
print(combos)

rawDescription: Extracting Unique String Combinations from List of List in Python


code:
def question(request, product_id):
    ...
    new_question.product = p

rawDescription: Pass current product_id to a Model in Django


code:
import theano
import theano.tensor as T

global_list = []

def f():

    a = np.zeros((4, 5), dtype=theano.config.floatX)
    b = theano.shared(a)
    global_list.append(b)

rawDescription: is TensorSharedVariable in theano initilized twice in function?

description: Is TensorSharedVariable in theano initilized twice in function


code:
def add_and_modulo(i, addition, modulo=26):
    return (i + addition) % modulo
i = 20
i = add_and_modulo(i, 10)
print(i)

rawDescription: Loop within 26 numbers

description: Loop within 26 numbers


code: myfunv({"key1": "value1", "key2": "value2"})

rawDescription: Formal parameter of the form **keyword

description: Formal parameter of the form **keyword


code:
for i in range(10):
    button=Button(root, text = i)
    button.grid(column=i)

rawDescription: disable buttons in Python and Tk

description: Disable buttons in Python and Tk


code:
writer = ConsoleWriter()
with writer.batch:
    print("begin batch")
    writer.a()
    writer.b()
    with writer.verbose():
        writer.c()
    print("before reentrant block")
    with writer.batch:
        writer.d()
    print("after reentrant block")
    print("end batch -- all data is now flushed")

rawDescription: Python multiple context managers in one class


code:
if isinstance(fname, basestring):
    ds=DataSource('.' if cache==True else None)
    fhd = iter(ds.open(fname, 'rbU'if cache==True else 'rbUD'))
    own_fhd = True

rawDescription: genfromtxt: how to disable caching

description: Genfromtxt: how to disable caching


code: dictionary = {}

rawDescription: How to store a list as a dictionary - python

description: Store a list as a dictionary - python


code:
def roomSetup():
    roomsfile = "roomsfile.txt"
    infile = open(roomsfile, 'r')
    rooms = {}
    for line in infile:
        newroom = makeRooms(line)
        rooms[newroom.roomName] = newroom
    infile.close()
    return rooms

rawDescription: Is there a way to find objects in a list without iterating through the list?


code:
pattern.match(" ".join(["0f"] * 44))
pattern.match(" ".join(["0f"] * 45))
pattern.match(" ".join(["0f"] * 46))
pattern.match(" ".join(["0f"] * 47))
pattern.match(" ".join(["0f"] * 48))
pattern.match(" ".join(["0f"] * 49))

rawDescription: Regular Expression for a pattern of 45 hex numbers OR 48 hex numbers - Python


code:
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('user', 'location','title','website')
        read_only_fields = ('user',)

rawDescription: Django REST: create CRUD operations for OneToOne Field


code: status = subprocess.check_output(['rsync', '-av', localdir, remotedir])

rawDescription: Automating SSH using Python

description: Automating SSH using Python


code:
iter = (ts.shift(-j) for j in range(3))
cnt = pd.Series(list(zip(*iter)))
cnt.iloc[:-2].value_counts()

rawDescription: Summary of recurring subseries w/in a pandas Series


rawDescription: python: convert to HTML special characters

description: Python: convert to HTML special characters


code:
lst = [[] for _ in xrange(3)]
lst
# The ids of the items in `lst` are different
id(lst[0])
id(lst[1])
id(lst[2])

rawDescription: Best and/or fastest way to create lists in python


code:
def IsConsecutive(string,pattern):
    return len(''.join(string.split(pattern))) == 0

rawDescription: Boolean expression with strings

description: Boolean expression with strings


code:
players = {playerA, playerB}
active_player = playerA

active_player = (players - {active_player}).pop()

rawDescription: Get the other element from pair

description: Get the other element from pair


code:
config = braintree.Configuration(
    environment=braintree.Environment.Sandbox,
    merchant_id='my_merchant_id',
    public_key='public_key',
    private_key='private_key'
)

rawDescription: Braintree + Python: Configure credential at transaction level rather than module


code:
from ctypes import *
test = CDLL('./test.so')
test.prnt_.argtypes = [c_char_p, c_long]
test.sin_2_.argtypes = [POINTER(c_float)]
test.sin_2_.restype = c_float
s = 'Mary had a little lamb'
test.prnt_(s, len(s))
x = c_float(4.56)
test.sin_2_(byref(x))

rawDescription: Using python-ctypes to interface fortran with python


rawDescription: Check if list is composed by other lists


code:
import re
text = '''\
Date: Wed, 6 Dec 2000 02:03:00 -0800 (PST)
From: donald.herrick@enron.com
To: brianherrick@email.msn.com, herriceu2@tdprs.state.tx.us,
    robertherrick@bankunited.com, kristi.demaiolo@enron.com,
    suresh.raghavan@enron.com, harry.arora@enron.com
Subject: FW: If Santa Answered his mail...
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
X-From: Donald W Herrick
X-To: brianherrick@email.msn.com, HERRICEU2@tdprs.state.tx.us, RobertHerrick@bankunited.com, Kristi Demaiolo, Suresh Raghavan, Harry Arora
X-cc:
X-bcc:
'''
re.findall(r'^To:\s+[\w\.-]+@[\w\.-]+', text)
re.findall(r'^To:\s+[\w\.-]+@[\w\.-]+', text, flags=re.M)

rawDescription: Ignore strings which do not completely match regex?


code:
v = arguments['**kwargs']  # or pop if you prefer
if v is not None:
    k, v = v.split('=')
    arguments[k] = int(v)

rawDescription: Using argparse with function that takes **kwargs argument


code:
@view_config(route_name='name_with_optional')
@view_config(route_name='name')
def my_view(request):
    optional = request.matchdict.get('optional')

rawDescription: Pyramid: Routing schemas and restraints

description: Pyramid: Routing schemas and restraints


rawDescription: create a list from a functions output?

description: Create a list from a functions output


code:
import itertools
[''.join(c) for c in itertools.product('abc', 'abc', 'abc')]

rawDescription: Help understanding how this recursive python function works?


rawDescription: Django specific sql query

description: Django specific sql query


code:
def inc_width():
    objeto.Width = objeto.Width + 1

for num in range(1,100):
    execute_in_ui(inc_width)
    Sleep(500)

rawDescription: IronPython as Scripting language to C# WPF VS 2015


rawDescription: Pandas - make a column dtype object or Factor


code:
import example
assert(example.decode([1,2,3,4]) == [3,7])

rawDescription: How to initialize boost::python::list with a given number of elements?

description: Initialize boost::python::list with a given number of elements


code:
H, W = 4,5
x, y = np.indices([H, W])
m

rawDescription: NumPy map calculation depending on the indices


code: thread = [threading.Thread(target=filestat, args=(files[x],)) for x in range(len(files))]

rawDescription: Python Threading with varying arguments (Python 2.4.3)


code: slices = tuple(slice(None if j-1 <= 0 else j-1, j+2, 1) for j in coords)

rawDescription: Efficiently recalculating the gradient of a numpy array with unknown dimensionality


code:
def count_number_unique(my_list):
    prev = None
    unique_count = 0
    for ele in sorted(my_list):
        if ele != prev:
            unique_count += 1
        prev = ele
    return unique_count

rawDescription: Count number of distinct items in a list without using a hash table


code:
def func(event):
    print("You hit return.")
root.bind('<Return>', func)

rawDescription: Entry widget Tkinter. I am getting confused


code:
import csv
import itertools
import StringIO

with open('input.txt', 'rb') as f_input:
    for line in itertools.ifilter(lambda x: len(x) > 2 and x[0] == '|' and x[1].isalpha(), f_input):
        header = [cols.strip() for cols in next(csv.reader(StringIO.StringIO(line), delimiter='|', skipinitialspace=True))][1:-1]
        break

with open('input.txt', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(header)
    for line in itertools.ifilter(lambda x: len(x) > 2 and x[0] == '|' and x[1] != '-' and not x[1].isalpha(), f_input):
        csv_input = csv.reader(StringIO.StringIO(line), delimiter='|', skipinitialspace=True)
        csv_output.writerow([col.strip().translate(None, ",!.;") for col in next(csv_input)[1:-1]])

rawDescription: I have a SAP generated file with many columns and some unwanted rows. How should I read directly into Pandas?


code:
def on_tree_clicked_left( self, index_start, index_end, keyboard_modifiers ):
    """
    :param index_start: QtCore.QModelIndex
    :param index_end: QtCore.QModelIndex
    :param keyboard_modifiers: QtGui.QApplication.keyboardModifiers
    """
    if ( index_start is None and index_end is None ) or \
        not index_start.isValid() or not index_end.isValid():
        self.model_data_objs.deselect_all()
        return None

    if index_start is None:
        index_start = index_end

    start_node  = index_start.model().mapToSource( index_start ).internalPointer()
    end_node    = index_end.model().mapToSource( index_end ).internalPointer()

    # get the nodes to operate on ...
    nodes = [ start_node ]
    if not index_start == index_end:
        nodes_above = list()
        nodes_below = list()
        index_above = self.gui_tree.indexAbove( index_start )
        index_below = self.gui_tree.indexBelow( index_start )

        while not end_node in nodes_above and not end_node in nodes_below:
            if index_above.isValid():
                node_after = index_above.model().mapToSource( index_above ).internalPointer()
                nodes_above.append( node_after )

                index_above = self.gui_tree.indexAbove( index_above )

            if index_below.isValid():
                node_before = index_below.model().mapToSource( index_below ).internalPointer()
                nodes_below.append( node_before )

                index_below = self.gui_tree.indexBelow( index_below )

        if end_node in nodes_above:
            nodes += nodes_above
        if end_node in nodes_below:
            nodes += nodes_below

    # get the operation, based on index_start column ...
    clicked_column = index_start.column()
    if not clicked_column == 0:
        attr    = COLUMNS[ clicked_column ].get( 'attr_name' )
    else:
        attr    = 'selected'
        if not keyboard_modifiers == QtCore.Qt.ControlModifier and \
            not keyboard_modifiers == QtCore.Qt.AltModifier:
            self.model_data_objs.deselect_all()

    # perform the operation
    new_value = not getattr( start_node, attr )
    for node in nodes:
        setattr( node, attr, new_value )

rawDescription: How to improve selection performance with PySide.QtCore.QAbstractItemModel and QTreeView?

description: Improve selection performance with PySide.QtCore.QAbstractItemModel and QTreeView


code: result = [ split(row, ',') for row in cursor.fetchall()]

rawDescription: MySQL table to Python list of lists using fetchall()


code: return 0 if n>=p else p-pow(A[p-n]%p,(p-2),p)

rawDescription: multiplication of all numbers (between 2 numbers) python

description: Multiplication of all numbers (between 2 numbers) python


code:
import itertools

item_list = [("apple", ""), ("sky", ""), ("red", ""), ("", "summer"), ("", "pizza")]
print(item_list)

flat_list = list(itertools.chain(*item_list))
result = filter(None, flat_list)
print(result)

rawDescription: OR statement and REGEX in Python

description: OR statement and REGEX in Python


code:
def __subclasscheck__(cls, subclass):
    return issubclass(subclass, tuple(cls._specializations.values()))

def __instancecheck__(cls, instance):
    return isinstance(instance, tuple(cls._specializations.values()))

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


code:
def generic_dict():
    return {'user': {'created': {}, 'modified': {}, 'errors': {}},
            'usermon': {'created': {}, 'modified':{}, 'ignored': {}, 'errors': {}}}

rawDescription: How can I properly copy nested dictionary objects?

description: Properly copy nested dictionary objects


code: filtered_records = filter_unique(records, ['col1','col2','col3'])

rawDescription: Extract specific column and group them from dictionary in Python


rawDescription: how to calculate ratio on some condition in pandas dataframe

description: Calculate ratio on some condition in pandas dataframe


code: print(' '.join([elt.strip() for elt in root.xpath('//a/descendant-or-self::text()')]))

rawDescription: Get data between two tags in Python

description: Get data between two tags in Python


code: function("please", 0, "work this time", 2.3)

rawDescription: Why would Python's variable length arguments be used over passing in a list/dictionary?


code:
df.set_index(['ID', 'status'], inplace=True)
print(df)
#                quantity
# ID     status
# STRSUB Red           56
# BOTDWG Red           20
# STRSUB Amber         60
# BOTDWG Amber         67
# STRSUB Yellow        74
# BOTDWG Yellow        87
# STRSUB White         40
# BOTDWG White         34

rawDescription: Grouping data by value ranges

description: Grouping data by value ranges


code: Planet.G = 1

rawDescription: Is it possible to define a class constant inside an Enum?


code:
db.tweet.aggregate([
    {
        '$match': {
            "user.statuses_count": {"$gt":99 },
            "user.time_zone": "Brasilia"
        }
    },
    {
        "$group": {
            "_id": "$user.id",
            "followers": { "$max": "$user.followers_count" },
            "doc": {
                "$addToSet": "$$ROOT"
            }
        }
    },
    {
        "$sort": { "followers": -1 }
    },
    {
        "$unwind": "$doc"
    },
    {
        "$project": {
            "_id": 0,
            "userId": "$_id",
            "screen_name": "$doc.user.screen_name",
            "retweet_count": "$doc.retweet_count",
            "followers": 1
        }
    },
    {
        "$limit": 1
    }
]);

rawDescription: Nothing happens when trying to use $project


code:
def middle(a, b, c) : #defining a method
    return min(max(a,b),max(b,c),max(a,c))

a = int(input("Give a value: "))
b = int(input("Give b value: "))
c = int(input("Give c value: "))
print("The requested value is ")
print(middle(a,b,c)) #calling a method

rawDescription: Middle value using python 3

description: Middle value using python 3


code:
for x in range(0, listedCodeAmount):
    listedCode[x] = letters()

rawDescription: how to change letters in a list to their corresponding alpabetical numbers in python

description: Change letters in a list to their corresponding alpabetical numbers in python


code:
x = 11 #no. of elements to get
text = 'string5' #text to search in elements of list
lst = ['string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7']
n = len(lst)

rawDescription: Iterate through a List Multiple times Cyclically starting from the Matching Index


code:
import requests
s = requests.Session()
s.cookies.set_policy(BlockAll())

rawDescription: How to disable cookie handling with the Python requests library?

description: Disable cookie handling with the Python requests library


rawDescription: Calling A function from multiple scripts in python


rawDescription: How to create a self resizing grid of buttons in tkinter?

description: Create a self resizing grid of buttons in tkinter


code:
if [gene for gene in genes if gene in text]:
    ...

rawDescription: python search for a set of words

description: Python search for a set of words


code: os.system("mkdir /.pdf")

rawDescription: How to convert the pdf files into png format using ghostscript in python

description: Convert the pdf files into png format using ghostscript in python


rawDescription: List Comprehension and traversing through a list


code:
request = urllib2.Request(url,None)
request.add_header('User-Agent','Python Script') # Or 'Not a python script'

rawDescription: Can a server find out I am accessing it with a python script? If so, how to hide it?


code: r = re.compile(r'|'.join(map(re.escape, separators)))

rawDescription: Using Python: to split long string, by given ‘separators’


code: "...AND list_id IN (%s)"%sql_string

rawDescription: Python, How to take a comma separated sys argv, and make it like '1','2' (for MySQL "IN" Query)