code: newdict = dict((k,v) for k,v in d.iteritems() if v > 20)

rawDescription: Fastest way to remove a lot of keys from a dictionary


rawDescription: tcpdump to only print urls

description: Tcpdump to only print urls


code:
import itertools
for i in itertools.count():
  if thereIsAReasonToBreak(i):
    break

rawDescription: Looping from 1 to infinity in Python

description: Looping from 1 to infinity in Python


code: lambda x: x[1]['std']

rawDescription: Sorting nested python dictionary by label


code:
s = 'hello world'
c = 'l'  # The letter we are looking for
results = [k for k,v in enumerate(s) if v == c]
results

rawDescription: Calculating the Letter Frequency in Python


code: def SetImage(self, *args): return _tesseract.TessBaseAPI_SetImage(self, *args)

rawDescription: python tesseract "AttributeError: setImage"

description: Python tesseract "AttributeError: setImage"


code:
class Impl1(YourAbstractFactory):
    def f1(self):
        print('Impl1.f1')

    def f2(self):
        print('Impl1.f2')

class Impl2(YourAbstractFactory):
    def f1(self):
        print('Impl2.f1')

    def f2(self):
        print('Impl2.f2')

rawDescription: Advantages to two modules with same interface or two classes with the same interface?


code: print("Class ID: ", x , "\tClass Name:" , classes[x]["className"] , "\tClass Instructor:" , classes[x]["classInst"])

rawDescription: adding data to a database on python

description: Adding data to a database on python


code:
if __package__ is None:
    import sys
    from os import path
    sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
    from packages.files import fileChecker
else:
    from packages.files import fileChecker

rawDescription: importing a package from within another package in python

description: Importing a package from within another package in python


code:
from lmfit import minimize, Parameters, Parameter, report_fit
import numpy as np

#http://cars9.uchicago.edu/software/python/lmfit/parameters.html

# create data to be fitted

x = np.linspace(0, 15, 301)
data = (5. * np.sin(2 * x - 0.1) * np.exp(-x*x*0.025) +
(-2.6 * np.sin(-0.6 * x + 1.5) * np.exp(-x*x*3.0)+np.random.normal(size=len(x), scale=0.2) ))

def fcn2min(params, x, data):
    model=0
    for i in range(2):
        exec("amp_%d=%s"%(i+1,repr(params['amp_%d'%(i+1)].value)))
        exec("shift_%d=%s"%(i+1,repr(params['shift_%d'%(i+1)].value)))
        exec("omega_%d=%s"%(i+1,repr(params['omega_%d'%(i+1)].value)))
        exec("decay_%d=%s"%(i+1,repr(params['decay_%d'%(i+1)].value)))
        model += eval("amp_%d"%(i+1)) * np.sin(x * eval("omega_%d"%(i+1)) + eval("shift_%d"%(i+1))) * np.exp(-x*x*eval("decay_%d"%(i+1)))
    return (model-data)#/data

params=Parameters()
for i in range(2):
    params.add('amp_%d'%(i+1),   value= 10,  vary=True, min=0, max=13)
    params.add('decay_%d'%(i+1), value= 0.1,vary=True,min=0,max=1.4)
    params.add('shift_%d'%(i+1), value= 0.0, vary=True,min=-np.pi, max=np.pi)
    params.add('omega_%d'%(i+1), value= 3.0, vary=True,min=-3.5, max=3.5)

result = minimize(fcn2min, params, args=(x, data),method='nelder')

final = data + result.residual
report_fit(params)
try:
    import pylab
    pylab.plot(x, data, 'k+')
    pylab.plot(x, final, 'r')
    pylab.show()
except:
    pass

rawDescription: Fitting two non-linear models to data

description: Fitting two non-linear models to data


code:
import os
import sys

class RotatingFile(object):
    def __init__(self, directory='', filename='foo', max_files=sys.maxint,
        max_file_size=50000):
        self.ii = 1
        self.directory, self.filename      = directory, filename
        self.max_file_size, self.max_files = max_file_size, max_files
        self.finished, self.fh             = False, None
        self.open()

    def rotate(self):
        """Rotate the file, if necessary"""
        if (os.stat(self.filename_template).st_size>self.max_file_size):
            self.close()
            self.ii += 1
            if (self.ii<=self.max_files):
                self.open()
            else:
                self.close()
                self.finished = True

    def open(self):
        self.fh = open(self.filename_template, 'w')

    def write(self, text=""):
        self.fh.write(text)
        self.fh.flush()
        self.rotate()

    def close(self):
        self.fh.close()

    @property
    def filename_template(self):
        return self.directory + self.filename + "_%0.2d" % self.ii

if __name__=='__main__':
    myfile = RotatingFile(max_files=9)
    while not myfile.finished:
        myfile.write('this is a test')

rawDescription: python: outfile to another text file if exceed certain file size

description: Python: outfile to another text file if exceed certain file size


rawDescription: Django form - filter foreignkey in model


code:
import json

result_object = json.loads(result)

rawDescription: Extracting data from a URL result with special formating


code:
list = [0,1,2,3,4,5] # zero added here.
for each in list:
    list[each] = 4
print(list)

rawDescription: Why doesn't this Python 3 for loop change every variable to 4?


code:
class MetaOne: pass

class Eggs: pass

__metaclass__ = MetaOne

class Spam: pass
class Scrambled: pass
class Fried: pass

rawDescription: How to apply a metaclass to all my class without hardcoding it in the class declaration

description: Apply a metaclass to all my class without hardcoding it in the class declaration


code:
from itertools import islice
import collections
from random import Random

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

class RewindRandom:
    def __init__(self):
        self._random = Random()
        self._state = self._random.getstate()
        self._count = 0

    def __iter__(self):
        while True:
            yield self._random.random()

    def __call__(self):
        self._count += 1
        return next(iter(self))

    def rollback(self, amount):
        self._random.setstate(self._state)
        consume(self, self._count-amount)
        self._count -= amount

rawDescription: Rolling back the random number generator in python?


code:
def create_models(my_term, my_link):
    (saved_term, created) = ProjectTerms.objects.update_or_create(terms = my_term)
    (saved_link, created) = ProjectLinks.objects.update_or_create(links = my_link)
    saved_link.relations.add(saved_term)
    saved_link.save()

rawDescription: Django Integrity Error - id cannot be null


code:
nouns = []
for key, value in pos_dictionary.iteritems():
    if key.startswith('NN'):
        nouns += value

rawDescription: how to write a conditional list comprehension, with "extend" functionality

description: Write a conditional list comprehension, with "extend" functionality


code:
alternate(list1, list2)
alternate(alternate(list1, list2), list3)

rawDescription: Combine numerous lists of different length in python in an alternating order


rawDescription: Python: Escaping strings for use in XML

description: Python: Escaping strings for use in XML


rawDescription: Equivalent of `polyfit` for a 2D polynomial in Python


code:
def repeat_middle(text):
    a, b = divmod(len(text) - 1, 2)
    middle = text[a:a + b + 1]
    exclamations = '!' * len(middle)
    return '{}{}{}'.format(exclamations, middle * len(text), exclamations)

rawDescription: Repeating Characters in the Middle of a String


code:
import os
fileName = 'News_2014.xml'
baseName, extension = os.path.splitext(fileName)
suffix = 0

while os.path.exists(os.path.join(directory, fileName)):
    suffix += 1
    fileName = '{}_{:02}.{}'.format(baseName, suffix, extension)

print(fileName)
os.rename(originalName, fileName)

rawDescription: Python : Rename files

description: Python : Rename files


code: output = high_results + medium_results + low_results

rawDescription: Inserting item in list in python

description: Inserting item in list in python


rawDescription: Call python function from other py file what goes in __init__.py


code:
from datetime import datetime,timedelta

def weird_time(current_time,duration):
    start = datetime.strptime(current_time, "%H:%M:%S")
    st_hr, st_min, st_sec = start.hour, start.minute, start.second
    comb = timedelta(minutes=st_min,seconds=st_sec) + timedelta(seconds=duration)
    mn, sec = divmod(comb.total_seconds(), 60)
    hour, mn = divmod(mn, 60)
    return "{:02}:{:02}:{:02}".format(int(st_hr+hour), int(mn), int(sec))

rawDescription: How to not start the next day with datetime while adding a timedelta?

description: Not start the next day with datetime while adding a timedelta


rawDescription: Test if two numpy arrays are (close to) equal, including shape


code:
import os
import sys

buf = sys.stdin.read()
wc = os.popen("usr/sbin/sendmail other@place.com","w")
wc.write(buf)
wc.close()
wc = os.popen("usr/sbin/sendmail first@place.com","w")
wc.write(buf)
wc.close()
sys.exit(0)

rawDescription: How to use os.spawnv to send email copy using Python?

description: Use os.spawnv to send email copy using Python


code:
obj = xrange(1,11,2)
obj.__reduce__()[1]
len(obj)

rawDescription: Accessing xrange internal structure

description: Accessing xrange internal structure


code:
def since_date_created(self):
    '''Compute the time since creation time based on self.date_created.'''

rawDescription: Django: Adding additional properties to Model Class Object


code:
e = Tkinter.Entry(self)
e.pack()
e.focus_set()

rawDescription: Tkinter, Python: How do I save text entered in the Entry widget? How do I move a label?


code:
new1, new2 = re.split(r'\s*-\s*', s)
new1
new2

rawDescription: Python Regular Expressions re.findall -- split a string into two


code:
t3 = {}
for key in t1:
    t3[t1[key]] = t2[key]

rawDescription: Create a Python Dictonary by taking joins of two dictionary


code: data = list(read)

rawDescription: Why can't I repeat the 'for' loop for csv.Reader? (Python)


rawDescription: iterating dicts out of a dict of matched-length lists

description: Iterating dicts out of a dict of matched-length lists


code:
dic = {'01':[1,2], '02':[1], '03':[2,3]}
import itertools as IT
{a+b: list(set(dic[a]+dic[b])) for a,b in IT.combinations(dic, 2)}

rawDescription: Get a dict whose keys are combinations of a given dict without duplicate values


code:
class Monster:
   def __init__ (self, name, age):
       self.name = name
       self.age = age

   def greet (self):
       print("Hello, I'm", self.name, "of age", self.age, ".")

   def rename (self, new_name):
       self.name = new_name

   def new_age (self, new_age):
       self.age = new_age

person = Monster("Bob", 35)
person.greet() # prints Hello, I'm Bob of age 35 .

person.rename("John")
person.new_age(36)
person.greet() # prints Hello, I'm John of age 36 .

rawDescription: When a class is created in Python, and an object referencing it is used, how would you use the name of the object in the class?


code: M *= w[:,None]

rawDescription: What is the nicest way to weight planes in a numpy array?


code:
def joinit(count, iterable, delimiter):
    for x in iterable:
        yield x
        for _ in range(count):
            yield delimiter

list(joinit(2, [1,2,3], 'a'))

rawDescription: add an element N times between elements in list

description: Add an element N times between elements in list


code:
process = subprocess.Popen(['echo', '`pwd`'], stdout=subprocess.PIPE, shell=True)
out, err = process.communicate()
out
process = subprocess.Popen(['echo', '`pwd`'], stdout=subprocess.PIPE, shell=False)
out, err = process.communicate()
out

rawDescription: Using back-ticks in Python subprocess

description: Using back-ticks in Python subprocess


code:
import urllib.request

url_to_txt_file = ""
print(urllib.request.urlopen(url_to_txt_file).read())

rawDescription: Can A Python Program Open An Text File On The Web?


code:
from BeautifulSoup import BeautifulSoup, Tag

soup = BeautifulSoup('Cows are being abducted by aliens according to the Washington Post.')
parsed_soup = ''

rawDescription: Finding Tags And Text In BeautifulSoup

description: Finding Tags And Text In BeautifulSoup


