code:
# Example from Bokeh 0.11.1

from bokeh.plotting import show, output_file
from bokeh.models import CustomJS, Slider, VBox

s1 = Slider(start=1, end=10, value=1, step=1)
s2 = Slider(start=0, end=1, value=0, step=1)

s1.callback = CustomJS(args=dict(s1=s1, s2=s2), code="""
    s2.set('end', s1.get('value'));
""")

output_file("foo.html")

show(VBox(s1,s2))

rawDescription: Dependent Sliders with Bokeh, how to write the callbacks


code:
# Success
def is_element_present(self, id_type, id_locator):
    driver = self.driver
    element_found = True
    driver.implicitly_wait(1)
    try:
        element = WebDriverWait(driver, 0).until(
            EC.presence_of_element_located((id_type, id_locator))
        )
    except:
        element_found = False
    driver.implicitly_wait(30)
    return element_found

rawDescription: How to test for absence of an element without waiting for a 30 second timeout

description: Test for absence of an element without waiting for a 30 second timeout


code:
import Tkinter as tk

root = tk.Tk()

def myfunction(*args):
    x = var.get()
    y = stringvar1.get()
    z = stringvar2.get()
    if x and y and z:
        button.config(state='normal')
    else:
        button.config(state='disabled')

stringvar1 = tk.StringVar(root)
stringvar2 = tk.StringVar(root)
var = tk.StringVar(root)

stringvar1.trace("w", myfunction)
stringvar2.trace("w", myfunction)
var.trace("w", myfunction)

entry1 = tk.Entry(root, width=15, textvariable=stringvar1)
entry1.grid(row=1,column=1)
entry2 = tk.Entry(root, width=15, textvariable=stringvar2)
entry2.grid(row=1,column=2)

choices = ('a','b','c')
option = tk.OptionMenu(root, var, *choices)
option.grid(row=1,column=3)

button = tk.Button(root,text="submit")
button.grid(row=1, column=4)

root.mainloop()

rawDescription: Python tkinter disable the button until all the fields are filled


code:
for word_index, letter in enumerate(letter_list):
    if letter == user_input:
        correct_letters[word_index] = user_input

rawDescription: Search Python list and return 2 or more of the same character


code:
all_valid = pd.concat([all_combinations, valid])
all_valid[~(all_valid.duplicated() | all_valid.duplicated(take_last=True))]

rawDescription: Dropping rows in dataframe if found in another one


code:
contests = Contest.objects.annotate(
    complete=Case(
        When(entries__user=user, then=Value(True)),
        default=Value(False),
        output_field=BooleanField(),
    )
).order_by('id', '-complete').distinct('id')

rawDescription: Django: annote through several multi-valued relationships


code:
lst = ['tag1', 'tag2', 'tag3 tag3']
', '.join(lst)

rawDescription: How to remove characters from Python list?

description: Remove characters from Python list


code:
file_name = 'my_file'
im.save( file_name + '.png' )

rawDescription: Using a variable as a Save file name ~ im.save(type, '.png')


code:
import urllib2
import json

url = 'http://url.com?u=user&p=pass'
data = json.dumps({'config':'configData'}) # your JSON File goes in here, as argument to dumps.
cont_len = len(data)
req = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Content-Length': cont_len})
f = urllib2.urlopen(req)
response = f.read()
f.close()

rawDescription: how to post data and binary data using urllib2 in python

description: Post data and binary data using urllib2 in python


code:
from collections import defaultdict
def on_missing():
    print("missing key!")
    return 'empty!'

T = defaultdict(on_missing)
T[0, 0] = True     # Store 'True' for key (0, 0) in T
T[0, 0]            # Retrieve the stored value
T[1, 2]            # (1, 2) does not exist, so call on_missing()
T[1, 2] = True     # Now store a value for (1, 2)
T[1, 2]            # We can see 'True' is stored.

rawDescription: What does it mean when an if statement has something like this in it if T[x,y]: and help explaining dynamic table code


code:
n=2  # or 5, or 10
output = [ ''.join(input[i:i+n]) for i in range(0, len(input), n)]

rawDescription: concatenating multiple items in list

description: Concatenating multiple items in list


code:
def step_log(message, *args, **kwargs):
  logging.info("Step %d:" % step_log.counter + message, *args, **kwargs)
  step_log.counter += 1
step_log.counter = 1

rawDescription: How to use an auto-incrementing integer in Python logger?

description: Use an auto-incrementing integer in Python logger


code:
browser = webdriver.Firefox()
browser.get('https://cdr.ffiec.gov/public/PWS/DownloadBulkData.aspx')

list1 = Select(browser.find_element_by_id("ListBox1"))
list1.select_by_visible_text("Call Reports -- Single Period")

date_field = Select(browser.find_element_by_id("DatesDropDownList"))
date_field.select_by_visible_text("03/31/2014")

rawDescription: Cannot select options with Python Selenium (javascript?)


code: outputFile = open('testDS', 'wb')

rawDescription: Error in using `struct.pack` for writing data to file


code:
def get_team_of_players(playerlist):
    cond = and_(*[Team.users.contains(p) for p in playerlist])
    q = Team.query.filter(cond)
    return q

p1, p2 = db.session.query(User).get(1), db.session.query(User).get(2)
q = get_team_of_players([p1, p2]).all()

def get_team_of_usernames(usernames):
    cond = and_(*[Team.users.any(User.username == p) for p in usernames])
    q = Team.query.filter(cond)
    return q

p1, p2 = 'user1', 'user2'
q = get_team_of_usernames([p1, p2]).all()

rawDescription: SQLAlchemy generating query in loop with contains


code:
set1 = set((x.id,x.name,...) for x in list1)
difference = [ x for x in list2 if (x.id,x.name,...) not in set1 ]

rawDescription: python: comparing 2 lists of instances

description: Python: comparing 2 lists of instances


code:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import DeferredReflection
from sqlalchemy import create_engine
Base = declarative_base()

class Messages(DeferredReflection, Base):
    __tablename__ = 'messages'

engine = create_engine( ... )
DeferredReflection.prepare(engine)

# make session etc...

rawDescription: How to use reflected tables with DeclarativeMeta interface?

description: Use reflected tables with DeclarativeMeta interface


code:
from collections import defaultdict

rasters = defaultdict(list)

for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
                                                  topdown = True,
                                                  datatype="RasterDataset"):
    for filename in filenames:
        rasters[filename].append(os.path.join(dirpath, filename))

rasters = rasters.values()

rawDescription: How to create a list within a list of duplicate files?

description: Create a list within a list of duplicate files


code:
stream = imagefield.open()
image = Image.open(stream)
stream.close()
# ... and then save image with: image.save(outfile, format, options)

rawDescription: How can I created a PIL Image from an in-memory file?

description: Created a PIL Image from an in-memory file


code: new_dict = {v: k for k,v in old_dict.items()}

rawDescription: Checking for duplicates in a series/dict


rawDescription: Extraction of data from a file if pattern matches in Python


code:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
Base = declarative_base()
Session = sessionmaker()

class EmployeeType(Base):
    __tablename__ = 'employee_type'
    id = Column(Integer(), primary_key=True)
    name = Column(String(20))

class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer(), primary_key=True)
    type_id = Column(Integer(), ForeignKey(EmployeeType.id))
    type = relationship(EmployeeType)

    @property
    def type_name(self):
        if self.type is not None:
            return self.type.name
        return None

    @type_name.setter
    def type_name(self, value):
        if value is None:
            self.type = None
        else:
            session = Session.object_session(self)
            if session is None:
                raise Exception("Can't set Employee type by name until added to session")
            self.type = session.query(EmployeeType).filter_by(name=value).one()

rawDescription: SqlAlchemy relationship to specific columns


code:
import imaplib

sess = imaplib.IMAP4()
sess.login('superuser', 'password')
# Honor the mailbox syntax of your server!
sess.select('INBOX/Luke') # Or something similar.
typ, data = sess.search(None, 'ALL') # All Messages.

subjectlines = []
for num in data[0].split():
    typ, msgdata = sess.fetch(num, '(RFC822.SIZE BODY[HEADER.FIELDS (SUBJECT)])')
    subject = msgdata[0][1].lstrip('Subject: ').strip()
    subjectlines.append(subject)

rawDescription: Integrate postfix mail into my (python)webapp


code:
import matplotlib.pyplot as plt
plt.interactive(False)

rawDescription: Matplotlib: global "switch off" for plotting?


code:
def find_word_vertical(crosswords,word):
    z=[list(i) for i in zip(*crosswords)]
    for rows in z:
        row_index = z.index(rows)
        single_row = ''.join(rows)
        column_index = single_row.find(word)
        if column_index >= 0:
            return([column_index, row_index])

rawDescription: Find word vertically from 2D crosswords or 2D lists


code:
# your data frame
df = pd.DataFrame(data = ["1 teaspoons vanilla extract","2 eggs","3 cups chopped walnuts","4 cups rolled oats","1 (10.75 ounce) can Campbell's Condensed Cream of Chicken with Herbs Soup","6 ounces smoke-flavored almonds, finely chopped","sdfgsfgsf","fsfgsgsfgfg","2 small strawberries"])

# Here you create mapping
mapping = pd.Series(index = ['vanilla extract' , 'walnut','walnuts','oat','oats','egg','eggs','almond','almonds','strawberry','strawberries','cherry','cherries'] ,
          data = ['vanilla extract' , 'walnut','walnut','oat','oat','egg','egg','almond','almond','strawberry','strawberry','cherry','cherry'])
# create a function that checks if the value you're looking for exist in specific phrase or not
def get_match(df):
    match = np.nan
    for key , value in mapping.iterkv():
        if key in df[0]:
            match = value
    return match
# apply this function on each row
df.apply(get_match, axis = 1)

rawDescription: Singular and Plural words matching with Pandas


code:
for number in str(row.get('PhoneNumbers')).split('|'):
  file.write("\t\t\t\t<PHONENUM>"+number+"</PHONENUM>\n")

rawDescription: parsing out a second delimited data structure

description: Parsing out a second delimited data structure


code:
import shlex
shlex.split("--flag1 'this is the argument'")

rawDescription: Parsing Flags in Python

description: Parsing Flags in Python


code:
class RecipeSerializer(serializers.ModelSerializer):
    ingredients = IngredientSerializer(many=True)

    class Meta:
        model = Recipe

    def create(self, validated_data):
        ingredients_data = validated_data.pop('ingredients')
        recipe = Recipe.objects.create(**validated_data)

        for ingredient in ingredients_data:
            ingredient, created = Ingredient.objects.get_or_create(name=ingredient['name'])
            recipe.ingredients.add(ingredient)
        return recipe

rawDescription: Django Rest Framework writable nested serializers


code:
if troll.collidesWith(monsters): # some monsters will need removing
    removals = []
    for mon in monsters: # figure out which
        if mon.collidesWith(GroupSingle(troll)):
            removals.append(mon)
    for mon in removals: # remove them
        mon.removeCharacter()
        screen.remove_character(mon)

rawDescription: Collisions with groups of sprites

description: Collisions with groups of sprites


rawDescription: Running a secondary script in a new terminal


code: driver.find_element_by_xpath('//a[@href="what I\'m looking for"]/following::div[@class="what I need to click"]').click()

rawDescription: xpath navigation - find element with X attribute and select its parent's sibling's child

description: Xpath navigation - find element with X attribute and select its parent's sibling's child


code:
import pandas as pd
df = pd.DataFrame([10, 30, 30, 40, 40, 50], columns=['x'])
df = df[df.groupby('x').x.transform(len) > 1]
df

rawDescription: Remove values that appear only once in a DataFrame column


