code:
from vtk import vtkDICOMImageReader
from vtk import vtkImageShiftScale
from vtk import vtkPNGWriter

reader = vtkDICOMImageReader()
reader.SetFileName('image.dcm')
reader.Update()
image = reader.GetOutput()

shiftScaleFilter = vtkImageShiftScale()
shiftScaleFilter.SetOutputScalarTypeToUnsignedChar()
shiftScaleFilter.SetInputConnection(reader.GetOutputPort())

shiftScaleFilter.SetShift(-1.0*image.GetScalarRange()[0])
oldRange = image.GetScalarRange()[1] - image.GetScalarRange()[0]
newRange = 255

shiftScaleFilter.SetScale(newRange/oldRange)
shiftScaleFilter.Update()

writer = vtkPNGWriter()
writer.SetFileName('output.jpg')
writer.SetInputConnection(shiftScaleFilter.GetOutputPort())
writer.Write()

rawDescription: Convert DICOM image using VTK

description: Convert DICOM image using VTK


code:
self.master = Tk()
self.master.configure(bg = 'magenta')

rawDescription: Python Tkinter how to color a window using grid


code: sampl = np.random.uniform(low=0.5, high=13.3, size=(50,))

rawDescription: Generate random array of floats between a range


code:
#!/usr/bin/env python

import glob
import shutil
import os

source="."
destination = "/tmp/newDestination/"

if not(os.path.exists(destination)):
    os.makedirs(destination)
elif not(os.path.isdir(destination)):
    raise OSError("Kabooom! The destination %s exists, but is not a directory" % destination)

for javaFile in glob.glob(os.path.join(source, "*.java")):
    if os.path.isfile(javaFile):
        shutil.move(os.path.abspath(javaFile), destination)

rawDescription: How to move only *.java files with python?

description: Move only *.java files with python


code:
lucky_number = 5
tries = 6
while tries:
  inp = raw_input("User input: ")
  if inp.isdigit() and int(inp) == lucky_number:
    return True
  elif inp.lower() == 'quit':
    break
  tries -= 1
return False

rawDescription: How can I input a value as a string and then input a int value without having two input boxes?

description: Input a value as a string and then input a int value without having two input boxes


code:
class Member(models.Model):
    nickname = models.CharField(max_length=30, blank=False)
    paid = models.BooleanField(default=False)

class Group(models.Model):
    group_name = models.CharField(max_length=50, db_index=True)
    description = models.CharField(max_length=255)
    created_by = models.ForeignKey('Member', related_name='created_by')
    created_date = models.DateTimeField(auto_now=True)
    members = models.ManyToManyField(Member, through="Membership")

    def __unicode__(self):
        return self.group_name

class Membership(models.Model):
     member = models.ForeignKey(Member)
     group = models.ForeignKey(Group)
     active = models.BooleanField(default=True, db_index=True)
     join_date = models.DateTimeField(auto_now=True)
     league_manager = models.BooleanField(default=False, db_index=True)

     def __unicode__(self):
         return "%s (%s)" % (self.member, self.group)

rawDescription: Can't get a handle on a Django ManyToMany Model object


code:
def naming(instance, file_name):
    model_name = instance.__class__.__name__
    return os.path.join(model_name, file_name)

rawDescription: how to specify a directory and a function with upload_to in django

description: Specify a directory and a function with upload_to in django


code:
def pop_all(self):
    result, self._internal_list = self._internal_list, []
    return result

rawDescription: Popping all items from Python list

description: Popping all items from Python list


code:
import os

for name in os.listdir(): # look through the entire directory
    # break up the name so we can work with it
    parts = name.split('_')
    # skip non-matching files
    if len(parts) != 3: continue
    if parts[0] != 'P' or parts[2] != '.map': continue
    # figure out the new name
    newname = "Ptest.%03d" % int(parts[1])
    # do the rename
    os.rename(name, newname)

rawDescription: How do I change file extension based on the number in a file name in Python

description: Change file extension based on the number in a file name in Python


code:
def repeat(a, b):
    stored = {}
    d = b - a + 2
    for c in range(1, d):
        stored[c] = random.randint(a, b)
        for f in stored:
            if stored[f] == stored[c]:
                return c

rawDescription: python: proper use of dictionaries

description: Python: proper use of dictionaries


code:
import pycurl, json

github_url = 'https://api.postmarkapp.com/email'

data = json.dumps({"From": "user@example.com", "To": "receiver@example.com", "Subject": "Pycurl", "TextBody": "Some text"})

c = pycurl.Curl()
c.setopt(pycurl.URL, github_url)
c.setopt(pycurl.HTTPHEADER, ['X-Postmark-Server-Token: API_TOKEN_HERE','Accept: application/json'])
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.perform()

rawDescription: Convert curl example to pycurl

description: Convert curl example to pycurl


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

fig, ax = plt.subplots()

ys = np.random.rand(10)

threshold = 0.5

ax.axhline(y=threshold, color='r', linestyle=':')
ax.plot(ys)

greater_than_threshold = [i for i, val in enumerate(ys) if val>threshold]
ax.plot(greater_than_threshold, ys[greater_than_threshold],
        linestyle='none', color='r', marker='o')

plt.show()

rawDescription: matplotlib: Different Marker colour when value crosses a threshold

description: Matplotlib: Different Marker colour when value crosses a threshold


code:
from scipy import polyfit
data = loadtxt("data.txt")
xdata,ydata = data[:,0],data[:,1]
xdata,ydata = zip(*sorted(zip(xdata,ydata))) # sorts the two lists after the xdata

xd,yd = log10(xdata),log10(ydata)
polycoef = polyfit(xd, yd, 1)
yfit = 10**( polycoef[0]*xd+polycoef[1] )

plt.subplot(211)
plt.plot(xdata,ydata,'.k',xdata,yfit,'-r')
plt.subplot(212)
plt.loglog(xdata,ydata,'.k',xdata,yfit,'-r')
plt.show()

rawDescription: Polynomial fitting with log log plot

description: Polynomial fitting with log log plot


code:
x = [1e-5, 1e-3, 1e-1]
y = np.arccos(np.cos(x))
assert_allclose(x, y, rtol=1e-5, atol=0)

rawDescription: Assert equality of floating point values to a significant figure tolerance


code:
import re, file_one
for name,val in file_one.__dict__.items():
    if re.match("[A-Z0-9_]+", name):
        globals()[name] = val

rawDescription: How to import large number of global variables without listing each one? (Python)

description: Import large number of global variables without listing each one? (Python)


code:
# -*- coding: iso-8859-1 -*-
from __future__ import print_function

cities = ['Paris', 'London', 'Helsinki', 'Amsterdam', 'Sant Julià de Lòria', 'New York',
          'Dublin']
SOURCE = 'world.txt'

for city in cities:
    with open(SOURCE) as fh:
        for line in fh:
            if city in line:
                fields = line.split(',')
                print(fields[0], 'Lat: ', fields[5], 'Long: ', fields[6])
                break

rawDescription: non-standard characters cause program to end

description: Non-standard characters cause program to end


code:
globals()

foo = 1
def bar():
  pass

globals()

rawDescription: Equivalent of getfenv in Python?

description: Equivalent of getfenv in Python


code: a = sudo("ls -l my_filename | awk '{print $11}'", capture=True )

rawDescription: Fabric, retrieving result of a bash command into a python variable


code:
i=2
print(type(i))
for i in '1234':  # i is reassigned
  print(type(i))
  print(i*2)

rawDescription: For loop in Python and data types

description: For loop in Python and data types


code:
def ff7_checksum(data): # data used to be 'qw'
  all_bits = 0xFFFF # a 16-bit value with all bits set.
  result = all_bits # result used to be 'r'
  pbit = 0x8000 # the highest-order bit in a 16-bit value.

  for byte in data: # byte used to be 't'
    result ^= byte << 8
    for i in range(8):
      result = (result << 1) ^ (0x1021 if result & pbit else 0)
    result &= all_bits
  return result ^ all_bits # the original &-mask is not necessary

rawDescription: Translate several lines of C to Python

description: Translate several lines of C to Python


code:
class Offer(serializers.ModelSerializer):
    class Meta:
        model = Offer
        fields = ('id', 'max_devices', 'bandwidth')

    # We add a custom field called "bandwidth",
    # which is served by a method in the serializer classs,
    # that returns the format you want.

    bandwidth = serializers.SerializerMethodField('get_bandwidth')

    def get_bandwidth(self, obj):
        return {'bandwidth': {'value': obj.bandwidth_value,
                             'unit': obj.bandwidth_unit}}

rawDescription: Django Rest framework group fields together


code:
foo = bar
baz = qux

rawDescription: make a hyperlink also submit some form information

description: Make a hyperlink also submit some form information


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

x=np.arange(-10.0,10.0,0.1)
y=np.arctan(x)

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

ax.plot(x,y,'b.')

y_pi   = y/np.pi
unit   = 0.25
y_tick = np.arange(-0.5, 0.5+unit, unit)

y_label = [r"$-\frac{\pi}{2}$", r"$-\frac{\pi}{4}$", r"$0$", r"$+\frac{\pi}{4}$",   r"$+\frac{\pi}{2}$"]
ax.set_yticks(y_tick*np.pi)
ax.set_yticklabels(y_label, fontsize=20)

y_label2 = [r"$" + format(r, ".2g")+ r"\pi$" for r in y_tick]
ax2 = ax.twinx()
ax2.set_yticks(y_tick*np.pi)
ax2.set_yticklabels(y_label2, fontsize=20)

plt.show()

rawDescription: How can I set the y axis in radians in a Python plot?

description: Set the y axis in radians in a Python plot


rawDescription: Pythonic way to sort list of objects by a dict value (by key) contained within the object


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.actionbar import ActionButton
from kivy.uix.label import Label
from kivy.clock import Clock

Builder.load_string("""
<Tooltip>:
    size_hint: None, None
    size: self.texture_size[0]+5, self.texture_size[1]+5
    canvas.before:
        Color:
            rgb: 0.2, 0.2, 0.2
        Rectangle:
            size: self.size
            pos: self.pos

<MyWidget>
    ActionBar:
        ActionView:
            MyActionButton:
                icon: 'atlas://data/images/defaulttheme/audio-volume-high'
            MyActionButton:
                icon: 'atlas://data/images/defaulttheme/audio-volume-high'
""")

class Tooltip(Label):
    pass

class MyActionButton(ActionButton):
    tooltip = Tooltip(text='Hello world')

    def __init__(self, **kwargs):
        Window.bind(mouse_pos=self.on_mouse_pos)
        super(ActionButton, self).__init__(**kwargs)

    def on_mouse_pos(self, *args):
        if not self.get_root_window():
            return
        pos = args[1]
        self.tooltip.pos = pos
        Clock.unschedule(self.display_tooltip) # cancel scheduled event since I moved the cursor
        self.close_tooltip() # close if it's opened
        if self.collide_point(*self.to_widget(*pos)):
            Clock.schedule_once(self.display_tooltip, 1)

    def close_tooltip(self, *args):
        Window.remove_widget(self.tooltip)

    def display_tooltip(self, *args):
        Window.add_widget(self.tooltip)

class MyWidget(Widget):
    pass

class ClientApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    ClientApp().run()

rawDescription: How to make ToolTip using Kivy?

description: Make ToolTip using Kivy


rawDescription: Update (repaint) application window (python)


code:
for i, inst in enumerate(record):
    append = True
    for rec in (x[1] for x in record[i + 1:]):
        if inst[1] in rec:
            append = False
            break
    if append:
        final_string = final_string + inst[0] + ' '

rawDescription: Iterating over a list of lists and ignoring strings if they appear inside a larger string - Python


rawDescription: Regex to find N numbers after some token in python


code:
ast.literal_eval(text.split(' ', 1)[1])
json.loads(text.split(' ', 1)[1])

rawDescription: Efficient parsing of strings in Python