code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster import hierarchy as hier
from scipy.spatial import distance as ssd
np.random.seed(2016)

points = np.random.random((10, 2))
arr = ssd.cdist(points, points)

fig, ax = plt.subplots(nrows=4)

ax[0].set_title("condensed upper triangular")
Z = hier.linkage(arr[np.triu_indices(arr.shape[0], 1)], method="average")
hier.dendrogram(Z, ax=ax[0])

ax[1].set_title("squareform")
Z = hier.linkage(ssd.squareform(arr), method="average")
hier.dendrogram(Z, ax=ax[1])

ax[2].set_title("pdist")
Z = hier.linkage(ssd.pdist(points), method="average")
hier.dendrogram(Z, ax=ax[2])

ax[3].set_title("sequence of observations")
Z = hier.linkage(points, method="average")
hier.dendrogram(Z, ax=ax[3])

plt.show()

rawDescription: Triangle vs. Square distance matrix for Hierarchical Clustering Python?


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

# Generate data
nrows, ncols = 20, 5
x = np.random.random((nrows, ncols))
y = np.random.random((nrows, ncols))

# Make data for display
mask = np.array(nrows * [ncols * [False, True]], dtype=bool)
red = np.ma.masked_where(mask, np.repeat(x, 2, axis=1))

mask = np.array(nrows * [ncols * [True, False]], dtype=bool)
blue = np.ma.masked_where(mask, np.repeat(y, 2, axis=1))

# Make a side-by-side plot
fig, ax = plt.subplots()
ax.pcolormesh(red, cmap='Reds')
ax.pcolormesh(blue, cmap='Blues')
plt.show()

rawDescription: Creating a matplotlib heatmap with two different coloured data sets


code: r.json().keys() # returns the following line:

rawDescription: Parsing large JSON - Python

description: Parsing large JSON - Python


code: response = yield non_blocking_func(**kwargs)

rawDescription: Tornado async call to a function

description: Tornado async call to a function


code:
import re
from bs4 import BeautifulSoup
soup = BeautifulSoup('''\
First CalMall
''')
soup.find_all('a', href=re.compile('https://www.here.com/.*?ref=br_rs'))

rawDescription: How to match all links in python regex?

description: Match all links in python regex


code:
from xlrd import open_workbook

path = '/Users/.../Desktop/Workbook1.xls'
wb = open_workbook(path, formatting_info=True)
sheet = wb.sheet_by_name("Sheet1")
cell = sheet.cell(0, 0) # The first cell
print("cell.xf_index is", cell.xf_index)
fmt = wb.xf_list[cell.xf_index]
print("type(fmt) is", type(fmt))
print("Dumped Info:")
fmt.dump()

rawDescription: How to read excel cell and retain or detect its format in Python

description: Read excel cell and retain or detect its format in Python


rawDescription: Is there a dedicated milli-sec precision timestamp data structure in python pandas?


code: ['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday']

rawDescription: index of a letter in string - python 2.7

description: Index of a letter in string - python 2.7


code:
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator

from .models import YourModel

class YourPaginatedListView(ListView):
    ...
    paginate_by = 20

    def get_context_data(self, **kwargs):

        context = super(YourPaginatedListView, self).get_context_data(**kwargs)
        object_list = YourModel.objects.all()

        paginator = Paginator(object_list, self.paginate_by)
        page = self.request.GET.get('page')

        try:
            current_objects = paginator.page(page)
        except PageNotAnInteger:
            current_objects = paginator.page(1)
        except EmptyPage:
            current_objects = paginator.page(paginator.num_pages)

        # Process the objects on the current page here

        context['object_list'] = current_objects
        return context

rawDescription: How to iterate over objects in current page in class-based paginated view in Django?

description: Iterate over objects in current page in class-based paginated view in Django


code:
sum(a, b)
a.append(5)
sum(a, b)

rawDescription: How to create dynamic link between list variables

description: Create dynamic link between list variables


rawDescription: Iterate with binary structure over numpy array to get cell sums


code:
if not any(input_a in  ele for ele in dictionary.values()):
        print('Sorry, try again')

rawDescription: How can I select all keys in a python dictionary?

description: Select all keys in a python dictionary


code: yy = [x - {2} for x in xx]

rawDescription: List comprehension against tuple of sets


code:
from collections import defaultdict

scores = defaultdict(list)

class_filenames = ['Class X.txt', 'Class Y.txt', 'Class Z.txt']

for class_file in class_filenames:
    with open(class_file, 'r') as f:
        for line in f.readlines():
            student, score = line.split(':')
            scores[student].append(int(score))

for student, scorelist in sorted(scores.items()):
    print("%s : %d" % (student, max(scorelist)))

rawDescription: Python - Highest with alphabetical order from text file


code: newBayes = [(person, prob * normalizeFactor) for person, prob in bayesList]

rawDescription: Python list reordering, remember original order?


code:
import re
from schema import Schema, And
pattern = re.compile('^12\d+$')
s = Schema(And(str, lambda x: pattern.match(x) is not None))
s.validate('123234')
s.validate('42')

rawDescription: Python object validation thanks to a Schema


code:
myList = [1, 1, 2, 2, 2, 3]
output = {}

for item in myList:
    if item not in output:
        output[item] = 0
    output[item] += 1

rawDescription: Python count the frequency of each number in a list without any count() functions or without importing anything


code:
import gevent
import gevent.monkey
gevent.monkey.patch_all()
import zmq.green as zmq
import json

context = zmq.Context()
socket = context.socket(zmq.ROUTER)
socket.bind("ipc:///tmp/myapp.ipc")

def do_something(parsed):
    return sum(parsed.get("values"))

def handle(msg):
    data = msg[1]
    parsed = json.loads(data)
    total = do_something(parsed)
    msg[1] = json.dumps({"response": total})
    socket.send_multipart(msg)

def handle_zmq():
    while True:
        msg = socket.recv_multipart()
        gevent.spawn(handle, msg)

if __name__ == "__main__":
    handle_zmq()

rawDescription: Exposing python daemon as a service

description: Exposing python daemon as a service


code:
def read_log_lines(filename):
    while True:
        # code to read lines
        if is_new(line):
            yield line

rawDescription: Using Return in a for loop

description: Using Return in a for loop


code:
imgTags = soup.select("div.classname ul.classname a.classname img")
#print number of <img> retreived :
print(len(imgTags))

for tag in imgTags:
    name = tag['alt']
    print(name)

rawDescription: How to count the number of lines of code retrieved using beautiful soup?

description: Count the number of lines of code retrieved using beautiful soup


code:
import collections
a=['not','not','not','not']
b=['not','not']
c1 = collections.Counter(a)
c2 = collections.Counter(b)

rawDescription: common elements in two lists where elements are the same

description: Common elements in two lists where elements are the same


code:
width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
height = GetSystemMetrics(SM_CYVIRTUALSCREEN);

rawDescription: Python PIL library-- Is there a way to select which screen ImageGrab.grab() grabs in a multi-monitor setup?


rawDescription: Finding largest value in a dictionary

description: Finding largest value in a dictionary


code:
df['B'] = lfilter([1], [1, -2], df['A'].astype(float))
df

rawDescription: Recursive definitions in Pandas

description: Recursive definitions in Pandas


code:
x     = np.array([0, 75, 150])
y     = np.array([0, 1, 3])
coeff = np.polyfit(x, y, 2)

xx = np.linspace(0, 150, 150)
yy = coeff[0] * xx**2 + coeff[1] * xx + coeff[2]

all_font = fmg.findSystemFonts()
fontprop = fmg.FontProperties(fname=all_font[223]) #you may have a different index
plt.title(unicode("Correction factor", "utf-8"), fontproperties=fontprop)
fontprop = fmg.FontProperties(fname=all_font[232])
plt.xlabel(unicode("Temperature in °C", "utf-8"), fontproperties=fontprop)
fontprop = fmg.FontProperties(fname=all_font[236])
plt.ylabel(unicode("fKorr", "utf-8"), fontproperties=fontprop)
plt.plot(xx,yy)

rawDescription: How to set matplotlib font for title, axes,

description: Set matplotlib font for title, axes,


code:
def do_checks():
    if not check1():
        return False
    if not check2():
        return False
    if not check3():
        return False
    return True

if do_checks():
    do_something()

rawDescription: How can I write C's do-while(0) in Python?

description: Write C's do-while(0) in Python


code:
class SomeHandler(tornado.web.RequestHandler):
    def initialize(self, ref_object):
        self.ref_object = ref_object

    def post(self):
       self.ref_object.method()

rawDescription: Tornado Get Reference to Instance Variable in RequestHandler


rawDescription: Python signals and slots between classes


code:
keys, (newkey, newvalue) = list_address[:-2], list_address[-2:]
reduce(dict.__getitem__, keys, dict_nested)[newkey] = newvalue

rawDescription: Python: Change values in dict of nested dicts using items in a list


code: help(abs)

rawDescription: Python what does abs do? I have tried looking at different pages for help, however i cannot understand the jargon


rawDescription: Intercept operator lookup on metaclass

description: Intercept operator lookup on metaclass


code:
def custom_format(td):
    minutes, seconds = divmod(td.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:d}:{:02d}'.format(hours, minutes)

rawDescription: Too many decimal places when using timedelta


rawDescription: Collecting data from .txt url in Python with strange encoding


code:
with open('words.txt','r') as f:
    for line in f:
        for word in line.split():
           print(word)

rawDescription: web scrape a .txt file using python

description: Web scrape a .txt file using python


code:
class Employees:
  _iter_attr__prio = ["name"]
  def gatherAttrs(self):
    attrs = []
    for key in sorted(self.__dict__, key=lambda key: self. _iter_attr__prio.index(key) if key in self. _iter_attr__prio else 0, reverse=True):
        attrs.append('%s = %s' % (key, getattr(self,key)))
    return ', '.join(attrs)

rawDescription: Print out dictionary by (specific) key

description: Print out dictionary by (specific) key


code:
import iptdump
import subprocess

ipt = iptdump.Iptables()
proc = subprocess.Popen(['sudo', '/sbin/iptables-restore'],
                        stdin=subprocess.PIPE)
proc.communicate(ipt.dump())

rawDescription: Giving django app root access?

description: Giving django app root access


code: l = [[0 for c in xrange(dim)] for r in xrange(dim)]

rawDescription: fast python matrix creation and iteration

description: Fast python matrix creation and iteration


rawDescription: how to retrieve value from text file using python?

description: Retrieve value from text file using python


code:
import pandas as pd
from io import BytesIO
df = pd.read_table(BytesIO("""\
col1 col2 col3 col4 col5 col6
WHI5    YOR083W CDC28   YBR160W "physical interactions"   19823668
WHI5    YOR083W CDC28   YBR160W "physical interactions"   21658602
WHI5    YOR083W CDC28   YBR160W "physical interactions"   24186061
WHI5    YOR083W RPD3    YNL330C "physical interactions"   19823668
WHI5    YOR083W SWI4    YER111C "physical interactions"   15210110
WHI5    YOR083W SWI4    YER111C "physical interactions"   15210111"""),
delim_whitespace=True)

rawDescription: Counting occurrence of a word in a column of a tsv file using python


code:
a = A("I am a")
b = A("I am b")
make_meth(a, A, "__len__", lambda self: 12)
make_meth(b, A, "__len__", lambda self: 44)
print(len(b))
print(len(a))
print(a.get_words())
print(b.get_words())

rawDescription: Making len() work with instance methods

description: Making len() work with instance methods


code:
import networkx as nx

G = nx.MultiDiGraph()
G.add_edge(0,1, label='A')
G.add_edge(1,0, label='B')
G.add_edge(2,3, label='foo')
G.add_edge(3,1, label='bar')
nx.write_dot(G, 'my_graph.dot')

rawDescription: graph-tool: Draw text on edges

description: Graph-tool: Draw text on edges