code:
from collections import namedtuple
import glob
import os

cache_dir = os.path.normpath('Q:\Qoros\Project_Assets\car\PublishedMXS')
filespec  = "*.mxs"

FileData = namedtuple("FileData", ["name", "prefix", "size"])

files = []
for fname in glob.glob(os.path.join(cache_dir, filespec)):
    name = os.path.abspath(fname)
    prefix = fname.split("_")[0]
    size = os.stat(fname).st_size
    files.append(FileData(name, prefix, size))

rawDescription: Suggestions on ways to store file information using python


code:
x = range(20)
k = 5
list(set(x) - set(x[::k]))

rawDescription: Python splitting list/array in kth item and non-kth item


code:
for l in a.copy():
    if "riding" in l:
        a.remove(l)

rawDescription: How to remove a list that contains certain element from a list

description: Remove a list that contains certain element from a list


code:
import multiprocessing

def myFunction(arguments):
    item1, item2 = arguments
    ...

nb_cpus = 2
pool = multiprocessing.Pool(processes=nb_cpus)
results = pool.map(myFunction, zip(list1, list2))

rawDescription: how do I parallelize a simple python def with multiple argument

description: Parallelize a simple python def with multiple argument


rawDescription: Concatenating Multiple DataFrames with Non-Standard Columns


code:
def makeList(self, aNode):
    if aNode is None:
        # Stop recursing here
        return []
    return self.makeList(aNode.lChild) + [aNode.data] + self.makeList(aNode.rChild)

rawDescription: Creating a List from a Binary Search Tree


rawDescription: How do I tell dict() in Python 2 to use unicode instead of byte string?

description: Tell dict() in Python 2 to use unicode instead of byte string


code:
def getText(self, word):
    try:
        counter = 0
        myfile=open("D:\\demo.txt","r");
        for line in myfile:
            counter += line.count(word)
        myfile.close()
        return counter
    except:
        return err

rawDescription: word count in python with Flask

description: Word count in python with Flask


rawDescription: How to cancel QProcess by clicking in QProgressDialog's cancel button?

description: Cancel QProcess by clicking in QProgressDialog's cancel button


code:
import itertools
a=[0,0,1,1,1,1,0,0,1,0,1,1,1,0]

b = []
for item, group in itertools.groupby(a):
    size = len(list(group))
    for i in range(size):
        if item == 0:
            b.append(0)
        else:
            b.append(size)

b
Out[8]: [0, 0, 4, 4, 4, 4, 0, 0, 1, 0, 3, 3, 3, 0]

rawDescription: python consecutive counts of an occurence with length

description: Python consecutive counts of an occurence with length


code: check = cells[1].get_text(strip=True)

rawDescription: Beautifulsoup, unable to compare strings


code:
guess_number = 800
tries_left = 3

while tries_left > 0:
    tries_left -= 1
    guess = int(input('Please enter the correct number in order to win: '))
    if guess == guess_number:
        print('That is correct...')
        break
    else:
        print('Incorrect number, you have ' + str(tries_left if tries_left > 0 else 'no')  + ' more attempts..')

rawDescription: How to add a loop to my python guessing game?

description: Add a loop to my python guessing game


code:
import random
result = []
with open("data.txt") as f:
    for line in f:
        if random.random() < 0.05:
            result.append(line)

rawDescription: Randomly Select Data from A Large Text File


rawDescription: Python - How to use .format() method with two strings?


code: cursor.execute("INSERT INTO Test (column1, column2) VALUES (?, ?)", "It's all right", 45)

rawDescription: Apostrophe (') help when dealing with sql using Python


rawDescription: Is there a way to make the Tkinter text widget read only?


code:
class ChoicesAdmin(admin.ModelAdmin):
    list_display = ['description']

class ProfilesAdmin(admin.ModelAdmin):
    list_display = ['user']
    filter_horizontal = ['planguages']

admin.site.register(UserProfile, ProfilesAdmin)
admin.site.register(Choices, ChoicesAdmin)

rawDescription: Django 2 models with ManyToManyField in admin.py


code:
import os,shutil,re

directory='F:\\Examples\\READ_FILES\\FILES'
ONE_STEP_UP='F:\\Examples\\READ_FILES'

os.chdir(directory)
files=os.listdir(directory)

##############################################################

shutil.copy(files[0],'FLOATING_INPUT_01.txt')
shutil.copy(files[1],'FLOATING_INPUT_02.txt')
shutil.copy(files[2],'FLOATING_INPUT_03.txt')
shutil.copy(files[3],'FLOATING_INPUT_04.txt')
##############################################################

lookup1= "#CONTENTS OF FIRST FILE#"
lookup2= "#END OF FIRST FILE#"

f1=open('FLOATING_INPUT_01.txt','r')
with open("FLOATING_INPUT_01.txt") as myFile1:
    for begin, line in enumerate(myFile1,1):
        if lookup1 in line:
            a1=begin

f1.close()

f2=open('FLOATING_INPUT_01.txt','r')
with open("FLOATING_INPUT_01.txt") as myFile2:
    for end, line in enumerate(myFile2,2):
        if lookup2 in line:
            b1=end

f2.close()

##############################################################

lookup1= "#CONTENTS OF SECOND FILE#"
lookup2= "#END OF SECOND FILE#"

f1=open('FLOATING_INPUT_02.txt','r')
with open("FLOATING_INPUT_02.txt") as myFile:
    for begin, line in enumerate(myFile,1):
        if lookup1 in line:
            a2=begin

f1.close()

f2=open('FLOATING_INPUT_02.txt','r')
with open("FLOATING_INPUT_02.txt") as myFile:
    for end, line in enumerate(myFile,1):
        if lookup2 in line:
            b2=end

f2.close()
##############################################################

lookup1= "#CONTENTS OF THIRD FILE#"
lookup2= "#END OF THIRD FILE#"

f1=open('FLOATING_INPUT_03.txt','r')
with open("FLOATING_INPUT_03.txt") as myFile:
    for begin, line in enumerate(myFile,1):
        if lookup1 in line:
            a3=begin

f1.close()

f2=open('FLOATING_INPUT_03.txt','r')
with open("FLOATING_INPUT_03.txt") as myfile:
    for end, line in enumerate(myfile,1):
        if lookup2 in line:
            b3=end

f2.close()
##############################################################

lookup1= "#CONTENTS OF FOURTH FILE#"
lookup2= "#END OF FOURTH FILE#"

f1=open('FLOATING_INPUT_04.txt','r')
with open("FLOATING_INPUT_04.txt") as myFile:
    for begin, line in enumerate(myFile,1):
        if lookup1 in line:
            a4=begin

f1.close()

f2=open('FLOATING_INPUT_04.txt','r')
with open("FLOATING_INPUT_04.txt") as myFile:
    for end, line in enumerate(myFile,1):
        if lookup2 in line:
            b4=end

f2.close()

##############################################################

f=open('FLOATING_INPUT_01.txt','r')
fout=open('OUT_01.txt','w')

with open("FLOATING_INPUT_01.txt") as myFile:
    Lines=f.readlines()
    for i in range(a1,b1-2):
        fout.write(Lines[i])

f.close()
fout.close()

##############################################################
f=open('FLOATING_INPUT_02.txt','r')
fout=open('OUT_02.txt','w')

with open("FLOATING_INPUT_02.txt") as myFile:
    Lines=f.readlines()
    for i in range(a2,b2-1):
        fout.write(Lines[i])

f.close()
fout.close()

##############################################################
f=open('FLOATING_INPUT_03.txt','r')
fout=open('OUT_03.txt','w')

with open("FLOATING_INPUT_03.txt") as myFile:
    Lines=f.readlines()
    for i in range(a3,b3-1):
        fout.write(Lines[i])

f.close()
fout.close()

##############################################################
f=open('FLOATING_INPUT_04.txt','r')
fout=open('OUT_04.txt','w')

with open("FLOATING_INPUT_04.txt") as myFile:
    Lines=f.readlines()
    for i in range(a4,b4-1):
        fout.write(Lines[i])

f.close()
fout.close()

##############################################################
f=open('OUT_01.txt','r+')
stra1=re.sub(r'FIRST FILE OLD TEXT',"FIRST FILE NEW TEXT",f.read(),re.M)
f.close()

f=open('OUT_02.txt','r+')
stra2=re.sub(r'SECOND FILE OLD TEXT',"SECOND FILE NEW TEXT",f.read(),re.M)
f.close()

f=open('OUT_03.txt','r+')
stra3=re.sub(r'THIRD FILE OLD TEXT',"THIRD FILE NEW TEXT",f.read(),re.M)
f.close()

f=open('OUT_04.txt','r+')
stra4=re.sub(r'FOURTH FILE OLD TEXT',"FOURTH FILE NEW TEXT",f.read(),re.M)
f.close()
################################################################
os.chdir(ONE_STEP_UP)
files=os.listdir(ONE_STEP_UP)
shutil.copy('TEMPLATE.txt','JOINT.txt')
with open('TEMPLATE.txt') as fin, open('JOINT.txt','r+') as fout:
    for line in fin:
        fout.write(line)
        if line == "PASTE FIRST FILE HERE\n":
           fout.write(stra1)
        if line == "PASTE SECOND FILE HERE\n":
           fout.write(stra2)
        if line == "PASTE THIRD FILE HERE\n":
           fout.write(stra3)
        if line == "PASTE FOURTH FILE HERE\n":
           fout.write(stra4)

################################################################
os.chdir(directory)
os.remove('OUT_01.txt')
os.remove('OUT_02.txt')
os.remove('OUT_03.txt')
os.remove('OUT_04.txt')
os.remove('FLOATING_INPUT_01.txt')
os.remove('FLOATING_INPUT_02.txt')
os.remove('FLOATING_INPUT_03.txt')
os.remove('FLOATING_INPUT_04.txt')
#################################################################

rawDescription: How do you perform replacement of text in files and paste the replaced text at a specific position in one file

description: Perform replacement of text in files and paste the replaced text at a specific position in one file


code:
import pickle
s = (2, 3, 5, 7, 11, 13)
data = pickle.dumps(s)
data
print(pickle.loads(data))

rawDescription: Open file containing tuples in python

description: Open file containing tuples in python


code:
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6, 8))

# Axes that share the x-axis
ax = fig.add_subplot(4, 1, 1)
axes = [ax] + [fig.add_subplot(4, 1, i, sharex=ax) for i in range(2, 4)]

# The bottom independent axes
axes.append(fig.add_subplot(4, 1, 4))

# Let's hide the tick labels for all but the last shared-x axes
for ax in axes[:2]:
    plt.setp(ax.get_xticklabels(), visible=False)

# And plot on  the first subplot just to demonstrate that the axes are shared
axes[0].plot(range(21), color='lightblue', lw=3)

plt.show()

rawDescription: Adding a subplot that doesn't share an x axis when others do


code:
import colander
id = colander.SchemaNode(colander.Integer())
id.deserialize('1')

rawDescription: Coercing JSON parameters to integer

description: Coercing JSON parameters to integer


code:
import re
line_inp = "12.abd23yahoo 04/44 231"
r = re.compile('^(.*[a-zA-Z])')
m = re.match(r, line_inp)
line_out = m.group(0) # 12.abd23yahoo

rawDescription: Stripping numbers dates until first alphabet is found from string


code:
try:
    chr = unichr  # Python 2
except NameError:
    pass          # Python 3

i = 404
c = chr(i) # c is now 'Ɣ' regardless of Python version

rawDescription: Converting int to Unicode char in a backwards compatible way


code:
class SomeClass(models.Model):

    def __unicode__(self):
        return unicode(self.name)

    boolean = models.BooleanField(default=1)
    name = models.CharField(max_length=64, unique=True)

