code:
@pytest.fixture(params=[1, 2, 3])
def number(request):
    return request.param

@pytest.mark.parametrize('letter', ['a', 'b', 'c'])
def test_combinations(number, letter):
    pass  # test assertions, etc.

rawDescription: When should I create multiple test functions and should I use pytest fixtures for global variables?


code:
import pandas as pd
myFile = pd.read_csv('ch06/ex1.csv')
myFile.head()

rawDescription: How do I open a CSV file in IPython on Windows

description: Open a CSV file in IPython on Windows


code:
import tkinter

class MyApp:
    def __init__(self):
        self.root = tkinter.Tk()
        self.root.title("App")
        self.root.geometry("400x400")
        self.root.update()
        self.box1Text = tkinter.Text(self.root, width=1, height=1)
        self.box1Text.pack(fill=tkinter.BOTH,side=tkinter.LEFT, expand=True)
        self.box2Text = tkinter.Text(self.root, width=1, height=1)
        self.box2Text.pack(fill=tkinter.BOTH,side=tkinter.RIGHT, expand=True)

App = MyApp()
App.root.mainloop()

rawDescription: Text widget to fill half of screen

description: Text widget to fill half of screen


code:
class Data(object):

    def __init__(self):

        self.SIZE = 8 # dimensions of the game field
        self.MAX_TURNS = 5 # amount of iterations for each of the players ("turns") before the end
        self.turns = 0 # count of turns done
        self.score_PC = self.score_PC2 = 0 # score values

        # create and init the data matrices
        self.data_PC = [['X' for j in xrange(self.SIZE)] for i in xrange(self.SIZE)]
        self.data_PC2 = [['X' for j in xrange(self.SIZE)] for i in xrange(self.SIZE)]

rawDescription: Issues with data sharing between processes


code:
def __array_wrap__(self, obj):
    if obj.shape == ():
        return obj[()]    # if ufunc output is scalar, return it
    else:
        return np.ndarray.__array_wrap__(self, obj)

rawDescription: numpy ndarray subclass: ufunc don't return scalar type

description: Numpy ndarray subclass: ufunc don't return scalar type


code:
from sympy import symbols
x = symbols('x')
str(x**2)

rawDescription: sympy output in IPython

description: Sympy output in IPython


code:
from threading import Thread
from queue import Queue
import random

import time

class DownloadWorker(Thread):
    def __init__(self, queue):
        Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            self.queue.get()
            print('Thread: {}'.format(self.name))
            time.sleep(random.random())

queue = Queue()
for i in range(100):
    queue.put('data')

queue.task_done()

for x in range(4):
    worker = DownloadWorker(queue)
    worker.daemon = True
    worker.start()

time.sleep(10)

rawDescription: How to know Python Queue in full active?

description: Know Python Queue in full active


code:
def sameSet(list1, list2):
        if contained(list1, list2) and contained(list2, list1):
                print("the same!!")
        else:
            print("not the same")

def contained(list1, list2):

    for element in list1:
        if element not in list2:
           return False

    return True

def main():
    # this prints "the same"
    sameSet([1, 4, 9, 16, 9, 7, 4, 9, 11, 11], [11, 11, 7, 9, 16, 4, 1])
    # this prints "not the same"
    sameSet([1, 4, 9, 16, 9, 7, 4, 9, 11, 11], [11, 11, 7, 9, 16, 4,12345])

if __name__=="__main__":
    main()

rawDescription: Writing function that checks if lists have the same elements


code:
import xml.etree.ElementTree as ET

# I find that using a dictionary to map prefixes to namespaces keeps
# things easier to understand. You can also use the namespaces directly
# though if you prefer
NAMESPACE_PREFIXES = {
    'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
    }

tree = ET.parse('document.xml')
root = tree.getroot()
text_elements = [element for element in root.iter() if element.tag ==
'{' + NAMESPACE_PREFIXES['w'] + '}t']
# Equivalent to:
# text_elements = [element for element in root.iter() if element.tag ==
# '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t']
for text_element in text_elements:
    if text_element.text == 'Hello world!':
        text_element.text = 'Goodbye world!'

rawDescription: Trying to parse Word docx file as a zip document using Python's xml.elementtree


code:
text = 'caramelosticosis'
print(text[::-1])

rawDescription: inverse characters from a string using 'for i in string'

description: Inverse characters from a string using 'for i in string'


code:
class MyObject( object ):
    def __init__( self, args ):
        pass # Something Expensive

class MyObjectFactory( object ):
    def __init__( self ):
        self.pool = {}
    def makeMyObject( self, args ):
        if args not in self.pool:
            self.pool[args] = MyObject( args )
        return self.pool[args]

rawDescription: How to create a class that doesn't re-create an object with identical input parameters

description: Create a class that doesn't re-create an object with identical input parameters


rawDescription: What are the first 32 bits of the fractional part of this float?


code:
dates = pd.date_range('01-Jan-2014','11-Jan-2014', freq='T')[0:-1]
s.size
s.groupby(lambda d: d.date()).resample('30min').size
s.groupby(lambda d: d.date()).resample('30min')
np.unique(_25.index.get_level_values(1).minute)
np.unique(_25.index.get_level_values(1).dayofweek)

rawDescription: Resample intraday pandas DataFrame without add new days


code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os

link_name = 'linkname'
file_name = './filename'

# hard link
cmd = 'ln ' + file_name + ' ' + link_name
os.popen(cmd)

# soft link
cmd = 'ln -s ' + file_name + ' ' + link_name
os.popen(cmd)

rawDescription: how to use package of python to create link

description: Use package of python to create link


code:
def remove_alpha(self):
    if 'noise' in self.__dict__:
        del self.noise

rawDescription: Getting the original class's member

description: Getting the original class's member


code:
import re
re.findall(r'one', 'one two one three')

rawDescription: Match string and put all results in a list in Python


code:
def repeatfunc(func, times=None, *args):
    """Repeat calls to func with specified arguments.

    Example:  repeatfunc(random.random)
    """
    if times is None:
        return starmap(func, repeat(args))
    return starmap(func, repeat(args, times))

rawDescription: Function for calling a function repeatedly?


code:
#!/usr/bin/python3

from numpy import *
from matplotlib import pyplot as plt

a = linspace(0, 6.28, 100)

x = sin(a)
y = cos(a)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(a, x, "k-", lw=3)
ax.plot(a, y, "k-", lw=3)

ax.fill_between(a, x, y, hatch = '///')

fig.savefig("mwe.png")

rawDescription: Hatching of region between two defined functions in matplotlib


code:
people = DBSession.query(Person)\
    .join(Person._name)\
    .filter(Name.name.like('Z%'))\
    .all()

# or more explicitly without using the relationship:

people = DBSession.query(Person)\
    .join(Name, Person.name_id == Name.id)\
    .filter(Name.name.like('Z%'))\
    .all()

rawDescription: SQLAlchemy: Use like() on a relationship()


code:
class SelectForm(forms.Form):
    selection = forms.ChoiceField(
    choices=[
        (HumanModel.__name__, 'Human'),
        (OtherHumanModel.__name__, 'Other Human')
    ]
)

class HumanModelFactory(object):
    def __init__(self, model_name):
        if model_name == "HumanModel":
            return HumanModel()
        if model_name == "OtherHumanModel":
            return OtherHumanModel()

# usage
model_name = request.POST['selection'] # e.g. 'HumanModel'
instance = HumanModelFactory(model_name)

rawDescription: django - class in ChoiceField

description: Django - class in ChoiceField


code:
# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8])
cb = plt.colorbar(ax1, cax = cbaxes)

rawDescription: positioning the colorbar

description: Positioning the colorbar


code:
list1 = ["a:b","x:y","s:e","w:x"]
dict(elem.split(':') for elem in list1)

rawDescription: How to convert List in to Dictionary in python?

description: Convert List in to Dictionary in python


code:
@app.route('/index')
def index():
    form = AddExpenses()
    allnames = getSalesman()
    form.salesperson.choices = [names for names in allnames]
    ...

rawDescription: Initialising the flask-wtf form when the page loads


code:
template_search_list = [
    "comments/%s/%s/form.html" % (ctype.app_label, ctype.model),
    "comments/%s/form.html" % ctype.app_label,
    "comments/form.html"
]

rawDescription: Customize django render_comment_form fields


code:
import gzip

def read_fasta(filename):
    with gzip.open(filename) as f:
        return dict(line.split() for line in f)

rawDescription: Python programming

description: Python programming


code:
import csv

#    B.csv:
#    store#  part#
#      xx     xx
#      xx     xx
#      xx     xx
#    ...

partNums = {}
with open('B.csv') as bfile:
    breader = csv.DictReader(bfile)
    for row in breader:
        partNums[row['part#']] = row['store#']

#    A.csv
#    part#  tag1  tag2  tag3 ...
#    xx     xx    xx    xx   ...
#    xx     xx    xx    xx   ...
#    xx     xx    xx    xx   ...
#    ...

with open('outfile.csv', 'wb') as outfile:
    with open('A.csv', 'rb') as afile:
        areader = csv.reader(afile)
        outwriter = csv.writer(outfile)
        headers = areader.next()
        headers.append('StoreCode')
        outwriter.writerow(headers)
        for row in areader:
            if row[0] in partNums:  #assuming first row is part#
                row.append(partNums[row[0]])
            else:  #value if no store number exists
                row.append('')
            outwriter.writerow(row)

rawDescription: Is there an Excel function or a script to find and replace fields that match in two different sheets by another data contained in the second sheet?


code:
import scrapy
from urlparse import urljoin

class CompItem(scrapy.Item):
    title = scrapy.Field()
    link = scrapy.Field()
    data = scrapy.Field()

class criticspider(scrapy.Spider):
    name = "comp"

    allowed_domains = ["iproperty.com.my"]
    start_urls = ["http://www.iproperty.com.my/property/searchresult.aspx?t=S&gpt=AR&st=&ct=&k=&pt=&mp=&xp=&mbr=&xbr=&mbu=&xbu=&lo=&wp=&wv=&wa=&ht=&au=&sby=&ns=1"]

    def parse(self, response):
        agents = response.xpath('//li[@class="search-listing"]//div[@class="article-right"]')
        for agent in agents:
            item = CompItem()
            item['title'] = agent.xpath('.//a/text()').extract()[0]
            item['link'] = agent.xpath('.//a/@href').extract()[0]
            yield scrapy.Request(urljoin("http://www.iproperty.com.my", item['link']),
                                 meta={'item': item},
                                 callback=self.anchor_page)

    def anchor_page(self, response):
        old_item = response.request.meta['item']

        old_item['data'] = response.xpath('.//*[@id="main-content3"]//table//table//p/text()').extract()
        yield old_item

rawDescription: What's wrong with my scraper?

description: What's wrong with my scraper


code:
d = {}
for x in result:
    d.setdefault(x[0], [] ).append(x[2])
for x in d:
    while len(d[x]) < 7:
        d[x].append(0)

rawDescription: How to store the sql query result into a dictionary object

description: Store the sql query result into a dictionary object


code:
from rpy2 import robjects
m = robjects.reval("matrix(1:6, nrow=2, ncol=3)")
import numpy as np
a = np.array(m)

rawDescription: Convert R Matrix to Pandas Dataframe

description: Convert R Matrix to Pandas Dataframe


code:
x
s = x.tostring()
numpy.fromstring(s)
y = numpy.fromstring(s).reshape((3, 3))
y

rawDescription: How to restore a 2-dimensional numpy.array from a bytestring?

description: Restore a 2-dimensional numpy.array from a bytestring


code:
x_max = 12
y_max = 4
vec1d = np.arange(x_max*y_max, dtype=complex)
vec1d.reshape([x_max, y_max])

rawDescription: Python: how to convert a complex array to a 2D array?