code:
get_type(Test, 'foo')
get_type(Test, 'bar')
get_type(Test, 'baz')
get_type(Test, 'nonexistant')

rawDescription: getattr on class objects

description: Getattr on class objects


rawDescription: convert a graph represented by a string of key-value pairs, to a dictionary. Python

description: Convert a graph represented by a string of key-value pairs, to a dictionary. Python


code:
@property
def nombre_moneda(self):
  return self.codes(self.codigo_moneda)

rawDescription: how to return choices value in mongoengine stringfield

description: Return choices value in mongoengine stringfield


code:
class Product(models.Model):
    name = models.CharField()

    class Meta:
        abstract = True

class ProductTypeA(Product):
    image = models.ImageField()

class ProductTypeB(Product):
     weight = models.DecimalField()

rawDescription: How do you implement multiple data types for an object in Django?

description: Implement multiple data types for an object in Django


code:
def countunreademail(request):
    exists, myid = myexists(request)
    return messagescount(myid)[0]

def listall(request, *args, **kwargs):
    unreadcount = countunreademail(request)
    return render(request, 'static/list.html', {'loggedin': True, 'unreadcount': unreadcount })

rawDescription: Appending render with decorator in Django


code:
string1
string2
string3
string4
string6
string7
string9

rawDescription: Python: How to skip lines that have extra characters while using Regular Expressions?


rawDescription: Python append dictionary item to array in dictionary


code:
def expantree():
    lines = txtfile.readlines()
    f = open(xmlfile,'wb')
    f.write('<LIBRARY>')
    for line in lines:
        split_line = line.split(',')
        book = create_book(split_line)
        f.write(ET.tostring(book))
    f.write('</LIBRARY>')
    f.close()

rawDescription: creating a xml file with For Loop in python

description: Creating a xml file with For Loop in python


rawDescription: How can I see the effect of sklearn.preprocessing.PolynomialFeatures?

description: See the effect of sklearn.preprocessing.PolynomialFeatures


code:
import urllib
a = (('p',1),('p',2), ('p', 3))
urllib.urlencode(a)

rawDescription: Python Dictionary to URL Parameters

description: Python Dictionary to URL Parameters


code:
dataList = {'a': df_a,
            'b': df_b}

rawDescription: Resampling and merging data frame with python


code:
for m in get_lengths(k):
    if m > 20:
        print(1)
    else:
        print(-1)

rawDescription: if the get_lengths(k) more than 20 then do something else do something

description: If the get_lengths(k) more than 20 then do something else do something


code:
def dp_coin(S, coins):
    mn = [float("inf") for j in range(S+1)]
    mn[0] = 0
    for i in range(1, S+1):
        for j in coins:
            if j <= i and mn[i-j]+1 < mn[i]:
                mn[i] = mn[i-j] + 1
    return mn[-1]

rawDescription: Using infinity in dynamic programming coins example - why does this not fail?


rawDescription: Delete Extra Space from Values In List

description: Delete Extra Space from Values In List


rawDescription: How should I wait for a keypress in both Python 2 and Python 3?


code:
from Bio import SeqIO
import sys

with open("fasta") as fh:
    fasta = fh.read().splitlines()

seen = set()
records = {}

for record in SeqIO.parse(open('fastq'), 'fastq'):
    seq = str(record.seq)
    if seq in fasta and seq not in seen:
        seen.add(seq)
        records[fasta.index(seq)] = record

for record in sorted(records):
    sys.stdout.write(records[record].format('fastq'))

rawDescription: find unique first top and bottom lines of fastq file from fasta file

description: Find unique first top and bottom lines of fastq file from fasta file


code:
arr1.dot(arr2.T) / np.outer(np.linalg.norm(arr1, axis=1),
                            np.linalg.norm(arr2, axis=1))

rawDescription: cosine distance between two matrices

description: Cosine distance between two matrices


code: points = cv2.reprojectImageTo3D(disp, Q)

rawDescription: put 3D world coordinates in 2D array

description: Put 3D world coordinates in 2D array


code:
def conditional(cond, warning=None):
    def noop_decorator(func):
        return func  # pass through

    def neutered_function(func):
        def neutered(*args, **kw):
            if warning:
                log.warn(warning)
            return
        return neutered

    return noop_decorator if cond else neutered_function

rawDescription: Deactivate function with decorator

description: Deactivate function with decorator


code:
from pyspark.sql.functions import udf
from pyspark.sql.types import BooleanType

rdd = sc.parallelize([
    (0, 3), (1, 4),
    (2, 5), (3, 4),
    (5, 8), (7, 10)
])

df = sqlContext.createDataFrame(rdd, ('start_time', 'end_time'))

def overlaps(start_first, end_first, start_second, end_second):
    return ((start_first < start_second < end_first) or
        (start_first < end_second < end_first))

sqlContext.registerFunction('overlaps', overlaps, BooleanType())
df.registerTempTable("df1")
df.registerTempTable("df2")

sqlContext.sql("""
     SELECT * FROM df1 JOIN df2
     WHERE overlaps(df1.start_time, df1.end_time, df2.start_time, df2.end_time)
""").show()

rawDescription: PySpark - Time Overlap for Object in RDD


code:
import Image
import ImageFont
import ImageDraw
import subprocess
import shlex

font = ImageFont.truetype(
    "/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 66)
text = "copyright"
size = font.getsize(text)
img = Image.new('RGBA', size=size, color='white')
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, fill=(209, 239, 8), font=font)
img.save('label.jpg')

cmd = 'composite -compose bumpmap -gravity southeast label.jpg in.jpg out.jpg'
proc = subprocess.Popen(shlex.split(cmd))
proc.communicate()

rawDescription: A watermark inside a rectangle which filled the certain color


code:
theDict = {'cereal': ['as', '1w', '45'],
           'pop': ['gh', 'er', '65'],
           'crackle': ['yu', 'po', '22']}

for key, value in theDict.items():
    if 'po' in value:
        print(key)

rawDescription: Python: Iterate through Dictionary Values and outPut the Key


code:
from util import get_content

class MyObj:
    def func():
        get_content()

rawDescription: mocking functions using python mock

description: Mocking functions using python mock


code: data = make_data(shape)

rawDescription: Python 2D Gaussian Fit with NaN Values in Data


rawDescription: Pandas - bucketing events close to each other


code: u = set.intersection(*setlist)

rawDescription: how best do I find the intersection of multiple sets in python?

description: How best do I find the intersection of multiple sets in python


code: pymc3.traceplot(trace, vars=['alpha', 'beta', 'sigma'])

rawDescription: Linear regression with pymc3 and belief

description: Linear regression with pymc3 and belief


code: [['{} {}'.format(greeting, name) for name in b] for greeting in a]

rawDescription: creating new lists by adding elements of lists

description: Creating new lists by adding elements of lists


code:
obj = DatModel()
with transaction.manager:
    session.add(obj)
obj = session.query(DatModel).one()

assert type(obj.timestamp) == datetime.datetime
assert obj.timestamp.date() == datetime.date.today()

objs = session.query(DatModel) \
    .filter(DatModel.timestamp < datetime.datetime.now())
assert objs.count() == 1

objs = session.query(Gateway) \
    .filter(DatModel.timestamp > datetime.datetime.now())
assert objs.count() == 0

rawDescription: Postgres function as column in SQLAlchemy


code:
a=np.array([1,2,np.nan,34,np.nan],float)
a
ind=a!=a
ind
a[ind]=0   # not trying None
a

rawDescription: Numpy does treat float('nan') and float differently - convert to None


rawDescription: Ignoring duplicate entries in sparse matrix


code:
tempspace._sys = __import__('sys')
globals.ps1 = tempspace._sys.ps1
del tempspace._sys
globals.ps1 = 'something else '

rawDescription: Python import and module scoping (specifically sys.ps1)


code:
def finder(s,w):
  return [i for i,j in enumerate(re.findall(r'\b\w+\b',s,re.U)) if j==w]

finder(test_str,word)

rawDescription: Python - Check If string Is In bigger String


code:
import datetime
currentMonth = datetime.now().month
currentMonthn = currentMonth.strftime("%B")

rawDescription: convert month numeric form into their name?

description: Convert month numeric form into their name


code: order = np.argsort(w)

rawDescription: Numpy "sort like" function

description: Numpy "sort like" function


rawDescription: Saving data into a text file

description: Saving data into a text file


code:
results = [anime.get('aid') for anime in tree.findall('anime')
           for title in anime.findall('title') if title.text == '3x3 Eyes']

rawDescription: Search xml for text and return element/node


code:
import numpy as np
from scipy import sparse

graph_array = np.array([[  1.0,   1.0,   5.0 , 9.0],
 [  2.0,   5.0 ,  6.0  , 5.0],
 [  3.0  , 5.0 ,  7.0 ,  6.0]])

r,c,d = [1,2,5], [5,8,7],[0.5,0.4,0.8]
matrix_coo = sparse.coo_matrix((d,(r,c)))

def org(graph_array, matrix_coo):
    row_idx = list(matrix_coo.row)
    col_idx = list(matrix_coo.col)
    data_idx = list(matrix_coo.data)

    x = 0
    while x < len(row_idx):
        for m in graph_array:
            if m[1] == row_idx[x]:
                if m[2] == col_idx[x]:
                    m[3] = data_idx[x]
        x += 1
    return graph_array

new_array = org(graph_array.copy(), matrix_coo)
print(graph_array)
print(new_array)

def alt(graph_array, matrix_coo):
    for r,c,d in zip(matrix_coo.row, matrix_coo.col, matrix_coo.data):
        for m in graph_array:
            if (m[[1,2]]==[r,c]).all():  # array test
                m[3] = d
    return graph_array

new_array = alt(graph_array.copy(), matrix_coo)
print(new_array)

def altlist(graph_array, matrix_coo):
    for r,c,d in zip(matrix_coo.row, matrix_coo.col, matrix_coo.data):
        for m in graph_array:
            if (m[1:3]==[r,c]):   # list test
                m[3] = d
    return graph_array

new_array = altlist(graph_array.tolist(), matrix_coo)
print(new_array)

def altarr(graph_array, matrix_coo):
    for r,c,d in zip(matrix_coo.row, matrix_coo.col, matrix_coo.data):
        mask = (graph_array[:, 1:3]==[r,c]).all(axis=1)
        graph_array[mask,3] = d
    return graph_array

new_array = alt(graph_array.copy(), matrix_coo)
print(new_array)

rawDescription: Speed up operations on a for loop with `coo` matrix and a numpy array in python


code: newimg = np.where(labels[..., None] != 0, img, 255)

rawDescription: numpy efficient array multiplication

description: Numpy efficient array multiplication


code:
def yield_adjacent(lst):
    it = iter(lst)
    sub = [next(it)]
    while True:
        try:
            n = next(it)
        except StopIteration:
            yield tuple(sub)
            raise
        if n - sub[-1] == 1:
            sub.append(n)
        else:
            yield tuple(sub)
            sub = [n]

rawDescription: Create a list of tuples containing adjacent numbers?


code:
import string
phrase = "'This has punctuation, and it's hard to remove!'"
[word.strip(string.punctuation) for word in phrase.split(" ")]

rawDescription: Removing single quotation marks while preserving apostrophes Python, NLTK


code:
forms.py
from django.forms import ModelForm
from . import models

class PresetListForm(ModelForm):
    class Meta:
        model = models.PresetList

rawDescription: HTML tags for choicefield in Django

description: HTML tags for choicefield in Django


rawDescription: Python: Counting repeating values of a dictionary


code: print('Current construct number is: #{} on row {}, which is a Gibson assembly'.format(row[construct_idx], counter))

rawDescription: Processing a sub-list of variable size within a larger list


code:
class Book(object):
    attrs = ('id', 'title', 'authors',...)
    def __init__(self, *args, **kwargs):
        self.__dict__.update(
            (attr, kwargs[k]) for k in kwargs.viewkeys() & self.attrs)