class SomeClass2(models.Model):

    def __unicode__(self):
        return unicode(self.name)

    child_item = models.ForeignKey(SomeClass, to_field='name',
                                   limit_choices_to={'boolean': True})

rawDescription: models in Django issue with foreign key

description: Models in Django issue with foreign key


code:
import subprocess

process = subprocess.Popen("my command", shell=True,
                           stdout=None, # print to terminal
                           stderr=subprocess.PIPE)
duplicator = subprocess.Popen("tee /dev/stderr", shell=True, # duplicate input stream
                              stdin=process.stderr,
                              stdout=subprocess.PIPE, # catch error stream of first process
                              stderr=None) # print to terminal
error_stream = duplicator.stdout
print('error_stream.read() = ' + error_stream.read())

rawDescription: Catching and outputting stderr at the same time with python's subprocess


code:
more_btn = WebDriverWait(self.driver, 10).until(
               EC.visibility_of_element_located((By.ID, "button_moreJobs"))
           )
more_btn.click()

rawDescription: Get to load "more" button for next page?

description: Get to load "more" button for next page


rawDescription: How do you determine which backend is being used by matplotlib?

description: Determine which backend is being used by matplotlib


code:
strs = "This is 123 and that is ABC."
match = re.search(r'.*?(\d+)',strs)
rep = match.group(0)
num = match.group(1)
"{}: {}".format(num, re.sub(rep,'That was XYZ',strs))
strs = 'This is 456 and that is OPQ.'
match = re.search(r'.*?(\d+)',strs)
rep = match.group(0)
num = match.group(1)
"{}: {}".format(num, re.sub(rep,'That was XYZ',strs))

rawDescription: Get value before replace in Python Regex


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

# data
df = pd.DataFrame(np.random.randn(100,3), columns=list('ABC'))

# plot
axes = df.plot(figsize=(10, 10), subplots=True, sharex=True, legend=False)
axes[0].set_ylabel('yA')
axes[1].set_ylabel('yB')
axes[2].set_ylabel('yC')

rawDescription: How to plot a ylabel per subplot using pandas DataFrame plot function

description: Plot a ylabel per subplot using pandas DataFrame plot function


code:
class Blog(Module):
    def _get_posts(self):
        return Post.objects.filter(module=self)
    posts = property(_get_posts)

rawDescription: How do I override related_name in inherited/child objects?

description: Override related_name in inherited/child objects


code:
from reportlab.platypus import SimpleDocTemplate, Image
from reportlab.lib.pagesizes import letter
from glob import glob

doc = SimpleDocTemplate('image-collection.pdf', pagesize=letter)
parts = [Image(filename) for filename in glob('*.jpg')]
doc.build(parts)

rawDescription: Is there a programmatic way to transform a sequence of image files into a PDF?


code:
class classonlymethod(classmethod):
    def __get__(self, instance, owner):
        if instance is not None:
            raise AttributeError("This method is available only on the view class.")
        return super(classonlymethod, self).__get__(instance, owner)

rawDescription: What is the difference between django classonlymethod and python classmethod?


code:
class PreemptiveBasicAuthHandler(urllib2.BaseHandler):

        def __init__(self, password_mgr=None):
                if password_mgr is None:
                        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
                self.passwd = password_mgr
                self.add_password = self.passwd.add_password

        def http_request(self,req):
                uri = req.get_full_url()
                user, pw = self.passwd.find_user_password(None,uri)
                #logging.debug('ADDING REQUEST HEADER for uri (%s): %s:%s',uri,user,pw)
                if pw is None: return req

                raw = "%s:%s" % (user, pw)
                auth = 'Basic %s' % base64.b64encode(raw).strip()
                req.add_unredirected_header('Authorization', auth)
                return req

rawDescription: does urllib2 support preemptive authentication authentication?

description: Does urllib2 support preemptive authentication authentication


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
import pandas as pd

# read in the date and group it by the frame number
data = pd.read_csv('data2.csv', index_col=0)
grouped = data.groupby('QuivPlotNum')

# set up the figure
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim(-200, 200)
ax.set_ylim(-200, 200)

# create empty plot for the update function to manipulate
plot = ax.quiver([], [], [], [], [], cmap='jet', headlength=3)

# create an iterator over the group, next() will return a tuple
# of QuivPlotNum, DataFrame
iterator = iter(grouped)

def update(i):
    # get next thing in the iterator
    key, data = next(iterator)
    # set new x, y coordinates for the plot
    plot.set_offsets(np.column_stack([data.QuivXLoc, data.QuivYLoc]))
    # update vector and color values
    plot.set_UVC(data.QuivXVal, data.QuivYVal, data.QuivColorVal)

# create the animation, update every 1000 ms
ani = FuncAnimation(fig, update, interval=1000)

# show it
plt.show()

rawDescription: Animate Quiver plot from values in Pandas dataframe


code: x = lambda x: sys.stdout.write("\n".join(x) + "\n")

rawDescription: Python loop for inside lambda

description: Python loop for inside lambda


code:
import urlparse

import lxml.html

with open('doc.htm') as f:
    doc = lxml.html.parse(f)

for el in doc.xpath('//*[@href | @src | @action]'):
    tag = el.tag
    href = el.get('href', '')
    if not href:
        continue

    # not really need to check for '/' when using urljoin, but this is just example
    if href.startswith('/'):
        el.attrib['href'] = urlparse.urljoin('http://stackoverflow.com/', href)

# then get string representation of tree back
result = lxml.html.tostring(doc)

rawDescription: Inside HTML, URL remap library in python


code:
# a vertex where name is "James" doesn't exist so lookup() returns None
g.vertices.index.lookup("name", "James")
# a vertex where name is "James" doesn't exist so a vertex is created
data = dict(name="James", city="Dallas")
james = g.vertices.get_or_create("name", "James", data)
james.data()
james.eid   # returns the element ID for the james vertex
1
# a vertex where name is "James" DOES exist so vertex is returned unmodified
data = dict(name="James", city="Dallas", age=35)
james = g.vertices.get_or_create("name", "James", data)
james.data()         # note age=35 was not added to the vertex properties
# one way to update the vertex properities
james.age = 35
james.save()
james.data()
{'city': 'Dallas', 'age': 35, 'name': 'James'}
# a way to update the vertex properties if you only have the vertex ID
# the vertex ID for the james vertex is 1
data = dict(name="James", city="Dallas", age=35)
g.vertices.update(1, data)
james = g.vertices.get(1)
james.data()
{'city': 'Dallas', 'age': 35, 'name': 'James'}

rawDescription: Bulbs: replacing create() with get_or_create()


code:
def force_user(user_name):
    request = tg.request
    response = tg.response

    request.cookies.clear()
    authentication_plugins = request.environ['repoze.who.plugins']
    identifier = authentication_plugins['main_identifier']

    try:
        response.headers = identifier.remember(request.environ, {'repoze.who.userid':user_name})
    except:
        pass

rawDescription: Turbogears change user via function calls


code:
for i, x in enumerate(listword):
    # i is the index, x is the character
    if x == current:
        blanks[i] = listword[i] + " "

rawDescription: Python, finding more than one index in a list of letters


code:
import pandas as pd
pd.__version__
s=pd.Series(list('abcbacb'))
pd.get_dummies(s,drop_first=True)

rawDescription: how to get pandas get_dummies to emit N-1 variables to avoid co-lineraity?

description: Get pandas get_dummies to emit N-1 variables to avoid co-lineraity


code:
import datetime as DT
DT.datetime.strptime("2012-12-12T12:00", '%Y-%m-%dT%H:%M')

rawDescription: python standard lib equivalent to dateutil.parser.parse

description: Python standard lib equivalent to dateutil.parser.parse


rawDescription: Replace all ascii symbols (other than alphabets) into HTML number in Python


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

xvec = np.linspace(-5.,5.,100)
x,y = np.meshgrid(xvec, xvec)
z = -np.hypot(x, y)

plt.contourf(x, y, z, 100)
plt.colorbar()

plt.axhline(0, color='white')
plt.axvline(0, color='white')

plt.show()

rawDescription: Draw axis lines or the origin for Matplotlib contour plot


code:
from collections import defaultdict
import itertools as it
import re

pairs = defaultdict(int)

for line in lines:
    for pair in it.combinations(re.findall('\w+', line), 2):
        pairs[tuple(pair)] += 1

resultList = [pair + (occurences, ) for pair, occurences in pairs.iterkeys()]

rawDescription: Python - Most efficient way to find how often each possible pair of words occurs in the same line in a text file?


code:
rlabels = ax.get_ymajorticklabels()
for label in rlabels:
    label.set_color('white')

rawDescription: Changing the color of the rticklabels in a polar plot


code:
@app.route("/transform-file", methods=["POST"])
def transform():
    # Check for valid file and assign it to `inbound_file`
    data = inbound_file.read()
    data = data.replace("A", "Z")
    response = make_response(data)
    response.headers["Content-Disposition"] = "attachment; filename=outbound.txt"
    return response

rawDescription: Download file, parse it and serve in Flask


code:
with open('words','rb') as f:
    for i, line in enumerate(f):
        if i >= 1000:
            break
        # do work for first 1000 lines

rawDescription: How to define length of lines to read in from a file

description: Define length of lines to read in from a file


code:
import pandas, re, numpy as np

def load_file(filename, num_cols, delimiter='\t'):
    data = None
    try:
        data = np.load(filename + '.npy')
    except:
        splitter = re.compile(delimiter)

        def items(infile):
            for line in infile:
                for item in splitter.split(line):
                    yield item

        with open(filename, 'r') as infile:
            data = np.fromiter(items(infile), float64, -1)
            data = data.reshape((-1, num_cols))
            np.save(filename, data)

    return pandas.DataFrame(data)

rawDescription: major memory problems reading in a csv file using numpy

description: Major memory problems reading in a csv file using numpy


code:
[DynamoDB]
region = us-west-2
validate_checksums = True

rawDescription: Set default region in boto config

description: Set default region in boto config


rawDescription: How to get row delta value by pandas dataframe

description: Get row delta value by pandas dataframe


code:
from Tkinter import *

root = Tk()
root.after(5000, lambda: root.focus_force())
root.mainloop()

rawDescription: Make Tkinter widget take focus

description: Make Tkinter widget take focus


rawDescription: Star Pattern Recursion Python

description: Star Pattern Recursion Python


code:
t1 = Thread(target=call_script, args=(scriptA + argumentsA))
t2 = Thread(target=call_script, args=(scriptA + argumentsB))
t3 = Thread(target=call_script, args=(scriptA + argumentsC))

t1.start()
t2.start()
t3.start()

t1.join()
t2.join()
t3.join()

rawDescription: python multithreading wait till all threads finished

description: Python multithreading wait till all threads finished


code:
import wx

class ListTest(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title, size=(380, 230))
        panel = wx.Panel(self, -1)

        #Create a list
        self.list = wx.ListCtrl(panel, -1, style=wx.LC_REPORT)
        self.list.InsertColumn(0, 'File-path', width=140)

        #Do the layout
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(self.list, 1, wx.EXPAND)
        panel.SetSizer(hbox)
        self.Centre()
        self.Show(True)

        #Create Menu
        menubar = wx.MenuBar()
        file = wx.Menu()
        self.loadFile = wx.MenuItem(file, -1, '&Open\tCtrl+L', 'Open a file')
        file.AppendItem(self.loadFile)
        menubar.Append(file, '&File')
        self.SetMenuBar(menubar)

        self.Bind(wx.EVT_MENU, self.on_openFile)

    def on_openFile(self, evt):
        loadFileDlg = wx.FileDialog(
            self, message="Open File",
            defaultDir="",
            defaultFile="",
            style=wx.OPEN | wx.CHANGE_DIR
            )
        #If the user clicked the open file button
        if loadFileDlg.ShowModal() == wx.ID_OK:
            #Get the file path
            path = loadFileDlg.GetPath()
        loadFileDlg.Destroy()

        #Call your file analysis method or whatever here

        #Create a message dialog
        fileAnalysedDlg = wx.MessageDialog(self, "File Has Been Analysed", "File Has Been Analysed", wx.OK)
        fileAnalysedDlg.ShowModal()
        fileAnalysedDlg.Destroy()

        #Add filepath to list
        self.list.InsertStringItem(0, path)