code:
class SampleClass(object):
    """Summary of class here.

    Longer class information....
    Longer class information....

    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """

    def __init__(self, likes_spam=False):
        """Inits SampleClass with blah."""
        self.likes_spam = likes_spam
        self.eggs = 0

    def public_method(self):
        """Performs operation blah."""

rawDescription: Proper way to comment code. Python

description: Proper way to comment code. Python


code:
new_tags = []
for t in tags:
    existing_tag = self.through.tag_model().objects.get(name__iexact=t)
    if existing_tag:
        new_tags.append(existing_tag)
    else:
        new_tags.append(t)
tags = set(new_tags)

rawDescription: Replace/Change item in python set

description: Replace/Change item in python set


code:
subject = request.GET.get('subject', '')
content = request.GET.get('content', '')
contact_form = ContactForm(initial={'subject': subject, 'content': content})

rawDescription: How to set dynamic default textarea data in a Django template?

description: Set dynamic default textarea data in a Django template


code:
@functools.lru_cache
def original_fn(x):
   blah
   return fnvalue, fnderiv

def new_fn_value(x):
   fnvalue, fnderiv = original_fn(x)
   return fnvalue

def new_fn_deriv(x):
   fnvalue, fnderiv = original_fn(x)
   return fnderiv

rawDescription: Can I pass the objective and derivative functions to scipy.optimize.minimize as one function?

description: Pass the objective and derivative functions to scipy.optimize.minimize as one function


rawDescription: Is it customary to have one "main" method call in a python script?


code:
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk

root = tk.Tk()
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
#print(root.winfo_screenheight(), root.winfo_screenwidth())
root.geometry("%dx%d" % (width, height))
#URL FOR BACKGROUND
#https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiVroCiyZHMAhXKeT4KHQHpDVAQjBwIBA&url=http%3A%2F%2Fwallpaperswide.com%2Fdownload%2Fblack_background_metal_hole_very_small-wallpaper-800x480.jpg&psig=AFQjCNEjZ7GDbjG9sFie-yXW3fP85_p0VQ&ust=1460840934258935
image = Image.open("background.jpg")
if image.size != (width, height):
    image = image.resize((width, height), Image.ANTIALIAS)
    #print("DONE RESIZING")
    # image.save("background.jpg")
#print(image.size)
image = ImageTk.PhotoImage(image)
bg_label = tk.Label(root, image = image)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)
bg_label.image = image
your_button = ttk.Button(root, text='This is a button')
your_button.grid()
root.mainloop()

rawDescription: Ttk background image

description: Ttk background image


code:
from bs4 import BeautifulSoup
s = 'link'
BeautifulSoup(s, "html.parser").a["href"]

rawDescription: How do you find patterns/combinations within a String in Python?

description: Find patterns/combinations within a String in Python


code:
file_number = 1
files = []
while file_number <= 100:
    file_name = 'C:/file%04d.csv' % file_number
    files.append(read_csv(file_name))
    file_number += 1

files[0].head()

rawDescription: Reading a large number of .csv files in Python pandas and assigning different variable names


code:
app_config = read_config()

def read_config():
    configparser = ConfigParser.RawConfigParser()
    configparser.read(some_config_filename)
    return configparser.as_dict() #An imaginery method which returns the vals as dict.

rawDescription: Python creating dynamic global variable from list


code:
from django import db
db.reset_queries()

rawDescription: Memory usage with Django + SQLite3

description: Memory usage with Django + SQLite3


rawDescription: Suppose I had a list in Python. What's the most pythonic and efficient way to randomize it by sections?


code:
from django.db.models import Max
from datetime import datetime, timedelta

Profile.objects.annotate(last_update=Max('subscription__created')).filter(last_update__lt=datetime.now()-timedelta(days=3))

rawDescription: Django ORM query to find all objects which don't have a recent related object


code:
import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt24
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

rawDescription: Recording 24-bit audio with pyaudio

description: Recording 24-bit audio with pyaudio


code:
import glob
for filename in glob.glob('*.txt'):
    with open(filename, 'w') as f:
        f.write("")

rawDescription: How to empty(delete all contents) all files in a directory without deleting the files?

description: Empty(delete all contents) all files in a directory without deleting the files


code:
pointsdict = {"a": apoints, "b": bpoints, "c": cpoints, "d": dpoints}
pointsdictsorted = sorted(pointsdict, key=pointsdict.__getitem__, reverse=True)
print(pointsdictsorted)

# Take the sorted list of values, and create a tuple for each: (value, rank)
for idx, elem in enumerate(pointsdictsorted):
    pointsdictsorted[idx] = (elem, idx + 1)

# Resort for teams, not scores, and assign.
ranks = sorted(pointsdictsorted)
arank = ranks[0][1]
brank = ranks[1][1]
crank = ranks[2][1]
drank = ranks[3][1]

print(arank, brank, crank, drank)

rawDescription: Python 3.4 - returning rankings based on two sets of data (with one only used when the other produces a tie)


code:
d = defaultdict(int)
for di in [d1,d2,d3]:
  for k,v in di.items():
    d[k] += v
dict(d)

rawDescription: Merge dictionaries and add values

description: Merge dictionaries and add values


code:
df
g = df.groupby('UserID').Date.nunique()
g
g > 1
g[g > 1]

rawDescription: Pandas Return Only Repeated Results

description: Pandas Return Only Repeated Results


code:
class Foo(object):
    def __init__(self, flag=False):
        self.flag = flag

    def flip_flag(self):
        self.flag = not self.flag

bar = Foo()
print(bar.flag)    # Prints False
viz.callback(viz.MOUSEDOWN_EVENT, bar.flip_flag)

# After some MOUSEDOWN_EVENT
print(bar.flag)    # Prints True

rawDescription: Return value from callback in Python (Vizard)


code:
#KeyWordFileItem = [word.strip() for word in KeyWordFileItem]
KeyWordFileItem = [word.decode('utf-8').strip() for word in KeyWordFileItem]

rawDescription: How to store words to a file by using : x for x in List A if x not in List B?

description: Store words to a file by using : x for x in List A if x not in List B


code:
class Person:
   def __init__(self,Fname,Lname,Byear):
       self.firtsName = Fname
       self.lastName = Lname
       self.birth_year = Byear
   def __str__(self):
       return "%s, %s Age: %s" %(self.lastName, self.firtsName, (datetime.datetime.now().year-self.birth_year))

p1=Person('Olivia','Parker',1985)
print(p1)

rawDescription: Add an integer to a class atribute

description: Add an integer to a class atribute


code:
from urllib3 import ProxyManager, make_headers

default_headers = make_headers(basic_auth='myusername:mypassword')
http = ProxyManager("https://myproxy.com:8080/", headers=default_headers)

# Now you can use `http` as you would a normal PoolManager
r = http.request('GET', 'https://stackoverflow.com/')

rawDescription: How to handle proxies in urllib3

description: Handle proxies in urllib3


code:
def owns_console():
    wnd = GetConsoleWindow()
    if wnd is None:
        return False
    return GetCurrentProcessId() == GetWindowThreadProcessId(wnd)

rawDescription: Prevent a console app from closing when not invoked from an existing terminal?


code:
def range_like(start, stop=None, step=1):
    if stop is None:
        start, stop = 0, start
    ...

rawDescription: Function definition like range

description: Function definition like range


code:
def get_known_fields_string(user, fieldSelector):
    entrys = HTTPRequestData.objects.filter(user=user)
    counter = Counter()

    for entry in entrys:
        counter[fieldSelector(entry)] += 1

    return counter_to_string(counter)

def get_known_citys_string(user):
    return get_known_fields_string(user, lambda entry: entry.city)

def get_known_devices_string(user):
    return get_known_fields_string(user, lambda entry: entry.device)

rawDescription: How do I stay DRY?

description: Stay DRY


code:
import threading
import time

class PeriodicThread(StoppableThread):
    '''Similar to a Timer(), but uses only one thread, stops cleanly and exits when the main thread exits'''

    def __init__ (self, period, callable, *args, **kwargs):
        super(PeriodicThread, self).__init__()
        self.period   = period
        self.args     = args
        self.callable = callable
        self.kwargs   = kwargs
        self.daemon   = True

    def run(self):
        while not self.stopped():
            self.callable(*self.args, **self.kwargs)
            time.sleep(self.period)

rawDescription: Periodic timers in python, with small period


rawDescription: How to get the current running module path/name

description: Get the current running module path/name


code:
years, year_fraction = divmod(5.08493150685, 1)
days = round(year_fraction * 365.25)
years
days

rawDescription: How would I convert decimal years in to years and days


code:
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
import os
import shutil
def run():
    os.chdir(path_dir)
    for fname in glob.glob("*.shp"):
        name,ex = fname.rsplit(".",1) # split on "." to rejoin later adding a ("A")
        # use shutil.copy to copy the file after adding ("A")
        shutil.copy(fname,os.path.join(path_res,"{}{}{}".format(name,"(A)",ex)))
        # to move and rename in one step
        #shutil.move(fname,os.path.join(path_res,"{}{}{}".format(name,"(A)",ex)))

rawDescription: How to add characters to filename using glob in Python?

description: Add characters to filename using glob in Python


code:
from path import path  # wrapper for os.path
import re
import tempfile

image_pdf = Image(blob=pdf_blob)
image_jpeg = image_pdf.convert('jpeg')
temp_dir = path(tempfile.mkdtemp())
# set base file name (join)
image_jpeg.save(temp_dir / 'pdf_title.jpeg')
images = temp_dir.files()

sorted_images = sorted(
    images,
    key=lambda img_path: int(re.search(r'\d+', img_path.name).group())
)
for img in sorted_images:
    with open(img, 'rb') as img_fd:
        memory_file = SimpleUploadedFile(
            img.name,
            img_fd.read()
        )
        spam = Spam.objects.create(
            page_image=memory_file,
            caption="Spam Spam",
        )
tempfile.rmtree(tempdir)

rawDescription: Wand convert pdf to jpeg and storing pages in file-like objects


code:
import logging

logger = logging.getLogger('my_logger')

formatter = logging.Formatter(FORMAT)

console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)

file_handler = logging.FileHandler(logname)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

rawDescription: Global logging and save log to file

description: Global logging and save log to file


code:
 # This RetailItem class holds data about products.
class RetailItem:

    # __int__ method initializes the attributes.
    def __init__(self, description, units, price):
        self.__item_description = description
        self.__units_in_inventory = units
        self.__price = price

    # The set_item_description method gets the item type.
    def set_item_description(self, description):
        self.__item_description = description

    # The set_units_in_inventory method gets number of items available.
    def set_units_in_inventory(self, units):
        self.__units_in_inventory = units

    # The set_price method gets the cost of item.
    def set_price(self, price):
        self.__price = price

    # The get_item_description method returns the item type.
    def get_item_description(self):
        return self.__item_description

    # The get_units_in_inventory returns the number of items available.
    def get_units_in_inventory(self):
        return self.__units_in_inventory

    # The get_price method returns the cost of item.
    def get_price(self):
        return self.__price

# This program will test the RetailItem class and return information
# using the mutator method.

import sys

# This defines the main function.
def main():
    # Get a list of RetailItem objects.
    inventory = make_list()

    # Display the data in the list.
    print('Here is the data you entered:')
    display_list(inventory)

    # The make_list will get data for three items. It will
    #return a list of available items.

def make_list():
    # Create an empty list.
    item_list = []

    # Add three item to the list.
    print('Enter data for three items.')
    for count in range(1, 4):
        # Get item data.
        print('Item number ' + str(count) + ':')
        item = input('Enter description of item: ')
        units = float(input('Enter number of units in inventory: '))
        price = float(input('Enter price per item: '))
        print()

        # Creat new RetailItem and assign items variable.
        items = RetailItem(item, units, price)
        # Add items to list.
        item_list.append(items)

        return item_list