rawDescription: Python - short syntax and list comprehension and iterations


code: from folder.childfilename import childclassname

rawDescription: How could I make a good application architecture in Python with PyQt?


code: spltr.whitespace += ','

rawDescription: Preserve consecutive whitespace with shlex


code: map(list, input_file)

rawDescription: Is there a more efficient way to create this 2D list?


code:
with open('filename.txt') as f:
    for line in f:
        ...

rawDescription: Python - Reading chunks and break if there is no lines


code:
def while_equal(seq, other):
    for this, that in zip(seq, other):
        if this != that:
            return
        yield this

def match(seq, other):
    return sum(1 for _ in while_equal(seq, other))

rawDescription: Find the 1 based position to which two lists are the same


code: x1, y1, x2, y2 = (int(x.strip("(),")) for x in s.split())

rawDescription: Extracting integers from a string of ordered pairs in Python?


code:
def multirange_loop(counts):
    counts = np.asarray(counts)
    ranges = np.empty(counts.sum(), dtype=int)
    seq = np.arange(counts.max())
    starts = np.zeros(len(counts), dtype=int)
    starts[1:] = np.cumsum(counts[:-1])
    for start, count in zip(starts, counts):
        ranges[start:start + count] = seq[:count]
    return ranges

rawDescription: How to efficiently concatenate many arange calls in numpy?

description: Efficiently concatenate many arange calls in numpy


code: regex = re.compile(r'\b[A-Z]{3,}\b')

rawDescription: In Python, how do I remove from a list any element containing certain kinds of characters?


code:
text(0.5, 0.5,'matplotlib',
     horizontalalignment='center',
     verticalalignment='center',
     transform = ax.transAxes)

rawDescription: Putting text in top left corner of matplotlib plot


code:
d = dictFromFile("test.txt")
for k in d: print(k,':',d[k])

rawDescription: Python forming a dictionary from a text file with value being a tuple


code:
# fetch up to 10 greetings by the current user
user = users.get_current_user()
results = Greeting.all().filter('author =', user).fetch(10)

rawDescription: Cannot access members of UserProperty in code


code:
listA = [1,2,3]
listB = [1,2,3,4,5]

newlist = list(set(listB) - set(listA))[:len(listA)]
print(newlist)

rawDescription: select from list B k distinct elements that are not in list A in python?

description: Select from list B k distinct elements that are not in list A in python


rawDescription: Pandas dataframe read large number as string


rawDescription: How to count the elements in a Numpy stride-tricks blocks?

description: Count the elements in a Numpy stride-tricks blocks


code:
from itertools import permutations

patterns = set(''.join(per) for per in permutations('AGUCN'))
unilist = [next(f2).strip() for line in f2 if line.strip() in patterns]

rawDescription: Look ahead without itertools

description: Look ahead without itertools


code:
import re

def _callback(match):
    """ This is a simple callback function for the regular expression which is
        in charge of doing the actual capitalization. It is designed to only
        capitalize words which aren't fully uppercased (like acronyms).
    """
    word = match.group(0)
    if word == word.upper():
        return word
    else:
        return word.capitalize()

def capwords(data):
    """ This function converts `data` into a capitalized version of itself. This
        function accomidates acronyms.
    """
    return re.sub("[\w\'\-\_]+", _callback, data)

rawDescription: is there a string method to capitalize acronyms in python?

description: Is there a string method to capitalize acronyms in python


code:
"""Opens the file(s) given on the command line in the appropriate program.
Some of the programs are X11 programs."""

from os.path import isdir, isfile
from re import search, IGNORECASE
from subprocess import Popen, check_output, CalledProcessError
from sys import argv
import argparse
import logging

__version__ = '1.3.0'

# You should adjust the programs called to suit your preferences.
filetypes = {
    '\.(pdf|epub)$': ['mupdf'],
    '\.html$': ['chrome', '--incognito'],
    '\.xcf$': ['gimp'],
    '\.e?ps$': ['gv'],
    '\.(jpe?g|png|gif|tiff?|p[abgp]m|svg)$': ['gpicview'],
    '\.(pax|cpio|zip|jar|ar|xar|rpm|7z)$': ['tar', 'tf'],
    '\.(tar\.|t)(z|gz|bz2?|xz)$': ['tar', 'tf'],
    '\.(mp4|mkv|avi|flv|mpg|movi?|m4v|webm)$': ['mpv']
}
othertypes = {'dir': ['rox'], 'txt': ['gvim', '--nofork']}

def main(argv):
    """Entry point for this script.

    Arguments:
        argv: command line arguments; list of strings.
    """
    if argv[0].endswith(('open', 'open.py')):
        del argv[0]
    opts = argparse.ArgumentParser(prog='open', description=__doc__)
    opts.add_argument('-v', '--version', action='version',
                      version=__version__)
    opts.add_argument('-a', '--application', help='application to use')
    opts.add_argument('--log', default='warning',
                      choices=['debug', 'info', 'warning', 'error'],
                      help="logging level (defaults to 'warning')")
    opts.add_argument("files", metavar='file', nargs='*',
                      help="one or more files to process")
    args = opts.parse_args(argv)
    logging.basicConfig(level=getattr(logging, args.log.upper(), None),
                        format='%(levelname)s: %(message)s')
    logging.info('command line arguments = {}'.format(argv))
    logging.info('parsed arguments = {}'.format(args))
    fail = "opening '{}' failed: {}"
    for nm in args.files:
        logging.info("Trying '{}'".format(nm))
        if not args.application:
            if isdir(nm):
                cmds = othertypes['dir'] + [nm]
            elif isfile(nm):
                cmds = matchfile(filetypes, othertypes, nm)
            else:
                cmds = None
        else:
            cmds = [args.application, nm]
        if not cmds:
            logging.warning("do not know how to open '{}'".format(nm))
            continue
        try:
            Popen(cmds)
        except OSError as e:
            logging.error(fail.format(nm, e))
    else:  # No files named
        if args.application:
            try:
                Popen([args.application])
            except OSError as e:
                logging.error(fail.format(args.application, e))

def matchfile(fdict, odict, fname):
    """For the given filename, returns the matching program. It uses the `file`
    utility commonly available on UNIX.

    Arguments:
        fdict: Handlers for files. A dictionary of regex:(commands)
            representing the file type and the action that is to be taken for
            opening one.
        odict: Handlers for other types. A dictionary of str:(arguments).
        fname: A string containing the name of the file to be opened.

    Returns: A list of commands for subprocess.Popen.
    """
    for k, v in fdict.items():
        if search(k, fname, IGNORECASE) is not None:
            return v + [fname]
    try:
        if b'text' in check_output(['file', fname]):
            return odict['txt'] + [fname]
    except CalledProcessError:
        logging.warning("the command 'file {}' failed.".format(fname))
        return None

if __name__ == '__main__':
    main(argv)

rawDescription: How to open external programs in Python

description: Open external programs in Python


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

# read the first line to determine the number of columns
with open('file.mtx', 'rb') as f:
    ncols = len(next(f).split('\t'))

x = np.genfromtxt('file.mtx', delimiter='\t', dtype=None, names=True,
                  usecols=range(1,ncols) # skip the first column
                  )
labels = x.dtype.names

# y is a view of x, so it will not require much additional memory
y = x.view(dtype=('int', len(x.dtype)))

G = nx.from_numpy_matrix(y)
G = nx.relabel_nodes(G, dict(zip(range(ncols-1), labels)))

print(G.edges(data=True))
# [('A', 'C', {'weight': 1}), ('A', 'B', {'weight': 1})]

rawDescription: Reading a networkx graph from a csv file with row and column header


rawDescription: the most pythonic matrix transposition

description: The most pythonic matrix transposition


code:
import termios
import struct
import fcntl

def set_winsize(fd, row, col, xpix=0, ypix=0):
    winsize = struct.pack("HHHH", row, col, xpix, ypix)
    fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)

rawDescription: Resize the terminal with Python?

description: Resize the terminal with Python


rawDescription: Getting digits in an order (left to right) after OCR from x,y coordinates


code:
def dot_aligned(seq):
    snums = [str(n) for n in seq]
    dots = []
    for s in snums:
        p = s.find('.')
        if p == -1:
            p = len(s)
        dots.append(p)
    m = max(dots)
    return [' '*(m - d) + s for s, d in zip(snums, dots)]

nums = [4.8, 49.723, 456.781, -72.18, 5, 13]

for s in dot_aligned(nums):
    print(s)

rawDescription: Formatting Numbers So They Allign On Decimal Point


rawDescription: Python: take the content of a list and append it to another list


code:
import numpy as np
a = np.array(['a', 'b', 'c'])
b = np.array(['x', 'y', 'z'])
c = np.array([i+j for i, j in zip(a, b)])
c

rawDescription: Combine all elements of two arrays python


code:
res = [i.lstrip('event_').split('of')[0] for i in mylist]

print(res)
['100', '17', '1000']

rawDescription: Python: how to retrieve some values from the elements of a list?


code:
import math
math.pow(27, 1/3)
math.pow(27, 1.0/3)
math.pow(27, 1/3.0)

rawDescription: Extracting of the arithmetic root of arbitrary degree


rawDescription: Calculate within categories: Equivalent of R's ddply in Python?


code:
from example import Window
w1 = Window(1)
w2 = Window(2)
w3 = Window(3)
del w2
w3 = None
w = w1
del w1
w.action()
w = None

rawDescription: Make Boost Python not delete the C++ object in destructor


code:
file_index = (file_index + 1) % len(files)
pygame.mixer.music.load(files[file_index])
pygame.mixer.music.play(15.0)

rawDescription: How can I play next mp3 file in directory?

description: Play next mp3 file in directory


code:
df.to_hdf('/tmp/my.h5', 'data2', format='table')
pd.read_hdf('/tmp/my.h5', 'data2')
pd.read_hdf('/tmp/my.h5', 'data2').index.levels[0]
pd.read_hdf('/tmp/my.h5', 'data2').index.levels[1]

rawDescription: Losing timezone-awareness when saving hyerarchical pandas DatetimeIndex to hdf5 in Python


code:
s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]

fruits = [Fruit(*l) for l in s]

rawDescription: Breaking down list of list into dictionaries


code:
import math
math.log(42**3, 42) #3.0

rawDescription: How to take the logarithm with base n in numpy?

description: Take the logarithm with base n in numpy


code:
import numpy as np
import pandas as pd

N = 365
corn = pd.DataFrame({'Open': np.random.random(N)},
                    index=pd.date_range('1980-1-1', periods=N))
samples = np.random.choice(corn[:'1981'].index,50)
dfs = [corn.loc[date:date+pd.Timedelta(days=29)] for date in samples]

rawDescription: Advanced array/dataframe slicing (numpy/pandas)


code:
for person in sorted(cat1):
    print(person, max(cat1.get(person)))

rawDescription: How to sort python dictionary/list?

description: Sort python dictionary/list


code:
def foo(s):
    c_string = "hello"
    return s == c_string

rawDescription: Hard coded variables in python function

description: Hard coded variables in python function


code: from cart import cart

rawDescription: no module named 'cart' when i go to admin

description: No module named 'cart' when i go to admin


code:
{'text': 'text_string_c', 'word': 'dissemble', 'pos': 3, 'word_id': 5}
{'text': 'text_string_c', 'word': 'dissemble', 'pos': 1, 'word_id': 5}

rawDescription: Interfering objects (or something less sinister?)


code:
def convert(text):
    replacements = {
        u"à": "a",
        u"Ö": "o",
        u"é": "e",
        u"ü": "u",
        u"ç": "c",
        u"ë": "e",
        u"è": "e",
    }
    def convert_letter(letter):
        try:
            return replacements[letter]
        except KeyError:
            return letter
    return [convert_letter(letter) for letter in text]