description: Efficient parsing of strings in Python


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

theta=np.arange(0,2*np.pi,2*np.pi/400)

a= 1.0      #semi-major axis
r = 10.
e1 = 2.
e2 = 3.

def get_r(theta, e, a):
    return a*(e**2 - 1)/(1+e*np.cos(theta))

def get_theta(r, e, a):
    return np.arccos((a*(e**2 - 1) -r)/(e*r))

offset1 = get_theta(r, e1, a)
offset2 = get_theta(r, e2, a)

ax = plt.subplot(111, polar=True)
ax.plot(theta, get_r(theta, e1, a), color='r', linewidth=2)
ax.plot(theta, get_r(theta - offset2 + offset1, e2, a), color='b', linewidth=2)
ax.set_rmax(30.0)
ax.grid(True)
plt.legend()
plt.show()

rawDescription: Plotting hyperbolas so that they cross at a certain point


code:
u = User(name="some_name")
u.set_password("some_password")
u.save()

rawDescription: What is the difference between various methods of creating a User object in django?


code:
class foo:
  def __init__ (self):
     self.result_needed = some_function()

  def bar (self):
     a = self.result_needed * 10
     return a

rawDescription: Python class function as attribute?

description: Python class function as attribute


code:
from celery import conf
conf.CELERYD_MAX_TASKS_PER_CHILD is None

rawDescription: python celery max-tasks-per-child-setting default

description: Python celery max-tasks-per-child-setting default


code:
import ctypes

kernel32 = ctypes.WinDLL('kernel32')
user32 = ctypes.WinDLL('user32')

SW_HIDE = 0

hWnd = kernel32.GetConsoleWindow()
if hWnd:
    user32.ShowWindow(hWnd, SW_HIDE)

rawDescription: Hiding the console window after reading input


rawDescription: Concatenating numpy vector and matrix horizontally


code:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import ColumnProperty
from sqlalchemy import event

def check_string_length(cls, key, inst):
    prop = inst.prop
    # Only interested in simple columns, not relations
    if isinstance(prop, ColumnProperty) and len(prop.columns) == 1:
        col = prop.columns[0]
        # if we have string column with a length, install a length validator
        if isinstance(col.type, String) and col.type.length:
            max_length = col.type.length
            def set_(instance, value, oldvalue, initiator):
                if len(value)>max_length:
                    raise ValueError("Length %d exceeds allowed %d" % \
                                            (len(value), max_length))
            event.listen(inst, 'set', set_)

Base = declarative_base()

event.listen(Base, 'attribute_instrument', check_string_length)

rawDescription: SQLAlchemy 0.7 - maximum column length

description: SQLAlchemy 0.7 - maximum column length


code:
import math

class BulletCalc(object):

    def __init__(self, bullet_type, velocity, muzzle_height):
        """
            Class constructor. Should pass the values here """

        self.bullet_type = bullet_type
        self.velocity = velocity
        self.muzzle_height = muzzle_height
        self.gravity = 9.8

    def time_air(self):
        sqrtvalue = 2*self.muzzle_height
        sqrtvalue = sqrtvalue/self.gravity
        timein = math.sqrt(sqrtvalue)
        return timein

    def drop(self):
        final_drop = self.muzzle_height - 1/2
        final_drop = final_drop * self.gravity
        final_drop = final_drop * self.time_air()
        final_drop = final_drop**2
        print(final_drop)

if __name__ == "__main__":
    Fiftyc = BulletCalc(
                        bullet_type = '50 Caliber',
                        velocity = 928.0,
                        muzzle_height = 0.3 )
    Fiftyc.drop()

rawDescription: How to return a number from a variable in a class

description: Return a number from a variable in a class


code:
mylist = [14,35,37,39,42]
sum(v for i, v in enumerate(mylist)
          if (i > 0 and v - mylist[i-1] <= 3) or
             (i < len(mylist) - 1 and mylist[i+1]-v <= 3))

rawDescription: remove element(s)/numbers from list that are not within x numbers of other numbers in the list

description: Remove element(s)/numbers from list that are not within x numbers of other numbers in the list


code:
import io
from scipy import stats
import pandas as pd

def h2f(df, n):
    list1 = []
    for index, row in df.iterrows():
        mean, std = row['hmean'], row['hstd']
        ff = stats.norm.rvs(loc=mean, scale=std, size=n)
        list1.append(ff)
    return list1

content = '''\
     Name      amax        hmean       hstd         amin
0    Bill    22.924545   22.515861   0.375822    22.110000
1    Bob     26.118182   24.713880   0.721507    23.738400
2    Becky   23.178606   22.722464   0.454028    22.096752'''

df = pd.read_table(io.BytesIO(content), sep='\s+')
df2 = pd.DataFrame(h2f(df, 100))
print(df2)

rawDescription: Iterate through data frame to generate random number in python


rawDescription: Plot horizontal bar chart with "nice alignment" of label


code:
@patch.object(xlwt.Workbook, 'save', return_value=None)
def test_patch_object(mock):
    wb = xlwt.Workbook()
    assert wb.save() == None

@patch('xlwt.Workbook.save', return_value=None)
def test_patch(mock):
    wb = xlwt.Workbook()
    assert wb.save() == None

rawDescription: how to mock internal calls (xlwt)?

description: Mock internal calls (xlwt)


code:
def init(*args):
    global connection
    connection = Connection(*args)
pPool = Pool(initializer=init, initargs=conargs)

rawDescription: Python 2.6: Process local storage while using multiprocessing.Pool


rawDescription: Add item to list if not already exists

description: Add item to list if not already exists


code:
#!python3
import csv
with open('file.csv',newline='') as f:
    r = csv.reader(f)
    data = [line for line in r]