#Display the items information.
def display_list(item_list):
    for item in item_list:
        print(item.get_item_description())
        print(item.get_units_in_inventory())
        print(item.get_price())
        print()

# Call the main function.
main()

rawDescription: Retail Item Class assignment

description: Retail Item Class assignment


code:
from nltk import FreqDist
from nltk.classify.naivebayes import NaiveBayesClassifier

def make_training_data(rdr):
    for c in rdr.categories():
        for f in rdr.fileids(c):
            yield FreqDist(rdr.words(fileids=[f])), c

clf = NaiveBayesClassifier.train(list(make_training_data(reader)))

rawDescription: Using my own corpus for category classification in Python NLTK


code:
def freq(a):
    D = {}
    for v in a:
        D[v] = D.get(v, 0) + 1
    return D

rawDescription: Dictionary of unique values and their occurances - Python


code:
class PassengerList(generics.ListCreateAPIView):
    model = Passenger
    serializer_class = PassengerSerializer

    # Show all of the PASSENGERS in particular WORKSPACE
    # or all of the PASSENGERS in particular AIRLINE
    def get_queryset(self):
        queryset = Passenger.objects.all()
        workspace = self.request.query_params.get('workspace', None)
        airline = self.request.query_params.get('airline', None)

        if workspace is not None:
            queryset = queryset.filter(workspace_id=workspace)
        elif airline is not None:
            queryset = queryset.filter(workspace__airline_id=airline)

        return queryset

rawDescription: Django REST framework - filtering against query param


code: set(line.strip() for line in open('filename.txt'))

rawDescription: Python: load words from file into a set

description: Python: load words from file into a set


code:
CASES = ("divides with both", False, False, "divides with 3", False, "divides with 5", "divides with 3", False, False, "divides with 3", "divides with 5", False, "divides with 3", False, False)

LIMIT = 100

k = []

for n in range (1, LIMIT + 1):
    result = ((n, CASES[n % len(CASES)]), n)

    k.append(result[result[0][1] == False])

print(k)

rawDescription: How can I achieve case condition in python?

description: Achieve case condition in python


code:
def find_smallest(N):
    x = 10**(N - 1)
    q = x / 60
    if q * 60 < x:
        x = q * 60 + 60
    return x

find_smallest(3)
find_smallest(4)
find_smallest(5)
find_smallest(6)

rawDescription: how to calculate the minimum number that consists of N digits without leading zeros and is divisible by 10 and 12

description: Calculate the minimum number that consists of N digits without leading zeros and is divisible by 10 and 12


code:
import subprocess
retcode = subprocess.call(['abq684', 'cae', 'script=XX.py'])

rawDescription: Run executable from script with conditions python2.6


code:
from django.utils import timezone
from datetime import timedelta

database.time = timezone.now()
expire_time = timezone.now() + timedelta(hours=24)

rawDescription: Python-Django timezone is not working properly


code:
#Usage: response.set_cookie( 'cookie_name', 'cookie_value' )

class RefererMiddleware(object):
    def process_response(self, request, response):
        if not request.COOKIES.has_key( 'HTTP_REFERER' ):
            response.set_cookie( 'HTTP_REFERER', request.META.get('HTTP_REFERER') )
        return response

rawDescription: Django saving HTTP_REFERER to use it as landingpage information


code:
m = __import__('xml.sax')
m.__name__
m = __import__('xml.sax', fromlist=[''])
m.__name__

rawDescription: Python : How to import a module if I have its path as a string?


rawDescription: Theano Matrix Inverse

description: Theano Matrix Inverse


code:
import multiprocessing
# L must is imported or defined somewhere up here...

if __name__ == '__main__':
    p = multiprocessing.Pool()  # Creates a pool with as many workers as you have CPU cores
    results = []
    for i in arayb:
        results.append(pool.apply_async(L, (r, g, p[i,:], h)))
    p.close()
    p.join()
    for result in results:
        print('l', result.get())

rawDescription: parallellization in python multiprocessing

description: Parallellization in python multiprocessing


code:
weight_var = tf.get_collection(tf.GraphKeys.VARIABLES, "conv_w_1")[0]

weight_var_value = session.run(weight_var)

rawDescription: TensorFlow: Access Contents of a Variable By Name


code:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
import numpy as np

fig, ax = plt.subplots(figsize=(5,4))
extent = (0, 100, 0, 50)
x, y = np.mgrid[-5:5:100j, -5:5:100j]
z = np.sin(2*x)*np.sin(y**2)
ax.contourf(x, y, z, cmap="YlGnBu_r")
axins = zoomed_inset_axes(ax, 2, loc=1)
axins.contourf(x, y, z, cmap="YlGnBu_r")
axins.set_xlim(1, 2)
axins.set_ylim(1, 2)
plt.xticks(visible=False)
plt.yticks(visible=False)
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.show()

rawDescription: How to zoom a part of plot by Matplolib

description: Zoom a part of plot by Matplolib


code:
with open(filenamex, 'rb') as currentx, open('foobar', 'w') as data:
    next(currentx)            #drop the first line
    data.writelines(currentx) #write rest of the content to `data`

rawDescription: Appending files to each other without adding the title row each time


code:
import ctypes

libfoo = ctypes.cdll.LoadLibrary('./foo.so')
foo = libfoo.foo
foo.argtypes = ()
foo.restype = ctypes.POINTER(ctypes.c_float)
result = foo()
print(result[0], result[1])

rawDescription: Reading array returned by c function in ctypes


code:
def prepare():
    os.setsid() # start a new detached session
    tty.setcbreak(sys.stdin) # set standard input to cbreak mode
    old = termios.tcgetattr(sys.stdin)
    old[0] |= termios.BRKINT # transforms break to SIGINT
    old[3] &= termios.ICANON # non-canonical mode
    old[3] |= termios.ECHO | termios.ISIG # set echo and signal characters handling
    cc = old[6]
    # make input unbuffered
    cc[termios.VMIN] = 1
    cc[termios.VTIME] = 0
    termios.tcsetattr(sys.stdin, termios.TCSANOW, old)

master, slave = pty.openpty()
master = os.fdopen(master, 'rb+wb', 0) # open file in an unbuffered mode
_make_non_blocking(master)

prog = subprocess.Popen(shell=False, args=['/bin/sh', '-i'], stdin=slave, stdout=slave, stderr=subprocess.STDOUT, preexec_fn=prepare)

rawDescription: How to run a shell in a separate process and get auto completions? (Python)

description: Run a shell in a separate process and get auto completions? (Python)


code: {{ article.content|safe }}

rawDescription: Django-ckeditor not displaying correctly in html


code:
from __future__ import absolute_import
import foo                   # import global foo.py, the first foo.py in sys.path
import tests.foo as test_foo # import tests/foo.py

rawDescription: How do I import a module whose name clashes with a module in my package?

description: Import a module whose name clashes with a module in my package


code: myList = filter(lambda x: myDict.get(x[1], None) != x[0], myList)

rawDescription: Python: remove lots of items from a list


code:
infinity = [0]
sentinelValue = 1000
for i in infinity:
    if i == sentinelValue:
        break

    # like a dog chasing the tail, we move the tail...
    infinity.append(i+1)

    print('Looped', i, 'times')

print('Sentinel value reached')

rawDescription: Can you use a for loop to implement a sentinel controlled loop in Python?

description: Use a for loop to implement a sentinel controlled loop in Python


code:
scores = [Myscore1, Myscore2, Myscore3]
[(x, (x == min(scores))) for x in scores]

rawDescription: How to calculate minimun value in all variables? Python

description: Calculate minimun value in all variables? Python


code:
with open('komad_namestaja.txt','r+') as f:
    data = f.readlines()
    output_data=[]
    for i in data:
        lst=i.split("|")
        if(lst[0]=='312'):
            lst[-1]='True\n'
        output_data.append("|".join(lst))
    f.seek(0)
    f.writelines(output_data)

rawDescription: How to change last parameter in file by first

description: Change last parameter in file by first


code: result = [item for word in words for item in word.split(',')]

rawDescription: split items in list

description: Split items in list


rawDescription: Traversing a Python list and making in-place changes


code:
def inversereplace(text, word, repl):
    parts = text.split(word)
    return word.join(repl*len(x) for x in parts)

rawDescription: Python: Inverse Replace Function

description: Python: Inverse Replace Function


code:
class MyDictionary( dict ) :
    def __init__(self, *arg, **kwargs ):
        # do some stuff for instance check mandatory keys are present
        super(self.__class__, self).__init__( *arg, **kwargs )

rawDescription: Docstring style: should I really have it this long?


rawDescription: Dynamically changing log level in python without restarting the application


code:
import numpy as np
a = np.array([[10, 20, 30, 40, 50],
              [ 6,  7,  8,  9, 10]])
your_permutation = [0,4,1,3,2]
i = np.argsort(your_permutation)
i
a[:,i]

rawDescription: Rearrange columns of numpy 2D array

description: Rearrange columns of numpy 2D array


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

data = [['N','0'],['1','4'],['2','8'],['3','12'],['N','1'],['1','3'],['2','6'],['3','9'],['N','2'],['1','2'],['2','4'],['3','6']]
# Dictionary with Nx as keys and corresponding plots as values
plot_dict = {}
curkey = None
for x, y in data:
    # Adding a new key
    if x == 'N':
        curkey = x + y
        plot_dict[curkey] = []
    # Add corresponding values to key
    elif curkey in plot_dict:
        # Cast as integers for plots
        plot_dict[curkey].append(map(int,(x,y)))

lines = []
names = []
for name, vals in plot_dict.items():
    # np.array(vals)[:,0] gets the first collumn so the x data
    # np.array(vals)[:,1] gets the second collumn of vals (y data)
    lines.append(plt.plot(np.array(vals)[:,0], np.array(vals)[:,1])[0])
    names.append(name)
plt.legend(lines, names)
plt.show()

rawDescription: Plot data with labels

description: Plot data with labels


code:
shipping_info = u'Expedited (2-3 Bus. Days)\xa0($17.99)'
shipping_info.replace(u'\xa0', u' ')

rawDescription: i cannot get rid \xa0 in this string using python?

description: I cannot get rid \xa0 in this string using python


rawDescription: How do I set a property in python using its string name

description: Set a property in python using its string name


code:
def round_up(value, multiple):
    return multiple * math.ceil(float(value) / multiple)

def digits(value):
    return int(math.log(value, 10)) + 1

def round_price(value):
    if value < 10000:
        return int(round_up(value, 1000))
    d = digits(value)
    new_value = int(round_up(value, 10 ** (d - 2)))
    new_value -= 10 ** (d - 3)
    return new_value

rawDescription: Python conditionally round up numbers

description: Python conditionally round up numbers


rawDescription: Calculate similarity/distance between rows using pandas faster


code:
from Tkinter import *

class App(Tk):

    def __init__(self):
        Tk.__init__(self)
        # self.x and self.y are the current mouse position
        # They are set to None here because nobody has clicked anywhere yet.
        self.x = None
        self.y = None
        self.makeCanvas()
        self.bind("<Any KeyPress>", lambda event: self.drawText(event.keysym))

    def makeCanvas(self):
        self.canvas = Canvas(self)
        self.canvas.pack()
        self.canvas.bind("<Button-1>", self.mouseDown)

    def mouseDown(self, event):
        # Set self.x and self.y to the current mouse position
        self.x = event.x
        self.y = event.y

    def drawText(self, newkey):
        # The if statement makes sure we have clicked somewhere.
        if None not in {self.x, self.y}:
            self.canvas.create_text(self.x, self.y, text=newkey)
            # I set x to increase by 5 each time (it looked the nicest).
            # 4 smashed the letters and 6 left gaps.
            self.x += 5