rawDescription: How to detect ASCII characters on a string in python

description: Detect ASCII characters on a string in python


code:
score_filehandle = open("filename.txt","w+")
# And then when a game ends:
score_filehandle.write(" ".join([current_time, player_id, "won", games_won, "games"]) + "\n")

rawDescription: Python - export result value to text file


code:
import random
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
some_list = random.sample(list1, 5)
result = list(set(list1) - set(some_list))
result
some_list

rawDescription: Avoiding a for-loop to remove a slice of the list


code:
def my_sum(items):
    result = ''
    for item in items:
        if type(item) == list:
            result += my_sum(item)
        else:
            result += item
    return result

rawDescription: Summing objects in recursive python function


code:
class Person:
  def __init__ (self, Name, Address, Phone, Height, Weight):
    self.name = Name
    self. Address = Address
    self.Phone = Phone
    self.Height = int(Height) # note
    self.Weight = int(Weight) # note
    self.PoundserPerInch = Height / Weight

rawDescription: Using Python, how would I take in an integer argument?


code:
c = test()
c.t2()

rawDescription: Calling previously defined functions within other functions(Python)


code:
import example
import time
foo = example.Foo()
foo.start()
time.sleep(3)
foo.stop()

rawDescription: boost python threading segmentation fault

description: Boost python threading segmentation fault


rawDescription: Internals of a tree

description: Internals of a tree


code:
import statsmodels.formula.api as smf

smresults = smf.ols('monthly_data_smoothed8 ~ date_delta', dframe).fit()

dframe['pred'] = smresults.predict()

rawDescription: Pandas/Statsmodel OLS predicting future values


code:
#python2:
In [444]: b'ff'=='ff'
Out[444]: True

#python3: ('bytes' is a builtin type different from 'str' in py3)
In [2]: type(b'ff')
Out[2]: builtins.bytes

In [3]: b'ff'=='ff'
Out[3]: False

rawDescription: Questions about different string, int, and hex types


rawDescription: Trouble getting browser to download from python cgi script


code: k.strftime('%H:%M:%S,%f ')

rawDescription: what would be the python code to add time to a specific timestamp?

description: What would be the python code to add time to a specific timestamp


rawDescription: Python RegEx for exact matches of brackets


code:
I = reduce(
    lambda l,r: np.intersect1d(l,r,False),
    (i[:,0] for i in (A,B,C)))

rawDescription: filtering multiple numpy arrays based on the intersection of one column

description: Filtering multiple numpy arrays based on the intersection of one column


code:
class SerialPort(serialport.SerialPort):
    def _serialFactory(self, dev, *args, **kwargs):
        " pyserial recommends the following for supporting serial urls "
        try:
            return serial.serial_for_url(dev)
        except AttributeError:
            return serial.Serial(dev, *args, **kwargs)

rawDescription: Use RFC2217 network serial ports with Twisted Python?


code:
from pprint import pprint
req_ids = ['964', '123', '534', '645', '876', '222']
res_result = [{'id':'123', 'name':'Sachin'},
              {'id':'534', 'name':'Vipin'},
              {'id':'222', 'name':'Ram'},
              {'id':'645', 'name':'Anoop'},
              {'id':'964', 'name':'Sani'},
              {'id':'876', 'name':'John'}]
id_to_pos = {key: i for i, key in enumerate(req_ids)}
sorted(res_result, key=lambda d: id_to_pos[d['id']])
pprint(_)

rawDescription: How can I order a list of dictionaries based on another list which has the key?

description: Order a list of dictionaries based on another list which has the key


code:
class foo(object):

    bar = 2

    @classmethod
    def frobble(self):
        return "I didn't even have to be instantiated!"

print(foo.bar)
print(foo.frobble())

rawDescription: python memory consumption and performance related to classes

description: Python memory consumption and performance related to classes


code:
from collections import Counter
totals = Counter(widget.datetime.month for widget in widgets)

rawDescription: Building a list of monthly totals

description: Building a list of monthly totals


code:
for j in pblist[0:10]:
        base_url = j['short_url']
        page = urllib.request.urlopen(base_url)
        soup = BeautifulSoup(page)
        if hasattr(soup, 'head') and \
            hasattr(soup.head, 'title'):
                print("Has head, title attributes.")
                try:
                    j['title'] = soup.head.title.string.encode('utf-8')
                except AttributeError:
                    print("Encountered attribute error on page, ", base_url)
                    j['title'] = "Attribute error."
                    pass

rawDescription: Python - Passing urls vs. an HTTPResponse object


code:
def foo(a:str) -> list:
    return("Works")

foo(1)

rawDescription: How to specify multiple return types using type-hints

description: Specify multiple return types using type-hints


code:
from timeit import timeit
stmt1 = '''
stmt2 = '''
setup2 = 'from itertools import permutations'
stmt3 = '''
stmt4 = '''
setup4 = setup2
timeit(stmt1, number=100)
timeit(stmt2, setup2, number=100)
timeit(stmt3, number=100)
timeit(stmt4, setup4, number=100)

rawDescription: What is the quickest way to get a number with unique digits in python?


code:
import csv

csv_reader = csv.reader(open('data.csv', 'rb'))

# Read first two rows of field text out as a prefix.
prefix = ' '.join(csv_reader.next()[2].strip() for i in range(2))

def collapsed_row_iter():
    depth_value_list = []
    for (_, field_id, field_text, _) in csv_reader:
        # Count number of leading <SPACE> chars to determine depth.
        pre_strip_text_len = len(field_text)
        field_text = field_text.lstrip()
        depth = pre_strip_text_len - len(field_text)

        depth_value_list_len = len(depth_value_list)
        if depth == depth_value_list_len + 1:
            # Append a new depth value.
            depth_value_list.append(field_text.rstrip())

        if depth <= depth_value_list_len:
            # Truncate list to depth, append new value.
            del depth_value_list[depth:]
            depth_value_list.append(field_text.rstrip())

        else:
            # Depth value is greater than current_depth + 1
            raise ValueError

        # Only yield the row if field_id value is non-NULL.
        if field_id:
            yield (field_id, '%s %s' % (prefix, ' '.join(depth_value_list)))

# Get CSV writer object, write the header.
csv_writer = csv.writer(open('collapsed.csv', 'wb'))
csv_writer.writerow(['FIELD', 'TEXT'])

# Iterate over collapsed rows, writing each to the output CSV.
for (field_id, collapsed_text) in collapsed_row_iter():
    csv_writer.writerow([field_id, collapsed_text])

rawDescription: How to produce a flatfile (?) from a hierarchical csv

description: Produce a flatfile (?) from a hierarchical csv


code:
class PyRect(object):
    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self._topright = None
    @property
    def topright(self):
        if self._topright is None:
            self._topright = (self.x + self.w, self.y)
        return self._topright
    @topright.setter
    def topright(self, newx, newy):
        self.x = newx - self.w
        self.y = newy
        self._topright = (newx, newy)

rawDescription: How are all member variables of a Pygame rect updated when only one member is modified?


code:
def __init__(self):
    self.value = None
    ...
    someTextView = build_textview("some text")
    ...
    def selection_changed_handler(widget, data):
        value = self.selection_changed(widget, data)

    tree_selection = someTreeView.get_child().get_selection()
    tree_selection.connect("changed", selection_changed_handler)
    ...

rawDescription: Save variable returned by signal handler?


code: desc_div = result.find('div', {'class': re.compile(r'\bs\b')})

rawDescription: Updated approach to Google search with python


code:
class Foo(metaclass=FooMeta):
    FOO = 123
    def a(self):
        pass

rawDescription: Python metaclasses: Why isn't __setattr__ called for attributes set during class definition?


code:
import pymssql
conn = pymssql.connect(host='SQL01', user='user', password='password', database='mydatabase')
cur = conn.cursor()

# frame is your dataframe
wildcards = ','.join(['?'] * len(frame.columns))
data = [tuple(x) for x in frame.values]
table_name = 'Table'

cur.executemany("INSERT INTO %s VALUES(%s)" % (table_name, wildcards), data)
conn.commit()

rawDescription: Can I export a Python Pandas dataframe to MS SQL?

description: Export a Python Pandas dataframe to MS SQL


code:
from heapq import nsmallest
from random import random
values = [random() for i in range(20)]
values
nsmallest(4, range(len(values)), key=lambda i: values[i])

rawDescription: Python - Finding elements in a list efficiently


code:
if price_now == 'Y':
    print(get_price())
else:
    price = 0.0
    # While price is lower than 7.74 continue to check for price changes.
    while price < 7.74:
        price = get_price()
        time.sleep(5)

rawDescription: time.sleep() function in Python 3.3?

description: Time.sleep() function in Python 3.3


rawDescription: Fetch partial string matched html tag using xpath


rawDescription: Missing data, insert rows in Pandas and fill with NAN


code:
numeric = np.array([dtype in [np.int64, np.float64] for dtype in y.dtypes])
numeric

rawDescription: Combining multiple data types in pandas DataFrame


rawDescription: Spark dataframe transform multiple rows to column


code:
my_input = "DECBBEFEAACDCFEC"
my_grid = zip(*[iter(my_input)]*int(len(my_input)**0.5))

rawDescription: Appending a list to make a 4x4 matrix cipher


code:
def longest_prefix_match(search, urllist):
    matches = [url for url in urllist if url.startswith(search)]
    if matches:
        return max(matches, key=len)
    else:
        raise Exception("Not found")

rawDescription: Longest Prefix Matches for URLs

description: Longest Prefix Matches for URLs


rawDescription: time.time() overflow/rollover

description: Time.time() overflow/rollover


code: print(b'\33]0;title you want\a')

rawDescription: Set GNOME terminal window title in Python?


code:
# A list with OS Family members
OS_FAMILY = dict(
    RedHat = 'RedHat', Fedora = 'RedHat', CentOS = 'RedHat', Scientific = 'RedHat',
    SLC = 'RedHat', Ascendos = 'RedHat', CloudLinux = 'RedHat', PSBM = 'RedHat',
    OracleLinux = 'RedHat', OVS = 'RedHat', OEL = 'RedHat', Amazon = 'RedHat',
    XenServer = 'RedHat', Ubuntu = 'Debian', Debian = 'Debian', Raspbian = 'Debian', Slackware = 'Slackware', SLES = 'Suse',
    SLED = 'Suse', openSUSE = 'Suse', SuSE = 'Suse', SLES_SAP = 'Suse', Gentoo = 'Gentoo', Funtoo = 'Gentoo',
    Archlinux = 'Archlinux', Manjaro = 'Archlinux', Mandriva = 'Mandrake', Mandrake = 'Mandrake',
    Solaris = 'Solaris', Nexenta = 'Solaris', OmniOS = 'Solaris', OpenIndiana = 'Solaris',
    SmartOS = 'Solaris', AIX = 'AIX', Alpine = 'Alpine', MacOSX = 'Darwin',
    FreeBSD = 'FreeBSD', HPUX = 'HP-UX'
)

rawDescription: Specifying the OS - Ansible

description: Specifying the OS - Ansible


code:
class NewBase(object):
    __metaclass__ = ParentBase

class Parent(NewBase):
    pass

rawDescription: Class inheritance and __new___

description: Class inheritance and __new___


code:
def test(list_of_lists, start = 0):
    final = []
    for L in list_of_lists[start:]:
        final += L
    return final

rawDescription: Iterate function changing parameter after each run


code: s.split(' r ')

rawDescription: Finding strings that are each separated by the same string


rawDescription: django - regex for optional url paramaters

description: Django - regex for optional url paramaters


code: ['cat', 'cat12', 'catcat']

rawDescription: How do I find a specific word in elements in a list (python)

description: Find a specific word in elements in a list (python)