app = wx.App()
ListTest(None, 'list test')
app.MainLoop()

rawDescription: how to implement this process in wxpython?

description: Implement this process in wxpython


code:
from itertools import product
vv = [True, False, None, True, None]
choose_from = [[True, False] if x is None else [x] for x in vv]
pp = product(*choose_from)
for p in pp:
    print(p)

rawDescription: Generate Truth Tables with some variables already set in python


code:
df['total'] = df['price'] * df['amount']
df.total.resample('30S', how='sum') / df.amount.resample('30S', how='sum')

rawDescription: Converting irregularly time stamped Dateframe object, having price and volume information into equally spaced, volume weighted average price


code:
# Set the default spec to use -- uglier is better than broken.
hour_fmt = '%I'

# If we're running on a platform that has an hour spec w/o leading zero
# then use that one instead.
if sys.platform.startswith('linux'):
    hour_fmt = '%l'
elif sys.platform.startswith('win'):
    hour_fmt = '%#I'
# etc

mydateformatter = DateFormatter("%b %d " + hour_fmt + ":%M %p", self._tz)

rawDescription: Remove leading zero from time of day in Matplotlib DateFormatter


code:
# In case of grayScale images the len(img.shape) == 2
if len(img.shape) > 2 and img.shape[2] == 4:
    #convert the image from RGBA2RGB
    img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)

rawDescription: How to remove 4th channel from PNG images

description: Remove 4th channel from PNG images


code:
import datetime
from dateutil.parser import parse as parse_date
from pandas import DataFrame

df = DataFrame([['2009-01-04 - 2009-01-10','Some Data'],
                ['2009-01-11 - 2009-01-17','Some Data']])
df.columns = ['week','data']

def generate_dates(date_range):
    day1_str, day2_str = date_range.split(' - ')
    day1, day2 = parse_date(day1_str), parse_date(day2_str)
    delta = day1 - day2
    return [day1 + datetime.timedelta(days=x) for x in range(0, abs(delta.days + 1))]

def create_rows_from_row(row):
    dates = generate_dates(row['week'])
    return [[d, row['data']] for d in dates]

def create_new_df(df):
    rows = []
    for idx in range(len(df)):
        rows.extend(create_rows_from_row(df.ix[idx]))

    new_df = DataFrame(rows)
    new_df.columns = ['week','data']
    return new_df

create_new_df(df)

rawDescription: Generate days row on the basis of date range column


code:
app.add_url_rule('/',
                 view_func=Main.as_view('main'),
                 methods = ['GET'])

app.add_url_rule('/<page>/',
                 view_func=Main.as_view('page'),
                 methods = ['GET'])

rawDescription: AssertionError: View function mapping is overwriting an existing endpoint function: main


code:
query = open('foo.sql', 'r').read()
cursor.execute(query)

rawDescription: Is there a way to run a saved SQL query from Python (using cx_Oracle)?


code:
result = []
for a in guest:
  for b in guest:
    for c in guest:
      # yield (a,b,c)
      result.append((a,b,c))

rawDescription: Explain python list comprehension technique


code:
from lxml import html
from lxml.html.clean import clean_html

tree = html.parse('http://www.example.com')
tree = clean_html(tree)

text = tree.getroot().text_content()

rawDescription: Remove all html in python?

description: Remove all html in python


code:
import inspect

def hello():
    (frame, filename, line_number,
     function_name, lines, index) = inspect.getouterframes(inspect.currentframe())[1]
    print(frame, filename, line_number, function_name, lines, index)

hello()
# (<frame object at 0x8ba7254>, '/home/unutbu/pybin/test.py', 10, '<module>', ['hello()\n'], 0)

rawDescription: How to use inspect to get the caller's info from callee in Python?

description: Use inspect to get the caller's info from callee in Python


code:
import itertools
s = list(itertools.product(('0','1','*'), repeat=8))
len(s)

rawDescription: Adding extra state to itertools.product

description: Adding extra state to itertools.product


code:
class LatestEntriesFeed(Feed):
    title = "Chicagocrime.org site news"
    link = "/sitenews/"
    description = "Updates on changes and additions to chicagocrime.org."

    def items(self):
        return NewsItem.objects.order_by('-pub_date')[:5]

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.description

    # item_link is only needed if NewsItem has no get_absolute_url method.
    def item_link(self, item):
        return reverse('news-item', args=[item.pk])

rawDescription: RSS Parser for Django

description: RSS Parser for Django


code:
df = pd.read_csv('mycsv.csv')
df_nowhitespace = df.applymap(str.strip)

rawDescription: Pandas: rsplit on whole dataframe

description: Pandas: rsplit on whole dataframe


code:
def foo(n):
  lol = [ [] ]
  i = 1
  for x in range(n):
    if len(lol[-1]) >= i:
      i += 1
      lol.append([])
    lol[-1].append(x)
  return lol

rawDescription: List of Lists in python?

description: List of Lists in python


code:
class IpRange(Base):
    def __init__(self, ip=None, **kwargs):
        if ip is not None:
            self.start_ip, self.end_ip = my_super_awesome_cidr_parser(ip)
        else:
            super(IpRange, self).__init__(**kwargs)

rawDescription: Can I use context-sensitive functions in SQLAlchemy with parameters?

description: Use context-sensitive functions in SQLAlchemy with parameters


code:
for filename in locate("*.dll"):
    if os.path.exists(filename + ".processed"):
        continue
    process(filename)
    open(filename + ".processed", "w").close()

for filename in locate("*.processed"):
    os.remove(filename)

rawDescription: Avoiding previous files

description: Avoiding previous files


rawDescription: Counting values in several columns

description: Counting values in several columns


rawDescription: Small probabilities in Python

description: Small probabilities in Python


code:
import struct
struct.pack(">L", 1)    # big endian
struct.pack("L", 1)

rawDescription: sending python c_types structure through network

description: Sending python c_types structure through network


code:
def index(request):
    rand = random.randint(1, len(Verse.objects.all()))
    verse = Verse.objects.get(id = rand)
    context = {
        'verse': verse,
        'ref': verse.reference
    }
    return render (request, 'verse/index.html', context)

rawDescription: It seems like url is not matching django


code: word in "".join(line.strip() for line in text)

rawDescription: Python - take words from text

description: Python - take words from text


code:
my_dict = {'full_name1' : 1, 'full_name2' : 2, 'full_name3' : 3}
another_dict = {'name1' : 'x', 'name2' : 'y', 'name3' : 'z'}
{key:value for S, key in my_dict.iteritems() for s, value in another_dict.iteritems() if s in S}

rawDescription: Check if dictionary key contains any of another dictionary's keys and print matching pairs


code:
import re
s = "a b c,d e"
re.sub(r',\S+', '', s)

rawDescription: remove content between a specific character and whitespace

description: Remove content between a specific character and whitespace


rawDescription: Match anything EXCEPT a sequence of periods or ellipses


code:
X = range(256)  # all byte values
Y = range(256)
all(x ^ z == y for x in X for y in Y for z in [x^y])

rawDescription: Solving for unknown in bit-wise algebra

description: Solving for unknown in bit-wise algebra


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('chart_line.xlsx')
worksheet = workbook.add_worksheet()
worksheet1 = workbook.add_worksheet()
# Add the worksheet data to be plotted.
data = [10, 40, 50, 20, 10, 50]
worksheet1.write_column('A1', data)

# Create a new chart object.
chart = workbook.add_chart({'type': 'line'})

# Add a series to the chart.
chart.add_series({'values': '=Sheet2!$A$1:$A$6'})

# Insert the chart into the worksheet.
worksheet.insert_chart('C1', chart)

workbook.close()

rawDescription: xlswriter - Python module to create excel files

description: Xlswriter - Python module to create excel files


code:
from PySide import QtCore
from PySide.phonon import Phonon

if __name__ == '__main__':
    app = QtCore.QCoreApplication([])
    app.setApplicationName('test')

    mime_types = Phonon.BackendCapabilities.availableMimeTypes()
    print(mime_types)

    app.quit()

rawDescription: Is it possible to play FLAC files in Phonon?


code:
def first_name_is_in(first_names, full_names):
    for name in first_names:
        for full_name in full_names:
            if full_name.startswith("%s " % (name,)):
               return True
    return False

rawDescription: python list intersection - regex match

description: Python list intersection - regex match


code:
def after_bulk_delete(session, query, query_context, result):
    affected_table = query_context.statement.froms[0]
    affected_rows = query_context.statement.execute().fetchall()

sqlalchemy.event.listen(Session, "after_bulk_delete", after_bulk_delete)

rawDescription: sqlalchemy: get rows affected by bulk delete

description: Sqlalchemy: get rows affected by bulk delete


code:
naws_command = struct.pack('!BBBHHBB',
        255, 250, 31, # IAC SB NAWS
        width, height,
        255, 240) # IAC SE
t.get_socket().send(naws_command)

rawDescription: Is it possible to send "resize pty" command with telnetlib?


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

N = 5
menMeans   = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd     = (2, 3, 4, 1, 2)
womenStd   = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

fig, ax = plt.subplots()

ax.bar(ind, menMeans,   width, color='r', yerr=womenStd,
             align='center', label='Woman')

ax.bar(ind, womenMeans, width, color='y', yerr=menStd,
             bottom=menMeans, align='center', label='Men')

ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks(np.arange(0,81,10))

ax.plot(np.random.randint(20,50,5), 'o-', lw=2, color='k', label='Line')

ax.legend()

rawDescription: matplotlib: Two chart types with two axes

description: Matplotlib: Two chart types with two axes


code:
import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
        connection.close()

rawDescription: Import data to database and retrieve

description: Import data to database and retrieve


code:
from os.path import expanduser
homedir = expanduser("~")
parser.add_option("-L", "--logfile", dest="logfile", default=os.path.join(homedir, "log-name.log"), help="log messages to LOGFILE [default: %default]", metavar="LOGFILE")

rawDescription: How to modify the default location where the python script is trying to write the log

description: Modify the default location where the python script is trying to write the log


code:
for i in m:
    print (i.attrib['property'], i.attrib['content'])

rawDescription: How to reliably extract property, content from meta tag?

description: Reliably extract property, content from meta tag


code: RES = [abs(L[i]-L[i+1]) for i in range(len(L)-1)]

rawDescription: List comprehension for series of deltas

description: List comprehension for series of deltas


code:
capture = cv.CaptureFromCAM(0)
frame = cv.QueryFrame(capture)

#some code ...

del(capture)

rawDescription: cant find ReleaseCapture in opencv while using python?

description: Cant find ReleaseCapture in opencv while using python


code:
import struct
struct.pack('>f', 1.23)
len(struct.pack('>f', 1.23))