App().mainloop()

rawDescription: Typing Text into the Tkinter Canvas Widget


code: self._ribbon = RB.RibbonBar(self, wx.ID_ANY, agwStyle = RB.RIBBON_BAR_DEFAULT_STYLE | RB.RIBBON_BAR_ALWAYS_SHOW_TABS)

rawDescription: How to have only one tab open in wxribbon bar in wxpython?

description: Have only one tab open in wxribbon bar in wxpython


code:
import re
import os
from __future__ import with_statement

PATH = "/home/tirengarfio/Desktop/pruebaba"

for path, dirs, files in os.walk(PATH):
    for filename in files:
        fullpath = os.path.join(path, filename)
        with open(fullpath, 'r') as f:
            data = re.sub(r'(\s*function\s+.*\s*{\s*)',
                r'\1echo "The function starts here."',
                f.read())
        with open(fullpath, 'w') as f:
            f.write(data)

rawDescription: Python 2.5.2: trying to open files recursively


code:
import asyncio

async def bar(i):
  print('started', i)
  await asyncio.sleep(1)
  print('finished', i)

async def main():
  await asyncio.wait([bar(i) for i in range(10)])

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

rawDescription: Combine awaitables like Promise.all

description: Combine awaitables like Promise.all


code:
import os

user_input = input('What is the name of your directory')
directory = os.listdir(user_input)

searchstring = input('What word are you trying to find?')

for fname in directory:
    if os.path.isfile(user_input + os.sep + fname):
        # Full path
        f = open(user_input + os.sep + fname, 'r')

        if searchstring in f.read():
            print('found string in file %s' % fname)
        else:
            print('string not found')
        f.close()

rawDescription: Find files in a directory containing desired string in Python


code:
def transform_exog_to_model(fit, exog):
    transform=True
    self=fit

    # The following is lifted straight from statsmodels.base.model.Results.predict()
    if transform and hasattr(self.model, 'formula') and exog is not None:
        from patsy import dmatrix
        exog = dmatrix(self.model.data.orig_exog.design_info.builder,
                       exog)

    if exog is not None:
        exog = np.asarray(exog)
        if exog.ndim == 1 and (self.model.exog.ndim == 1 or
                               self.model.exog.shape[1] == 1):
            exog = exog[:, None]
        exog = np.atleast_2d(exog)  # needed in count model shape[1]

    # end lifted code
    return exog

transformed_exog = transform_exog_to_model(lm, out_of_sample_df)
print(transformed_exog)
prstd2, iv_l2, iv_u2 = wls_prediction_std(lm, transformed_exog, weights=[1])
print(prstd2)

rawDescription: Return std and confidence intervals for out-of-sample prediction in StatsModels


code: arr = contacts.values()

rawDescription: Remove items in key value pairs and place in array?


code:
from itertools import permutations
x = range(3)
list(permutations(x))

rawDescription: Try all the combinations (cases) Function


code:
import itertools
combined = [f + ' ' + l for f, l in itertools.product(first, last)]

rawDescription: Python permutation

description: Python permutation


code: mymodule_ext = Extension('mymodule', ['mymodule.c'], libraries=['otherproject'])

rawDescription: Creating a Python type in C using an external library: ctypes or setuptools?


rawDescription: How do I interpret the data read by matplotlib's imread?

description: Interpret the data read by matplotlib's imread


code:
myDialog = QtGui.QDialog()
isVis = myDialog.isVisible()

rawDescription: PyQt - How to check is QDialog is visible?


code:
import time

def my_time():
    return 0.0

old_time = time.time
time.time = my_time

rawDescription: monkey patching time.time() in python

description: Monkey patching time.time() in python


code:
import json
class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return "%.2f" % obj
        return json.JSONEncoder.default(self, obj)

rawDescription: Decimal to JSON

description: Decimal to JSON


code:
data = "Hello World"
file_hande = sftp_client.file(pollFile, mode='a', bufsize=1)
file_handle.write(data)
file_handle.flush()
file_handle.close()

rawDescription: Paramiko, appending file on SSH server

description: Paramiko, appending file on SSH server


rawDescription: Bazaar: bzrlib equivalent of "bzr info"

description: Bazaar: bzrlib equivalent of "bzr info"


code:
def getchildren(node, ignore_nodes=[]):
    child_nodes = []
    for child in node.children():
        if child in ignore_nodes:
            continue
        child_nodes.append(child)
        ignore_nodes.append(child)
        nodes, ignore_nodes = getchildren(child, ignore_nodes)
        child_nodes.extend(nodes)
    return child_nodes, ignore_nodes

rawDescription: Parent/Child database contains cyclical references


code:
from Tkinter import *

class App(object):

    def __init__(self, top):
        self.top = top
        self.ok_button = Button(self.top, text='OK', command=self.ok)
        self.make_entries()

    def make_entries(self):
        self.entries = []
        for d in extra:
            e2 = Entry(self.top, bd = 5)
            e2.grid(column = 1, row = row)
            self.entries.append(e2)
            row += 1

    def ok(self):
        values = [e.get().strip() for e in self.entries]

root = Tk()
app = App(root)
root.mainloop()

rawDescription: Python Tkinter: How to obtain all available Entry values


code:
import random
M = 16**4
"2001:cafe:" + ":".join(("%x" % random.randint(0, M) for i in range(6)))

rawDescription: How to generate random IPv6 address using Python(or in Scapy)?

description: Generate random IPv6 address using Python(or in Scapy)


code:
import re
s = "
Current Data Usage:  	221.59GB
"
match = re.search(r"([\d\.]*)GB", s)
match.group(1)

rawDescription: Filtering output in python?

description: Filtering output in python


code:
a = str(input())
b = a[0]
c = a[1]
d = a[2]
e = a[3]
f = a[4]
g = a[5]
if int(b)+int(c)+int(d) == int(e)+int(f)+int(g):
    print('Lucky')
else:
    print('Common')

rawDescription: Need help to solve very simple python task


code:
# Interpolate the data using a cubic spline to "new_length" samples
new_length = 50
interpolated_x = np.linspace(x.min(), x.max(), new_length - len(x) + 2)
new_x = np.sort(np.append(interpolated_x, x[1:-1]))  # include the original points
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

rawDescription: Python Keep points in spline interpolation


code:
if sys.stdin is not sys.__stdin__:
    return fallback_getpass(prompt, stream)

rawDescription: Is there easy way to prevent echo from input?


code:
import MySQLdb
import sqlalchemy
import pandas

con = MySQLdb.connect('localhost','root','my_password', 'database_name')
con_str = 'mysql+mysqldb://root:my_password@localhost/database_name'
engine = sqlalchemy.create_engine(con_str) #because I am using mysql
df = pandas.read_sql('SELECT * from PRODUCT', con=engine)
df_product_id = df['product_id']
product_id_str = (str(list(df_product_id.values))).strip('[]')
delete_str = 'DELETE FROM XML_FEED WHERE feed_id IN ({0})'.format(product_id_str)
cur = con.cursor()
cur.execute(delete_str)
con.commit()
df.to_sql('XML_FEED', if_exists='append', con=engine)# you can use flavor='mysql' if you do not want to create sqlalchemy engine but it is depreciated

rawDescription: REPLACE rows in mysql database table with pandas DataFrame


code:
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.core import urlresolvers

class MyModelAdmin(admin.ModelAdmin):

    readonly_fields = ['user_link']

    def user_link(self, obj):
        change_url = urlresolvers.reverse('admin:auth_user_change', args=(obj.user.id,))
        return mark_safe('%s' % (change_url, obj.user.email))
    user_link.short_description = 'User'

rawDescription: Making Django Readonly ForeignKey Field in Admin Render as a Link


code:
method= sys.argv[1]
getattr(script1, method)()

rawDescription: Python: call a method with the name stored in a variable


code:
users_to_exclude = Noticesetting.objects.filter(send=False, notice_type__label='announcement').values('user')
emails = Emailaddress.objects.exclude(user__in=users_to_exclude)

rawDescription: Convert SQL query to Django friendly format for application


rawDescription: Add a 0 or 1 based on a value in a certain column


code:
import os
os.symlink('file.ext', '/path/to/some/directory/symlink')

rawDescription: Creating a relative symlink in python without using os.chdir()


code:
import re
text = "versions/4.5.0.10a/"
re.search('\d+\.\d+\.\d+\.\d+[a-z]', text).group()
Output: '4.5.0.10a'

rawDescription: parsing a path based on regex - Python

description: Parsing a path based on regex - Python


code:
def replace(node, newNode):
    if node.value == 1:
        raise ValueError("can't replace the current node this way")

    for index, child in enumerate(node.children):
        if child.data == 1:
            node.children[index] = newNode
            return True

        if replace(child, newNode):
            return True

    return False

rawDescription: How to replace a subtree in python

description: Replace a subtree in python


code:
import urllib
urllib.urlencode({'a': 1, 'b': 2})

rawDescription: Django: Convert a POST request parameters to query string


code:
def factorial(n): # only works for positive numbers
    if n == 1: return 1 # base case
    return n * factorial(n-1) # recursive case; only executed if the above is not
                              # executed because 'return' stops a function

rawDescription: How does the return function work in recursion?


code:
from django.utils.html import strip_tags
rows = Post.objects.filter(Q(name__icontains=keyword) | Q(description__icontain=keyword))
if rows:
    for j,i in enumerate(rows):
        if keyword not in strip_tags(i.name) and keyword not in strip_tags(i.description):
            del rows[j]
return render(request,'posts.html',{'rows':rows})

rawDescription: Search a value in HTML content with Django ORM that don't consider HTML tags


rawDescription: Python: Remove division decimal

description: Python: Remove division decimal


code:
from matplotlib.pyplot import imshow, colorbar

data = [[0.0,0.2],[0.5,1.0]]
imshow(data)

cb = colorbar()
cb.ax.plot([0,1],[cb.norm(0.3),cb.norm(0.3)],'r')
cb.ax.plot([0,1],[cb.norm(0.8),cb.norm(0.8)],'r')

rawDescription: how can I plot on colorbar python

description: Plot on colorbar python


code:
fileInfos = list(DirectoryInfo(path).GetFiles())
fileInfos.sort(key=lambda f: f.CreationTime, reverse=True)

rawDescription: how to sort list of FileInfo in IronPython

description: Sort list of FileInfo in IronPython


rawDescription: Cycling through webbrowser tabs with autokey


rawDescription: Unpacking a 1-tuple in a list of length 1


code:
for key in expected_keys:
    foo.__dict__[key] = d.pop(key)
foo.additional_attributes(**d)

rawDescription: Pythonic dictionary traversal

description: Pythonic dictionary traversal


code:
import subprocess
import shlex
import sys

def parse_fdisk(fdisk_output):
    result = {}
    for line in fdisk_output.split("\n"):
        if not line.startswith("/"): continue
        parts = line.split()

        inf = {}
        if parts[1] == "*":
            inf['bootable'] = True
            del parts[1]

        else:
            inf['bootable'] = False

        inf['start'] = int(parts[1])
        inf['end'] = int(parts[2])
        inf['blocks'] = int(parts[3].rstrip("+"))
        inf['partition_id'] = int(parts[4], 16)
        inf['partition_id_string'] = " ".join(parts[5:])

        result[parts[0]] = inf
    return result