code:
()    # this is a 0-length tuple
(1,)  # this is a tuple containing "1"
1,    # this is a tuple containing "1"
(1)   # this is number one - it's exactly the same as:
1     # also number one
(1,2) # tuple with 2 elements
1,2   # tuple with 2 elements

rawDescription: How to pass tuple as argument in Python?

description: Pass tuple as argument in Python


code:
from collections import defaultdict, deque
d = defaultdict(deque)
for i, j in li:
    for k, t in li:
       if (i, j) != (k, t) and (i == t or j == k):
            d[(i, j)].append((k, t))

d

rawDescription: Turning list of pairs into list of pairs of pairs that share last item with first or vice versa


code: (path for path in files if filterex(path, 'txt'))

rawDescription: Python: Passing functions with arguments to a built-in function?


code: setattr(object, 'threshold', 'mean')

rawDescription: How to gridsearch over transform arguments within a pipeline in scikit-learn

description: Gridsearch over transform arguments within a pipeline in scikit-learn


code:
from io import open

with open(filename, 'r', encoding="unicode_escape") as inputfile:
    for line in inputfile:
        print(inputfile)

rawDescription: python ascii to unicode conversion

description: Python ascii to unicode conversion


code:
opener = poster.streaminghttp.register_openers()
opener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) # Add cookie handler
params = {'file': open("test.txt", "rb"), 'name': 'upload test'}
datagen, headers = poster.encode.multipart_encode(params)
request = urllib2.Request(upload_url, datagen, headers)
result = urllib2.urlopen(request)

rawDescription: How to post a file via HTTP with cookies using python poster lib

description: Post a file via HTTP with cookies using python poster lib


rawDescription: How to plot values for multiple factors from one column across several dates in pandas + matplotlib?

description: Plot values for multiple factors from one column across several dates in pandas + matplotlib


code: result = filter(particle)

rawDescription: How to remove duplicate items in multiple tuples of a dictionary?

description: Remove duplicate items in multiple tuples of a dictionary


rawDescription: Keep firstly found duplicate items in a list


code: set(my_list)-{i for e in bad for i in my_list if e in i}

rawDescription: Check if list item contains items from another list


code:
_format_changes = (
    ('yyyy', '%Y'), ('yyy', '%Y'), ('yy', '%y'),('y', '%y'),
    ('MMMM', '%B'), ('MMM', '%b'), ('MM', '%m'),('M', '%m'),
    ('dddd', '%A'), ('ddd', '%a'), ('dd', '%d'),('d', '%d'),
    ('HH', '%H'), ('H', '%H'), ('hh', '%I'), ('h', '%I'),
    ('mm', '%M'), ('m', '%M'),
    ('ss', '%S'), ('s', '%S'),
    ('tt', '%p'), ('t', '%p'),
    ('zzz', '%z'), ('zz', '%z'), ('z', '%z'),
    )

def cnv_csharp_date_fmt(in_fmt):
    ofmt = ""
    fmt = in_fmt
    while fmt:
        if fmt[0] == "'":
            # literal text enclosed in ''
            apos = fmt.find("'", 1)
            if apos == -1:
                # Input format is broken.
                apos = len(fmt)
            ofmt += fmt[1:apos].replace("%", "%%")
            fmt = fmt[apos+1:]
        elif fmt[0] == "\\":
            # One escaped literal character.
            # Note graceful behaviour when \ is the last character.
            ofmt += fmt[1:2].replace("%", "%%")
            fmt = fmt[2:]
        else:
            # This loop could be done with a regex "(yyyy)|(yyy)|etc".
            for intok, outtok in _format_changes:
                if fmt.startswith(intok):
                    ofmt += outtok
                    fmt = fmt[len(intok):]
                    break
            else:
                # Hmmmm, what does C# do here?
                # What do *you* want to do here?
                # I'll just emit one character as literal text
                # and carry on. Alternative: raise an exception.
                ofmt += fmt[0].replace("%", "%%")
                fmt = fmt[1:]
    return ofmt

rawDescription: Python datetime format like C# String.Format


rawDescription: Showing page count with ReportLab

description: Showing page count with ReportLab


code:
import operator
from itertools import product
digits = '123456789'
ops = (' - ', ' + ', '')
for combo in product(ops, repeat=len(digits) - 1):
    expr = zip(digits, combo + ('',))
    expr = ''.join([c for digit_oper in expr for c in digit_oper])
    result = eval(expr)
    if result == 100:
        print(expr)

rawDescription: Python - How to join elements in a list that are separated by a certain value


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

# Generate some test data
x = np.random.randn(8873)
y = np.random.randn(8873)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)

surf = plt.pcolormesh(xedges, yedges, heatmap)
plt.axis('image')
plt.colorbar(surf, shrink=0.75, aspect=5)
plt.show()

rawDescription: heatmap in matplotlib with vector format

description: Heatmap in matplotlib with vector format


code:
from gluon.validators import is_empty
from gluon.validators import Validator

class IS_NOT_EMPTY_IF_OTHER(Validator):

    def __init__(self, other,
                 error_message='must be filled because other value '
                               'is present'):
        self.other = other
        self.error_message = error_message

    def __call__(self, value):
        if isinstance(self.other, (list, tuple)):
            others = self.other
        else:
            others = [self.other]

        has_other = False
        for other in others:
            other, empty = is_empty(other)
            if not empty:
                has_other = True
                break
        value, empty = is_empty(value)
        if empty and has_other:
            return (value, T(self.error_message))
        else:
            return (value, None)

rawDescription: Web2py Custom Validators

description: Web2py Custom Validators


rawDescription: python if...elif always not working

description: Python if...elif always not working


code: binarySearch( array, desiderata, midP + 1, iMax )

rawDescription: Python function returns None (all trivial solutions checked and they do not work)


rawDescription: How do I suppress scientific notation in Python?

description: Suppress scientific notation in Python


rawDescription: 128 bit Integer hash function

description: 128 bit Integer hash function


code:
df.columns = ['TradeDate',
                                      'TradeTime',
                                      'CumPnL',
                                      'DailyCumPnL',
                                      'RealisedPnL',
                                      'UnRealisedPnL',
                                      'CCYCCY',
                                      'CCYCCYPnLDaily',
                                      'Position',
                                      'CandleOpen',
                                      'CandleHigh',
                                      'CandleLow',
                                      'CandleClose',
                                      'CandleDir',
                                      'CandleDirSwings',
                                      'TradeAmount',
                                      'Rate',
                                      'PnL/Trade',
                                      'Venue',
                                      'OrderType',
                                      'OrderID'
                                      'Code']

rawDescription: Adding Column headers to pandas dataframe.. but NAN's all the data even though headers are same dimension


code: help(min)

rawDescription: Python finding minimum values of functions of list items, but returning the list item


code:
PyQt4.QtCore.QPoint(242, 285)
PyQt4.QtCore.QPoint(1741, 423)
PyQt4.QtCore.QPoint(439, 372)
PyQt4.QtCore.QPoint(1509, 549)
PyQt4.QtCore.QPoint(90, 6)
PyQt4.QtCore.QPoint(1468, 50)
PyQt4.QtCore.QPoint(302, 372)
PyQt4.QtCore.QPoint(1674, 382)
PyQt4.QtCore.QPoint(501, 416)
PyQt4.QtCore.QPoint(1867, 416)
PyQt4.QtCore.QPoint(605, 391)
PyQt4.QtCore.QPoint(1971, 391)
PyQt4.QtCore.QPoint(18, 16)
PyQt4.QtCore.QPoint(1384, 16)
PyQt4.QtCore.QPoint(12, 12)
PyQt4.QtCore.QPoint(1378, 12)
PyQt4.QtCore.QPoint(12, 12)
PyQt4.QtCore.QPoint(1378, 12)
PyQt4.QtCore.QPoint(12, 12)
PyQt4.QtCore.QPoint(1378, 12)
PyQt4.QtCore.QPoint(1019, 14)
PyQt4.QtCore.QPoint(2385, 14)

rawDescription: Python - PyQT4 how to detect the mouse click position anywhere in the window?


rawDescription: Using re and extract some patterns from list Python2.7


rawDescription: Python: Split NumPy array based on values in the array


code:
class Content:
    def __init__(self, reply_channel):
        self.reply_channel = reply_channel

    def send(self, json):
        self.reply_channel.send({
            'reply_channel': str(self.reply_channel),
            'text': dumps(json)
        })

def ws_message(message):
    content = Content(message.reply_channel)
    content.send({'hello': 'world'})

rawDescription: How to use Channel instead of Group when using django channels?

description: Use Channel instead of Group when using django channels


code: b = np.delete(a,-1,1)

rawDescription: Remove one column for a numpy array

description: Remove one column for a numpy array


code:
df['fruit'] = df['fruit'].map(lambda x: x.lower())

res = df.groupby('fruit').sum()

res
#         val1  val2
# fruit
# apple     13    13
# mango      5     5
# orange     3     3

rawDescription: Merge Duplicates based on column?

description: Merge Duplicates based on column


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

rawDescription: Appending python dictionaries, without replacing if the value is empty


code:
self.treeWidget.setColumnCount(2) # two columns, url result
for i in range(10):
    self.treeWidget.insertTopLevelItem(i, QTreeWidgetItem(QStringList('url %s' % i)))

rawDescription: PyQT QTreeWidget iterating

description: PyQT QTreeWidget iterating


code:
import sys, termios
previous_mode= termios.tcgetattr( sys.stdin.fileno() )

rawDescription: How can I determine when a user is in the process of entering something as an input in Python?

description: Determine when a user is in the process of entering something as an input in Python


code:
with open(path, 'r+b') as f:
    f.seek(position)
    f.write(new_bytes)

rawDescription: How do I edit an executable with python by address/offset/bytes, like in a hex editor?

description: Edit an executable with python by address/offset/bytes, like in a hex editor


rawDescription: Assigning to a Row in Pandas

description: Assigning to a Row in Pandas


rawDescription: How to make Checkbutton which is automatically checked using gtk

description: Make Checkbutton which is automatically checked using gtk


rawDescription: How do I get a formatted list of methods from a given object?

description: Get a formatted list of methods from a given object


code:
grades = { 'k':'x'}
grades
grades = { 'newinput':'newval'}
grades

rawDescription: Iterating on a dictionary, adding keys and values


code:
print ("Making A Cup Of Tea")
num_orders = int(input("How many for Tea? "))
print ("there are", num_orders, "People for tea")
orders = []
for i in range(num_orders):
    b = input ("Person %i, Would you like Sugar? YES/NO " % (i + 1))
    sugar = None
    if b in ("YES", "Y", "y", "yes"):
        sugar = input("How many sugars? ")
    else:
        print ("Okay No sugar")

    milk = input("How Much Milk Would You Like? SMALL/MEDIUM/LARGE ")

    print ("Order is being processed, next order:\n")
    orders.append({'sugar': sugar, 'milk': milk })

print('The orders has been processed with these data:')
for i in range(num_orders):
    order = orders[i]
    print (' - Person', i + 1, 'wants tea', ('with %i' % int(order['sugar']) if order['sugar'] else 'without'), 'sugar and ', order['milk'], 'milk')

rawDescription: How to Repeat a piece of code a certain amount of times in python


code:
result = grequests.map(request)
json = [r.json() for r in result]

rawDescription: Python: How can i send multiple HTTP requests and receive the response?


code:
timeit.timeit("Spam() in l", """
# Old-style
class Spam: pass
l = [Spam() for i in xrange(100000)]""", number=10)
timeit.timeit("Spam() in l", """
# New-style
class Spam(object): pass
l = [Spam() for i in xrange(100000)]""", number=10)
timeit.timeit("'a' in l", 'l = ["b" for i in xrange(100000)]', number=10)

rawDescription: Python - "in" statement seach slow for list of objects


code: re.findall(".*theme=pseudo.*", line)

rawDescription: re.findall() doesn't matches with it's finding