rawDescription: python encode/decoder for serialization/deserialization (Java's kyro equivalence in python)

description: Python encode/decoder for serialization/deserialization (Java's kyro equivalence in python)


code:
with open('testdata1.csv', 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        print(row)
        if row[0] in (None, ""):
             print("12")

rawDescription: Python: How to check if cell in CSV file is empty?


code: result = "\n".join(map(str, potions))

rawDescription: Can i join list of classes?

description: Join list of classes


code:
#forms.py
class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author

    def __init__(self, *args, **kwargs):
        super(AuthorForm, self).__init__(*args, **kwargs)
        if self.instance.id:
            self.fields['weight'].widget.attrs['readonly'] = True

#views.py
AuthorFormSet = modelformset_factory(Author, extra=2, form=AuthorForm)

rawDescription: Readonly fields in django formset

description: Readonly fields in django formset


code:
import os
import shutil
import sys

source = "source\to\large\file"
target = "destination\directory"

if sys.platform == 'win32':
    os.system('xcopy "%s" "%s"' % (source, target))
else:
    shutil.copy(source, target)

rawDescription: Python copy larger file too slow

description: Python copy larger file too slow


code:
from PyQt4 import QtGui, QtWebKit

class Browser(QtWebKit.QWebView):
    def __init__(self):
        super(Browser, self).__init__()
        self.setHtml('''
        <title>Test Page</title>

link

        ''')

    def contextMenuEvent(self, event):
        menu = self.page().createStandardContextMenu()
        hit = self.page().currentFrame().hitTestContent(event.pos())
        url = hit.linkUrl()
        if not url.isEmpty():
            menu.addSeparator()
            action = menu.addAction('Download')
            action.triggered.connect(lambda: self.download(url))
        menu.exec_(event.globalPos())

    def download(self, url):
        print('download:', url)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    browser = Browser()
    browser.setGeometry(800, 200, 400, 200)
    browser.show()
    sys.exit(app.exec_())

rawDescription: Reimplement QWebView copy link

description: Reimplement QWebView copy link


code: datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')

rawDescription: How to derive the week start for a given (iso) weeknumber / year in python

description: Derive the week start for a given (iso) weeknumber / year in python


code:
import numpy as np
a = np.zeros((2, 2))
a
np.insert(a, 1, np.array((1, 1)), 0)
np.insert(a, 1, np.array((1, 1)), 1)

rawDescription: Inserting a row at a specific location in a 2d array in numpy?


code:
import base64
img = 'test.jpg'
with open(img, 'rb') as imgfile:
    img64 = base64.encodestring(imgfile.read())

###

html = """\

Hi!

       How are you?

       Here is the link you wanted.

""".format(img64)

###

rawDescription: How to send mails in python

description: Send mails in python


code:
def tokenize(phrase, stop_words=()):
    stop_words = '|'.join(re.escape(x) + r'\b' for x in stop_words)
    other = '\s+|\w+|[^\s\w]+'
    regex = stop_words + '|' + other if stop_words else other
    return re.findall(regex, phrase)

rawDescription: How can I further profile and optimize this string tokenization function?

description: Further profile and optimize this string tokenization function


code:
def pairSum(data, value):
  s = set()
  for i in data:
    if (value - i) in s:
      return True
    else:
      s.add(i)
  else:
    return False

rawDescription: Python pairSum function with Dictionaries


code:
from numpy.random import randn
from pandas import DataFrame
D = DataFrame(randn(10,5))
D
D[2] >= 0
D[D[2] >=0]
N = D[D[2] >= 0]
N

rawDescription: Drop entire row subject to value in column


code:
a = lambda: func(g)
g = something
a()

rawDescription: python equivalent of quote in lisp

description: Python equivalent of quote in lisp


code: sorted(names, key=lambda name: int(name[4:]))

rawDescription: python custom sort list 1/2/3/../9/10

description: Python custom sort list 1/2/3/../9/10


code:
import arcpy
from arcpy.sa import *
import numpy as np
arcpy.CheckOutExtension("Spatial")
arcpy.env.extent = "MAXOF" # this ensures the extents of all my rasters will be the same, VERY IMPORTANT

extract = ExtractByMask("cost.img", "points.shp") # this step creates a raster that only has two value cells (where my points are) but the extent is that of my cost raster and the rest of the cells are NoData
extract = Con(extract>0,500,0) # changes the value of those two points to 500, a value much higher than the other cells, choose whatever value (positive or negative) that you know won't be in your cost raster
cost = arcpy.RasterToNumPyArray("cost.img")
calc = arcpy.RasterToNumPyArray(extract)
points = np.where(calc==500) #This produces the indices of all the entries in the array that are 500. However, the output is not in (12, 8), (17, 4) format, it looks like: (array([12, 17]), array([8, 4])) so must create the point indices with the next two lines
start = points[0][0], points[1][0]
end = points[0][1], points[1][1]

rawDescription: Convert location of point on raster layer to location of point in NumPy array


code:
name_of_the_list = ["abcdefgh", "ijkl"]
max(name_of_the_list)
len(max(name_of_the_list))
max(name_of_the_list, key=len)
len(max(name_of_the_list, key=len))

rawDescription: List max() Method

description: List max() Method


code:
myhash = bcrypt.hashpw('testpassword', bcrypt.gensalt(12))
myhash
bcrypt.hashpw('testpassword', myhash)

rawDescription: bcrypt mechanism in auth (no match hashes)

description: Bcrypt mechanism in auth (no match hashes)


code:
class MemberRegistrationForm(forms.ModelForm):
    year = forms.ChoiceField(choices=[])

    def __init__(self, *args, **kwargs):
        super(MemberRegistrationForm, self).__init__(*args, **kwargs)
        year = datetime.datetime.now().year
        self.fields['year'].choices = [(i, i) for i in range(year-20, year+1)]

rawDescription: Using ModelChoiceField and queryset argument using Django


rawDescription: check if element is in list already?

description: Check if element is in list already


rawDescription: How to convert a list of string to a list of int

description: Convert a list of string to a list of int


code:
def codevalue(char):
    return ord(char) - 64

rawDescription: How do I assign a numerical value to each uppercase Letter?

description: Assign a numerical value to each uppercase Letter


code:
class B(A):
    def f(self,num):
        return 7 * A.f(self,num)

rawDescription: how to refer to a parent method in python?

description: Refer to a parent method in python


code:
for row_num, row in enumerate(myData):
    primary_key_pattern_match = re.search('\d{3}-\d{3}-\d{4}, row[0]', re.I)
    if primary_key_pattern_match is not None:
        row_num_and_row_data = (row_num, row)
        # You now have a tuple whose 1st element is the row number
        # and whose 2nd element is the row (a tuple or list).

        # You can also skip making a tuple and add the row
        # to a dictionary immediately (declare it before the loop):
        row_dict[row_num] = row

        # or to add the results of the regex:
        row_dict[row_num] = primary_key_pattern_match.group(0)

rawDescription: How do you make a dictionary key from a CSV?

description: Make a dictionary key from a CSV


rawDescription: Python pandas sort groupby results

description: Python pandas sort groupby results


code: timestamps, elements = zip(*sorted(zip(timestamps, elements)))

rawDescription: Python: Sort list with parallel list

description: Python: Sort list with parallel list


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

# Suggested tweaks.

import re

class PropertyNumber(object):

    def __init__(self, str, pattern = "(?<=FINCA Nº: ).*"):
        self.regex_pattern = re.compile(pattern)
        self.text_to_search = str
        self.text_found = ""

    def search_p_number(self):
        matched_p_number = self.regex_pattern.search(self.text_to_search)
        print(self.text_to_search)
        print(matched_p_number)
        self.text_found = matched_p_number.group()
        return self.text_found

def main():
    file_input = open("nota_simple.txt", mode='r', encoding='utf-8')
    property_report = file_input.read()
    property_number = PropertyNumber(property_report)
    print(property_number.search_p_number())

if __name__ == '__main__':
    main()

rawDescription: The same regex pattern that works fine doesn't work implemented into a Class


code:
from collections import defaultdict

sets = set(map(frozenset, lists))

def remove_subsets(sets):
    # map each element to the sets in which it occurs
    sets_containing = defaultdict(set)
    for s in sets:
        for x in s:
            sets_containing[x].add(s)

    for s in sets:
        supersets = set.intersection(*(sets_containing[x] for x in s))
        if len(supersets) == 1:
            yield s

rawDescription: Yet another merging list of lists, but most pythonic way


code:
from django.contrib import admin
from myproject.myapp.models import Article

class ArticleAdmin(admin.ModelAdmin):
    fields = ('title', 'body')
admin.site.register(Article, ArticleAdmin)

rawDescription: custom django aministration view

description: Custom django aministration view


code:
numList = []
for i in range(10):
    numList.append(random.randrange(0,11))

maxNum = -1
for i in numList:
    if i > maxNum:
        maxNum = i

print(maxNum)

rawDescription: How do you find the maximum number in a list without using the function "max"?

description: Find the maximum number in a list without using the function "max"


code:
def similarity(haystack, needle):

    if needle not in haystack:
        return 0

    words = haystack.lower().split()

    if needle in words:
        return 10

    for word in words:
        if word.startswith(needle):
            return 10 ** (len(needle) / len(word))

    return 1

rawDescription: Python - fast file search

description: Python - fast file search


code:
@property
def foo(self):
    return 4

@property
def bar(self):
    return self._bar**2

@property
def baz(self):
    sys.exit(1)

@property
def spam(self):
    if self._spam is None:
        self._spam = self._lazily_compute_spam()
    return self._spam

rawDescription: Python - How to get the attribute behind @property


code: import pdb; pdb.set_trace()

rawDescription: How can I interact with rather long python scripts?

description: Interact with rather long python scripts


code:
import weighted
from matplotlib.cbook import violin_stats
from scipy import stats
import statsmodels.api as sm

def vdensity_with_weights(weights):
    ''' Outer function allows innder function access to weights. Matplotlib
    needs function to take in data and coords, so this seems like only way
    to 'pass' custom density function a set of weights '''

    def vdensity(data, coords):
        ''' Custom matplotlib weighted violin stats function '''
        # Using weights from closure, get KDE fomr statsmodels
        weighted_cost = sm.nonparametric.KDEUnivariate(data)
        weighted_cost.fit(fft=False, weights=weights)

        # Return y-values for graph of KDE by evaluating on coords
        return weighted_cost.evaluate(coords)
    return vdensity

def custom_violin_stats(data, weights):
    # Get weighted median and mean (using weighted module for median)
    median = weighted.quantile_1D(data, weights, 0.5)
    mean, sumw = np.ma.average(data, weights=list(weights), returned=True)

    # Use matplotlib violin_stats, which expects a function that takes in data and coords
    # which we get from closure above
    results = violin_stats(data, vdensity_with_weights(weights))

    # Update result dictionary with our updated info
    results[0][u"mean"] = mean
    results[0][u"median"] = median

    # No need to do this, since it should be populated from violin_stats
    # results[0][u"min"] =  np.min(data)
    # results[0][u"max"] =  np.max(data)

    return results

### Example
#vpstats1 = custom_violin_stats(np.asarray(df_column_data), np.asarray(df_column_weights))
#vplot = ax.violin(vpstats1, [pos_idx], vert=False, showmeans=True, showextrema=True, showmedians=True)
#current_color_palette = ...
#for pc in vplot['bodies']:
#    pc.set_facecolor(current_color_palette[pos_idx])
#    pc.set_edgecolor('black')

rawDescription: Python: weighted violinplots

description: Python: weighted violinplots


code:
from shapely.geometry import box, Polygon

for pixel in pixels:
    # say the pixel has llx, lly, urx, ury values.
    pixel_shape = box(llx, lly, urx, ury)

    for polygon in approximately_overlapping:
        # say the polygon has a ``value`` and a 2-D array of coordinates
        # [[x0,y0],...] named ``xy``.
        polygon_shape = Polygon(xy)
        pixel_value += polygon_shape.intersection(pixel_shape).area * value

rawDescription: Data binning: irregular polygons to regular mesh


code:
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: vanderplas@astro.washington.edu
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import math

# Initializing number of dots
N = 25

# Creating dot class
class dot(object):
    def __init__(self):
        self.x = 10 * np.random.random_sample()
        self.y = 10 * np.random.random_sample()
        self.velx = self.generate_new_vel()
        self.vely = self.generate_new_vel()

    def generate_new_vel(self):
        return (np.random.random_sample() - 0.5) / 5

    def move(self):
        def distance(x1, y1, x2, y2):
            return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

        def inside(x1, y1):
            if distance(x1, y1, 5, 5) <= 1:
                return True
            else:
                return False

        def calc_dist(d):
            ret = 0
            for x in dots:
                if inside(x.x, x.y) and x != d:
                    ret = ret + distance(x.x, x.y, d.x, d.y)
            return ret

        # if dot is inside the circle it tries to maximize the distances to
        # other dots inside circle
        if inside(self.x, self.y):
            dist = calc_dist(self)
            for i in xrange(1, 10):
                self.velx = self.generate_new_vel()
                self.vely = self.generate_new_vel()
                self.x = self.x + self.velx
                self.y = self.y + self.vely
                if calc_dist(self) <= dist or not inside(self.x, self.y):
                    self.x = self.x - self.velx
                    self.y = self.y - self.vely
        else:
            if np.random.random_sample() < 0.95:
                self.x = self.x + self.velx
                self.y = self.y + self.vely
            else:
                self.velx = self.generate_new_vel()
                self.vely = self.generate_new_vel()
                self.x = self.x + self.velx
                self.y = self.y + self.vely
            if self.x >= 10:
                self.x = 10
                self.velx = -1 * self.velx
            if self.x <= 0:
                self.x = 0
                self.velx = -1 * self.velx
            if self.y >= 10:
                self.y = 10
                self.vely = -1 * self.vely
            if self.y <= 0:
                self.y = 0
                self.vely = -1 * self.vely

# Initializing dots
dots = [dot() for i in xrange(N)]

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(0, 10))
d, = ax.plot([dot.x for dot in dots],
             [dot.y for dot in dots], 'ro')
circle = plt.Circle((5, 5), 1, color='b', fill=False)
ax.add_artist(circle)

# animation function.  This is called sequentially
def animate(i):
    for dot in dots:
        dot.move()
    d.set_data([dot.x for dot in dots],
               [dot.y for dot in dots])
    return d,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, frames=200, interval=20)

plt.show()

rawDescription: Animating a moving dot

description: Animating a moving dot


code:
class BasicTest(TestCase):
    def setUp(self):
        u = InactiveUserFactory()
        u.set_password('test_pass')
        u.save()
        self.participant = ParticipantFactory(user=u)
        self.u = self.participant.user

        self.u.is_active = True
        self.u.save()
        login = self.client.login(username=self.u.username,
                                  password='test_pass')
        assert(login is True)

        self.u.is_active = False
        self.u.save()

rawDescription: Logging in as an inactive user in a Django test


code: crc = zlib.crc32(some_segment) & 0xffffffff

rawDescription: Unsigned CRC 32 for Python to match Java's CRC 32?


code:
class StartPartneredDeliveryForm(Form):
    def __init__(self, *args, **kwargs):
        super(StartPartneredDeliveryForm, self).__init__(*args, **kwargs)

        choices = [(business.id, business.contact.organization_name)
                   for business in PartneredBusiness.objects.all()]

        self.fields['partnered_business'] = forms.ChoiceField(widget=forms.RadioSelect(),
                                                              choices=choices)

rawDescription: Django create choices based on database query


code:
vals_seen = {}
for key, val in itemscopy.iteritems():
    if val['description'] in vals_seen:
        del items[key]
    else:
        vals_seen[val['description']] = 1

rawDescription: Removing duplicate items by value within a dict


code:
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)