with open('file.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['ColA','ColB'])
    w.writerows(data)

rawDescription: Append a Header for CSV file in Python

description: Append a Header for CSV file in Python


code:
release = ''
latex_elements = { 'releasename': '' }

rawDescription: Cannot remove "Release" appearing in sphinx-doc generated pdf


code:
from sqlalchemy.sql import func
query = session.query(A, func.count(B.service_name))
query = query.outerjoin(B, A.username == B.username)
query = query.group_by(A.username).filter(A.username.like('foo%'))
for (user, user_service_count) in query.all():
    print(user, user_service)

rawDescription: How to use SQLAlchemy addcolumn to include a func.count value

description: Use SQLAlchemy addcolumn to include a func.count value


rawDescription: lxml -- how to change img src to absolute link

description: Lxml -- how to change img src to absolute link


rawDescription: Display a float with two decimal places in Python


code:
def print_input(*args):
    for entry in entries:
        print(entry.get())

entries = [Entry(tk) for _ in range(2)]
for entry in entries:
    entry.pack()

btn = Button(tk, text="Print", command=print_input)

rawDescription: Python Tkinter how to take the input from multiple Entry widgets stored in one variable


code:
with open('example.txt', 'r') as in_file:
    key = None
    sequences = {}

    for line in in_file:
        if '.' in line:
            if key:
                sequences[key] = values
            key = line.split()[1]
            values = []
        else:
            values.append([line[:-1].strip()])
    sequences[key] = values

rawDescription: Add values to a key between string match instances in Python


code: np.linspace(np.pi/(N+1), np.pi, N, endpoint = False)

rawDescription: Exclude enpoints in uniform mesh

description: Exclude enpoints in uniform mesh


rawDescription: Switching Two Values in Dictionary, Keeping Keys Constant


code:
private_key = private_key.replace('-----BEGIN RSA PRIVATE KEY-----', '')
private_key = private_key.replace('-----END RSA PRIVATE KEY-----', '')

rawDescription: Stripping headers and footers

description: Stripping headers and footers


code:
sld_list = re.findall("^.*SLD[0-9]*?=(.*?)$", enom, re.M)
tld_list = re.findall("^.*TLD[0-9]*?=(.*?)$", enom, re.M)
map(lambda x: x[0] + '.' + x[1], zip(sld_list, tld_list))

rawDescription: Regular Expression in Python

description: Regular Expression in Python


code:
import subprocess
p = subprocess.Popen([command, argument1,...], cwd=working_directory)
p.wait()

rawDescription: Command line execution in different folder


code:
find_suffix = re.compile('(.+)(_(\d+)\.\w+)$')
text_list.sort(key = lambda x: (find_suffix.match(x).groups()[0], int(find_suffix.match(x).groups()[2])))

rawDescription: Python sort list by 2 parts of the string


code:
menu = driver.find_element_by_css_selector("")
hidden_submenu = driver.find_element_by_css_selector("")
ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()

rawDescription: Click on invisible button on webpage (google maps)


code: (d in set1) == (newd in set2)

rawDescription: Check if two variables have values from two different sets, the DRY way


code:
from scrapy.http import Request
from scrapy.item import Item, Field
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector

class EpinionsTestItem(Item):
    title = Field()
    star = Field()
    date = Field()
    review = Field()

class MySpider(BaseSpider):
    name = "epinions"
    allow_domains = ["epinions.com"]
    start_urls = ['http://www.epinions.com/reviews/samsung-galaxy-note-16-gb-cell-phone/pa_~1']

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//div[@class="review_info"]')

        for sites in sites:
            item = EpinionsTestItem()
            item["title"] = sites.select('h2/a/text()').extract()
            item["star"] = sites.select('span/a/span/@title').extract()
            item["date"] = sites.select('span/span/span/@title').extract()

            url = sites.select('p/span/a/@href').extract()
            url = str("http://www.epinions.com%s" % str(url)[3:-2])

            yield Request(url=url, callback=self.parse_url2, meta={'item': item})

    def parse_url2(self, response):
        hxs = HtmlXPathSelector(response)

        item = response.meta['item']
        fullReview = hxs.select('//div[@class = "user_review_full"]')
        item["review"] = fullReview.select('p/text()').extract()
        yield item

rawDescription: scrapy: A tiny "spider" in a spider?

description: Scrapy: A tiny "spider" in a spider


code:
import pandas as pd
import glob
import os

path =r'X:\PublicFiles\TradingData\CSV\RealMarkets\Weekly\Futures\Contracts\Corn C'
allFiles = glob.glob(path + "/*.csv")  ##'*' means any file name can be grabbed
df = pd.DataFrame()

for file_ in allFiles:
    names = ['Date', 'Open', 'High', 'Low', 'Close', 'Vol', 'OI']
    df_temp = pd.read_csv(file_, index_col = None, names = names)
    df_temp['beforelast'] = 0
    df_temp.iloc[-2,-1] = 1
    df = df.append(df_temp)

df = df.reset_index(drop=True)

rawDescription: python, pandas and importing multiple csv's into a dataframe

description: Python, pandas and importing multiple csv's into a dataframe


code:
from tkinter import *
from tkinter import ttk
import glob
import os

search = '*log'

found_files = []

for dirname, dirnames, filenames in os.walk('/tmp'):
    for i in glob.glob(dirname+'/'+search+'*'):
        print(i)
        found_files.append(i)

root = Tk()
root.geometry( "640x480" );

listbox = Listbox(root)

for a_file in found_files:
    listbox.insert(END, a_file)

listbox.pack(fill=BOTH, expand=YES)

root.mainloop()

rawDescription: how do i display search results in Python Tkinter window

description: Display search results in Python Tkinter window


code:
class OwnedViewSet(viewsets.ModelViewSet):
    ''' ModelViewSets that use hyperlinked model serializers
        can inherit this to automatically
        set `owner` = current user.
    '''
    def create(self, request, *args, **kwargs):
        serialized_owner = UserSerializer(request.user, context={'request': request})
        request.data['owner'] = serialized_owner.data['url']
        return super(OwnedViewSet, self).create(request, *args, **kwargs)

rawDescription: Django Rest Framework: Find URL for hyperlinked model


code:
import xmltodict
import json

json.dumps(xmltodict.parase(txt))

rawDescription: How do I parse Xml in a textarea using python and return json?

description: Parse Xml in a textarea using python and return json


code:
str = """ Your HTML String here"""

pattern = re.compile(r"""Device Time:([ \d\-:]*)""")
s = pattern.search(str)

time = s.group(1)

rawDescription: Python - regex matching in HTML Body

description: Python - regex matching in HTML Body


code:
import fcntl, os
fcntl.fcntl(your_process.stdout, fcntl.F_SETFL, os.O_NONBLOCK)

rawDescription: how do I read everything currently in a subprocess.stdout pipe and then return?

description: Read everything currently in a subprocess.stdout pipe and then return


code:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.exceptions import CloseSpider
from scrapy.http import Request
from test.items import CraigslistSampleItem
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor

URL = "http://example.com/subpage/%d"

class MySpider(BaseSpider):
  name = "craig"
  allowed_domains = ["xyz.com"]

  def start_requests(self):
      for i in range(10):
          yield Request(URL % i, callback=self.parse)

  def parse(self, response):
      titles = response.xpath("//div[@class='thumb']")
      if not titles:
            raise CloseSpider('No more pages')
      for title in titles:
          item = CraigslistSampleItem()
          item ["title"] = title.xpath("./a/@title").extract()
          item ["url"] = title.xpath("./a/@href").extract()
          yield item

rawDescription: how to output multiple webpages crawled data into csv file using python with scrapy

description: Output multiple webpages crawled data into csv file using python with scrapy


code:
image = Image.open(...)
rotated = image.rotate(degrees, Image.BICUBIC, True)

aspect_ratio = float(image.size[0]) / image.size[1]
rotated_aspect_ratio = float(rotated.size[0]) / rotated.size[1]
angle = math.fabs(degrees) * math.pi / 180

if aspect_ratio < 1:
    total_height = float(image.size[0]) / rotated_aspect_ratio
else:
    total_height = float(image.size[1])

h = total_height / (aspect_ratio * math.sin(angle) + math.cos(angle))
w = h * aspect_ratio

rawDescription: Cropping rotated image with same aspect ratio


code:
from stocktrace.util import settings
from stocktrace.parse.sinaparser import getMyStock
import time, os, sys, sched

class Monitor(object):
    def __init__(self):
        self.schedule = sched.scheduler(time.time, time.sleep)
        self.interval = settings.POLLING_INTERVAL
        self._running = False

    def periodic(self, action, actionargs=()):
        if self._running:
            self.event = self.scheduler.enter(self.interval, 1, self.periodic, (action, actionargs))
            action(*actionargs)

    def start(self):
        self._running = True
        self.periodic(getMyStock)
        self.schedule.run( )

    def stop(self):
        self._running = False
        if self.schedule and self.event:
            self.schedule.cancel(self.event)

rawDescription: how to cancel python schedule

description: Cancel python schedule


code:
words = ["dog","cat","mouse"]
print(*words)

rawDescription: Variable inputs into a function in Pymongo


code:
from PySide import QtCore

class InvokeEvent(QtCore.QEvent):
    EVENT_TYPE = QtCore.QEvent.Type(QtCore.QEvent.registerEventType())

    def __init__(self, fn, *args, **kwargs):
        QtCore.QEvent.__init__(self, InvokeEvent.EVENT_TYPE)
        self.fn = fn
        self.args = args
        self.kwargs = kwargs

class Invoker(QtCore.QObject):
    def event(self, event):
        event.fn(*event.args, **event.kwargs)

        return True

_invoker = Invoker()

def invoke_in_main_thread(fn, *args, **kwargs):
    QtCore.QCoreApplication.postEvent(_invoker,
        InvokeEvent(fn, *args, **kwargs))

rawDescription: PySide: Easier way of updating GUI from another thread


code:
from Tkinter import *
win = Tk()
button = Button( Frame( win, name = "myframe" ), name = "mybutton" )
win.nametowidget("myframe.mybutton")

rawDescription: Is it possible to search widget by name in Tkinter?


code:
from collections import OrderedDict
o = OrderedDict([("a", 1), ("b", 2)])
# `a` is first; `b` is second.

rawDescription: Displaying the same order of keys which I have in my list of dictionary keys in my output


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

G = nx.Graph()
G.add_edge('a'*50,'b'*50)
nx.draw(G,with_labels=True)
plt.savefig('before.png')
l,r = plt.xlim()
print(l,r)
plt.xlim(l-2,r+2)
plt.savefig('after.png')

rawDescription: networkx graph display using matplotlib- missing labels

description: Networkx graph display using matplotlib- missing labels


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

# Random data
num = 100
xy = np.random.random((2,num)) + 0.01 * np.arange(num)

eigvals, eigvecs = np.linalg.eig(np.cov(xy))

fig, (ax1, ax2) = plt.subplots(nrows=2)
x,y = xy
center = xy.mean(axis=-1)
for ax in [ax1, ax2]:
    ax.plot(x,y, 'ro')
    ax.axis('equal')

for val, vec in zip(eigvals, eigvecs.T):
    val *= 2
    x,y = np.vstack((center + val * vec, center, center - val * vec)).T
    ax2.plot(x,y, 'b-', lw=3)

plt.show()

rawDescription: Estimating aspect ratio of a convex hull


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

fig = plt.figure()
pi  = np.pi
n = 10
x = np.linspace(-pi,pi,100)
y = (1/(2*pi)) + (1/pi)*(sum(np.cos(i * x) for i in xrange(1, n)))

plt.plot(x,y)
plt.show()

rawDescription: For Loop for a Fourier Series Equation

description: For Loop for a Fourier Series Equation


code: numpy.sum(g, axis=0)

rawDescription: Collapse nD numpy array into a 1D array

description: Collapse nD numpy array into a 1D array


code:
s = "These are oranges and apples and pears, but not pinapples or .."
r = re.compile(r'\bAND\b | \bOR\b | \bNOT\b', flags=re.I | re.X)
r.findall(s)

rawDescription: Python regular expression match multiple words anywhere


code:
# Create the dict for the movies object.
id_movies = dict([(m.id, m) for m in movies])

# Get the data in order.
order_movies = [id_movies[i] for i in movie_ids]

rawDescription: How can I create a dictionary of two lists that preserves the order of the first list in the minimum number of queries?

description: Create a dictionary of two lists that preserves the order of the first list in the minimum number of queries


code:
import numpy as np
from pandas import Timestamp

months = range(1, 13)
df['ep0'] = df.opdate.where(df.opdate > Timestamp('20140101'), Timestamp('20140101'))
for month in months:
    colname = 'ep%d' % month
    prev_colname = 'ep%d' % (month - 1)
    df[colname] = df[prev_colname] + np.timedelta64(40, 'D')

rawDescription: python pandas: how to loop over dateframe and add columns

description: Python pandas: how to loop over dateframe and add columns


code:
from lxml import etree

tree = etree.parse("file.xml")
root = tree.getroot()
validityLst = root.xpath('Validity')
validityLineLst = root.xpath('ValidityLine')

rawDescription: Node name from an xml file using lxml

description: Node name from an xml file using lxml


code:
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
from datetime import datetime

# Load in some sample data
bond_yields = np.loadtxt('bond_yields.txt',
                         converters={0: mdates.strpdate2num('%Y-%m-%d')},
                         dtype = {'names': ('date', 'bond_yield'),
                                  'formats': (datetime, float)})
bank_deposits = np.loadtxt('bank_deposits.txt',
                         converters={0: mdates.strpdate2num('%Y-%m-%d')},
                         dtype = {'names': ('date', 'bank_deposits'),
                                  'formats': (datetime, float)})

# Bond yields line is in light blue, bank deposits line in dark red:
bond_yield_color = (0.424, 0.153, 0.090)
bank_deposits_color = (0.255, 0.627, 0.843)

# Set up a figure, and twin the x-axis so we can have two different y-axes
fig = plt.figure(figsize=(8, 4), frameon=False, facecolor='white')
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
# Make sure the gridlines don't end up on top of the plotted data
ax1.set_axisbelow(True)
ax2.set_axisbelow(True)

# The light gray, horizontal gridlines
ax1.yaxis.grid(True, color='0.65', ls='-', lw=1.5, zorder=0)

# Plot the data
l1, = ax1.plot(bank_deposits['date'], bank_deposits['bank_deposits'],
         c=bank_deposits_color, lw=3.5)
l2, = ax2.plot(bond_yields['date'], bond_yields['bond_yield'],
         c=bond_yield_color, lw=3.5)

# Set the y-tick ranges: chosen so that ax2 labels will match the ax1 gridlines
ax1.set_yticks(range(120,280,20))
ax2.set_yticks(range(0, 40, 5))

# Turn off spines left, top, bottom and right (do it twice because of the twinning)
ax1.spines['left'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
# We do want ticks on the bottom x-axis only
ax1.xaxis.set_ticks_position('bottom')
ax2.xaxis.set_ticks_position('bottom')

# Remove ticks from the y-axes
ax1.tick_params(axis='y', length=0)
ax2.tick_params(axis='y', length=0)

# Set tick-labels for the two y-axes in the appropriate colors
for tick_label in ax1.yaxis.get_ticklabels():
    tick_label.set_fontsize(12)
    tick_label.set_color(bank_deposits_color)
for tick_label in ax2.yaxis.get_ticklabels():
    tick_label.set_fontsize(12)
    tick_label.set_color(bond_yield_color)

# Set the x-axis tick marks to two-digit years
ax1.xaxis.set_major_locator(mdates.YearLocator())
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%y'))

# Tweak the x-axis tick label sizes
for tick in ax1.xaxis.get_major_ticks():
    tick.label.set_fontsize(12)
    tick.label.set_horizontalalignment('center')

# Lengthen the bottom x-ticks and set them to dark gray
ax1.tick_params(direction='in', axis='x', length=7, color='0.1')

# Add the line legends as annotations
ax1.annotate(u'private-sector bank deposits, €bn', xy=(0.09, 0.95),
             xycoords='figure fraction', size=12, color=bank_deposits_color,
             fontstyle='italic')
ax2.annotate(u'ten-year government bond yield, %', xy=(0.6, 0.95),
             xycoords='figure fraction', size=12, color=bond_yield_color,
             fontstyle='italic')

# Add an annotation at the date of the first bail-out. relpos=(0,0) ensures
# that the label lines up on the right of a vertical line
first_bailout_date = datetime.strptime('2010-05-02', '%Y-%m-%d')
xpos = mdates.date2num(first_bailout_date)
ax1.annotate(u'FIRST BAIL-OUT', xy=(xpos, 120), xytext=(xpos, 250), color='r',
             arrowprops=dict(arrowstyle='-', edgecolor='r', ls='dashed',
             relpos=(0,0)), fontsize=9, fontstyle='italic')

fig.savefig('fig.png', facecolor=fig.get_facecolor(), edgecolor='none')

rawDescription: Create "The Economist" style graphs from python


code:
registry = {}

class MultiMethod(object):
    def __init__(self, name):
        self.name = name
        self.typemap = {}

    # self = a MultiMethod instance, instance = the object we want to bind to
    def __call__(self, instance, *args):
        types = tuple(arg.__class__ for arg in args) # a generator expression!
        function = self.typemap.get(types)

        if function is None:
            raise TypeError("no match")
        return function(instance, *args)

    def register(self, types, function):
        if types in self.typemap:
            raise TypeError("duplicate registration")
        self.typemap[types] = function

def multimethod(function):
    name = function.__name__
    mm = registry.get(name)
    if mm is None:
        mm = registry[name] = MultiMethod(name)

    types = tuple(function.__annotations__.values())
    mm.register(types, function)
    # return a function instead of a object - Python binds this automatically
    def getter(instance, *args, **kwargs):
        return mm(instance, *args, **kwargs)
    return getter

class A:
    @multimethod
    def foo(self, a: int):
        return "an int", a

a = A()
print( a.foo( 1 ) )

rawDescription: Decorating method (class methods overloading)


code:
def initialize(self):

      self.grid()

      self.entry = Tkinter.Entry(self)
      self.entry.grid(column=0,row=1,sticky='EW')

      label = Tkinter.Label(self, text = "ns lookup")
      button = Tkinter.Button(self,text="Click me !", command = lambda: self.on_button(label))

      label.grid(column=0,row=0,columnspan=2,sticky='EW')
      button.grid(column=1,row=1)

def on_button(self, label):

    ns = self.entry.get()
    label['text'] = ns

rawDescription: printing out something to there gui with Tkinter

description: Printing out something to there gui with Tkinter


code:
import re
f = open('file', 'r')                 # Opens the file for reading
fil = f.read()                        # Read the entire data and store it in a variabl.
f.close()                             # Close the corresponding file
w = open('file', 'w')                 # Opens the file for wrting
w.write(re.sub(r';.*', r'', fil))     # Replaces all the chars from `;` upto the last with empty string.
w.close()

rawDescription: Python: is there any way this code can write to my file while replacing its contents?


code:
def interlace(imgL, imgR, h, w):
    inter = np.empty((h, w, 3), imgL.dtype)
    inter[:h:2, :w, :] = imgL[:h:2, :w, :]
    inter[1:h:2, :w, :] = imgL[1:h:2, :w, :]
    return inter.astype(np.float32) / 255

rawDescription: how to create an interlaced rows images with python and openCv

description: Create an interlaced rows images with python and openCv


code:
image = Image.new("RGBA", (600,150), (255,255,255))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("resources/HelveticaNeueLight.ttf", fontsize)

draw.text((10, 0), txt, (0,0,0), font=font)
img_resized = image.resize((188,45), Image.ANTIALIAS)

rawDescription: Python Imaging Library - Text rendering

description: Python Imaging Library - Text rendering


code:
st_st= "IJUYIJIJUUIJIJ"
import re
re.findall(r'(?:IJ)+', st_st)
len(re.findall(r'(?:IJ)+', st_st))

rawDescription: Python - Count consecutive string but exclude repeated values


code:
import ftputil

host = ftputil.FTPHost(constants.FTP_HOST, constants.FTP_LOGIN, constants.FTP_PASS)
host.makedirs(path)
host.close()

rawDescription: Is there an FTP equivalent of Python's makedirs()?


code:
import tkinter as tk
import tkinter.scrolledtext as st
import random

colors = ['red', 'blue', 'yellow', 'orange', 'green']

root = tk.Tk()
#Or set initial state to disabled and toggle state as needed for inserts
a_text_widget = st.ScrolledText(root)
for i in range(500):
    a_text_widget.insert("1.0", "Some Random Text Inserted Here")
a_text_widget['state'] = 'disabled'
a_text_widget.pack(fill=tk.BOTH, expand=1)
for i in range(10):
    a_frame = tk.Frame(root, bg=random.choice(colors), padx=1, pady=1)
    tk.Label(a_frame, text='A Text Label').pack()
    a_frame.pack(side=tk.LEFT)
root.mainloop()

rawDescription: What is a good simple text display widget and how to add borders to diffrent widgets


code:
#!/usr/bin/python

from selenium import webdriver
import time

def main():
    browser = webdriver.Chrome()
    browser.set_window_size(1000, 1000)
    browser.get("http://stackoverflow.com/users/1953475/b-mr-w")

    browser.execute_script("$('#content').css('zoom', 5);")
    time.sleep(5)

    browser.get_screenshot_as_file('screenshot.png')

if __name__ == '__main__':
    main()

rawDescription: Python Selenium Change Texts Size (Zoom?Setting?...)


rawDescription: Reverse elements in dictionary

description: Reverse elements in dictionary


code:
class Reservation(models.Model):
     resource = models.ForeignKey(Resource)
     date = models.DateField()
     hour = models.PositiveSmallIntegerField()

     class Meta:
         unique_together = ('resource', 'date', 'hour')

rawDescription: Attaining uniqueness through 3 columns in Django


code:
with open("bind.txt") as f:
    contents = f.read()
    main_label.text = contents # main_label is an instance of kivy's Label class.

rawDescription: How to load string from text file to kivy label, Python 3.5

description: Load string from text file to kivy label, Python 3.5


code: filtered = [x for x in set(lst) if x < C]

rawDescription: What is the most Pythonic way to filter a set?


code: len(data) - numpy.count_nonzero(data)

rawDescription: Finding number of zero elements in data

description: Finding number of zero elements in data


code:
users.store([
    {'name': 'Charlie', 'color': 'green'},
    {'name': 'Huey', 'color': 'white'},
    {'name': 'Mickey', 'color': 'black'}])
users.store({'name': 'Leslie', 'color': 'also green'})
users.fetch(0)  # Fetch the first record.
users.delete(0)  # Delete the first record.
users.delete(users.last_record_id())  # Delete the last record.
users.all()
users.filter(lambda obj: obj['name'].startswith('H'))

rawDescription: Reading collection from UnQLite?

description: Reading collection from UnQLite


code:
import string

chars = []

with open("notes.txt", "r") as f:
    for c in f.read():
        chars.append(c)

num_chars = len(chars)

num_upper = 0;
num_vowels = 0;
num_letters = 0

vowels = "aeiouAEIOU"
for c in chars:
    if c in vowels:
        num_vowels += 1
    if c in string.ascii_uppercase:
        num_upper += 1
    if c in string.ascii_letters:
        num_letters += 1

print(num_chars)
print(num_letters)
print(num_upper)
print(num_vowels)

rawDescription: counting letters in a text file in python

description: Counting letters in a text file in python


rawDescription: Scrapy returns unicode - how to convert to a string?


code:
def storefront(request):
    if request.GET.get('enki') == '0011':
        request.session['from_main_site'] = True
        return redirect('storefront')
    elif not request.session.get('from_main_site'):
        return redirect('http://main-site.com/')

    # at this point the user has come from the main site
    # and doesn't have "enki" in the url

    return render(request, 'storefront.html')

rawDescription: How to rewrite url in django

description: Rewrite url in django


code:
from itertools import groupby
from operator import itemgetter
from collections import deque

with open('/home/jon/testdata.txt') as fin:
    lines = (line.split() for line in fin)
    for k, g in groupby(lines, itemgetter(0)):
        fst = next(g)
        lst = next(iter(deque(g, 1)), fst)
        with open(k + '.txt', 'w') as fout:
            fout.write(fst[1] + ' ' + lst[2])

rawDescription: How to delete duplicate values and write to different files?

description: Delete duplicate values and write to different files


code:
env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:include',
                CPPDEFINES=[],
                LIBS=['glib-2.0'])

if ARGUMENTS.get('debug', 0):
    env.Append(CCFLAGS = ' -g')

env.Program('template', Glob('src/*.cc'))

rawDescription: scons : src and include dirs

description: Scons : src and include dirs


code: result = map(list, zip(*test))

rawDescription: In python, trying to combine elements from a list of lists into a new list of combined-element lists


rawDescription: How can I compare two ordered lists in python?

description: Compare two ordered lists in python


code: from mydatabase.model import *

rawDescription: Working with multiple code files and folders in Python


rawDescription: Efficiently replacing pixel values in R,G,B planes python-openCV


code:
from urllib import quote_plus as urlquote
from sqlalchemy.engine import create_engine
engine = create_engine('postgres://user:%s@host/database' % urlquote('badpass'))

rawDescription: Writing a connection string when password contains special characters


code:
with open(filename, 'a') as out:
    out.write(var + '\n')

rawDescription: How to write to .txt files in Python 3

description: Write to .txt files in Python 3


code:
def divisorGen(n):
    factors = list(factorGenerator(n))
    nfactors = len(factors)
    f = [0] * nfactors
    while True:
        yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
        i = 0
        while True:
            f[i] += 1
            if f[i] <= factors[i][1]:
                break
            f[i] = 0
            i += 1
            if i >= nfactors:
                return

rawDescription: What is the best way to get all the divisors of a number?


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(0, 5)
Y = np.arange(0, 5)
X, Y = np.meshgrid(X, Y)
Z = [[  3.,   6.,   4.,   0.,  10.],
    [  1.,   9.,   4.,  18.,  13.],
    [  5.,   6.,   4.,   1.,   0.],
    [  5.,   5.,   6.,   3.,   3.],
    [ 19.,   9.,   6.,   5.,   5.]]

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
ax.set_zlim(0, 20)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

rawDescription: How to plot a surface chart from a array of frequency

description: Plot a surface chart from a array of frequency


code:
class GameCompany(Base):
    id = Column(Integer, primary_key=True)
    company_id = Column(ForeignKey('games.id'))
    # ...

class Games(Base):
    __tablename__ = 'games'
    id = Column(Integer, primary_key=True)
    # ...
    publishers = relationship(GameCompany,
        primaryjoin=and_(GameCompany.game_id == id, GameCompany.role == 'publisher'))
    developers = relationship(GameCompany,
        primaryjoin=and_(GameCompany.game_id == id, GameCompany.role == 'developer'))

rawDescription: SQL Alchemy relationship with `where` clause


code:
date = datetime.datetime.today()
date += datetime.timedelta(days=9)
url = 'http://www.opentable.com/s/PopRestaurantList?covers=2&currentview=list&datetime={date}+19%3A00&metroid=15&onlypoptimes=true&personalizer=true&ref=2213&showmap=false&size=100&sort=Popularity'
html = urlopen(url.format(date=date.strftime('%Y-%m-%d')))

rawDescription: Automatically scraping a dynamic URL that has a date 9 days in the future


code:
from matplotlib.widgets import AxesWidget

class VertSlider(AxesWidget):
    """
    A slider representing a floating point range

    The following attributes are defined
      *ax*        : the slider :class:`matplotlib.axes.Axes` instance

      *val*       : the current slider value

      *vline*     : a :class:`matplotlib.lines.Line2D` instance
                     representing the initial value of the slider

      *poly*      : A :class:`matplotlib.patches.Polygon` instance
                     which is the slider knob

      *valfmt*    : the format string for formatting the slider text

      *label*     : a :class:`matplotlib.text.Text` instance
                     for the slider label

      *closedmin* : whether the slider is closed on the minimum

      *closedmax* : whether the slider is closed on the maximum

      *slidermin* : another slider - if not *None*, this slider must be
                     greater than *slidermin*

      *slidermax* : another slider - if not *None*, this slider must be
                     less than *slidermax*

      *dragging*  : allow for mouse dragging on slider

    Call :meth:`on_changed` to connect to the slider event
    """
    def __init__(self, ax, label, valmin, valmax, valinit=0.5, valfmt='%1.2f',
                 closedmin=True, closedmax=True, slidermin=None,
                 slidermax=None, dragging=True, **kwargs):
        """
        Create a slider from *valmin* to *valmax* in axes *ax*

        *valinit*
            The slider initial position

        *label*
            The slider label

        *valfmt*
            Used to format the slider value

        *closedmin* and *closedmax*
            Indicate whether the slider interval is closed

        *slidermin* and *slidermax*
            Used to constrain the value of this slider to the values
            of other sliders.

        additional kwargs are passed on to ``self.poly`` which is the
        :class:`matplotlib.patches.Rectangle` which draws the slider
        knob.  See the :class:`matplotlib.patches.Rectangle` documentation
        valid property names (e.g., *facecolor*, *edgecolor*, *alpha*, ...)
        """
        AxesWidget.__init__(self, ax)

        self.valmin = valmin
        self.valmax = valmax
        self.val = valinit
        self.valinit = valinit
        self.poly = ax.axhspan(valmin, valinit, 0, 1, **kwargs)

        self.vline = ax.axhline(valinit, 0, 1, color='r', lw=1)

        self.valfmt = valfmt
        ax.set_xticks([])
        ax.set_ylim((valmin, valmax))
        ax.set_yticks([])
        ax.set_navigate(False)

        self.connect_event('button_press_event', self._update)
        self.connect_event('button_release_event', self._update)
        if dragging:
            self.connect_event('motion_notify_event', self._update)
        self.label = ax.text(0.5, 1.03, label, transform=ax.transAxes,
                             verticalalignment='center',
                             horizontalalignment='center')

        self.valtext = ax.text(0.5, -0.03, valfmt % valinit,
                               transform=ax.transAxes,
                               verticalalignment='center',
                               horizontalalignment='center')

        self.cnt = 0
        self.observers = {}

        self.closedmin = closedmin
        self.closedmax = closedmax
        self.slidermin = slidermin
        self.slidermax = slidermax
        self.drag_active = False

    def _update(self, event):
        """update the slider position"""
        if self.ignore(event):
            return

        if event.button != 1:
            return

        if event.name == 'button_press_event' and event.inaxes == self.ax:
            self.drag_active = True
            event.canvas.grab_mouse(self.ax)

        if not self.drag_active:
            return

        elif ((event.name == 'button_release_event') or
              (event.name == 'button_press_event' and
               event.inaxes != self.ax)):
            self.drag_active = False
            event.canvas.release_mouse(self.ax)
            return

        val = event.ydata
        if val <= self.valmin:
            if not self.closedmin:
                return
            val = self.valmin
        elif val >= self.valmax:
            if not self.closedmax:
                return
            val = self.valmax

        if self.slidermin is not None and val <= self.slidermin.val:
            if not self.closedmin:
                return
            val = self.slidermin.val

        if self.slidermax is not None and val >= self.slidermax.val:
            if not self.closedmax:
                return
            val = self.slidermax.val

        self.set_val(val)

    def set_val(self, val):
        xy = self.poly.xy
        xy[1] = 0, val
        xy[2] = 1, val
        self.poly.xy = xy
        self.valtext.set_text(self.valfmt % val)
        if self.drawon:
            self.ax.figure.canvas.draw()
        self.val = val
        if not self.eventson:
            return
        for cid, func in self.observers.iteritems():
            func(val)

    def on_changed(self, func):
        """
        When the slider value is changed, call *func* with the new
        slider position

        A connection id is returned which can be used to disconnect
        """
        cid = self.cnt
        self.observers[cid] = func
        self.cnt += 1
        return cid

    def disconnect(self, cid):
        """remove the observer with connection id *cid*"""
        try:
            del self.observers[cid]
        except KeyError:
            pass

    def reset(self):
        """reset the slider to the initial value if needed"""
        if (self.val != self.valinit):
            self.set_val(self.valinit)

rawDescription: Add a vertical slider with matplotlib

description: Add a vertical slider with matplotlib


code:
class Metnadev(DeclarativeBase):
    #...
    @property
    def activities(self):
        return object_session(self).query(Activity).filter_by(visible=True).with_parent(self).all()

rawDescription: Sqlalchemy - how to get an object, and filter which rows in the child class


code:
import re
non_word = re.compile(r'\W+') # If your sentences may
sentence = '''The formatting sucks, but the only change that I've made to your code was shortening the "symbols" string to one character. The only issue that I can identify is either with the "symbols" string (though it looks like all chars in it are properly escaped) that you used, or the punctuation is not actually separate words'''
words = re.split(non_word, sentence)
words

rawDescription: Python 2.7 : Remove elements from a multidimensional list


code:
from PIL import Image
from PIL import ImageOps
img = Image.open('img.png')
img_with_border = ImageOps.expand(img, border=1, fill='black')
img_with_border.save('img-with-border.png')

rawDescription: Frame around inline images

description: Frame around inline images


code:
import sys
from gzip import GzipFile

class MyStream(object):
    def write(self, data):
        #write to your stream...
        sys.stdout.write(data) #stdout, for example

gz= GzipFile( fileobj=MyStream(), mode='w'  )
gz.write("something")

rawDescription: Generate zip stream without using temp files


code:
import collections

colorCounts = collections.defaultdict(int, collections.Counter(input("cars: ").lower().split()))
needed = 'red blue'.split()
for n in needed:
    print("{}:".format(n), colorCounts[n])

rawDescription: How to find how many words there are in python?

description: Find how many words there are in python


code:
from IPython.core.inputtransformer import CoroutineInputTransformer, _strip_prompts

@CoroutineInputTransformer.wrap
def my_prompt():
    prompt_re = re.compile(r'foo')
    return _strip_prompts(prompt_re)

ip = get_ipython()
ip.input_splitter.physical_line_transforms.insert(0, my_prompt())
ip.input_transformer_manager.physical_line_transforms.insert(0, my_prompt())

rawDescription: Preserving ipython's input prompt filtering in customized prompts


code:
# Perform the pivot.
df = df.pivot_table(
    values='value',
    index=['stream_name', 'preferred_timestamp', 'internal_timestamp'],
    columns='value_id'
    )

# Formatting.
df.reset_index(inplace=True)
df.columns.name = None

rawDescription: Python Pandas: pivot only certain columns in the DataFrame while keeping others


code:
with open("file1") as f1:
    with open("file2") as f2:
        for line1, line2 in zip(f1, f2):
            items1 = line1.split()
            items2 = line2.split()
            sums = ["({}+{})".format(i1, i2) for i1, i2 in zip(items1, items2)]
            print(" ".join(sums))

rawDescription: Sum two files column by column in python


code:
def delete_song(self, id):
    song = self.get_song(id)
    song['apikey'] = self.API
    r = requests.delete(self.SONG_URL + str(id), data=json.dumps(song))

rawDescription: Python: delete function with requests & json


code:
for attr in dir(project):
    if not attr.startswith("_"):
        globals()[attr] = getattr(project, attr)

rawDescription: Import object attributes as global variables


code:
def testcallback(obj, callback):
    getattr(obj, callback)()

rawDescription: how do you call arbitrary object methods from a standalone function python

description: Call arbitrary object methods from a standalone function python


code:
def exportEFS(self):
  self.exportGUI = Toplevel()
  Button(self.exportGUI, text='Backup', command=self.backup).pack(padx=100,pady=5)
  Button(self.exportGUI, text='Restore', command=self.restore).pack(padx=100,pady=5)

def backup(self):
  self.backupWindow = Toplevel()
  self.backupWindow.grab_set()

  message = "Enter a name for your Backup."

  Label(self.backupWindow, text=message).pack()

  self.entry = Entry(self.backupWindow,text="enter your choice")
  self.entry.pack(side=TOP,padx=10,pady=12)

  self.button = Button(self.backupWindow, text="Backup",command=self.backupCallBack)
  self.button.pack(side=BOTTOM,padx=10,pady=10)

rawDescription: Python tkinter, how to disable background buttons from being clicked


code:
window.Freeze()
for i in LARGELIST:
    list.SetStringItem(i, 1, str(a))
window.Thaw()

rawDescription: Wxpython textctrl sluggish when using SetStringItem on a loop


code:
filename = ...
with open(filename,'r') as f:
    message = MIMEText(f.read())
    message.add_header('Content-Disposition', 'attachment', filename=filename)
    msg.attach(message)

rawDescription: Sending mail with attachment from Python using SMTP


code:
class EntryTitle(Base):
    __tablename__ = 'entry_title'
    entry_id = Column('entry_id', Integer, primary_key=True)
    title = Column('title', String(155))
    # Assuming this is a one-to-one relationship, so setting uselist to False.
    entry_data = relationship('EntryData', backref='entry_title',
                              uselist=False)

class EntryData(Base):
    __tablename__ = 'entry_data'
    # Simply define this primary key as a foreign key to entry_title table.
    entry_id = Column('entry_id', Integer, ForeignKey('entry_title.entry_id'),
                      primary_key=True)
    body = Column('body', String(255))

# Add new objects to a session.
entry_title = EntryTitle(title='Foo')
entry_title.entry_data = EntryData(body='Bar')
session.add(entry_title)
session.commit()

# Query whole models.
q1 = session.query(EntryTitle, EntryData).join(EntryData)
# Or just the columns you need.
q2 = session.query(EntryTitle.title, EntryData.body).\
    join(EntryData).\
    filter(EntryTitle.entry_id == 42)

rawDescription: SQLAlchemy two identically named primary keys that are also foreign


code:
def get_user_profile(self, access_token, selectors=None, headers=None, **kwargs):
    """
    Get a user profile.  If keyword argument "id" is not supplied, this
    returns the current user's profile, else it will return the profile of
    the user whose id is specificed.  The "selectors" keyword argument takes
    a list of LinkedIn compatible field selectors.
    """

rawDescription: Linkedin API for python

description: Linkedin API for python


code:
c = []

for i in range(len(a)):
    c.append(a[i])
    c.append(b[i])

rawDescription: Python program:How to concatenate two lists so that elements are in alternative position?


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

y1D = np.hstack([0, np.random.random(9)])
y1D = np.sort(y1D)/np.max(y1D)

x, y = np.meshgrid(np.arange(0,1.1,0.1),y1D)

plt.pcolormesh(x,y, np.random.random((10,10)))
plt.show()

rawDescription: Custom scale from simple list or dict?

description: Custom scale from simple list or dict


code:
from os.path import splitext

def get_name():
    while True:
        name = input("File name> ")
        if splitext(name)[1] != '.txt':
            print("Invalid name, give another")
        else:
            return name

filename = get_name()

rawDescription: Transform a local variable into a global variable


code:
from scrapy.spider import Spider
from scrapy.http import Request
from scrapy.exceptions import CloseSpider

class SeekingAlpha(Spider):
    name = "so"
    download_delay = 0.1

    more_pages = True
    next_page = 1

    start_urls = ['http://seekingalpha.com/account/ajax_headlines_content?type=in_focus_articles&page=0'+
                      '&slugs=tsla&is_symbol_page=true']

    allowed_domains = ['seekingalpha.com']

    def create_ajax_request(self, page_number):
        """
        Helper function to create ajax request for next page.
        """
        ajax_template = 'http://seekingalpha.com/account/ajax_headlines_content?type=in_focus_articles&page={pagenum}&slugs=tsla&is_symbol_page=true'

        url = ajax_template.format(pagenum=page_number)
        return Request(url, callback=self.parse)

    def parse(self, response):
        """
        Parsing of each page.
        """
        if "There are no Focus articles on your stocks." in response.body:
            self.log("About to close spider", log.WARNING)
            raise CloseSpider(reason="no more pages to parse")

        # there is some content extract links to articles
        sel = Selector(response)
        links_xpath = "//div[@class='symbol_article']/a/@href"
        links = sel.xpath(links_xpath).extract()
        for link in links:
            url = urljoin(response.url, link)
            # follow link to article
            # commented out to see how pagination works
            #yield Request(url, callback=self.parse_item)

        # generate request for next page
        self.next_page += 1
        yield self.create_ajax_request(self.next_page)

    def parse_item(self, response):
        """
        Parsing of each article page.
        """
        self.log("Scraping: %s" % response.url, level=log.INFO)

        hxs = Selector(response)

        item = NewsItem()

        item['url'] = response.url
        item['source'] = 'seekingalpha'
        item['title'] = hxs.xpath('//title/text()')
        item['date'] = hxs.xpath('//div[@class="article_info_pos"]/span/text()')

        yield item

rawDescription: Scrapy CrawlSpider for AJAX content

description: Scrapy CrawlSpider for AJAX content


code:
from __future__ import print_function
enable_print = 0

def print(*args, **kwargs):
    if enable_print:
        return __builtins__.print(*args, **kwargs)

print('foo') # doesn't get printed
enable_print = 1
print('bar') # gets printed

rawDescription: Efficient way of toggling on/off print statements in Python?


code:
import operator
operator.contains([1,2,3,4,5,6], 5)
operator.contains([1,2,3,4,5,6], 10)

rawDescription: In Python is there a function for the "in" operator


code:
@classmethod
def count_events_per_day(cls, myqueryset, attr_name):
    return myqueryset.filter(**{
        attr_name + '__range': (a, b)
    })

rawDescription: Using name attributes as parameters in Python (Django)


code:
### let's create a file find_strings.py

import os

list = ['the','in','red']
for l in list :
   os.system('grep ' + str(l) + ' fileX.txt')

### after saving the file, run the below command in the console .
### $ python find_strings.py > list_found_strings.txt

rawDescription: Selecting lines of a file specified by a list of strings


code:
import Image, pickle, cStringIO

i = open('button_home.gif', 'rb')
i.seek(0)
w = i.read()
i.close()
dic = {'1':w,'2':w,'3':w,'4':w}

F=open('allicons.dat','w')
pickle.dump(dic,F)
F.close()

#Ok now you take your pickled string and unpickle your object and select
#the item you want and put it in a cStringIO or StringIO so we can open
#it directly with PIL.
F=open('allicons.dat','r')
o=pickle.load(F)
F.close()

one_im = o['1']
c = cStringIO.StringIO()
c.write(one_im)
c.seek(0)
im = Image.open(c)
im.show()

rawDescription: python: container to memorize a large number of images

description: Python: container to memorize a large number of images


code:
def print_console():
    print(console.get("1.0", "end-1c"))
    main.after(1000, print_console)

print_console()

main.mainloop()

rawDescription: How can I perform an action after mainloop() has been called in Tkinter?

description: Perform an action after mainloop() has been called in Tkinter


code:
def get_thread(msg):
    messages = [] # empty message set

    while msg.response_to:
         messages.append(msg)
         msg = msg.response_to

    messages.append(msg) # will append the original message

    return messages

rawDescription: recursive function for a django model instance

description: Recursive function for a django model instance


code:
from threading import Thread
import time
import gtk, gobject, urllib

URL = 'http://releases.ubuntu.com//precise/ubuntu-12.04.1-desktop-i386.iso'

def download(url):
    filename = url.split('/')[-1]
    out = open(filename, 'wb')
    gobject.idle_add(label.set_text, "connecting...")
    f = urllib.urlopen(url)
    buffer = f.read(1024)
    counter = 0
    while buffer:
        counter += len(buffer)
        out.write(buffer)
        msg = "downloaded {0:,} bytes".format(counter)
        gobject.idle_add(label.set_text, msg)
        buffer = f.read(1024)
    out.close()
    gobject.idle_add(label.set_text, "download complete")

def clicked(button):
    url = entry.get_text()
    Thread(target=download, args=(url,)).start()

gtk.gdk.threads_init()
win = gtk.Window()
win.set_default_size(400, 100)
entry = gtk.Entry()
entry.set_text(URL)
label = gtk.Label("Press the button")
button = gtk.Button(label="Download")
button.connect('clicked', clicked)

box = gtk.VBox()
box.pack_start(entry)
box.pack_start(label)
box.pack_start(button)
win.add(box)

win.show_all()

gtk.main()

rawDescription: Why can't I view updates to a label while making an HTTP request in Python


code:
m = max(a)
max_pos = [i for i, j in enumerate(a) if j == m]
random.choice(max_pos)

rawDescription: Retrieve List Position Of Highest Value?

description: Retrieve List Position Of Highest Value


rawDescription: Reflection in Python: how to view all parameter of a function in Python 2.7


code:
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.minsize(300, 300)
root.geometry("1000x700")

s = ttk.Style()
s.configure('TNotebook', tabposition='ne') #'ne' as in compass direction

box = ttk.Notebook(root, width=1000, height=650)

tab1 = tk.Frame(root)
tab2 = tk.Frame(root)
tab3 = tk.Frame(root)

box.add(tab1, text="tab1")
box.add(tab2, text="tab2")
box.add(tab3, text="tab3")

box.pack(side=tk.TOP)

root.mainloop()

rawDescription: Align tabs from right to left using ttk.Notebook widget


code:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.errorhandler(404)
def page_not_found(error):
    return 'This page does not exist', 777

if __name__ == '__main__':
    app.run()

rawDescription: Flask custom "not found" code

description: Flask custom "not found" code


code:
def __init__(self, frame):
    self.frame = frame
    ...
    self.frame.after(1000, self.update)

def update(self):
    ...
    self.frame.after(1000, self.update)

rawDescription: Python Tkinter after() Only Executing Once


code:
setup(
    install_requires=['python-daemon >= 1.5']
)

rawDescription: Python: setup.py - want to make sure the correct version of python-daemonize is installed


code:
self.grid.opacity = 0
anim = Animation(opacity=1)
anim.start(self.grid)

rawDescription: Float comparison (1.0 == 1.0) always false


code:
text = """
Pellentesque habitant morbi tristique senectus et netus et
lesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae
ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam
egestas
semper
tizi ouzou
Tizi Ouzou
       """

res = text.rsplit('
', 2)[-2]
#Tizi Ouzou

rawDescription: Match last occurence with regex

description: Match last occurence with regex


code:
class Name(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text) # or varchar

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name_id = db.Column(db.Integer, db.ForeignKey('name.id'))

    _name = db.relationship('Name')

    @property
    def name(self):
        return self._name.name

rawDescription: SQLAlchemy - select data associated with foreign key, NOT the foreign key itself


code:
status_list = api.user_timeline(user_handler)
status = status_list[0]
json_str = json.dumps(status._json)

rawDescription: Convert Tweepy Status object into JSON

description: Convert Tweepy Status object into JSON


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.clock import Clock

Builder.load_string("""
<MyWidget>:
    MyTextInput:
    MyTextInput:
""")

class MyTextInput(TextInput):
    def copy(self, data=''):
        # wrap copied text with ---
        if data:
            data = "--- {} ---".format(data)
        else:
            data = "--- {} ---".format(self.selection_text)
        return super(MyTextInput, self).copy(data)

class MyWidget(BoxLayout):
    pass

class ClientApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    ClientApp().run()

rawDescription: Kivy on_copy event?

description: Kivy on_copy event


code:
n = 'my fancy extension'
array = n.split()
array[0] + ''.join(map(str.capitalize, array[1:]))

rawDescription: except first item in list - python

description: Except first item in list - python


code: min(filter(None, [1, 2, 0, None, 5, False]))

rawDescription: Find the lowest value that is not null using python


code:
def socketCom(comSocket, length, message, time):
    comSocket.send(message)
    comSocket.settimeout(8)
    if (time != 0):
        sleep(time)
    try:
        rawData = comSocket.recv(length)
    except socket.timeout:
        errorLog("[COM. ERROR] Station took too long to reply. \n")
        comSocket.shutdown(1)
        comSocket.close()
        sys.exit(0)

    return rawData

rawDescription: Python: Passing socket by reference

description: Python: Passing socket by reference


code: dense = X.toarray()

rawDescription: How to make TF-IDF matrix dense?

description: Make TF-IDF matrix dense


code:
import inspect
from datetime import datetime
now = datetime.now()
inspect.getmembers(now)

rawDescription: Listing Class Attributes and Their Types in Python


code:
for i in range(len(cell_list)):
    print (cell_list[i] + ": " + cell_data[i])

rawDescription: Iterating over two lists at the same time in Python


rawDescription: Python: removing everything including and after a certain character on a line


code:
def createSocket(ip): # return the new socket object
    s = socket.socket()
    s.connect((ip, 55555))
    return s

addresses=[ip, ip2, ip3, ...]
sockets=[createSocket(addr) for addr in addresses]

sock = chooseSocket(sockets) # pick one (somehow)
sock.send(data)              # use the selected socket

rawDescription: Create required number of sockets during execution


rawDescription: Pandas: How do I make a dataframe manually calculate missing values by averaging adjacent values?


code:
from collective.transmogrifier.interfaces import ISection
from collective.transmogrifier.interfaces import ISectionBlueprint

import itertools

class DoSomethingAtTheVeryEndSection(object):

    classProvides(ISectionBlueprint)
    implements(ISection)

    def __init__(self, transmogrifier, name, options, previous):
        self.previous = previous

    def __iter__(self):
        self.previous, self.postprocess = itertools.tee(self.previous)
        for item in self.previous:
            yield item

        for item in self.postprocess:
            do_something()

rawDescription: It is possible to run a transmogrifier section after all other have completely run?


code: xCoords = [i[0] for i in Coords]

rawDescription: Retrieving specific entries in Nested Lists


code:
import sys
import subprocess as subp

if logged_in == True:
    subp.call([sys.executable, "someprogram.py", "arg1", "arg2"])

rawDescription: How can i launch a new .py file from a python script

description: Launch a new .py file from a python script


code:
from rpy2.robjects.lib import ggplot2
from rpy2.robjects import r
from rpy2.robjects.packages import importr

scales = importr('scales')

iris = r('iris')

p = ggplot2.ggplot(iris) + \
    ggplot2.geom_point(ggplot2.aes_string(x="Sepal.Length", y="Sepal.Width")) + \
    ggplot2.scale_x_continuous(trans = scales.log2_trans())

p.plot()

rawDescription: Using log axes scales in ggplot from Rpy2


rawDescription: numpy.array.__iadd__ and repeated indices

description: Numpy.array.__iadd__ and repeated indices


code: reversed_df = df.iloc[::-1]

rawDescription: reverse dataframe's rows' order with pandas

description: Reverse dataframe's rows' order with pandas


code:
for couple in findreplace:
    s = s.replace(couple[0],couple[1])

s = re.compile('Title: (.*)', re.I).sub(r'\\title {\1}', s)
s = re.compile('Author: (.*)', re.I).sub(r'\\author {\1}', s)
s = re.compile('Date: (.*)', re.I).sub(r'\\date {\1}', s)

rawDescription: Please help me optimize my Python code

description: Please help me optimize my Python code


code:
aa = (d3 for dd in (d for _,d in dummy.iteritems()) for d3 in dd)
next(aa)
next(aa)
next(aa)
next(aa)
next(aa)
next(aa)
next(aa)
next(aa)
next(aa)
next(aa)

rawDescription: Misunderstanding about nested generator comprehension over a dictionary


code:
class SomeObject(TableModel):
    __tablename__ = 'some_table'

    id = UnsignedInteger64(pk=True)
    updated_at = DateTime(server_default=func.now(), onupdate=func.now())
    some_data = Unicode

class SomeWriteObject(TableModel):
    __tablename__ = 'some_table'

    id = UnsignedInteger64(pk=True)
    some_data = Unicode

# or, you could do this:
class SomeWriteObject(TableModel):
    __tablename__ = 'some_table'
    _type_info = [ (k,v) for k,v in SomeObject._type_info.items()
                                                  if not k in ('updated_at',) ]
class SomeService(ServiceBase):
    @rpc(SomeWriteObject, _returns=UnsignedInteger64)
    def add_some_object(ctx, obj):
        ctx.udc.session.add(obj)
        ctx.udc.session.commit()
        return obj.id

rawDescription: Set up spyne to skip a field which is not present in SOAP request?


code:
import csv
from pylab import *
from itertools import groupby

def by_hour(value):
    return value[0] // 3600

def plot_data_for(data, map_, reduce_):
    keys = []
    values = []
    for k,v in groupby(data, key=map_):
        keys.append(k)
        values.append(reduce_(v))
    return (keys, values)

times = []
requests = []
reader = csv.reader(open("results.csv"))

for row in reader:
    times.append(int(row[0]))
    requests.append(int(row[1]))

increments = map(lambda x: x[1] - x[0], zip(requests, requests[1:] + [requests[-1]]))
plot(*plot_data_for(zip(times, increments), by_hour, lambda values: sum(map(lambda x: x[1], values))))

rawDescription: Requests per second, per hour, per day out of a time series


code:
class EntityWeight(Base):
    __tablename__ = "entity_weights"
    id = Column(Integer, primary_key=True)
    parent_entity_id = Column(Integer, ForeignKey('entity.id'))
    entity_id = Column(Integer, ForeignKey('entity.id'))
    weight = Column(Float)
    entity = relationship("Entity", primaryjoin=lambda: EntityWeight.entity_id == Entity.id)

class Entity(Base):
    ...
    _child_weights = relationship(EntityWeight, primaryjoin=id == EntityWeight.parent_entity_id)
    child_weights = association_proxy("_child_weights", "weight")
    child_entities = association_proxy("_child_weights", "entity")

rawDescription: Self referential relationship including a relationship attribute


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import PatchCollection
from matplotlib.patches import Wedge, Circle
from math import degrees, pi

fig, ax = plt.subplots()
wedges = []
circles = []

for x in np.arange(0, 3.3, .3):
    for y in np.arange(0, 3.3, .3):
        theta, phi = np.random.random(2)  # functions of (x,y) in reality
        for v in (0, pi):
            wedges.append(Wedge((x, y),
                            .15,
                            degrees(v - phi - theta/2),
                            degrees(v - phi + theta/2),
                            edgecolor='none'),
                            )
        circles.append(Circle((x, y),
                             .15,
                             edgecolor='none'))

colors = np.linspace(0, 1, len(circles))  # function of (x,y) in reality
collection = PatchCollection(circles, cmap=plt.cm.jet, alpha=0.2)
collection.set_array(np.array(colors))
collection.set_edgecolor('none')
ax.add_collection(collection)

#wedgecolors = list(chain.from_iterable(repeat(i,2) for i in colors))
wedgecolors = np.array([colors, colors]).flatten('F') # no itertools
collection = PatchCollection(wedges, cmap=plt.cm.jet, alpha=1)
collection.set_array(np.array(wedgecolors))
collection.set_edgecolor('none')
ax.add_collection(collection)

ax.set_xlim(0,3)
ax.set_ylim(0,3)
ax.set_aspect('equal')
plt.show()

rawDescription: Draw a plot of glyphs in Matplotlib

description: Draw a plot of glyphs in Matplotlib


code:
import requests

url = 'https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewMultiRoom?cc=us&fcId=363484947'
headers = {
    'X-Apple-Store-Front': '143441-1,12',
    'X-Apple-Tz': '3600',
}

requests.get(url, headers=headers)

rawDescription: Convert curl command to requests

description: Convert curl command to requests


code:
def edit_form(self):
    form = model_form(BulkMessage)

    form.source_address = SelectField(
        'Source Address',
        choices=[(sa.id, sa.title) for sa in SourceAddress.select().where(SourceAddress.owner == current_user.id)]
    )

    return form(obj=obj)

rawDescription: Flask-Admin: Custom Query for Select Field with Peewee?


code:
csv_file = 'similarweb/domains.csv'

final_result = ""
with open(csv_file, 'r') as csv_read_file:
    reader = csv.reader(csv_read_file)
    for i, line in enumerate(reader):
        url = ', '.join(str(e) for e in line)
        final_result += url + " " + (content_client.category(url)['Category']) + "\n"

with open(csv_file, 'w') as csv_write_file:
    csv_write_file.write(final_result)

rawDescription: Export processed text in a csv file in Python


code:
from rfc3987 import parse

parse('http://fdasdf.fdsfîășîs.fss/ăîăî', rule='IRI')

rawDescription: Python: How to check if a string is a valid IRI?


code:
import sys,inspect,os
_logLevel = 10
def debugPrint(*args,**kwargs):
    if _logLevel > kwargs.get('required_level',0):
        args = list(args)
        info = inspect.stack()[1]
        info = tuple([os.path.basename(info[1]),info[2]])
        args.insert(0,"%s %s:"%info)
        sys.stdout.write(" ".join("%s"%arg for arg in args))

debugPrint("Hello world!")

rawDescription: Python : which importing module is calling my function at runtime


code:
from numpy import *
count_total = array((0,0))
count_total += (1,2)
count_total

rawDescription: Not possible to do (a, b) += (1, 2) in python?


code:
import csv
filenames = (
    'file2010.csv',
    'file2011.csv',
    'file2012.csv',
    'file2013.csv',
    'file2014.csv'
)

outF = open('fileAll.csv', 'wb')
csvF_out = csv.writer(outF, delimiter=',')

def extract_content(filename):
    return [("0","1","boy"),("2","3","girl")]

for filename in filenames:
    name, ext = filename.split('.')
    year = name[-4:]
    result = extract_content(filename)
    for row in result:
        csvF_out.writerow((year,)+row)

outF.close()

#  fileall.csv:
# 2010  | x |   y | z
# 2011  | x |   y | z
# 2012  | x |   y | z
# 2013  | x |   y | z
# 2014  | x |   y | z

rawDescription: Adding extra column to output csv file in python


code:
user_id = 142187
User.objects.filter(id=user_id).update(name='tom')

rawDescription: How to save a model without sending a signal?

description: Save a model without sending a signal


rawDescription: how to load a large RGB image in python?

description: Load a large RGB image in python


code:
root = tk.Tk() # create a Tk root window
x = -10

...

def mainloop():
    global root
    print ("Starting loop")
    # calls to other root methods must come before call to mainloop().
    root.after(1000, deplaceWindow)
    root.mainloop() # starts the mainloop

def deplaceWindow():
    global root,x
    print (x)
    root.geometry('%dx%d+%d+%d' % (w, h, x, y))
    x -= 10
    root.after(1000, deplaceWindow)   # 1000 miliseconds

if __name__=="__main__":
    print ("starting mainloop")
    mainloop()

rawDescription: Tkinter and threads

description: Tkinter and threads


rawDescription: Python- How to retrieve the vertex set by its attributes


code:
class CommonEqualityMixin(object):

    def __eq__(self, other):
        return (isinstance(other, self.__class__)
            and self.__dict__ == other.__dict__)

    def __ne__(self, other):
        return not self.__eq__(other)

class Foo(CommonEqualityMixin):

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

rawDescription: Elegant ways to support equivalence ("equality") in Python classes


code: urllib.urlretrieve(URL, directory + "\\" + filename + "." + extension)

rawDescription: I want the actual file name that is returned by a PHP script


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

# Generate some data...
data = np.random.random((100, 5))
y = data.mean(axis=0)
x = np.random.random(y.size) * 10
x -= x.min()
x.sort()

# Plot a line between the means of each dataset
plt.plot(x, y, 'b-')

# Save the default tick positions, so we can reset them...
locs, labels = plt.xticks()

plt.boxplot(data, positions=x, notch=True)

# Reset the xtick locations.
plt.xticks(locs)
plt.show()

rawDescription: Combining plt.plot(x,y) with plt.boxplot()


code: df.reindex(sorted(df.index, key=lambda x: x.lower()))

rawDescription: How to sort row index case-insensitive way in Pandas DataFrame

description: Sort row index case-insensitive way in Pandas DataFrame


code:
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtCore, QtGui

rawDescription: PyQt QVariant with dictionary

description: PyQt QVariant with dictionary


code:
def OnSelection(self, event):
    """Simulate CTRL-click"""
    selection = self.myListBox.GetSelections()

    for i in selection:
        if i not in self.selectedItems:
            # add to list of selected items
            self.selectedItems.append(i)
            self.myListBox.Select(i)
        elif len(selection) == 1:
            # remove from list of selected items
            self.selectedItems.remove(i)
            self.myListBox.Deselect(i)

    for i in self.selectedItems:
        # actually select all the items in the list
        self.myListBox.Select(i)

rawDescription: CTRL-click behavior in wx.ListBox with multiple selections


code:
my_cmap=matplotlib[:cm][:get_cmap]("Spectral",100)
my_cmap[:set_bad](color="#663300", alpha=0)
my_cmap[:set_under](color="#663300", alpha=0)
plt[:register_cmap](name="my_cmap",cmap=my_cmap)

rawDescription: How to get transparency into pcolormesh in JuliaLang?

description: Get transparency into pcolormesh in JuliaLang


code:
words_fixed = []
last = None
for word in words:
    if (last,word) in bigrams:
        words_fixed.append( "%s_%s" % (last,word) )
        last = None
    else:
        if last:
            words_fixed.append( last )
        last = word
if last:
    words_fixed.append( last )

rawDescription: Match adjacent list elements with a list of tuples in Python


rawDescription: Faster way to rank rows in subgroups in pandas dataframe


code: super(SubClass, self).__init__(...)

rawDescription: Python: Inherit the superclass __init__

description: Python: Inherit the superclass __init__


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

raw = np.random.random((20,5))
legends = [" ", "CH1 ","CH2 ","CH3 ","CH4 "]
units = [" ", "A","A","A","A"]
numChannels = 4

if numChannels == 1:
    plt.plot(raw[:,0],raw[:,1], label=legends[1] + " (" + units[1] + ")")
elif numChannels == 2:
    plt.plot(raw[:,0],raw[:,1], label=legends[1] + " (" + units[1] + ")")
    plt.plot(raw[:,0],raw[:,2], label=legends[2] + " (" + units[2] + ")")
elif numChannels == 3:
    plt.plot(raw[:,0],raw[:,1], label=legends[1] + " (" + units[1] + ")")
    plt.plot(raw[:,0],raw[:,2], label=legends[2] + " (" + units[2] + ")")
    plt.plot(raw[:,0],raw[:,3], label=legends[3] + " (" + units[3] + ")")
elif numChannels == 4:
    plt.plot(raw[:,0],raw[:,1], label=legends[1] + " (" + units[1] + ")")
    plt.plot(raw[:,0],raw[:,2], label=legends[2] + " (" + units[2] + ")")
    plt.plot(raw[:,0],raw[:,3], label=legends[3] + " (" + units[3] + ")")
    plt.plot(raw[:,0],raw[:,4], label=legends[4] + " (" + units[4] + ")")
plt.legend(loc=0)
plt.xlabel(legends[0])
plt.ylabel("Data")
plt.show()

rawDescription: Python plot Legend Key Format

description: Python plot Legend Key Format


code:
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from skimage import measure

x=y=z= np.linspace(-1, 1, 11)

grid=np.meshgrid(x,y,z)

def f(x, y, z):
    return x*x+y*y+z*z   # more fun ;)

def scale_marching(x,verts):
    return x[0]+ (x[-1]-x[0])/len(x)*verts

verts, faces = measure.marching_cubes(f(*grid), 1.5)
verts=scale_marching(x,verts)

ax = plt.figure().add_subplot(111, projection='3d')
ax.add_collection3d(Poly3DCollection(verts[faces]))
ax.auto_scale_xyz(*grid)

rawDescription: Map an array of indexes to an array of coordinates


code: a[xmin:xmax,ymin:ymax,:] = 0.

rawDescription: Zero out portion of multidim numpy array


code:
my_list = [1, 3, 4, 5, 3]
new_list = []
for i,x in enumerate(my_list):
    if i==0:
        new_list.append(my_list[-1] + my_list[i+1])
    elif i==len(my_list)-1:
        new_list.append(my_list[0] + my_list[i-1])
    else:
        new_list.append(my_list[i-1] + my_list[i+1])

new_list
[6, 5, 8, 7, 6]

rawDescription: python sum right and left components in list

description: Python sum right and left components in list


code:
url = '/api/v1/test?par1=val1&par2=val2a%3D1%26val2b%3Dfoo%26val2c%3Dbar'
q = parse_qs(urlparse(url).query)
q
parse_qs(q['par2'][0])

rawDescription: Split list returned from urlparse in python


rawDescription: How to use Pandas (Python) to report user-item interactions

description: Use Pandas (Python) to report user-item interactions


rawDescription: Pandas - Plot stacked bar chart

description: Pandas - Plot stacked bar chart


code:
import os
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email import Encoders

#Set up crap for the attachments
files = "/tmp/test/dbfiles"
filenames = [os.path.join(files, f) for f in os.listdir(files)]
#print filenames

#Set up users for email
gmail_user = "joe@email.com"
gmail_pwd = "somepasswd"
recipients = ['recipient1','recipient2']

#Create Module
def mail(to, subject, text, attach):
   msg = MIMEMultipart()
   msg['From'] = gmail_user
   msg['To'] = ", ".join(recipients)
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   #get all the attachments
   for file in filenames:
      part = MIMEBase('application', 'octet-stream')
      part.set_payload(open(file, 'rb').read())
      Encoders.encode_base64(part)
      part.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
      msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()

#send it
mail(recipients,
   "Todays report",
   "Test email",
   filenames)

rawDescription: Gmail Python multiple attachments

description: Gmail Python multiple attachments


code:
messagebox.finished.connect(self.handler)
messagebox.setWindowModality(QtCore.Qt.WindowModal)
messagebox.setParent(messagebox.parentWidget(), QtCore.Qt.Sheet)
messagebox.setResult(0)
messagebox.show()

rawDescription: creating message box as sheets for mac in PyQt

description: Creating message box as sheets for mac in PyQt


code:
import socket
socket.getservbyport(80)
socket.getservbyport(21)
socket.getservbyport(53, 'udp')

rawDescription: Detect Application layer protocols, python?


code:
def balanceable_rec(L, R, weights):

    print("L =", L, "  R =", R, "  weights =", weights)

    if (L == 0  or  L==R  or L in weights):
        return True
    if (len(weights) == 0):
        return False

    w = weights.pop(0)
    if balanceable_rec(L + w, R, weights[:]):  return True
    if balanceable_rec(L, R, weights[:]):      return True
    if balanceable_rec(L, R + w, weights[:]):  return True

    return False

rawDescription: Recursive backtracking in Python -- balancing weights on a scale


code:
array = []
with open('file.txt', 'r') as f:
   for line in f:
      name, value = line.split()
      value = int(value)
      array.append((name, value))

rawDescription: About text files to arrays in Python

description: About text files to arrays in Python


code:
import re
method = 'images/:id/huge'
re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)

rawDescription: Python re.sub replace with matched content


rawDescription: PIL image show() doesn't work on windows 7


code:
from itertools import permutations
perms = [''.join(p) for p in permutations('AAAABBBB', 4)]
len(perms)
len(set(perms))
filtered = [p for p in sorted(set(perms)) if 'AB' not in p]
filtered

rawDescription: Automatic dictionary generation - Python


code:
class oObject(object):
    def __init__(self, x = 0, y = 0, z = 0):
        self.x = Variant(x)
        self.y = Variant(y)
        self.z = Variant(z)

class Variant(object):
    def __init__(self, obj):
        self._obj = obj

    def __repr__(self):
        return '<%s: %s>' % (self.__class__.__name__, self.asString())

    def __str__(self):
        return self.asString()

    def asString(self):
        return str(self._obj)

    def value(self):
        return self._obj

rawDescription: Metaclass and syntax in Python

description: Metaclass and syntax in Python


code: vect= CountVectorizer(ngram_range=(1,2), binary =True, min_df = 500)

rawDescription: CountVectorizer in sklearn with only words above some minimum number of occurrences


code:
f = open(xmlfile).readlines()
w = open('src_model.xml','w')
empty=re.compile('^$')
for line in open(xmlfile).readlines():
    if empty.match(line):
        continue
    else:
        w.write(line)

rawDescription: Python xml.dom.minidom removeChild whitespace problem


code:
import numpy as np

arr = np.array([["City","Score1","Score2","Score3"],
                ["Berkley",23,432,321],
                ["Ohio",3,432,54],
                ["Columbia",123,432,53]])

new_arr = arr[1:, 1:].astype(float)

rawDescription: Use specific columns and lines numpy array


code: from multiprocessing.pool import ThreadPool

rawDescription: python: spawn threads as per requirements

description: Python: spawn threads as per requirements


code:
for _ in range(num_dots):

    dots_pos_x = randint(-max_coord, max_coord)
    dots_pos_y = randint(-max_coord, max_coord)

    penup()
    goto(dots_pos_x, dots_pos_y)
    if -200 <= dots_pos_x <= 200 and -200 <= dots_pos_y <= 200:
        pencolor((255, 0, 0))
    else:
        pencolor((0, 0, 0))
    dot(7)
    pendown()

rawDescription: how can i make dots change color when they enter a square

description: Make dots change color when they enter a square


code:
# Your while
i = 0
while i < len(self.option_space_dict[k]):
    if set(v) != set(self.option_space_dict[k][i]):
      result.append((k,v))
    i = i+1

# For loop
for item in self.option_space_dict[k]:
    if set(v) != set(item):
        result.append((k,v))

# As list comprehension
[(k,v) for item in self.option_space_dict[k] if set(v) != set(item)]

rawDescription: Making the loops to handle set object type conversion of nested dictionary objects more concise


code:
X,Y =  np.indices(data.shape)
Z = data.ravel()
X = X.ravel()
Y = Y.ravel()

rawDescription: Is there a method to load a 2D array into three 1D arrays?


code:
import urllib
resp = urllib.urlopen('http://example.com/')

if resp.getcode() == 200:
    rejoice()
if resp.getcode() == 404:
    sulk()

rawDescription: How to validate JSON with simplejson

description: Validate JSON with simplejson


code:
class Foo(object):
    def beep(self):
        print('Hi')

class Bar(object):
    x=1

bar=Bar()
# bar.beep()
# AttributeError: 'Bar' object has no attribute 'beep'

Bar=type('Bar',(Foo,object),Bar.__dict__.copy())
bar.__class__=Bar
bar.beep()
# Hi

rawDescription: Adding inheritance to a class programmatically in python?


code:
from math import sqrt
from trueskill import BETA
from trueskill.backends import cdf

def win_probability(player_rating, opponent_rating):
    delta_mu = player_rating.mu - opponent_rating.mu
    denom = sqrt(2 * (BETA * BETA) + pow(player_rating.sigma, 2) + pow(opponent_rating.sigma, 2))
    return cdf(delta_mu / denom)

rawDescription: With the trueskill algorithm, given two players' ratings, how can I calculate the win/loss probability?


rawDescription: Filter Excel Dataframe with Pandas

description: Filter Excel Dataframe with Pandas


code:
A = [[1,2],[3,4]]
for ii in itertools.product(*A):
    print(ii)

rawDescription: How do I iterate in a cascaded format (in a for loop) over a list of unknown length in Python?

description: Iterate in a cascaded format (in a for loop) over a list of unknown length in Python


code:
def mapper(keys, values):
    n = len(keys)
    return [dict(zip(keys, values[i:i + n]))
            for i in range(0, len(values), n)]

rawDescription: Map two lists into one single list of dictionaries


code:
import json
json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
json.loads('["foo", {"bar": ["baz", null, 1.0, 2]}]')

rawDescription: Python to javascript communication

description: Python to javascript communication


code:
import re
emos = { ':)' : 'smiley.jpg',
         ':(' : 'saddy.jpg',
         ';p' : 'bllinky.jpg' }
pattern = re.compile('|'.join( re.escape(emo) for emo in emos))
def emoImg(emoMatch):
    return '<img src = "/images/{0}>'.format(emos[emoMatch.group(0)])
def emoSub(string):
    return pattern.sub(emoImg,string)
print(emoSub('Hi :) I miss you :('))

rawDescription: Python - Replace characters for emoticons


code:
import arial10

class FitSheetWrapper(object):
    """Try to fit columns to max size of any entry.
    To use, wrap this around a worksheet returned from the
    workbook's add_sheet method, like follows:

        sheet = FitSheetWrapper(book.add_sheet(sheet_name))

    The worksheet interface remains the same: this is a drop-in wrapper
    for auto-sizing columns.
    """
    def __init__(self, sheet):
        self.sheet = sheet
        self.widths = dict()

    def write(self, r, c, label='', *args, **kwargs):
        self.sheet.write(r, c, label, *args, **kwargs)
        width = arial10.fitwidth(label)
        if width > self.widths.get(c, 0):
            self.widths[c] = width
            self.sheet.col(c).width = width

    def __getattr__(self, attr):
        return getattr(self.sheet, attr)

rawDescription: Python xlwt - accessing existing cell content, auto-adjust column width


code:
f = zipfile.ZipFile('path/to/file')
for attempt in attempts:
    try:
        f.extractall(pwd=attempt)
    except RuntimeError:
        continue
    else:
        return attempt

rawDescription: Zip file cracker python 3 - Proof of concept


code:
import os
os.startfile('my_mp3.mp3')

rawDescription: Can python open a mp3 file

description: Can python open a mp3 file


code:
def make_model():
    a = pymc.Poisson("a", 100)  # better to have the stochastics themselves available
    b = pymc.Poisson("b", 100)

    precision = 1e-4**-2 #  Seems like precision is fixed in Anglican model (and different from the meaning of precision in PyMC)

    @pymc.deterministic
    def mu(a=a, b=b):
        return (a-100) + (b-100)

    y = pymc.Normal("y", mu=mu, tau=precision, observed=True, value=7)

    return pymc.Model(locals())

def run_mcmc(model):
    mcmc = pymc.MCMC(model)
    mcmc.use_step_method(pymc.AdaptiveMetropolis, [mcmc.a, mcmc.b])
    mcmc.sample(20000, burn=10000, thin=10)
    return mcmc

result = run_mcmc(make_model())
pymc.Matplot.plot(result)

rawDescription: How to model sum of two Poisson distributions with pymc 2?

description: Model sum of two Poisson distributions with pymc 2


code:
class StopAdminForm(forms.ModelForm):
  class Meta:
    model = Stop
    widgets = {
      'approve_ts': ApproveStopWidget(),
    }

class StopAdmin(admin.ModelAdmin):
  form = StopAdminForm

rawDescription: Django Admin: Using a custom widget for only one model field


code:
import tkinter as tk
import threading

root = tk.Tk()
thread = threading.Thread(target=root.mainloop)
thread.start()

while True:
    print("Hello, World!");
    # TODO - add more stuff to this while loop

rawDescription: Replace while loop in Tkinter without using a function


code:
from future_builtins import map   # Only on Python 2 to avoid intermediate list
from itertools import chain

total = sum(map(int, chain.from_iterable(numlist)))

rawDescription: how to write double nested for loops and not have a tuple as output

description: Write double nested for loops and not have a tuple as output


code:
def main():
    output_file_loc = "overview.pdf"
    imgDoc = canvas.Canvas(output_file_loc)
    imgDoc.setPageSize(A4) # This is actually the default page size
    document_width, document_height = A4

    images = image_search()
    for image in images:
        # Open the image file to get image dimensions
        Image_file = Image.open(image)
        image_width, image_height = Image_file.size
        image_aspect = image_height / float(image_width)

        # Determine the dimensions of the image in the overview
        print_width = document_width
        print_height = document_width * image_aspect

        # Draw the image on the current page
        # Note: As reportlab uses bottom left as (0,0) we need to determine the start position by subtracting the
        #       dimensions of the image from those of the document
        imgDoc.drawImage(image, document_width - print_width, document_height - print_height, width=print_width,
                         height=print_height)

        # Inform Reportlab that we want a new page
        imgDoc.showPage()

    # Save the document
    imgDoc.save()

rawDescription: Image drawn to reportlab pdf bigger than pdf paper size


rawDescription: How to compare two files in Python when line indices differ and regular expression has multiple matches?

description: Compare two files in Python when line indices differ and regular expression has multiple matches


code:
import os

os.system("dot -Tpdf somefile.dot -o somefile.pdf")

rawDescription: Execute script from Python code

description: Execute script from Python code


code:
text = """
def fun1():
    print 'fun1'

def fun2():
    print 'fun2'

"""

import ast
tree = ast.parse(text)
# tree.body[0] contains FunctionDef for fun1, tree.body[1] for fun2

wrapped = ast.Interactive(body=[a.body[1]])
code = compile(wrapped, 'yourfile', 'single')
eval(code)
fun2() # prints 'fun2'

rawDescription: Parse Python file and evaluate selected functions