description: Re.findall() doesn't matches with it's finding


code:
a = ["Three","Four","Five","Six"]
b = range(3,7)
zip(a,b)
[term for pair in zip(a,b) for term in pair]

rawDescription: Pythonically inserting multiple values to a list


code:
Module(
  [Expr(
    Lambda(
      arguments(
        [Name('S', Param()), Name('b', Param())],
        None,
        None,
        []
      ),
      Subscript(
        Tuple(
          [Call(
              Name('g', Load()),
              [Subscript(Name('S', Load()), Slice(Num(1), None, None), Load()), Name('b', Load())],
              [],
              None,
              None
            ),
            Name('S', Load())
          ],
          Load()
        ),
        Index(
          Compare(
            Call(Name('len', Load()), [Name('S', Load())], [], None, None),
            [Eq()],
            [Name('b', Load())]
          )
        ),
        Load()
      )
    )
  )]
)

rawDescription: Recursion with ternary operator 'hack' in Python


rawDescription: Understanding Floating-point doc

description: Understanding Floating-point doc


code:
# In numerical order, setting missing numbers to 0
for i in range(1, max(hist) + 1):
    print('{}: {}'.format(i, hist.get(i, 0)))

# In most common to least order
# In numerical order
for number, count in hist.most_common():
    print('{}: {}'.format(number, count))

rawDescription: incrementing list values Python 3

description: Incrementing list values Python 3


code:
data = """'{"data": [{"content": "blabla"}]}'"""
check_output('''curl -d {0} http://service.location.com'''.format(data), shell=True)

rawDescription: Passing string as argument adds escape characters


code:
for i in range(0, len(array_dg)):
  plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())

rawDescription: Create own colormap using matplotlib and plot color scale


code:
def func(X,W):
    def f(i,j): return np.dot(X[i],W[j])
    return f

rawDescription: Double sum in Python

description: Double sum in Python


code: 1 - residual / (n * y.var())

rawDescription: Converting Numpy Lstsq residual value to R^2


code:
@api.depends('product_id.product_tmpl_id.type')
def _niu_validation(self):
    for rec in self:
        if rec.product_id.product_tmpl_id.type == 'product' and not rec.niu:
            rec.niu = self.env['ir.sequence'].next_by_code('sale.order.line')

rawDescription: How to create an incremental field (sequence) that is validated with a method (def)

description: Create an incremental field (sequence) that is validated with a method (def)


code:
def get_ptr_ctypes2(x):
    return x.ctypes._data

def get_ptr_array(x):
    return x.__array_interface__['data'][0]

try:
    from accel import _get_ptr as get_ptr
except ImportError:
    get_ptr = get_ptr_array

rawDescription: Portable/fast way to obtain a pointer to Numpy/Numpypy data


code:
x = 'hi'
print (x)
y = '%s' %x
y

rawDescription: How to copy what Python last printed and put it to a string

description: Copy what Python last printed and put it to a string


code: sh.sh('-c', 'source test.sh')

rawDescription: Python's sh module - Running 'source' command


code:
if number < 0:
    ...

rawDescription: Python - Identify a negative number in a list


code: ids = set(itertools.chain((str(result[5]) for result in text_results), (str(result[4]) for result in doc_results)))

rawDescription: Create a set from items in two lists

description: Create a set from items in two lists


code:
import wx

class MyFrame1(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)

        pnl = wx.Panel(self, wx.ID_ANY)
        szmain = wx.BoxSizer(wx.VERTICAL)
        color_choices = [u"-- Select --", u"Red", u"Green", u"Pink", u"Blue", u"Yellow", u"White", u"Brown"]
        self.color_options = wx.Choice(pnl, wx.ID_ANY, choices=color_choices)
        self.color_options.SetSelection(0)

        self.reset_button = wx.Button(pnl, wx.ID_ANY, u"Reset")

        szmain.Add(self.color_options, 0, wx.ALL|wx.EXPAND, 4)
        szmain.Add(self.reset_button, 0, wx.ALL|wx.EXPAND, 4)
        pnl.SetSizer(szmain)

        self.reset_button.Bind( wx.EVT_BUTTON, self.OnResetButton )

    def OnResetButton(self, event):
        val = '-- Select --'  # NOT WORKING
        #  val = ' '  # THIS WORKS, BUT RESETS TO EMPTY CHOICE

        self.color_options.SetLabel(val)

app = wx.App(0)
MyFrame1(None).Show()
app.MainLoop()

rawDescription: Python/wxPython: How to reset wx.Choice to a default value


code:
for line2 in f2data:
    if line1 in line2:
        linecount+=1

rawDescription: Using Python to Compare Two Text Files Line by Line


rawDescription: Retrieve rows from Monday to Friday in Django?


code: #self.terminate() # does it works at this place?

rawDescription: Python/PySide: How can i destroy a terminated thread object?


rawDescription: Insert a list into another list, without brackets and by replacing the current item in that index


code:
import re

a = ['Benny']

rawDescription: python reuse code, parse add to list and print match line

description: Python reuse code, parse add to list and print match line


code:
frame2 = Frame(self, relief=FLAT, borderwidth=2)
frame2.pack(side=TOP, fill=BOTH, expand=False)

rawDescription: How do I access a label to change its text in Tkinter

description: Access a label to change its text in Tkinter


code:
zip(x,y) # zip the lists together
t  = (['a', 'b', 'c'], ['A', 'B', 'C']) # first "t"
zip(*t) # transpose, row to columns, columns to rows
list(map(list,zip(*t))) # convert inner tuples to lists

rawDescription: Python: merging lists like this

description: Python: merging lists like this


code:
import scipy.stats
ci = grouped.aggregate(lambda x: scipy.stats.sem(x, ddof=1) * 1.96) #use mean +(-) ci to get 95% conf interval

rawDescription: bootstrap on a groupby object in pandas

description: Bootstrap on a groupby object in pandas


code:
# x in dct
h = hash(x)
items = getItemsForHash(dct, h)
for item in items:
    if x == item:
        return True
# items is empty, or no match inside the loop
return False

rawDescription: `object in list` behaves different from `object in dict`?


code:
lis = []
class Object():
    def __init__(self, var):
        self.something = var
        lis.append(self)  #here self is the reference to the instance being created and you can save it in a list to access it later
xxx = Object('123')
xx = Object('12')
x = Object('1')

for x in lis:
    print(x.something)

rawDescription: Simple OOP: Python, saving object names via __init__ v2


code:
if __name__ == '__main__':
    p = Process(target=login, args=(name,pwd))
    p.start()
    p.join()

rawDescription: should I use multiprocessing in all function call from the start function?

description: Should I use multiprocessing in all function call from the start function


code:
for x in range (1, 11):
    for y in range (1, 11):
        print ('{:3}'.format(x*y), end=' ')
    print()

rawDescription: How to print a 10*10 times table as a grid?

description: Print a 10*10 times table as a grid


code:
def update (self):
    if self.right>544 and self.dx > 0:
        self.dx = -self.dx
    if (self.top > 11 and self.dy < 0) or (self.bottom > 470 and self.dy > 0):
        self.dy = -self.dy
    if self.left < 0:
        self.iLost()

rawDescription: Debugging ping pong game in Python

description: Debugging ping pong game in Python


rawDescription: How do I get the raw representation of a string in Python?

description: Get the raw representation of a string in Python


code:
def token_of(line):
  return line.partition(':')[-1].strip()

class FileParser(object):
  def __init__(self, filename):
    self.tokenList = open(filename, 'r')

  def cleaned_input(self):
    cleanedInput = []
    prevLine = 0

    for line in self.tokenList:
        if line.startswith('LINE:'):
            lineNo = int(token_of(line))
            diff = lineNo - prevLine - 1
            cleanedInput.append('\n' * (diff if diff>1 else diff+1))
            prevLine = lineNo
        else:
            cleanedLine = token_of(line)
            cleanedInput.append(cleanedLine + ' ')

    return cleanedInput

rawDescription: Making a Python script Object-Oriented

description: Making a Python script Object-Oriented


code:
print(list(takewhile(lambda x: x< 6, lst))) # good reason why we should not use list as a variable name
[1, 2, 3, 4, 5]

rawDescription: How to limit for loop to print first few element from list in terms of their value in python?

description: Limit for loop to print first few element from list in terms of their value in python


code:
def show_multiples(low, high, num):
    first = high // num * num # Divided the high by num and floor it (ie. 100 // 15 == 6) ... then mutiply by 6.
    # can be written as
    # first = (high // num) * num
    # if that is clearer

    multiples = list(range(first, low-1, -num)) # more efficient for large delta
    # OR
    # multiples = [value for value in range(high, low-1, -1) if not value % num]

    odd, even = [], []
    for value in multiples:
        if value % 2 == 0:
            even.append(value)
        else:
            odd.append(value)

    print(" ".join(map(str, multiples)))  # just some trickery to get a list of numbers to work with join
    # could also do this - the comma prevents a newline
    # for multiple in multiples:
    #     print(multiple),
    # print()

    print("{} even numbers total {}".format(len(even), sum(even))) # string.format
    print("{} odd numbers total {}".format(len(odd), sum(odd)))

def main():
    high = int(input('Enter the high integer for the range: ')) # Enter the high integer
    low = int(input('Enter the low integer for the range: '))   # Enter the lower integer
    num = int(input('Enter the @integer for the multiples: '))   # Enter integer to find multiples

    show_multiples(low, high, num)

if __name__ == "__main__":
    main()

rawDescription: Count even and odd numbers and the totals (python)


code: groupA[name] = [count]  # creating new single-element list

rawDescription: When i add to the list in my dictionary, it doesn't actually add to the list? python


code:
import colander
import limone

@limone.content_schema
class Characteristic(colander.MappingSchema):
    id = colander.SchemaNode(colander.Int(),
                             validator=colander.Range(0, 9999))
    name = colander.SchemaNode(colander.String())
    rating = colander.SchemaNode(colander.String())

class Characteristics(colander.SequenceSchema):
    characteristic = Characteristic()

@limone.content_schema
class Person(colander.MappingSchema):
    id = colander.SchemaNode(colander.Int(),
                             validator=colander.Range(0, 9999))
    name = colander.SchemaNode(colander.String())
    phone = colander.SchemaNode(colander.String())
    characteristics = Characteristics()

class Data(colander.SequenceSchema):
    person = Person()

rawDescription: Typed JSON serialization/deserialization in Python


code:
xy = line2d[0].get_xydata()
xy[-2]

rawDescription: How to extract points from a graph?

description: Extract points from a graph


rawDescription: threading programming in python

description: Threading programming in python


code:
import Tkinter as tk

class dropDown(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self,master)

        #background set_up
        image1 = tk.PhotoImage(file="test.gif")
        panel1 = tk.Label(root, image=image1)
        panel1.pack(side='top', fill='both', expand='yes')

        # save the panel's image from 'garbage collection'
        panel1.image = image1

        #Drop down menu
        self.var = tk.StringVar(master)
        self.var.set('Alaska') # initial value

        #Have not used countries list just pasted
        self.option = tk.OptionMenu(master, self.var, 'Alaska','Alberta', 'Australia')
        self.option.pack()

root = tk.Tk()
root.title('drop down test')
d=dropDown(root)
d.pack(side='top',fill='both',expand='yes')
root.mainloop()

rawDescription: python - TKinter - Can I send background to back?

description: Python - TKinter - Can I send background to back


code:
stu = []
while True:
    inp = input('Add a student: ')
    if not inp:
        break
    stu.append(inp)

rawDescription: Printing on new line - python

description: Printing on new line - python


rawDescription: How to get all items in multi list in bottle?

description: Get all items in multi list in bottle


rawDescription: Best way to store fixed-keys key:value datasets that are accessed by keys in python?

description: Store fixed-keys key:value datasets that are accessed by keys in python


code:
ciphertext = b'SplitsEvenly'