b = re.compile(r"\d+\.\d*")

rawDescription: Clean Python Regular Expressions

description: Clean Python Regular Expressions


code:
import six
class DirMixIn:
    """ Mix-in to make implementing __dir__ method in subclasses simpler
    """

    def __dir__(self):
        if six.PY3:
            return super(DirMixIn, self).__dir__()
        else:
            # code is based on
            # http://www.quora.com/How-dir-is-implemented-Is-there-any-PEP-related-to-that
            def get_attrs(obj):
                import types
                if not hasattr(obj, '__dict__'):
                    return []  # slots only
                if not isinstance(obj.__dict__, (dict, types.DictProxyType)):
                    raise TypeError("%s.__dict__ is not a dictionary"
                                    "" % obj.__name__)
                return obj.__dict__.keys()

            def dir2(obj):
                attrs = set()
                if not hasattr(obj, '__bases__'):
                    # obj is an instance
                    if not hasattr(obj, '__class__'):
                        # slots
                        return sorted(get_attrs(obj))
                    klass = obj.__class__
                    attrs.update(get_attrs(klass))
                else:
                    # obj is a class
                    klass = obj

                for cls in klass.__bases__:
                    attrs.update(get_attrs(cls))
                    attrs.update(dir2(cls))
                attrs.update(get_attrs(obj))
                return list(attrs)

            return dir2(self)

rawDescription: The correct way to override the __dir__ method in python


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import re
from bs4 import BeautifulSoup #use bs4 from now on.

browser = webdriver.Firefox()

browser.get('https://investor.vanguard.com/mutual-funds/vanguard-mutual-funds-list')

html = browser.page_source
soup = BeautifulSoup(html)

mydata = soup.find_all('tr')

rawDescription: BeautifulSoup: scraping a table by class attribute -- why don't I get any data?


code:
import json
data = (1, 'jsmith', 'Ferrari', '10 million', 39, 16, 2, 0, '-')
json.dumps({'John Smith': data})

rawDescription: Representing tuples with multiple types as JSON in python


code:
import Tkinter as tk

class MyDialog(object):
    def __init__(self, parent, prompt):
        self.toplevel = tk.Toplevel(parent)
        self.var = tk.StringVar()
        label = tk.Label(self.toplevel, text=prompt)
        entry = tk.Entry(self.toplevel, width=40, textvariable=self.var)
        button = tk.Button(self.toplevel, text="OK", command=self.toplevel.destroy)

        label.pack(side="top", fill="x")
        entry.pack(side="top", fill="x")
        button.pack(side="bottom", anchor="e", padx=4, pady=4)

    def show(self):
        self.toplevel.grab_set()
        self.toplevel.wait_window()
        value = self.var.get()
        return value

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.button = tk.Button(self, text="Click me!", command=self.on_click)
        self.label = tk.Label(self, text="", width=40)
        self.label.pack(side="top", fill="x")
        self.button.pack(padx=20, pady=20)

    def on_click(self):
        result = MyDialog(self, "Enter your name:").show()
        self.label.configure(text="your result: '%s'" % result)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Blocking Input Dialog Box

description: Blocking Input Dialog Box


code:
x, y = zip(*sorted((xVal, np.mean([yVal for a, yVal in zip(x, y) if xVal==a])) for xVal in set(x)))
x
y

rawDescription: How to take draw an average line for a scatter / a plot in MatPlotLib?

description: Take draw an average line for a scatter / a plot in MatPlotLib


code:
for i in xrange(0, len(seq), 2):
    seq[i].attribute1
    seq[i].attribute2
    seq[i+1].attribute1
    seq[i+1].attribute2

rawDescription: Python For Loop list

description: Python For Loop list


code:
'''Example that demonstrates keeping track of multiple key events'''
from Tkinter import *

class Playfield:
    def __init__(self):
        # this dict keeps track of keys that have been pressed but not
        # released
        self.pressed = {}

        self._create_ui()

    def start(self):
        self._animate()
        self.root.mainloop()

    def _create_ui(self):
        self.root = Tk()
        self.p1label = Label(text="press w, s to move player 1 up, down",
                             anchor="w")
        self.p2label = Label(text="press o, l to move player 2 up, down",
                             anchor="w")
        self.canvas = Canvas(width=440, height=440)
        self.canvas.config(scrollregion=(-20, -20, 420, 420))

        self.p1label.pack(side="top", fill="x")
        self.p2label.pack(side="top", fill="x")
        self.canvas.pack(side="top", fill="both", expand="true")

        self.p1 = Paddle(self.canvas, tag="p1", color="red", x=0, y=0)
        self.p2 = Paddle(self.canvas, tag="p2", color="blue", x=400, y=0)

        self._set_bindings()

    def _animate(self):
        if self.pressed["w"]: self.p1.move_up()
        if self.pressed["s"]: self.p1.move_down()
        if self.pressed["o"]: self.p2.move_up()
        if self.pressed["l"]: self.p2.move_down()
        self.p1.redraw()
        self.p2.redraw()
        self.root.after(10, self._animate)

    def _set_bindings(self):
        for char in ["w","s","o", "l"]:
            self.root.bind("<KeyPress-%s>" % char, self._pressed)
            self.root.bind("<KeyRelease-%s>" % char, self._released)
            self.pressed[char] = False

    def _pressed(self, event):
        self.pressed[event.char] = True

    def _released(self, event):
        self.pressed[event.char] = False

class Paddle():
    def __init__(self, canvas, tag, color="red", x=0, y=0):
        self.canvas = canvas
        self.tag = tag
        self.x = x
        self.y = y
        self.color = color
        self.redraw()

    def move_up(self):
        self.y = max(self.y -2, 0)

    def move_down(self):
        self.y = min(self.y + 2, 400)

    def redraw(self):
        x0 = self.x - 10
        x1 = self.x + 10
        y0 = self.y - 20
        y1 = self.y + 20
        self.canvas.delete(self.tag)
        self.canvas.create_rectangle(x0,y0,x1,y1,tags=self.tag, fill=self.color)

if __name__ == "__main__":
    p = Playfield()
    p.start()

rawDescription: Python bind - allow multiple keys to be pressed simultaniously


code:
import numpy as np
import scipy.misc.pilutil as smp

# Create a 1024x1024x3 array of 8 bit unsigned integers
data = np.zeros( (1024,1024,3), dtype=np.uint8 )

data[512,512] = [254,0,0]       # Makes the middle pixel red
data[512,513] = [0,0,255]       # Makes the next pixel blue

img = smp.toimage( data )       # Create a PIL image
img.show()                      # View in default viewer

rawDescription: What is the fastest way to draw an image from discrete pixel values in Python?


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

pylab.ion()
x = np.arange(0,5,0.1)
y = np.sin(x)
plt.plot(x,y)
pylab.show()
tin = input("Test Input: ")

rawDescription: matplotlib plot doesn't appear even after editing the backend and using pylab.show()

description: Matplotlib plot doesn't appear even after editing the backend and using pylab.show()


code:
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1285968547.0498569
_template_filename='<snip>'
_template_uri='<snip>'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
_exports = ['function']

# SOURCE LINE 1

lookup = { 'key': function }

def render_body(context,**pageargs):
    context.caller_stack._push_frame()
    try:
        __M_locals = __M_dict_builtin(pageargs=pageargs)
        __M_writer = context.writer()
        # SOURCE LINE 3
        __M_writer(u'\n\n')
        # SOURCE LINE 7
        __M_writer(u'\n')
        return ''
    finally:
        context.caller_stack._pop_frame()

def render_function(context):
    context.caller_stack._push_frame()
    try:
        __M_writer = context.writer()
        # SOURCE LINE 5
        __M_writer(u'\n    Output\n')
        return ''
    finally:
        context.caller_stack._pop_frame()