def main():
    proc = subprocess.Popen(shlex.split("fdisk -l"),
                            stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    fdisk_output, fdisk_error = proc.communicate()
    fdisk_output = fdisk_output.decode(sys.stdout.encoding)
    for disk, info in parse_fdisk(fdisk_output).items():
        print(disk, " ".join(["%s=%r" % i for i in info.items()]))

main()

rawDescription: view partitions in Linux using python3.x

description: View partitions in Linux using python3.x


code:
import subprocess
subprocess.call(['notepad', '/p', filename])

rawDescription: How to print a file to paper in Python 3 on windows XP/7?

description: Print a file to paper in Python 3 on windows XP/7


code:
for company in companies:
    company_html = requests.get(company['href'])
    company_bs = BeautifulSoup(company_html)
    company_page_links = company_bs('a')
    for link in company_page_links:
        if link['href'].startswith('mailto:'):
            #You found the e-mail address!
            break#Exits the loop, as you already found the address

rawDescription: How can I iterate over multiple internal links on a site to output all email addresses using BeautifulSoup?

description: Iterate over multiple internal links on a site to output all email addresses using BeautifulSoup


code:
try:
    while True:
        #Get the block hit events
        blockHits = mc.events.pollBlockHits()
        # if a block has been hit
        if blockHits:
            # for each block that has been hit
            for blockHit in blockHits:
                #Create and run the exploding block class in its own thread
                # pass the position of the block, fuse time in seconds and blast radius
                # threads are used so multiple exploding blocks can be created
                explodingBlock = ExplodingBlock(blockHit.pos, 3, 3)
                explodingBlock.daemon
                explodingBlock.start()
        time.sleep(0.1)
except KeyboardInterrupt:
    print("stopped")

rawDescription: If Statement Has Invalid Syntax

description: If Statement Has Invalid Syntax


code:
#!/usr/bin/env python
from __future__ import print_function
import os
from subprocess import Popen, PIPE, CalledProcessError

answers = {
    'Root path': 'doc',
    'source and build': 'y',
    'autodoc': 'y',
    'Project name': '<Project name>',
    'Author name': '<author>',
    'Project version': '<version>',
}

def iter_chunks(pipe, terminator_char):
    """Yield chunks from *pipe* that end with *terminator_char*."""
    buf = []
    for char in iter(lambda: pipe.read(1), ''):
        buf.append(char)
        if char == terminator_char:
            yield ''.join(buf)
            del buf[:]

cmd = ['sphinx-quickstart']
p = Popen(cmd, stdin=PIPE, stdout=PIPE, universal_newlines=True, bufsize=0,
          env=dict(PYTHONUNBUFFERED='1', **os.environ))
with p.stdin, p.stdout: # close pipes at the end
    for chunk in iter_chunks(p.stdout, ':'):
        line = chunk.rpartition('\n')[-1] # get last line
        if line.lstrip().startswith('>') and line.endswith(':'): # found prompt
            answer = next((a for q, a in answers.items() if q in line), '')
            print(answer, file=p.stdin) #NOTE: short write is possible
if p.wait() != 0: # raise on non-zero exit status
    raise CalledProcessError(p.returncode, cmd)

rawDescription: I can't see the output of a subprocess in Python


code:
f = open('data', 'r')
f.read(2)
f.tell() # prints 2
f.read(3)
f.tell() # prints 5

rawDescription: Absolute index of the read() function

description: Absolute index of the read() function


code:
import math
IJ.run("Set Measurements...", "area centroid perimeter shape feret's area_fraction     redirect=None decimal=6")
IJ.run("Analyze Particles...")
rt = ResultsTable.getResultsTable()
row=0
for roi in RoiManager.getInstance().getRoisAsArray():
  a = rt.getValue("Feret", row)
  b = rt.getValue("MinFeret", row)
  nu= 1
  L = 1
  p = 1
  s = (math.pi/4) * (1/(nu*L)) * math.pow(a, 3) * math.pow(b, 3) / (math.pow(a, 2) + math.pow(a, 2))*p
  rt.setValue("S", row, s)
  row = row + 1
rt.show("Results")

rawDescription: ImageJ/Fiji: Iteration through and printing in results table


code: recent_menu.add_command(label=file_display, command=lambda i=i: processFile(i))

rawDescription: Trying to create a dynamic menu with a common command function


code:
from twisted.internet import protocol, reactor

class Echo(protocol.Protocol):
    def dataReceived(self, data):
        self.transport.write(data)

class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo()

class Echo2(protocol.Protocol):
    def dataReceived(self, data):
        self.transport.write(data+" From 2")

class EchoFactory2(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo2()

reactor.listenTCP(1234, EchoFactory())

reactor.listenTCP(1235, EchoFactory2())
reactor.run()

rawDescription: How to "merge" two Python twisted applications?

description: "merge" two Python twisted applications


code:
words = {"this": 0, "that": 0}
for w in text.split():
  if w in words:
    words[w] += 1

rawDescription: Python: best/efficient way of finding a list of words in a text?


code:
import scipy.stats as stats

import matplotlib.pyplot as plt
import numpy as np
import numpy.random as rnd

#plot the original distribution
xrng=np.arange(-10,10,.1)
yrng=stats.logistic.pdf(xrng)
plt.plot(xrng,yrng)

#plot the truncated distribution
nrm=stats.logistic.cdf(1)-stats.logistic.cdf(0)
xrng=np.arange(0,1,.01)
yrng=stats.logistic.pdf(xrng)/nrm
plt.plot(xrng,yrng)

#sample using the inverse cdf
yr=rnd.rand(100000)*(nrm)+stats.logistic.cdf(0)
xr=stats.logistic.ppf(yr)
plt.hist(xr,normed=True)

plt.show()

rawDescription: Truncating SciPy random distributions

description: Truncating SciPy random distributions


code: request = 'GET {path} HTTP 1.1\r\nHost: {host}\r\nConnection: Close\r\n\r\n'.format(path=path, host=host)

rawDescription: Python - Building a HTTP request string variable


code: import tkFileDialog

rawDescription: Using Tkinter on OSX Mountain Lion 8.2

description: Using Tkinter on OSX Mountain Lion 8.2


code:
from glob import iglob
import shutil

for path in iglob('.../run*'):
    shutil.rmtree(path)

rawDescription: How to remove a lot of folders at once using Python?

description: Remove a lot of folders at once using Python


code:
mydic = [{'name':'a', 'loc':{'locname':'z'}, 'id':{'value':'1'}},{'name':'b', 'loc':{'locname':'o'}, 'id':{'value':'2'}}]
sorted(mydic,key = lambda x:x['loc']['locname'])

rawDescription: How to sort a list of dictionaries of dictionaries by value

description: Sort a list of dictionaries of dictionaries by value


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

def add_patch(ax, **kwargs):
    if 'rasterized' in kwargs and kwargs['rasterized']:
        ax.set_rasterization_zorder(0)
    ax.fill_between(np.arange(1, 10), 1, 2, zorder=-1, **kwargs)
    ax.set_xlim(0, 10)
    ax.set_ylim(0, 3)
    if 'alpha' in kwargs and kwargs['alpha'] < 1:
        txt = 'This patch is transparent!'
    else:
        txt = 'This patch is not transparent!'
    ax.text(5, 1.5, txt, ha='center', va='center', fontsize=25, zorder=-2,
            rasterized=True)

fig, axes = plt.subplots(nrows=4, sharex=True)
add_patch(axes[0], alpha=0.2, rasterized=False)
add_patch(axes[1], alpha=0.2, rasterized=True)
add_patch(axes[2], rasterized=False)
add_patch(axes[3], rasterized=True)

plt.tight_layout()
plt.savefig('rasterized_transparency.eps')

rawDescription: How to better rasterize a plot without blurring the labels in matplotlib?

description: Better rasterize a plot without blurring the labels in matplotlib


code:
import gmpy
x = gmpy.mpf(10**1000)
x.digits(10, 0, -1, 1)

rawDescription: Print extremely large long in scientific notation in python


code:
profile.setPreference("browser.download.dir", "c:/yourDownloadDir");
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/csv, text/csv");

rawDescription: Disable firefox save as dialog-selenium

description: Disable firefox save as dialog-selenium


code:
for i,row in enumerate(arr1):
    if row[0]=='1' and row[1]=='4320':
        val = '1'
    else:
        val = '0'
    arr1[i].append(val)

rawDescription: Adding columns to list in python

description: Adding columns to list in python


code:
class Post(models.Model):
    author = models.CharField(max_length=255)
    text = models.TextField()

class Tag(models.Model):
    name = models.CharField(max_length=100)
    attached_to = models.ForeignKey(Post)

rawDescription: Arbitrary Amount of Fields for Django Model


code:
def fib(r,a,b):
    return [a] + fib(r-1,b,a+b) if r>0 else []

rawDescription: Fibonacci with recursion method

description: Fibonacci with recursion method


code:
from collections import Counter

# for testing
from random import choice, randrange
from string import ascii_uppercase
big_word = "".join(choice(ascii_uppercase) for i in range(10000))
words = [big_word[randrange(len(big_word)):][:randrange(1, 10)] for i in range(100000)] # words of up to 9 letters; all are substrings of big_word

# now the real code
def insertions(words):
    for word in words:
        for i in range(1, len(word) - 1):
            ins = word[:i]
            rest = word[i:]
            for j in range(1, len(rest)):
                if rest[:j] in words:
                    yield ins
        for i in range(1, len(word) - 1):
            rest = word[:i]
            ins = word[i:]
            for j in range(len(rest) - 1):
                if rest[j:] in words:
                    yield ins

transforms = Counter(insertions(set(words)))

rawDescription: searching substring across a large list

description: Searching substring across a large list


code:
def send(self, data):
    """Send `data' to the server."""
    if self.sock is None:
        if self.auto_open:
            self.connect()
        else:
            raise NotConnected()
    ...

rawDescription: close() func of http.client.HTTPConnection doesn't work?

description: Close() func of http.client.HTTPConnection doesn't work


code:
from glob import glob
glob('/home/*.txt')
[glob(i) for i in ['/home/*.txt', '/home/*.jpeg']]

rawDescription: Find files of the same type in the same directory with Python


code:
import urllib2
import re

htmlfile = urllib2.urlopen('http://www.kino.de/rss/neu-im-kino/')
htmltext = htmlfile.read()
regex = '<link>(.+?)</link>'
pattern = re.compile(regex)
links = re.findall(pattern,htmltext)

print( ' '.join(links) ) # or print( '\n'.join(links) )

for link in links:
    htmlfile_2 = urllib2.urlopen(link)
    htmltext_2 = htmlfile_2.read()
    regex_2 = '<meta itemprop="contentURL" content="(.+?)" />'
    pattern_2 = re.compile(regex_2)
    links_2 = re.findall(pattern_2,htmltext_2)

    print( ' '.join(links_2) ) # or print( '\n'.join(links_2) )

rawDescription: Python open a link into links

description: Python open a link into links


code:
request = urllib2.Request(query)
request.add_header('Accept-encoding', 'gzip')
response = urllib2.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
    buf = StringIO( response.read())
    f = gzip.GzipFile(fileobj=buf)
    data = f.read()
    result = json.loads(data)

rawDescription: Garbled text returned while opening a URL in Python 2.7


code:
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
SECRET_KEY = get_random_string(50, chars)

rawDescription: Django logs out when dev server restarts


code:
#graph[i] contains all possible neighbors of the i-th person
def held_karp(graph):
    n = len(graph)#number of persons

    #remember the set of already seated persons (as bitmask) and the last person in the line
    #thus a configuration consists from the set of seated persons and the last person in the line
    #start with every possible person:
    possible=set([(2**i, i) for i in xrange(n)])

    #remember the predecessor configuration for every possible configuration:
    preds=dict([((2**i, i), (0,-1)) for i in xrange(n)])

    #there are maximal n persons in the line - every iterations adds a person
    for _ in xrange(n-1):
        next_possible=set()
        #iterate through all possible configurations
        for seated, last in possible:
            for neighbor in graph[last]:
                bit_mask=2**neighbor
                if (bit_mask&seated)==0: #this possible neighbor is not yet seated!
                    next_config=(seated|bit_mask, neighbor)#add neighbor to the bit mask of seated
                    next_possible.add(next_config)
                    preds[next_config]=(seated, last)
        possible=next_possible

    #now reconstruct the line
    if not possible:
      return []#it is not possible for all to be seated

    line=[]
    config=possible.pop() #any configuration in possible has n person seated and is good enough!
    while config[1]!=-1:
        line.insert(0, config[1])
        config=preds[config]#go a step back

    return line

rawDescription: Algorithm to find "good" neighbours - graph coloring?


code:
import inspect
import numpy as np
import scipy as sp
import scipy.sparse as sparse
import scipy.sparse.linalg as splinalg
import random

def report(xk):
    frame = inspect.currentframe().f_back
    print(frame.f_locals['resid'])

N = 200
A = sparse.lil_matrix( (N, N) )
for _ in xrange(N):
    A[random.randint(0, N-1), random.randint(0, N-1)] = random.randint(1, 100)

b = np.random.randint(0, N-1, size = N)
x, info = splinalg.cg(A, b, callback = report)

rawDescription: Print current residual from callback in scipy.sparse.linalg.cg


code:
import requests
import gzip
from StringIO import StringIO

r = requests.get('http://example.com/sitemap.xml.gz')
sitemap = gzip.GzipFile(fileobj=StringIO(r.content)).read()

rawDescription: How to parse compressed sitemap using python without downloading it to disk?

description: Parse compressed sitemap using python without downloading it to disk


code:
class FakeGlobalSectionHead(object):
    def __init__(self, fp):
        self.fp = fp
        self.sechead = '[global]\n'
    def readline(self):
        if self.sechead:
            try: return self.sechead
            finally: self.sechead = None
        else: return self.fp.readline()
cp = ConfigParser()
cp.readfp(FakeGlobalSectionHead(open('rsyncd.conf')))
print(cp.items('global'))

rawDescription: ConfigParser.MissingSectionHeaderError when parsing rsyncd config file with global options


code:
def every_other_player(self, func, *args, **kwargs):
    i = self.self_index()
    j = i + 1
    while j % len(players) != i:
        func(players[j % len(players)], *args, **kwargs)
        j += 1

rawDescription: Can these functions that call functions be combined in Python?


code:
def message():
    num = str(random.randint(137849013724,934234850490))
    print(num)
    if num[3] == "5" and num[6] == "7":
        print("access granted")
    else:
        threading.Timer(0.125, message).start()  # <== moved

rawDescription: Stopping a Timer in python

description: Stopping a Timer in python


code: s.split('mango', 1)[1]

rawDescription: Splitting on first occurrence

description: Splitting on first occurrence


code:
class MyRand(object):
    def __init__(self):
        self.last = None

    def __call__(self):
        r = random.randint(0, 9)
        while r == self.last:
            r = random.randint(0, 9)
        self.last = r
        return r

randint = MyRand()
x = randint()
y = randint()
...

rawDescription: How often does random.randint generate the same number?


rawDescription: Timedelta on Django DateTimeField reverts changes after save


code:
index = []
def add_to_index(index,keyword,url):
    for entry in index:
        if entry[0] == keyword:
            # We have found a matching keyword, so add the url to list of urls and exit the function
            entry[1].append(url)
            return
    # We didn't find a matching keyword so add a new keyword, url list to the collection
    index.append([keyword,[url]])

rawDescription: Can't work out why function behaves the way it does?


code:
from PyQt4 import QtGui, QtCore
from functools import partial

class Window(QtGui.QWidget):
    def __init__(self, mapping):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.buttons = []
        for key, value in mapping.items():
            self.buttons.append(QtGui.QPushButton(key, self))
            self.buttons[-1].clicked.connect(partial(handleButton, data=value))
            layout.addWidget(self.buttons[-1])

def handleButton(self, data="\n"):
    print (data)

if __name__ == '__main__':
    import sys

    buttons = {'foo': 'bar', 'something': 'other'}
    app = QtGui.QApplication(sys.argv)
    window = Window(buttons)
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt4: Create many buttons from dict dynamically


code:
cmd = [
    'mysql',
    '--database=%s' % self._database,
    '--password=%s' % self._password,
    '--execute=%s' % query
]

(...)

p = subprocess.Popen(cmd, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = p.communicate()
errcode = p.returncode

rawDescription: How to prevent subprocess to add spaces between some parameters?

description: Prevent subprocess to add spaces between some parameters


code:
image = np.zeros((max_x, max_y))
image[coordinates] = 1

rawDescription: How to convert python list of points to numpy image array?

description: Convert python list of points to numpy image array


code:
def merge(x, y):
    return range(min(x.start, y.start), max(x.stop, y.stop))

def overlap(x, y):
    return x.start in y or y.start in x

groups = {a: {a}, b: {b}, c: {c}, d: {d}, e: {e}}

while True:
    for key, value in groups.items():
        for otherkey, othervalue in groups.items():
            if key is otherkey:
                continue
            if overlap(key, otherkey):
                del groups[otherkey]
                del groups[key]
                groups[merge(key, otherkey)] = value | othervalue
                break
        else:
            continue
        break
    else:
        break

rawDescription: Group overlapping arrays

description: Group overlapping arrays


code:
from pydub import AudioSegment

# wave and raw don’t use ffmpeg
wav_audio = AudioSegment.from_file("audio.wav", format="wav")
raw_audio = AudioSegment.from_file("audio.wav", format="raw",
                                   frame_rate=44100, channels=2, sample_width=2)

wav_audio.export("audio.mp3", format="mp3")
raw_audio.export("audio1.mp3", format="mp3")

rawDescription: Convert any audio to mp3 format using python


code:
import pygame
import sys
from multiprocessing import Process, Pipe

class Grid:
    colors = {"blue":(0, 0, 255), "red":(255, 0, 0), "green":(0, 255, 0), "black":(0, 0, 0), "white":(255, 255, 255)}

    def __init__(self, width, height, cellSize, borderWidth=1):
        self.cellSize = cellSize
        self.borderWidth = borderWidth
        self.width = width * (cellSize + borderWidth)
        self.height = height * (cellSize + borderWidth)

        #pygame.draw.rect(self.screen, todo[1], (todo[2], todo[3], todo[4], todo[5]), 0)
        self.parent_conn, self.child_conn = Pipe()
        self.p = Process(target=self.mainLoop, args=(self.child_conn, self.width, self.height,))
        self.p.start()

    def close():
        self.p.join()

    def clearGrid(self):
        pass

    def highlightBox(self, x, y, color):
        xx = x * (self.cellSize + self.borderWidth)
        yy = y * (self.cellSize + self.borderWidth)
        self.parent_conn.send(["box", color, xx, yy, self.cellSize, self.cellSize])

    def mainLoop(self, conn, width, height):
        #make window
        screen = pygame.display.set_mode((self.width, self.height))

        running = True
        while running:
            # is there data to read
            if conn.poll():
                #read all data
                todo = conn.recv()
                print("Recived " + str(todo))

            #do the drawing
            if todo[0] == "box":
                print("drawing box")
                pygame.draw.rect(screen, todo[1], (todo[2], todo[3], todo[4], todo[5]), 0) #color, x, y, width, height
                todo = ["none"]

            #draw to screen
            pygame.display.flip()

            #get events
            event = pygame.event.poll()
            if event.type == pygame.QUIT:
                running = False

rawDescription: pygame class structure

description: Pygame class structure


rawDescription: Django: Calling save() on FileField using field name as string


code:
#!/usr/bin/python3

# Iterate over every line in file1.
#   Iterate over every line in file2.
#     If lines intersect, print combined line.

with open('file1') as file1:
    for line1 in file1:
        u1,h1,s1 = line1.rstrip().split(':')

        with open('file2') as file2:
            for line2 in file2:
                h2,s2,p2 = line2.rstrip().split(':')

                if h1 == h2 and s1 == s2:
                    print(':'.join((u1,h1,s2,p2)))

rawDescription: Connecting similar lines from two filles


code:
exts = tuple(extensions)
[f for f in filenames if f.endswith(exts)]

rawDescription: Python : Check for filename ending with an extension present in a list of extensions


code:
class RegularAvailDateForm(ModelForm):
    class Meta:
        model = AvailabilitySchedule
        fields = ('active','dow', 'hour_start', 'hour_end')
        widgets = {
            'active' :  CheckboxInput(),
            'dow': HiddenInput(),
            'hour_start': NumberInput(attrs={'min': '0', 'max': '23', 'step': '1'}),
            'hour_end': NumberInput(attrs={'min': '1', 'max': '24', 'step': '1'}),
        }

FormSet = modelformset_factory(AvailabilitySchedule, RegularAvailDateForm)

rawDescription: Django 1.4 Model formsets specify widget and change label


code:
import numpy as np
from sklearn.cross_validation import KFold, cross_val_score
from sklearn.linear_model import LassoCV

X = np.random.randn(20, 10)
y = np.random.randn(len(X))

cv_outer = KFold(len(X), n_folds=5)
lasso = LassoCV(cv=3)  # cv=3 makes a KFold inner splitting with 3 folds

scores = cross_val_score(lasso, X, y, cv=cv_outer)

rawDescription: How does LassoCV in scikit-learn partition data?


code:
x = [[a, b, c], [d, e, f], [g, h, i]]
itertools.product(*x)

rawDescription: Passing list of arguments of varying length


code:
subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)

rawDescription: Running bash commands inside a Python script


code:
def solve(n):
    return n*(n+1)

solve(2)
solve(3)
solve(4)
solve(5)

rawDescription: How to realize this in Python?

description: Realize this in Python


code:
return Projekt.objects.all().extra(
    select={
        "date_reached_state_checked": "SELECT created_at FROM tracking_statechange WHERE tracking_statechange.projekt_id = projekt_projekt.id AND tracking_statechange.state = 20",
        "date_reached_state_construction_ordered": "SELECT created_at FROM tracking_statechange WHERE tracking_statechange.projekt_id = projekt_projekt.id AND tracking_statewechsel.state = 50"
    })

rawDescription: Filter on annotated column in django

description: Filter on annotated column in django


rawDescription: Storing an array of integers with Django


code:
cmds = [
    "lock",
    "read",
    "write",
    "request",
    "log",
    ]

def match_cmd(s):
    matched = [c for c in cmds if c.startswith(s)]
    if matched:
        return matched[0]

rawDescription: fastest way to compare strings in python

description: Fastest way to compare strings in python


code:
# Call getLogger with no args to set up the handler
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.FileHandler('test_log.log', mode='w'))

if __name__ == '__main__':
    # call getLogger again with a name to tag subsequent log statements
    logger = logging.getLogger(__name__)
    logger.info('Importing class')
    t = TestClass()
    t.make_call()
    t.make_another_call()
    logger.info('End')

rawDescription: Python. Enable logging for a class instance, imported from separated module


code:
lst = ['Frank', 'Sam', 'Kevin', 'Jack']
dct = {x:{y:0 for y in lst if y != x} for x in lst}
dct
# Just to demonstrate
from pprint import pprint
pprint(dct)

rawDescription: Creating a dictionary with a list of names


code:
#!/usr/bin/python

with open('in.txt', 'r') as f:
      text = f.read()

      text = text.replace("<VirtualHost *:80>\n    ServerName REMOVE\n</VirtualHost>\n\n", '')

      with open('out.txt', 'w') as f:
            f.write(text)

rawDescription: Remove multiple lines in Python

description: Remove multiple lines in Python


code:
#! /usr/bin/env python3
import os
import pickle

# Uncomment one of these imports to enable file compression:
# from bz2 import open
# from gzip import open
# from lzma import open

DATA_FILE = 'results.dat'
KB = 1 << 10
MB = 1 << 20
GB = 1 << 30
TB = 1 << 40

def main():
    """Demonstrate saving data to and loading data from a file."""
    save_data(develop_data())
    analyze_data(load_data())

def develop_data():
    """Create some sample data that can be saved for later processing."""
    return (os.urandom(1 * KB) * (1 * MB // KB) for _ in range(32 * GB // MB))

def save_data(data):
    """Take in all data and save it for retrieval later on."""
    with open(DATA_FILE, 'wb') as file:
        for obj in data:
            pickle.dump(obj, file, pickle.HIGHEST_PROTOCOL)

def load_data():
    """Load each item that was previously written to disk."""
    with open(DATA_FILE, 'rb') as file:
        try:
            while True:
                yield pickle.load(file)
        except EOFError:
            pass

def analyze_data(data):
    """Pretend to do something useful with each object that was loaded."""
    for obj in data:
        print(hash(obj))

if __name__ == '__main__':
    main()

rawDescription: writing python objects to disk without loading into memory?

description: Writing python objects to disk without loading into memory


rawDescription: Get a related profile via request.user in django 1.8+


code:
# Clarified from comments - the program is to act as a filter so that any lines
# which have a pattern 'ZINC' in the second file but do not belong in the first
# should stop the dump until the next matching zinc is found

fileZ = open ('file_with_zinc_only.txt', 'r').readlines()
fileX = open ('file_with_x_info.txt', 'r').readlines()
fileOutput = open ('file_for_output.txt', 'w')

thisLineHasZinc = False
zincMatching = False

for xline in fileX:
    #print "Dealing with", xline
    if len(xline.split('ZINC')) != 1:
        thisLineHasZinc = True
        zincMatching = False
        for zline in fileZ:
            #print "Trying to match",zline
            if zline == xline:
                #print "************MATCH***************"
                zincMatching = True
                fileOutput.write (zline)
                #print "**",xline
                break
    else:
        thisLineHasZinc = False

    # If we are currently under a block where we've found a ZINC previously
    # but not yet reached another ZINC line, write to file
    #print 'thisLineHasZinc',thisLineHasZinc,'zincMatching',zincMatching
    if thisLineHasZinc == False and zincMatching == True:
        fileOutput.write (xline)
        #print "**** "+ xline

fileOutput.close()

rawDescription: Search file for string and copy all lines following until string2


code:
df['sum_num'] = df.sum(axis=1)
df

rawDescription: Python Pandas: How to sum up columns that also include missing values?


rawDescription: Python: Effective replacing of substring


code:
file = ['A', 'A', 'B', 'C', 'A', 'C', 'B']
control_value = ''
for line in file:
    if line == 'A':
        control_value = line
        continue
    if line == 'B' and control_value == 'A':
        print('Do something here')
    control_value = ''

rawDescription: Best way to check next iteration value

description: Check next iteration value


code:
self.sensorTable = Frame(master=self.root)
self.sensorNameColumn = LabelFrame(self.sensorTable, text="Name", padx=5, pady=5)
self.sensorNameColumn.grid(row = 0, column = 0)
self.sensorValueColumn = LabelFrame(self.sensorTable, text="Value", padx=5, pady=5)
self.sensorValueColumn.grid(row = 0, column = 1)

rawDescription: How To Create Frame With Two Columns of Labels using Python and Tkinter?


rawDescription: Frequency of unique values in different columns in pandas


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

class Topic(models.Model):
    user = models.ForeignKey(User)

rawDescription: Django: Foreign Key relation with User Table does not validate


code: manager = relationship(ClaimAccount, backref=backref('claims', order_by=Claims.created.desc()))

rawDescription: Custom collections in SQL Alchemy

description: Custom collections in SQL Alchemy


code:
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle

def genText():
    text = ["Call me Ishmael.",
        "Some years ago- never mind how long precisely- having little or no money in my purse,",
        "and nothing particular to interest me on shore,",
        "I thought I would sail about a little and see the watery part of the world."]
    return text

styles = getSampleStyleSheet()
doc = SimpleDocTemplate("my_doc.pdf", pagesize=A4)
Story=[]
text = genText()
for t in text:
    Story.append(Paragraph(t, styles["Normal"]))
Story.append(Spacer(10, 10))
t = "lorem ipsum " * 100
Story.append(Paragraph(t, styles["Normal"]))
doc.build(Story)

rawDescription: PDF generation in python

description: PDF generation in python


code:
items=input("Students: ")
items.capitalize()
items = items.split()
items.sort()
print('')
for item in items:
    print(item)

rawDescription: How do I get a list to print one word per line?

description: Get a list to print one word per line


code:
import falcon

class StaticResource(object):
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.content_type = 'text/html'
        with open('index.html', 'r') as f:
            resp.body = f.read()

app = falcon.API()
app.add_route('/', StaticResource())

rawDescription: How to serve a static webpage from falcon application?

description: Serve a static webpage from falcon application


code:
for page in data["query"]["pages"].values():
    title = page["title"]
    langlinks = page["langlinks"]
    # do something with langlinks...

rawDescription: Reach a string behind unknown value in JSON


code:
def route_num(cube_size):
    L = [1] * cube_size
    for i in range(cube_size):
        for j in range(i):
            L[j] = L[j]+L[j-1]
        L[i] = 2 * L[i - 1]
    return L[cube_size - 1]

rawDescription: Code to find number of route-combinations in a N by N grid


code:
def review():
    getId = db.games(request.args(0)) or redirect(URL('default', 'index'))
    db.reviews.game_id.default = request.args(0)
    formReview = SQLFORM(db.reviews, fields=['game_id','title','review']).process()
    if formReview.accepted: redirect(URL('index'))
    return dict(formReview=formReview, getId=getId)

rawDescription: Web2Py GET value

description: Web2Py GET value


code:
from Tkinter import *

from threading import Thread
import pyglet

root = Tk()
app = Frame(root)
app.pack(side='bottom')

player = pyglet.media.Player()
music_file = pyglet.media.load('foo.mp3')

def startPlaying():
    player.queue(music_file)
    player.play()
    pyglet.app.run()

def playSound():
    global sound_thread
    sound_thread = Thread(target=startPlaying)
    sound_thread.start()

button1 = Button(app, text="Enter Program", command=playSound)
button1.pack()

root.mainloop()
pyglet.app.exit()

rawDescription: Playing mp3 files using python 2.7 buttons - TKinter


code:
X = IndexedBase("X")
Y = IndexedBase("Y")
beta = IndexedBase("beta")
expr = Sum(Y[i]*exp(Sum(X[i, j]*beta[j], (j, 1, 5))), (i, 1, 20))
pprint(expr)

rawDescription: sum over matrix entries in sympy 1.0 with python 3.5

description: Sum over matrix entries in sympy 1.0 with python 3.5


code:
#!/usr/bin/python3

# myList = [['keith', 'roger', 'david'], [5, 'nobody', 31], ['attack', 'thomas', 4]]
# myDict = {'55': '...', 'roger': '...'}

secondElements = {x[1] for x in myList}

filteredDict = {k:v for k,v in myDict.items() if (k in secondElements)}

print(filteredDict)
# prints: {'roger': '...'}

rawDescription: How do you cross-check a dictionary with a list in Python?

description: Cross-check a dictionary with a list in Python


rawDescription: Find key value of python list for use with other arrays


code:
class mygenerator(object):
    def __init__(self):
        next_value = compute_first_value()
    def __iter__(self):
        return self
    def next(self):
        if next_value == terminating_value:
            raise StopIteration()
        return next_value

rawDescription: How can I run the initialization code for a generator function immediately, rather than at the first call?

description: Run the initialization code for a generator function immediately, rather than at the first call


code:
from suds import WebFault
from suds.client import *
from suds.transport.https import WindowsHttpAuthenticated

user = r'SERVER\user'
password = "yourpassword"
url = "http://sharepointserver/_vti_bin/SiteData.asmx?WSDL"

ntlm = WindowsHttpAuthenticated(username = user, password = password)
client = Client(url, transport=ntlm)

rawDescription: how can i use sharepoint (via soap?) from python?

description: Use sharepoint (via soap?) from python


code:
import numpy as np
from mayavi import mlab

mlab.clf()
x, y, z = np.mgrid[-3:3:50j, -3:3:50j, -3:3:50j]

# Plot a sphere of radius 1
values = x*x + y*y + z*z - np.sqrt(3)
mlab.contour3d(x, y, z, values, contours=[0])
mlab.axes()

# Plot a torus
R = 2
r = 1
values = (R - np.sqrt(x**2 + y**2))**2 + z**2 - r**2
mlab.figure()
mlab.contour3d(x, y, z, values, contours=[0])
mlab.axes()

# Plot a Scherk's second surface
x, y, z = np.mgrid[-4:4:100j, -4:4:100j, -8:8:100j]
values = np.sin(z) - np.sinh(x)*np.sinh(y)
mlab.figure()
mlab.contour3d(x, y, z, values, contours=[0])
mlab.axes()
mlab.show()

rawDescription: Is it possible to plot implicit 3d equation using sympy?


code:
import subprocess
import re
import sys

print('Dry run:')
cmd = 'rsync -az --stats --dry-run ' + sys.argv[1] + ' ' + sys.argv[2]
proc = subprocess.Popen(cmd,
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,)

remainder = proc.communicate()[0]
mn = re.findall(r'Number of files: (\d+)', remainder)
total_files = int(mn[0])
print('Number of files: ' + str(total_files))

print('Real rsync:')
cmd = 'rsync -avz  --progress ' + sys.argv[1] + ' ' + sys.argv[2]
proc = subprocess.Popen(cmd,
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,)

while True:
             output = proc.stdout.readline()
if 'to-check' in output:
             m = re.findall(r'to-check=(\d+)/(\d+)', output)
             progress = (100 * (int(m[0][1]) - int(m[0][0]))) / total_files
             sys.stdout.write('\rDone: ' + str(progress) + '%')
             sys.stdout.flush()
             if int(m[0][0]) == 0:
                      break

print('\rFinished')

rawDescription: How to show the rsync --progress in web browser using DJango?

description: Show the rsync --progress in web browser using DJango


code:
df1 = (df.groupby('CloneID').filter(lambda x: (x.ID.str.startswith("H").any())))

df1.groupby('CloneID').apply(lambda x: x.to_csv('CloneID{}.txt'.format(x.name), index=False))

rawDescription: output multiple files based on multiple column values pandas python

description: Output multiple files based on multiple column values pandas python


code: menu = self.cget("menu")

rawDescription: Getting an existing menu for tkinter Toplevel


code: filtered_list = [obj for obj in list1 if obj.attrib==someValue]

rawDescription: Extract list of objects from another Python list based on attribute


code:
import django.utils.timezone
from pytz import timezone

class TimezoneMiddleware(object):
    def process_request(self, request):
        # Put logic here to choose timezone based on domain.
        if request.META['HTTP_HOST'] == 'hotel1.subdomain.com':
            tz = timezone('US/Eastern')
        else:
            tz = timezone('UTC')

        if tz:
            django.utils.timezone.activate(tz)
        else:
            django.utils.timezone.deactivate()

rawDescription: How to set different Time zones in Django

description: Set different Time zones in Django


code:
decorated_functions = []

def decorate(foo):
    def inner():
        print("Some stuff 1")
        foo()
        print("Some stuff 2")

    decorated_functions.append(inner)
    return inner

@decorate
def hello():
    print("Hello")

## The above is the same as:
# def hello():
#     print("Hello")
# hello = decorate(hello)

print(decorated_functions[0] == hello) # prints True
decorated_functions[0]() # prints "Some stuff 1", "Hello", and "Some stuff 2"
hello() # same as above

rawDescription: How do decorators mark a function?

description: How do decorators mark a function


code:
st = '{{ link.description | default text }}'
re.findall(r'\|\s*(.*?)\s*}',st)
st1  = '{{ link.description | default text }}'
re.findall(r'\|\s*(.*?)\s*}',st1)

rawDescription: Extracing text from the middle of a string


code: subcategories = ct.values_list('subcategory__name', flat=True).distinct()

rawDescription: Get foreign key value for queried object in Django


code:
div_neg = plt.Line2D((0, 1), (0, 0), color='white', linestyle='--', linewidth=2)
div_pos = plt.Line2D((0, 1), (0, 0), color='white', linestyle='-', linewidth=2)
rot_neg = plt.Line2D((0, 1), (0, 0), color='lightgoldenrodyellow', linestyle='--', linewidth=2)
rot_pos = plt.Line2D((0, 1), (0, 0), color='lightgoldenrodyellow', linestyle='-', linewidth=2)

plt.legend([rot_max, div_neg, div_pos, rot_neg, rot_pos],
           ['Rot Max Points', 'Div Neg', 'Div Pos', 'Rot Neg', 'Rot Pos'])

rawDescription: Contour plot legent - Matplotlib

description: Contour plot legent - Matplotlib


code:
with open("/tmp/myfile.html", "w") as my_file:
  my_file.write("
")
  for x in range(5):
    my_file.write("
%d
" % x)
  my_file.write("
")

rawDescription: Python Output to html file

description: Python Output to html file


rawDescription: Increment elements of a subset of elements in a 3d numpy array python


code:
A
B = np.sort(np.array(A).ravel())
B[::-1]

rawDescription: Python numpy convert 2d array in 1d array sorted


code:
from itertools import combinations
list(combinations('ABCD', 2))

rawDescription: Generate arrays that contain every combination of elements from an array


code:
countries = {}

country_list = Country.objects.all()

for c in country_list:
    # check the stories that has the country
    stories = Story.objects.filter(country_set__name__exact=c.name)

    # only if the country have stories
    if stories.count() > 0:
        ## check for initialize list
        if not countries.has_key(c.continent.name):
            countries[c.continent.name] = []

        ## finally we add the country
        countries[c.continent.name].append(c)

rawDescription: Fetching data from related tables

description: Fetching data from related tables


code: "xterm -e msfconsole -x 'sleep 2; use auxiliary/scanner/discovery/arp_sweep; set RHOSTS '\%{0}'; exploit'".format(RHOST)

rawDescription: User input passed as a variable to subprocess.call


code:
import cv2

vidcap = cv2.VideoCapture('d:/video/keep/Le Sang Des Betes.mp4')
vidcap.set(cv2.CAP_PROP_POS_MSEC,20000)      # just cue to 20 sec. position
success,image = vidcap.read()
if success:
    cv2.imwrite("frame20sec.jpg", image)     # save frame as JPEG file
    cv2.imshow("20sec",image)
    cv2.waitKey()

rawDescription: Extracting image from video at a given time using OpenCV


code:
from Tkinter import *

class app:
    def __init__(self, root):
        win1 = Frame(root)
        win1.grid(row=0,column=0)

        self.variable = StringVar(win1)
        self.variable.set(42)
        self.type = OptionMenu(win1, self.variable,
                          "None", "Clear", "Dark", "Heavy",
                          command = self.varMenu)
        self.type.grid(row=1, column=3, sticky="nsew", padx=1, pady=1)

        self.variableunit = StringVar(win1)
        self.variableunit.set('mm')
        self.unit = OptionMenu(win1,
                          self.variableunit, "mm", "colour", "shade")
        self.unit.grid(row=1, column=5, sticky="nsew", padx=1, pady=1)

    def varMenu(self, selection):
        if selection == "Heavy":
            self.variableunit.set("colour")
            self.unit.config(state = DISABLED)
        else:
            self.variableunit.set("mm")
            self.unit.config(state = NORMAL)

root = Tk()
a = app(root)
root.mainloop()

rawDescription: Linking two OptionMenu widgets Tkinter

description: Linking two OptionMenu widgets Tkinter


code:
def __init__(self, out_file='out.csv', tmp_folder=None):
    self.tmp_folder = tmp_folder or join(getcwd(), '__tmp__')

rawDescription: Initialize variable with default value in python


code:
import pymc as pm
import numpy as np

x_data = np.linspace(0,1,100)
y_data = np.linspace(0,1,100)

slope  = pm.Normal('slope',  mu=0, tau=10**-2)
tau    = pm.Uniform('tau', lower=0, upper=20)

@pm.deterministic
def y_gen(x=x_data, slope=slope):
  return slope * x

like = pm.Normal('likelihood', mu=y_gen, tau=tau, observed=True, value=y_data)

model = pm.Model([slope, y_gen, like, tau])
mcmc  = pm.MCMC(model)
mcmc.sample(100000, 5000)

# This returns 10
final_guess = mcmc.trace('slope')[:].mean()

rawDescription: Simplest linear model with PyMC

description: Simplest linear model with PyMC


code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import wx

class Page(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        t = wx.StaticText(self, -1, "THIS IS A PAGE OBJECT", (20,20))

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Notebook Remove Pages Example")

        pannel  = wx.Panel(self)
        vbox    = wx.BoxSizer(wx.VERTICAL)
        hbox    = wx.BoxSizer(wx.HORIZONTAL)

        self.buttonRemove = wx.Button(pannel, id=wx.ID_ANY, label="DELETE", size=(80, 25))
        self.buttonRemove.Bind(wx.EVT_BUTTON, self.onButtonRemove)
        hbox.Add(self.buttonRemove)

        self.buttonInsert = wx.Button(pannel, id=wx.ID_ANY, label="CREATE", size=(80, 25))
        self.buttonInsert.Bind(wx.EVT_BUTTON, self.onButtonInsert)
        hbox.Add(self.buttonInsert)

        vbox.Add(hbox)

        self.Notebook3 = wx.Notebook(pannel)
        vbox.Add(self.Notebook3, 2, flag=wx.EXPAND)

        pannel.SetSizer(vbox)

        self.pageCounter = 0
        self.addPage()

    def addPage(self):
        self.pageCounter += 1
        page      = Page(self.Notebook3)
        pageTitle = "Page: {0}".format(str(self.pageCounter))
        self.Notebook3.AddPage(page, pageTitle)

    def onButtonRemove(self, event):
        self.Notebook3.DeletePage(0)

    def onButtonInsert(self, event):
        self.addPage()

if __name__ == "__main__":
    app = wx.App()
    MainFrame().Show()
    app.MainLoop()

rawDescription: Add Notebook Page in wxpython

description: Add Notebook Page in wxpython


code:
import networkx as nx
G=nx.path_graph(3)
pos=nx.spring_layout(G)
nx.draw(G,pos)
x,y=pos[1]
import matplotlib.pyplot as plt
plt.text(x,y+0.1,s='some text', bbox=dict(facecolor='red', alpha=0.5),horizontalalignment='center')

rawDescription: Networkx in Python - draw node attributes as labels outside the node


code:
from django.db.models import Count
Answer.objects.all().values('question', 'points_achieved').annotate(total=Count('points_achieved')).order_by('total')

rawDescription: How to retrieve a distribution of values for a models field using Django?

description: Retrieve a distribution of values for a models field using Django


code:
from django import template

register = template.Library()

@register.filter
def my_points(idemployee):

    answer_query = answers.objects.select_related(
        'question').filter(empleado=idemployee)

    points_total = 0
    match = 0

    for answer in answer_query:

        if answer.question.golesEquipoA == answer.equipoA and answer.question.golesEquipoB == answer.equipoB:
            points_total += 4
            match += 1
        else:

            if answer.question.golesEquipoA == answer.question.golesEquipoB and answer.equipoA == answer.equipoB:
                points_total += 3
                match += 1

            else:

                if answer.question.golesEquipoA < answer.question.golesEquipoB and answer.equipoA < answer.equipoB:
                    points_total += 3
                    match += 1

        if answer.question.golesEquipoA > answer.question.golesEquipoB and answer.equipoA > answer.equipoB:
            points_total += 3
            match += 1

    args = {}
    args['points'] = points_total
    args['match'] = match

    return args

rawDescription: How to use a function inside a template?

description: Use a function inside a template


code:
from django.core.servers import basehttp

del basehttp._hop_headers['proxy-authenticate']
del basehttp._hop_headers['proxy-authorization']

rawDescription: Allow hop-by-hop headers in Django proxy middleware


code:
def extract_from_zipfile(inzipfile):
    txtfile = ""
    with zipfile.ZipFile(inzipfile, "r") as z:
        z.extractall(txtfile)
        names = z.namelist()    # <---
        if names:               # <--- To prevent IndexError for empty zip file.
            txtfile = names[-1] # <---
    return txtfile

rawDescription: Converting zipfile extracting code from ruby to python


code:
import csv
sList = ['a cat', 'great wall', 'mediocre wall']
vals = []
with open('data.csv', 'r') as f:
    r = csv.reader(f)
    for w in sList:
        val = 0
        f.seek(0)  #<-- set the iterator to beginning of the input file
        for row in r:
            print(row)
            if row[0] in w:
                val += 1
        vals.append(val)

rawDescription: Can only iterate once through csv reader


code: [([int(item1 == item2) for item2 in list2], [n for n, item2 in enumerate(list2) if item1 == item2]) for item1 in list1]

rawDescription: In Python, how to compare two lists and get all indices of matches?


code:
import tkinter as Tk
import tkinter.messagebox

def show_pass_user(password, user):
    # show what we got
    tkinter.messagebox.showinfo("Data received", "Hey just got your username \"" + user + "\"" +
                                " and password \"" + password + "\"")
    # run your sql here

def main():
    root = Tk.Tk()

    entry_user = Tk.Entry(root)
    entry_user.insert(0, "Username")

    entry_pass = Tk.Entry(root)
    entry_pass.insert(0, "Password")

    # use a lambda to get Username and Password when button is pressed
    pressme = Tk.Button(root, text="Press Me", command=lambda:
        show_pass_user(entry_pass.get(), entry_user.get()))

    entry_user.grid()
    entry_pass.grid()
    pressme.grid()
    root.mainloop()

if __name__ == "__main__":
    main()

rawDescription: After the login Button is pressed, how to obtain the value of Tkinter entry and pass it to the SQL query?


code:
class TestMyClass(unittest.TestCase):
    def test_should_raise(self):
        x = myClass()
        def assign_bad_name():
            x.name = "7"
        self.assertRaises(ValueError, assign_bad_name)

rawDescription: AssertRaises non-callable

description: AssertRaises non-callable


code:
def foo():
    return_list = []
    for i in range(0, len(lstInput) - intCount + 1):
        if intCount == 1:
            return_list.append([lstInput[i]])
        else:
            current = lstInput[i]
            remainder = lstInput[i+1:]
            for rest in yieldLotto(remainder, intCount - 1):
                return_list.append([current] + rest)
    return return_list

rawDescription: Alternative to Yield in Python

description: Alternative to Yield in Python


code: [t for j in [map(int,i.strip('[]').split()) for i in arr] for t in j]

rawDescription: Array of str objects into a single int array in python


code:
import os
from google.appengine.api import app_identity

app_id = app_identity.get_application_id()

if os.environ.get('SERVER_SOFTWARE', 'dev').lower().startswith('dev'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'local settings'
elif app_id == MY_DEV_ID:
    os.environ['DJANGO_SETTINGS_MODULE'] = 'dev settings'
elif app_id == MY_STAGING_ID:
    os.environ['DJANGO_SETTINGS_MODULE'] = 'staging settings'
elif app_id == MY_PROD_ID:
    os.environ['DJANGO_SETTINGS_MODULE'] = 'prod settings'
else:
    raise ValueError("Unknown app id %" % app_id)

rawDescription: Multiple settings with Django and AppEngine