blocks = [ciphertext[i:i+keylength] for i in range(0, len(ciphertext)+1, keylength)]
# [b'Spl', b'its', b'Eve', b'nly', b'']

rawDescription: Break bytes object into n equally sized blocks based on index


code:
from itertools import count
def sieveL(l=0,Data={}):#l is not used, its how the test calls the generators
    '''modified from
    http://code.activestate.com/recipes/117119-sieve-of-eratosthenes/
    L for loadable'''

    if Data.get('I',0):#there's data from a previous run, load it
        D,C=Data['I'] #I for inner

    else:#no data, start from scratch
        yield 2
        D={}
        C=3#starting counter

    for i in count(C,2):
        if STOP:
            Internals['I']=[D,i]#store the current counter and the internal data
            break
        s=D.pop(i, 0)
        if not s:
            yield i
            D[i*i]=2*i
        else:
            i+=s
            while i in D:i+=s
            D[i]=s

rawDescription: Pausable prime generator

description: Pausable prime generator


code: args = parser.parse_args()

rawDescription: Accessing argument values for argparse in Python


code:
d['b']=[3,4,5] #d['b'] refers to another list
l

rawDescription: How to point to python dictionary value?

description: Point to python dictionary value


rawDescription: Python dataframe groupby by dictionary list then sum


code:
import csv
import random

def select_n_random(n):
    fin = open('emails.csv', 'rb')
    reader = csv.reader(fin)
    email_list = list(reader)[0]
    output_list = []
    for i in range(n):
        idx = random.randint(0, len(email_list)-1)
        output_list.append(email_list.pop(idx))

    fout = open('email_output.csv', 'wb')
    writer = csv.writer(fout, quoting=csv.QUOTE_ALL)
    writer.writerow(output_list)

    fout.close()
    fin.close()

select_n_random(10)

rawDescription: Random Email Picker of Size n

description: Random Email Picker of Size n


rawDescription: Select siblings between two nodes

description: Select siblings between two nodes


code:
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False, unique=True)
    active = db.Column(db.Boolean, nullable=False, default=True)

    @property
    def is_active(self):
        # override UserMixin property which always returns true
        # return the value of the active column instead
        return self.active

rawDescription: How do I define and create a User model for use with Flask-Login?

description: Define and create a User model for use with Flask-Login


code:
def readfile(file):
    lines = []
    for l in file.readlines():
        if pattern in l:
            lines.append(l)
    return lines
    #alternatively:
    #return [l for l in file.readlines() if pattern in l]

lines = readfile(file)
for line in lines:
    print(line)

rawDescription: With return get only the one line

description: With return get only the one line


code:
cols = pd.MultiIndex.from_product((['Very Happy', 'Happy', 'Sad', 'Very Sad'], [True, False]))
pv.reindex(index=range(1, 5), columns=cols, fill_value=0)

rawDescription: Crosstab in pandas with enforced values

description: Crosstab in pandas with enforced values


code:
t = (1, 3)
any(el > 2 for el in t)

rawDescription: Could someone explain the logic here or what I am asking? (Boolean operations)


rawDescription: Python flattening my tuple structure

description: Python flattening my tuple structure


code: elems_in_both_lists = set(list1) & set(list2)

rawDescription: Python - checking if an element is in two lists at the same time


code:
@decorator
def decorated():
    pass

rawDescription: Catch signals in Flask Blueprint

description: Catch signals in Flask Blueprint


code:
def parse_date(string):
    # Split the string into year/month/date, time, and seconds
    split_string = string.split()
    # get year month and date
    year = split_string[0].split('-')[0]
    month = split_string[0].split('-')[1]
    date = split_string[0].split('-')[2]

    # get hour minute second
    hour = split_string[1].split(':')[0]
    minute = split_string[1].split(':')[1]
    second = split_string[1].split(':')[2]

    return datetime.datetime(int(year), int(month), int(date), hour=int(hour), minute=int(minute), second=int(second))

filename = open('./data.txt', 'r')
frames = []
dates = []
counter = 1

for line in filename:
    # print(counter % 31)
    if line.startswith('20'):
        print(line)
        dates.append(parse_date(line))
    # frames.append(f_nov15_hereford)

print(dates)

rawDescription: Datetime header when reading in a file with pandas


code:
import datetime

mdate = "2010-10-05"
rdate = "2010-10-05"
mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d").date()
rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d").date()
delta =  (mdate1 - rdate1).days

rawDescription: Integer difference in python between two dates


code:
from binascii import unhexlify
result = list(bytearray(unhexlify(s)))

rawDescription: Encode string as hex bytes

description: Encode string as hex bytes


code:
from viewflow import flow
from viewflow.base import Flow
from viewflow.flow import flow_start_view

class NewUserFlow(Flow):
     registration = flow.StartView(registraton_view).Next(...)

@flow_start_view()
def registraton_view(request, activation):
     activation.prepare(request.POST or None, user=request.user)
     form = RegistrationForm(request.POST or None)

     if form.is_valid():
         activation.process.user = form.save()
         activation.done()
         return redirect(...)

     return render(request, 'registration.html', {
        'form': form,
        'activation': activation,
     })

rawDescription: viewflow.io: How can I present a custom form for gathering input for a specific task?

description: Viewflow.io: How can I present a custom form for gathering input for a specific task


code:
import datetime
td = datetime.datetime.now() - datetime.datetime.now()
print(td)
td
td.days
td.seconds
td.microseconds
(24 * 60 * 60)  # 1 day in seconds
(24 * 60 * 60) - td.seconds
1000000 - td.microseconds

rawDescription: Why does datetime.datetime.now() - datetime.datetime.now() equal to datetime.timedelta(-1, 86399, 999974)?


rawDescription: Set an array equal to the first half of it's entries in python


code: [x.split(variable)[1].split('_')[0] for x in the_list]

rawDescription: Edit a list to remove a defined variable and everything after and including a character


code:
newDict = dict((k1.lower(),
                dict((k2.lower(),
                      [s.lower() for s in v2]) for k2, v2 in v1.iteritems()))
               for k1, v1 in myDict.iteritems())

rawDescription: Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings?


code:
import os
wordReplacements = {'document':'file', 'notepad':'Notepad'}

def transform_line(line):
    for key, value in wordReplacements.iteritems():
        line = line.replace(key, value)
    return line

with open("Output.txt", "w") as output_file, open("Input.txt") as input_file:
    for line in input_file:
        output_file.write(transform_line(line))

os.rename("Output.txt", "Input.txt")

rawDescription: python replace word in text file without going line by line

description: Python replace word in text file without going line by line


code:
from collections import Counter
counts = Counter(play_turn() for i in xrange(100000))
counts
probabilities = {score: count / 100000.0 for score, count in counts.items()}
probabilities

rawDescription: Probability Dice Game in Python with two dices


code:
from pandas.util.testing import assert_frame_equal
assert_frame_equal(csvdata, csvdata_old)

rawDescription: Comparing two pandas dataframes for differences


code:
import os

newtime = createnewtime()
command = 'echo "python setHeater.py" | at ' + newtime
os.system(command)

rawDescription: How can i execute this command from Python

description: Execute this command from Python


code:
def make_toys(df):
    result = []
    for index, row in df.iterrows():
        prob = np.random.binomial(row['number'], 0.1)
        result.extend([Toy(row) for _ in range(prob)])
    return result

rawDescription: Parallel and conditional: NoneType object has no attribute '__dict__'


code:
[int(n) for n in a.split(',')]
[int(n) for n in b.split(',')]
set(map(int, a.split(',')))
set(map(int, a.split(','))).intersection(map(int, b.split(',')))
bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))

rawDescription: comparing numbers in 2 string A and B

description: Comparing numbers in 2 string A and B


code:
pd.options.display.max_columns = None
display(data)

rawDescription: ipython notebook pandas max allowable columns

description: Ipython notebook pandas max allowable columns


code:
source = ["Mulan", "and", 5, "Aladdin", "is", True, "Quality"]
[word for word in source if isinstance(word, str)]

rawDescription: Searching for strings in list

description: Searching for strings in list


code:
INSTALLED_APPS = (
    'longer_username',
    ...
)

rawDescription: Made Django's auth track on emails, how to relate username field to email?


rawDescription: Display tick and cross icons for a property in the Django administration console


rawDescription: Getting positions of specific values of a 2D NumPy array with mask


code:
import colorsys
hue = 0.0        # 0 is red
saturation = 1.0 # fully saturated

for luminance in range(0, 10, 1):
   r, g, b = colorsys.hls_to_rgb(hue, luminance / 10.0, saturation)
   print('{:d}, {:d}, {:d}'.format(int(r * 255), int(g * 255), int(b * 255)))

rawDescription: Find colour based on brightness in python


rawDescription: Extracting multiple rows from pandas dataframe and converting to columns


code:
list(XinY_Product(2, 3))
list(XinY_Iter(2, 3))

rawDescription: Is it possible to remove recursion from this function?


code:
# Lookup for values by (id, level)
values = {}
minlevel, maxlevel = float('inf'), float('-inf')
for id_, level, value in inputlist:
    values[id_, level] = value
    if level < minlevel:
        minlevel = level
    if level > maxlevel:
        maxlevel = level

def level_sort(tup):
    id_, level, value = tup
    sortkey = [level]
    for l in range(minlevel, maxlevel + 1):
        sortkey.append(values.get((id_, l)) if l >= level else None)
    return sortkey

sorted(inputlist, key=level_sort)

rawDescription: Python advanced list ordering

description: Python advanced list ordering


code: ['New Abbey|Ceredigion|United Kingdom', 'New Albany|Indiana|United States', 'New Albany|Kansas|United States', 'New Albany|Mississippi|United States', 'New Albany|Ohio|United States']

rawDescription: how to apply binary search in python on sorted list of string elements?

description: Apply binary search in python on sorted list of string elements


code:
for _ in range(5):
   print(choice('abcdefghijklmnopqrstuvwxyz'))
   sys.stdout.flush()

rawDescription: Python asyncio timely event handling

description: Python asyncio timely event handling


code: main_module = __import__(main_module_name, fromlist=list(map(str, ['bar'])))

rawDescription: Portable code: __import__ parameter string type between Python 2 and Python 3


code:
for thing_in_both_sets in intersect(input_set, set_1):
    user_score += 1

rawDescription: Finding the intersection between sets and awarding points


code:
index = index_from_xy(1234, 5678)
index
xy_from_index(index)

rawDescription: Python convert int to unsigned short then back to int


code:
from io import StringIO
dir(StringIO)
help(StringIO.truncate)

rawDescription: how do I clear a stringio object?

description: Clear a stringio object


code:
list_1 = [ "cat", "rat", "mat" ]
list_A = [ "cat", "car", "cab" ]
list_B = [ "cat", "rat", "bat", "mat" ]
list_C = [ "cat_mittens", "rat", "mat" ]
check_all(list_1, list_A)
check_all(list_1, list_B)
check_all(list_1, list_C)
check_all(list_1, ["ratcatmat"])
check_all(["bc", "ab"], ["abc"])

rawDescription: Check if list of 'partial' strings is in list of full strings


code:
ascending = "".join(sorted(str(number)))

descending = "".join(sorted(str(number), reverse=True))

rawDescription: How to sort digits in a number?

description: Sort digits in a number


code:
io.seek(0)
print(io.tell()) #print where we are in the object now

rawDescription: creating stream to iterate over from string in Python

description: Creating stream to iterate over from string in Python


rawDescription: IPython Notebook save location

description: IPython Notebook save location


code:
import db_fixtures

class SQliteTest(db_fixtures.BaseDB):
  def setUp(self):
    self.db = createSqliteconnection()

class MySQLTest(db_fixtures.BaseDB):
  def setUp(self):
    self.db = createMySQLconnection()

rawDescription: Running the same tests with different configurations