rawDescription: Python lookup function

description: Python lookup function


code:
from collections import defaultdict

WORDS = {'cat', 'hat', 'sat', 'car', 'cad', 'had', 'pad', 'pat', 'can', 'man'}

D1 = defaultdict(set)
D2 = defaultdict(set)
D3 = defaultdict(set)

for w in WORDS:
    D1[w[:2]].add(w)
    D2[w[0]+w[2]].add(w)
    D3[w[1:]].add(w)

def follows(w):
    followers = set(D1.get(w[:2]).union(D2.get(w[0]+w[2]), D3.get(w[1:])))
    followers.discard(w)
    return followers

for w in WORDS:
    print(w, follows(w))

rawDescription: Breadth first search with three-letter words, optimization


code: [float(i) for i in lst]

rawDescription: In Python, how to I convert all items in a list to floats?


code:
import numpy as np

dtype = 'float128'
abs_tolerance = 1.0

y = np.arange(0.001, 2, 0.02).astype(dtype)
N = y.shape[0]

x = np.zeros(N, dtype=dtype)
z = np.zeros(N, dtype=dtype)
x[0] = 2
z[0] = 1  # initialize the first step

for idx in range(1, N):
    y[idx] = x[idx-1] + y[idx-1]
    x[idx] = z[idx-1] + y[idx-1]
    if np.abs(y[idx] - y[idx-1]) < abs_tolerance:
        print('Convergence reached')
        break

else:
    print('Convergence failed, exiting after {} steps'.format(idx))

x = np.asarray(x)
z = np.asarray(z)
print(x)
print(y)
print(z)

rawDescription: Populating Lists or Vectors dynamically

description: Populating Lists or Vectors dynamically


code:
class PinpyTests(Object):
    test = False

    def __init__(self, jsonstr, campaign):
        self.data = json.loads(jsonstr)
        self.campaign = campaign

    def testAll(self):
        passed = True
        if self.data.get('dwellTime') is not None:
            passed = passed and self.dwellTest()
        if self.data.get('proximity') is not None:
            passed = passed and self.proximityTest()
        return passed

    def dwellTest(self):
        if self.data.get('dwellTime') >= self.campaign.needed_dwellTime:
            # Result matches, dwell time test passed.
            return True
        return False

    def proximityTest(self):
        if self.data.get('proximity') == self.campaign.needed_proximity:
            # Result matches, proximity passed.
            return True
        return False

rawDescription: running tests against a json string python

description: Running tests against a json string python


code:
def load(root_import_path, is_valid=lambda entity: True):
    """Returns modules in ``root_import_path`` that satisfy the ``is_valid`` test

    :param root_import_path: An string name for importing (i.e. "myapp").
    :param is_valid: A callable that takes a variable and returns ``True``
                     if it is of interest to us."""

    prefix = root_import_path + u"."
    modules = []

    for _, name, is_pkg in walk_packages(root_import_path, prefix=prefix):
        if is_pkg:
            continue
        module_code = __import__(name)
        contents = dir(module_code)
        for thing in contents:
            if is_valid(thing):
                modules.append(thing)

    return modules

rawDescription: How do you dynamically load python classes from a given directory?

description: Dynamically load python classes from a given directory


code:
(num, den, dt)
(zeros, poles, gain, dt)
(A, B, C, D, dt)

rawDescription: Why does scipy.signal.cont2discrete return dt?


code:
data = {'hash': hash, 'confirm': 'Continue as Free User'}
r = requests.post(url, data)
html = r.text

rawDescription: HTTP requests.post fails

description: HTTP requests.post fails


code:
import sys, os.path, ctypes, ctypes.wintypes

Psapi = ctypes.WinDLL('Psapi.dll')
EnumProcesses = Psapi.EnumProcesses
EnumProcesses.restype = ctypes.wintypes.BOOL
GetProcessImageFileName = Psapi.GetProcessImageFileNameA
GetProcessImageFileName.restype = ctypes.wintypes.DWORD

Kernel32 = ctypes.WinDLL('kernel32.dll')
OpenProcess = Kernel32.OpenProcess
OpenProcess.restype = ctypes.wintypes.HANDLE
TerminateProcess = Kernel32.TerminateProcess
TerminateProcess.restype = ctypes.wintypes.BOOL
CloseHandle = Kernel32.CloseHandle

MAX_PATH = 260
PROCESS_TERMINATE = 0x0001
PROCESS_QUERY_INFORMATION = 0x0400

count = 32
while True:
    ProcessIds = (ctypes.wintypes.DWORD*count)()
    cb = ctypes.sizeof(ProcessIds)
    BytesReturned = ctypes.wintypes.DWORD()
    if EnumProcesses(ctypes.byref(ProcessIds), cb, ctypes.byref(BytesReturned)):
        if BytesReturned.value<cb:
            break
        else:
            count *= 2
    else:
        sys.exit("Call to EnumProcesses failed")

for index in range(BytesReturned.value / ctypes.sizeof(ctypes.wintypes.DWORD)):
    ProcessId = ProcessIds[index]
    hProcess = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, False, ProcessId)
    if hProcess:
        ImageFileName = (ctypes.c_char*MAX_PATH)()
        if GetProcessImageFileName(hProcess, ImageFileName, MAX_PATH)>0:
            filename = os.path.basename(ImageFileName.value)
            if filename == 'notepad.exe':
                TerminateProcess(hProcess, 1)
        CloseHandle(hProcess)

rawDescription: How can I find a process by name and kill using ctypes?

description: Find a process by name and kill using ctypes


code:
def endcode(msg,secret_d):
    newstr=""
    for ch in msg:
        for key,value in secret_d.iteritems():
            if ch == key:
                newstr=newstr+value
    print(msg)
endcode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'})

rawDescription: update string from a dictionary with the values from matching keys

description: Update string from a dictionary with the values from matching keys


code:
import os, sys
lib_path = os.path.abspath('.')
sys.path.append(lib_path)

import mymodule

rawDescription: Python not recognising another file

description: Python not recognising another file


code:
from django.template import Library, Node, TemplateSyntaxError
from django.utils.encoding import smart_unicode

register = Library()

class FirstNotNoneNode(Node):
    def __init__(self, vars):
        self.vars = vars

    def render(self, context):
        for var in self.vars:
            value = var.resolve(context, True)
            if value is not None:
                return smart_unicode(value)
        return u''

def firstnotnone(parser,token):
    """
    Outputs the first variable passed that is not None
    """
    bits = token.split_contents()[1:]
    if len(bits) < 1:
        raise TemplateSyntaxError("'firstnotnone' statement requires at least one argument")
    return FirstNotNoneNode([parser.compile_filter(bit) for bit in bits])

firstnotnone = register.tag(firstnotnone)

rawDescription: how to make django custom template tag with variable length arg list

description: Make django custom template tag with variable length arg list


rawDescription: How can I make my code be a set?

description: Make my code be a set


code:
class Item(models.Model):
    ...
    category = models.ManyToManyField(Category, null=True,blank=True)
    category.help_text = ''
    ...

rawDescription: Django (1.2) Forms: ManyToManyField Help Text


code:
import MySQLdb

class DB:
  conn = None

  def connect(self):
    self.conn = MySQLdb.connect()

  def query(self, sql):
    try:
      cursor = self.conn.cursor()
      cursor.execute(sql)
    except (AttributeError, MySQLdb.OperationalError):
      self.connect()
      cursor = self.conn.cursor()
      cursor.execute(sql)
    return cursor

db = DB()
sql = "SELECT * FROM foo"
cur = db.query(sql)
# wait a long time for the Mysql connection to timeout
cur = db.query(sql)
# still works

rawDescription: Correct way of keeping mysql connection

description: Correct way of keeping mysql connection


rawDescription: Most efficient way to cycle over Python sublists while making them grow (insert method)?


rawDescription: How to click language/region link using Selenium Webdriver and Python?

description: Click language/region link using Selenium Webdriver and Python


code:
import random

def condition_manipulate(value):
    list_set=[]
    for i in range(value):
        new_list=initial_conditions[:]
        i=random.choice(range(len(initial_conditions)))
        new_list[i]=new_sum(new_list[i])
        list_set.append(new_list)
    return list_set

rawDescription: Python function to create and manipulate lists


code:
a
data = []
for x in a:
    data.append(re.findall("\"(\w+)\" \((\d+)\).*\t{2,5}(\S+)", x)[0])

import pandas as pd
pd.DataFrame(data, columns=['Movie', 'Year', 'Keyword'])

rawDescription: extract strings from patterned string list and convert it into dataFrame in python

description: Extract strings from patterned string list and convert it into dataFrame in python


code:
row = 0
col = 0

worksheet.write(row, col,     'First Name')
worksheet.write(row, col + 1, 'Last Name')
worksheet.write(row, col + 2, 'Age')
worksheet.write(row, col + 3, 'User Name')
worksheet.write(row, col + 4, 'Password')
worksheet.write(row, col + 5, 'Email ID')

row += 1
worksheet.write_string(row, col,     userfirstname)
worksheet.write_string(row, col + 1, userlastname)
worksheet.write_string(row, col + 2, userage)
worksheet.write_string(row, col + 3, username)
worksheet.write_string(row, col + 4, userpwd)
worksheet.write_string(row, col + 5, usermailid)

rawDescription: Python Xlsx Writer - Write String to new row


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

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()

rawDescription: python numpy/scipy curve fitting

description: Python numpy/scipy curve fitting


code:
import subprocess
log_file = open('/path/to/file', 'a')

return_code = subprocess.Popen(['/usr/bin/foo', 'arg1', 'arg2'], stdout=log_file).wait()

rawDescription: Python run command line (time)

description: Python run command line (time)


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

n = 15; m = 40                        # graph size
L = np.random.choice(xrange(n), 2*m)  # select some edge destinations
weights = 0.5 + 5 * np.random.rand(m) # give each edge a weight

G = nx.Graph()                           # create a graph object
G.add_nodes_from(xrange(n))              # add n nodes to it
for i, (fr, to) in enumerate(zip(L[1::2], L[::2])):
  G.add_edge(fr, to, weight=weights[i])  # add each edge

# use one of the edge properties to control line thickness
edgewidth = [ d['weight'] for (u,v,d) in G.edges(data=True)]

# and create a filtered version (still need an entry for each edge)
w_threshold = 2
edgewidth_filtered = [ d['weight'] if d['weight'] > w_threshold else 0
                      for (u,v,d) in G.edges(data=True)]

# alt. filtering - all edges that meet some criterion are displayed uniformly
binary_filtered_edges = [ 1 if d['weight'] > w_threshold else 0
                      for (u,v,d) in G.edges(data=True)]

titles = [ 'edges drawn with lineweight=1', 'edge width from edge weight',
  'edge width from edge weight, only strong edges',
  'strong edges shown as lineweight=1', ]

edge_display_params = [ np.ones(len(edgewidth),), edgewidth,
  edgewidth_filtered, binary_filtered_edges,]

# to illustrate drawing an unknown number of graphs, add some repeats repeats
n_extra = np.random.randint(0, 5)
indices = range(len(edge_display_params)) * 3
indices = indices[len(edge_display_params) + n_extra:]

# layout
pos = nx.spring_layout(G, iterations=50)
pos = nx.circular_layout(G)
#pos = nx.random_layout(G)

# rendering
fig = plt.figure(1); plt.clf()
# compute a grid size that will fit all graphs on it (couple blanks likely)
nr = int(np.ceil(np.sqrt(len(indices))))
fig, ax = plt.subplots(nr, nr, num=1)

for i, j in enumerate(indices):
    # dereference index into valid data (needed here since some repeated rather
    # than creating more, to illustrate handling unknown amount of data)
    k = indices[j]
    widths = edge_display_params[k]
    # compute index for the subplot, and set this subplot as current
    ix = np.unravel_index(i, ax.shape)
    plt.sca(ax[ix])
    # draw all nodes homogeneously, and edge weights as filtered
    nx.draw_networkx_nodes(G, pos, ax=ax[ix])
    nx.draw_networkx_edges(G, pos, width=widths, ax=ax[ix],)

    ax[ix].set_title(titles[k], fontsize=10)
    ax[ix].set_axis_off()

plt.show()

rawDescription: subplots with network analysis networkx

description: Subplots with network analysis networkx


rawDescription: Getting monitor size in python

description: Getting monitor size in python


code: newlist = [key for key in mylist if key not in mydict]

rawDescription: How to reverse this comprehension?

description: Reverse this comprehension


code:
class MyImgPattern(Pattern):
    def handleMatch(self, m):
        a = etree.Element('a', attrib={'href':m.group(3)})
        img = etree.Element('img', attrib={
            'width': '100%',
            'src': m.group(3),
            'alt': m.group(2),
            'title': m.group(4)
        })
        a.append(img)
        return a

rawDescription: How to create a new markdown cue extending another one using python-markdown

description: Create a new markdown cue extending another one using python-markdown


code:
from pylab import *
import matplotlib.animation as animation

class Monitor(object):
    """  This is supposed to be the class that will capture the data from
        whatever you are doing.
    """
    def __init__(self,N):
        self._t    = linspace(0,100,N)
        self._data = self._t*0

    def captureNewDataPoint(self):
        """  The function that should be modified to capture the data
            according to your needs
        """
        return 2.0*rand()-1.0

    def updataData(self):
        while True:
            self._data[:]  = roll(self._data,-1)
            self._data[-1] = self.captureNewDataPoint()
            yield self._data

class StreamingDisplay(object):

    def __init__(self):
        self._fig = figure()
        self._ax  = self._fig.add_subplot(111)

    def set_labels(self,xlabel,ylabel):
        self._ax.set_xlabel(xlabel)
        self._ax.set_ylabel(ylabel)

    def set_lims(self,xlim,ylim):
        self._ax.set_xlim(xlim)
        self._ax.set_ylim(ylim)

    def plot(self,monitor):
        self._line, = (self._ax.plot(monitor._t,monitor._data))

    def update(self,data):
        self._line.set_ydata(data)
        return self._line

# Main
if __name__ == '__main__':
    m = Monitor(100)
    sd = StreamingDisplay()
    sd.plot(m)
    sd.set_lims((0,100),(-1,1))

    ani = animation.FuncAnimation(sd._fig, sd.update, m.updataData, interval=500) # interval is in ms
    plt.show()

rawDescription: MatPlotLib dynamic time axis

description: MatPlotLib dynamic time axis


code:
def outline(im):
    ''' Input binary 2D (NxM) image. Ouput array (2xK) of K (y,x) coordinates
        where 0 <= K <= 2*M.
    '''
    topbottom = np.empty((1,2*im.shape[1]), dtype=np.uint16)
    topbottom[0,0:im.shape[1]] = np.argmax(im, axis=0)
    topbottom[0,im.shape[1]:] = (im.shape[0]-1)-np.argmax(np.flipud(im), axis=0)
    mask      = np.tile(np.any(im, axis=0), (2,))
    xvalues   = np.tile(np.arange(im.shape[1]), (1,2))
    return np.vstack([topbottom,xvalues])[:,mask].T

rawDescription: python contour for binary 2D matrix

description: Python contour for binary 2D matrix


code:
class ImageMetadataMixin(object):
    """Mixin can be added to any image file"""
    @property
    def iptc(self):
        """Or something like this"""

class ImageWithMetadataFieldFile(ImageMetadataMixin, ImageFieldFile):
    pass

class ImageWithMetadataField(ImageField):
    attr_class = ImageWithMetadataFieldFile

rawDescription: Subclassing the Django ImageFileField

description: Subclassing the Django ImageFileField


code:
import pandas as pd
import numpy as np
import matplotlib.pylab as pl

df1 = pd.DataFrame(np.random.random(10))
df2 = pd.DataFrame(np.random.random(10))

pl.figure()
ax=pl.subplot(121)
df1.plot(kind='bar', ax=ax)

ax=pl.subplot(122)
df2.plot(kind='bar', ax=ax)

rawDescription: How to have a figure with panels composed of plots from a data frame (python 2.7)?

description: Have a figure with panels composed of plots from a data frame (python 2.7)


code:
#!/usr/bin/env python

import web
from urllib import quote

urls = ('(.*)', 'urlhandler')

def adaptHeader(txt):
  """Input: string, header name as it is in web.ctx.env
  Output: string, header name according to http protocol.
  es: "HTTP_CACHE_CONTROL" => "Cache-Control"
  """
  txt = txt.replace('HTTP_', '')
  return '-'.join((t[0] + t[1:].lower() for t in txt.split('_')))

def rawRequest(env):
  """Reconstruct and return the web request based on web.ctx.env"""

  # url reconstruction
  # see http://www.python.org/dev/peps/pep-0333/#url-reconstruction
  url = env['wsgi.url_scheme']+'://' # http/https
  url += env.get('HTTP_HOST') or (env['SERVER_NAME']+':'+env['SERVER_PORT']) # host + port
  url += quote(env.get('SCRIPT_NAME', ''))
  url += quote(env.get('PATH_INFO', ''))
  url += ('?' + env['QUERY_STRING']) if env.get('QUERY_STRING') else '' # GET querystring

  # get/post request
  req = ' '.join((env['REQUEST_METHOD'], url, env['SERVER_PROTOCOL'])) + '\n'

  # headers
  for k, v in env.items():
    if k.startswith('HTTP') or k in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
      req += adaptHeader(k) + ': ' + str(v) + '\n'

  # post data
  try:
    req += '\n' + env['wsgi.input'].read(int(env['CONTENT_LENGTH']))
  except:
    pass

  return req

class urlhandler:
  def GET(self, url):
    return rawRequest(web.ctx.env)
  def POST(self, url):
    return rawRequest(web.ctx.env)

if __name__ == '__main__':
  app = web.application(urls, globals())
  app.run()

rawDescription: web.py: Get the original web request

description: Web.py: Get the original web request


code:
def CreateFile(filename,imageFile):
  with gcs.open(filename, 'w', content_type = 'image/jpeg') as f:
    f.write(imageFile)
    f.close()

  blobstore_filename = '/gs' + filename
  return blobstore.create_gs_key(blobstore_filename)

class MyImageHandler(webapp2.RequestHandler):
  def post(self):
    bucket='youbucketname'
    imageFile = self.request.get('file')
    nameOfFile = self.request.get('filename1')
    fileName = '/youbucketname' + '/' + nameOfFile
    blob_key = CreateFile(fileName, imageFile)
    imageUrl = 'https://%(bucket)s.storage.googleapis.com/%(file)s' % {'bucket':bucket, 'file':naemofFile}
    logging.info("Image-URL " + imageUrl)

app = webapp2.WSGIApplication([('/myimagehandler', MyImageHandler)],
                              debug=True)

rawDescription: how to upload image using google cloud client library on cloud storage in python?

description: Upload image using google cloud client library on cloud storage in python


code:
from azure.mgmt.network import NetworkManagementClient, NetworkManagementClientConfiguration

subscription_id = '33333333-3333-3333-3333-333333333333'

credentials = ...

network_client = NetworkManagementClient(
    NetworkManagementClientConfiguration(
        credentials,
        subscription_id
    )
)

GROUP_NAME = 'XXX'
VM_NAME = 'xxx'
PUBLIC_IP_NAME = VM_NAME

public_ip_address = network_client.public_ip_addresses.get(GROUP_NAME, PUBLIC_IP_NAME)
print(public_ip_address.ip_address)
print(public_ip_address.ip_configuration.private_ip_address)

rawDescription: Is there any python API which can get the IP address (internal or external) of Virtual machine in Azure


rawDescription: copy value of a list into another within a method in python

description: Copy value of a list into another within a method in python


code:
for book_type in BOOK_TYPES:
  setattr(self, 'has_book_type_%s' % book_type, self.has_book_type_(book_type))

rawDescription: Meta programming in Django get_foo_display, foo_set and others, how does it work?


code:
from datetime import datetime
datestr = datetime.strftime(datetime.today(), "%Hh %Mm %Ss %A, %B %Y")
examplefile = open("/home/michael/file{0}".format(datestr), 'w')
print(examplefile)

rawDescription: Using variables in creating a file name

description: Using variables in creating a file name


code:
a = np.arange(10, 0, -1)
a
b = a[2:-2]
b
i = b.argsort()
b[:] = b[i]  # change the values inside the view
a            # note `a` has been sorted in [2:-2] slice

rawDescription: Inplace permutation of a numpy arrray

description: Inplace permutation of a numpy arrray


code:
def main_func():
    final_d = {}
    for _ in range(10):
        for key, val in part_func().items():
            final_d.setdefault(key, []).append(val)
    return final_d

rawDescription: Python merge dictionaries within a while loop


code:
df
df.groupby(level=0)['val'].nunique()

rawDescription: pandas hierarchical indexing unique values

description: Pandas hierarchical indexing unique values


code:
def Stern_Brocot(n):
    states = [(0, 1, 1, 1)]
    result = []
    while len(states) != 0:
        a, b, c, d = states.pop()
        if a + b + c + d <= n:
            result.append((a+c, b+d))
            states.append((a, b, a+c, b+d))
            states.append((a+c, b+d, c, d))
    return result

rawDescription: Iterating over parts of the Stern-Brocot tree in Python


code:
humaninput = "This is me typing a whole bunch of say things with words after it"
breakdown = humaninput.split()
say = "say"
if say in breakdown:
    split = breakdown.index(say)
    after = breakdown[split+1:]
    print(after)

rawDescription: print after a certain word in python

description: Print after a certain word in python


code:
utf8_url = 'Escola Superior de Ci\xc3\xaancias Empresariais (Set\xc3\xbabal)'
percent_url = urllib2.quote(utf8_url)

rawDescription: Wikipedia API: getting articles with unicoded titles


code:
df1 = pd.melt(df, value_vars=['Val1', 'Val2', 'Val3', 'Val4'],
              id_vars=['Statistic', 'Ref'], var_name='Values')
df1.pivot_table(values='value', rows=['Ref', 'Values'], cols='Statistic')

rawDescription: Pandas; tricky pivot table

description: Pandas; tricky pivot table


code:
from ghost import Ghost, Session

ghost = Ghost()
USERAGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0"

with ghost.start():
    session = Session(ghost, download_images=False, display=True, user_agent=USERAGENT)
    page, rs = session.open("https://m.facebook.com/login.php", timeout=120)
    assert page.http_status == 200

    session.evaluate("""
    document.querySelector('input[name="email"]').value = 'email@email.com';
    document.querySelector('input[name="pass"]').value = 'email-password';
    """)

    session.evaluate("""document.querySelector('input[name="login"]').click();""",
                 expect_loading=True)

    """
    import codecs

    with codecs.open('fb.html', encoding='utf-8', mode='w') as f:
       f.write(session.content)
    """

    # session.save_cookies('fbookie')
    session.capture_to(path='fbookie.png')

    # gracefully clean off to avoid errors
    session.webview.setHtml('')
    session.exit()

rawDescription: login to facebook using the Ghost.py python package

description: Login to facebook using the Ghost.py python package