code:
from ctypes import *

your_dll = cdll.LoadLibrary("your_dll.dll")

PFloat = POINTER(c_float)
PInt   = POINTER(c_int)

p_data    = PFloat()
p_classes = PInt()
buff      = create_string_buffer(1024)
n1        = c_int( 0 )
n2        = c_int( 0 )

ret = your_dll.read_data( buff, byref(n1), byref(n2), byref(p_data), byref(p_classes) )

print('Data:    ', p_data.contents)
print('Classes: ', p_classes.contents)

rawDescription: How to use float ** from C in Python?

description: Use float ** from C in Python


rawDescription: Python date string to date object

description: Python date string to date object


code:
import inspect

def config_wrap(func, name):
    @view_config(name=name)
    def wrapped(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapped

def dynamic_names(cls):
    for name, m in inspect.getmembers(cls, inspect.ismethod):
        setattr(cls,name,config_wrap(m, name))
    return cls

@dynamic_names
@view_defaults(context=models.Group)
class GroupView(object):
    def __init__(self, context, request):
        self.context = context
        self.request = request

    def members(self):
        pass

    def add(self):
        pass

rawDescription: Pyramid traversal view lookup using method names


rawDescription: Pandas: Elementwise multiplication of two dataframes


code:
txt.set_bbox(dict(facecolor='w', alpha=0, boxstyle='round, pad=1'))
plt.draw()
txtbb = txt.get_bbox_patch().get_window_extent()
ymax = p.transData.inverted().transform(txtbb).ravel()[-1]
ybnd = p.get_ybound()
if ymax > ybnd[-1]:
    p.set_ybound(ybnd[0], ymax)
plt.draw()
plt.show()

rawDescription: pyplot auto-adjust axis limits

description: Pyplot auto-adjust axis limits


code:
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
sm = ScreenManager()

class scr1(Screen):
    pass

#layout that occupies the entire window. Everything else will be added on this
glayout = GridLayout(cols=1)

#layout that should occupy 25% of the window
layout1 = GridLayout(cols=1,size_hint_y=0.25)

#layout to be added on the scrollview
layout2 = GridLayout(cols=1,size_hint_y=None)
layout2.bind(minimum_height=layout2.setter('height'))

#screen to hold the glayout
screen1 = scr1(name = '1')

#adding a couple of widgets to layout1
layout1.add_widget(Button(text = 'hey'))
layout1.add_widget(TextInput(text = 'hey'))

#scroller that should occupy 75% of the window
scroller = ScrollView(size_hint_y=.75)
scroller.add_widget(layout2)

#adding buttons to be scrolled
for i in range(15):
    layout2.add_widget(Button(text=str(i),height=70,size_hint_y=None))

#adding scroller and layout1 to glayout and then the glayout to the screen
glayout.add_widget(scroller)
glayout.add_widget(layout1)
screen1.add_widget(glayout)

#adding the screen to the screen manager
sm.add_widget(screen1)
from kivy.app import App

class Ap(App):
    def build(self):
        return sm

Ap().run()

rawDescription: Unable to size widgets properly

description: Unable to size widgets properly


code:
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from selenium import webdriver
from urlparse import urljoin
import time
from selenium.webdriver.common.keys import Keys

class CompItem(scrapy.Item):
    model_name = scrapy.Field()
    model_link = scrapy.Field()
    url  =scrapy.Field()

class criticspider(CrawlSpider):
    name = "paytm_l"
    allowed_domains = ["paytm.com"]
    start_urls = ["https://paytm.com/shop/g/electronics/mobile-accessories/mobiles"]

    def __init__(self, *args, **kwargs):
        super(criticspider, self).__init__(*args, **kwargs)
        self.download_delay = 0.25
        self.browser = webdriver.Firefox()

        self.browser.implicitly_wait(2)

    def parse_start_url(self, response):
        self.browser.get(response.url)
        #sites = response.xpath('//div[@class="single-review"]/div[@class="review-header"]')
        self.browser.implicitly_wait(30)

        items = []
        time.sleep(20)
    #   for i in range(0,200):
            #self.browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        sel = Selector(text=self.browser.page_source)
        sites = sel.xpath('//div[contains(@class,"overflow-hidden")]')

        item = CompItem()

        for r in range(1,5):

                    #item['model_name'] = site.xpath('.//p[contains(@ng-if,"applyLimit")]/text()')
                    button = self.browser.find_element_by_xpath("/html/body/div[5]/div[5]/div/div[5]/div[3]/ul/li[%d]/a"%r)
                    main_window = self.browser.current_window_handle
                    button.send_keys(Keys.CONTROL + Keys.RETURN)
                    self.browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
                    time.sleep(5)
                    self.browser.switch_to_window(main_window)

                    item["url"]=self.browser.current_url
                    time.sleep(10)

                    time.sleep(10)

                    self.browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
                    self.browser.switch_to_window(main_window)

                    #item['model_link'] = site.xpath('//a[contains(@class,"{"na": !productClasses(product)}"]/@href').extract()[0]

                    yield item

rawDescription: How to get the url of current tab in selenium?

description: Get the url of current tab in selenium


code:
import cmd

completions = [
    'Mage Slayer (Alara Reborn)',
    'Magefire Wings (Alara Reborn)',
    'Sages of the Anima (Alara Reborn)',
    'Sanctum Plowbeast (Alara Reborn)',
    'Sangrite Backlash (Alara Reborn)',
    'Sanity Gnawers (Alara Reborn)',
    'Sen Triplets (Alara Reborn)'
]

class mycmd(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)

    def do_quit(self, s):
        return True

    def do_add(self, s):
        pass

    def complete_add(self, text, line, begidx, endidx):
        mline = line.partition(' ')[2]
        offs = len(mline) - len(text)
        return [s[offs:] for s in completions if s.startswith(mline)]

if __name__ == '__main__':
    mycmd().cmdloop()

rawDescription: Change how Python Cmd Module handles autocompletion


code:
import urllib
urllib.urlretrieve ("http://8.8.8.8/t1.txt", "t1.txt")

rawDescription: Get response from an ip address in python


code:
import numpy as np
from scipy.optimize import leastsq
import matplotlib.pyplot as plt

######################################
# Setting up test data
def norm(x, mean, sd):
  norm = []
  for i in range(x.size):
    norm += [1.0/(sd*np.sqrt(2*np.pi))*np.exp(-(x[i] - mean)**2/(2*sd**2))]
  return np.array(norm)

mean1, mean2 = 0, -2
std1, std2 = 0.5, 1

x = np.linspace(-20, 20, 500)
y_real = norm(x, mean1, std1) + norm(x, mean2, std2)

######################################
# Solving
m, dm, sd1, sd2 = [5, 10, 1, 1]
p = [m, dm, sd1, sd2] # Initial guesses for leastsq
y_init = norm(x, m, sd1) + norm(x, m + dm, sd2) # For final comparison plot

def res(p, y, x):
  m, dm, sd1, sd2 = p
  m1 = m
  m2 = m1 + dm
  y_fit = norm(x, m1, sd1) + norm(x, m2, sd2)
  err = y - y_fit
  return err

plsq = leastsq(res, p, args = (y_real, x))

y_est = norm(x, plsq[0][0], plsq[0][2]) + norm(x, plsq[0][0] + plsq[0][1], plsq[0][3])

plt.plot(x, y_real, label='Real Data')
plt.plot(x, y_init, 'r.', label='Starting Guess')
plt.plot(x, y_est, 'g.', label='Fitted')
plt.legend()
plt.show()

rawDescription: Python: two-curve gaussian fitting with non-linear least-squares


code:
import csv

file_name = "test.tsv"
TEMPLATE = "template.tsv"
fil = open(file_name, "w")

# you forgot this line, which will open the file
template_file = open(TEMPLATE, 'r')

template = csv.DictReader(template_file, delimiter='\t')
new_file = csv.DictWriter(fil, fieldnames=template.fieldnames, delimiter='\t')
new_file.writeheader()

rawDescription: Python csv not writing to file

description: Python csv not writing to file


code:
import common
common.f1()

rawDescription: Simplest way to Import a shared python script relative to the current script


code:
l = []
for s in srall10:
    if s.current_rate is not None and s.start_rate is not None:
        gain10 = s.current_rate - s.start_rate
    else:
        gain10 = 0
    l.append(gain10 / lessons10)  # average if each item

# total average
total_average = sum(l) / len(l)

rawDescription: Confusion with Python for loop and range()


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx, wx.lib.mixins.listctrl as wxlc

class EditVariable(wx.Dialog):
    def __init__(self, parent, data=None):
        wx.Dialog.__init__(self, parent, title='VQ: Edit Variable')

        sizer = wx.BoxSizer(wx.VERTICAL)
        grid = wx.GridBagSizer(6, 6)
        grid.AddGrowableCol(1)

        grid.Add(wx.StaticText(self, label='Type:'), (0,0))
        self.choType = wx.Choice(self, choices=['Distributed value',
                                                'Enumerated choice'])
        self.choType.Bind(wx.EVT_CHOICE, self.choType_change)
        grid.Add(self.choType, (0,1), flag=wx.EXPAND)

        self.lblDistribution = wx.StaticText(self, label='Distribution:')
        self.choDistribution = wx.Choice(self, choices=['Normal',
                                                        'Uniform',
                                                        'Uniform discrete',
                                                        'Geometric',
                                                        'Binomial',
                                                        'Poisson'])
        grid.Add(self.lblDistribution, (1,0))
        grid.Add(self.choDistribution, (1,1), flag=wx.EXPAND)
        self.choDistribution.Bind(wx.EVT_CHOICE, self.choDistribution_change)

        self.lblMean = wx.StaticText(self, label='Mean:')
        self.txtMean = wx.TextCtrl(self)
        grid.Add(self.lblMean, (2,0))
        grid.Add(self.txtMean, (2,1), flag=wx.EXPAND)

        self.lblVariance = wx.StaticText(self, label='Variance:')
        self.txtVariance = wx.TextCtrl(self)
        grid.Add(self.lblVariance, (3,0))
        grid.Add(self.txtVariance, (3,1), flag=wx.EXPAND)

        self.lblStep = wx.StaticText(self, label='Step:')
        self.txtStep = wx.TextCtrl(self)
        grid.Add(self.lblStep, (4,0))
        grid.Add(self.txtStep, (4,1), flag=wx.EXPAND)

        self.lblSigFigs = wx.StaticText(self, label='Significant figures:')
        self.txtSigFigs = wx.TextCtrl(self)
        grid.Add(self.lblSigFigs, (5,0))
        grid.Add(self.txtSigFigs, (5,1), flag=wx.EXPAND)

        self.lstEnum = EditListCtrl(self)
        self.lstEnum.InsertColumn(0, 'Text')
        self.lstEnum.InsertColumn(1, 'Value')
        self.lstEnum.SetColumnWidth(0, wx.LIST_AUTOSIZE_USEHEADER)
        self.lstEnum.SetColumnWidth(1, wx.LIST_AUTOSIZE_USEHEADER)
        self.lstEnum.setResizeColumn(0)
        self.lstEnum.Append(['', '0'])
        self.lstEnum.SetInitialSize((120, 240))
        grid.Add(self.lstEnum, (6,0), span=(1,2), flag=wx.EXPAND | wx.ALL)

        self.btnAdd = wx.Button(self, label='Add')
        self.btnAdd.Bind(wx.EVT_BUTTON, self.btnAdd_click)
        self.btnRemove = wx.Button(self, label='Remove')
        self.btnRemove.Bind(wx.EVT_BUTTON, self.btnRemove_click)
        grid.Add(self.btnAdd, (7,0))
        grid.Add(self.btnRemove, (7,1))

        grid.Add(wx.Button(self, label='Test'), (8,0), span=(1,2))
        grid.Add(wx.StaticText(self, label='Text:'), (9,0))
        grid.Add(wx.StaticText(self), (9,1))
        grid.Add(wx.StaticText(self, label='Value:'), (10,0))
        grid.Add(wx.StaticText(self), (10,1))

        buttonsSizer = wx.BoxSizer(wx.HORIZONTAL)
        buttonsSizer.Add(wx.Button(self, label='Save && close'),
                         flag=wx.ALIGN_RIGHT)
        grid.Add(buttonsSizer, (11,0), span=(1,2), flag=wx.ALIGN_RIGHT)

        sizer.Add(grid, 0, wx.EXPAND | wx.ALL, 6)

        self.SetSizer(sizer)
        #self.CreateStatusBar()
        self.SetAutoLayout(1)
        sizer.Fit(self)
        self.Show(True)

        grid.SetEmptyCellSize((0,0)) #added by Jerry
        self.UpdateFields()

    def choType_change(self, e):
        self.UpdateFields()

    def choDistribution_change(self, e):
        self.UpdateFields()

    def UpdateFields(self):
        isDistr = self.choType.GetSelection() == 0

        self.choDistribution.Show(isDistr)
        self.lblMean.Show(isDistr)
        self.txtMean.Show(isDistr)
        self.lblVariance.Show(isDistr)
        self.txtVariance.Show(isDistr)
        self.lblStep.Show(isDistr)
        self.txtStep.Show(isDistr)
        self.lblSigFigs.Show(isDistr)
        self.txtSigFigs.Show(isDistr)

        self.lstEnum.Show(not isDistr)
        self.btnAdd.Show(not isDistr)
        self.btnRemove.Show(not isDistr)

        if isDistr:
            self.lblDistribution.SetLabel('Distribution:')
            n = self.choDistribution.GetSelection()
            if n == 0:
                #Normal
                self.lblMean.SetLabel('Mean:')
                self.lblVariance.SetLabel('Variance:')
                self.lblStep.Hide()
                self.txtStep.Hide()
            elif n == 1:
                #Uniform
                self.lblMean.SetLabel('Minimum:')
                self.lblVariance.SetLabel('Maximum:')
                self.lblStep.Hide()
                self.txtStep.Hide()
            elif n == 2:
                #Uniform discrete
                self.lblMean.SetLabel('Minimum:')
                self.lblVariance.SetLabel('Maximum:')
                self.lblStep.SetLabel('Step:')
            elif n == 3:
                #Geometric
                self.lblMean.SetLabel('Probability:')
                self.lblVariance.Hide()
                self.txtVariance.Hide()
                self.lblStep.Hide()
                self.txtStep.Hide()
            elif n == 4:
                #Binomial
                self.lblMean.SetLabel('Number:')
                self.lblVariance.SetLabel('Probability:')
                self.lblStep.Hide()
                self.txtStep.Hide()
            elif n == 5:
                #Poisson
                self.lblMean.SetLabel('Mean:')
                self.lblVariance.Hide()
                self.txtVariance.Hide()
                self.lblStep.Hide()
                self.txtStep.Hide()
        else:
            self.lblDistribution.SetLabel('Options:')
        #self.Layout()
        self.Fit() #added by Jerry

    def btnAdd_click(self, e):
        self.lstEnum.Append(['', '0'])
        for i in range(self.lstEnum.GetItemCount() - 1):
            self.lstEnum.Select(i, 0)
        self.lstEnum.Select(self.lstEnum.GetItemCount() - 1)

    def btnRemove_click(self, e):
        item = self.lstEnum.GetFirstSelected()
        while item != -1:
            self.lstEnum.DeleteItem(item)
            item = self.lstEnum.GetFirstSelected()

class EditListCtrl(wx.ListCtrl, wxlc.TextEditMixin,
                   wxlc.ListCtrlAutoWidthMixin):
    def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.LC_REPORT):
        wx.ListCtrl.__init__(self, parent, id, pos, size, style | wx.LC_REPORT)
        wxlc.TextEditMixin.__init__(self)
        wxlc.ListCtrlAutoWidthMixin.__init__(self)

if __name__ == '__main__':
    app = wx.App(redirect=False)
    main = EditVariable(None, 'VQ')
    app.MainLoop()

rawDescription: Hide rows in wx.GridBagSizer

description: Hide rows in wx.GridBagSizer


code: struct.unpack("<L", "y\xcc\xa6\xbb")[0]

rawDescription: convert a string of bytes into an int (python)

description: Convert a string of bytes into an int (python)


code:
for record in myList:
    wait = None
    if isinstance(record,(list,tuple)):
       record,wait = record

rawDescription: Iterate over "1 or more" elements in iterator object?


rawDescription: Pandas calculate number of values between each range


code:
class Example(object):
    pass

Example
del Example
Example

rawDescription: Is it possible to remove a class definition from Python?


code:
#in main
self.worker = Worker(self.spinbox.value())
self.worker.beep.connect(self.update)
self.spinbox.valueChanged.connect(self.worker.update_value)

class Worker(QtCore.QThread):
    beep=QtCore.pyqtSignal(int)

    def __init__(self,sleep_time):
        super(Worker, self).__init__()
        self.running = False
        self.sleep_time=sleep_time

    def run(self):
        self.running = True
        i = 0
        while self.running:
            i += 1
            self.beep.emit(i)
            time.sleep(self.sleep_time)

    def stop(self):
        self.running = False

    def update_value(self,value):
        self.sleep_time=value

rawDescription: In PyQt, what is the best way to share data between the main window and a thread


code:
import pandas as pd
import pandas.core.common as com

t = pd.DataFrame({'a':[1,2,3], 'b':[2,6,0.75], 'c':['foo','bar','beer']})
cols_to_check = ['a', 'b']

assert all(com.is_numeric_dtype(t[col]) for col in cols_to_check)
# True

rawDescription: Asserting column(s) data type in Pandas

description: Asserting column(s) data type in Pandas


rawDescription: Python 3 regex - How to match all unicode alphabetic characters and spaces?


code:
import numpy as numpy

import matplotlib.pyplot as plt
from matplotlib.dates import date2num, DateFormatter

import datetime as dt

base = dt.datetime(2014, 1, 27, 11, 7, 59)

x = [base + dt.timedelta(seconds=i) for i in range(10)]
y = [i**2 for i in range(10)]

x = date2num(x) # Convert datetime objects to the correct format for matplotlib.

fig, ax = plt.subplots()

ax.plot_date(x, y) # Use plot_date rather than plot

# Set the xaxis major formatter as a DateFormatter object
# The string argument shows what format you want (HH:MM:SS)
ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))

# This simply makes them look pretty by setting them diagonal.
fig.autofmt_xdate()

plt.show()

rawDescription: Precision plotting in time axis

description: Precision plotting in time axis


code:
r1 = r_original(x, y)
r1.prop_a.prop_b.prop_c
returner = mock.MagicMock()
returner.prop_a.prop_b.prop_c = 'fish'
r_mocked = mock.MagicMock(spec_set=r_original, return_value=returner)
r2 = r_mocked(x, y)
r2.prop_a.prop_b
r2.prop_a.prop_b.prop_c

rawDescription: Mocking nested properties with mock

description: Mocking nested properties with mock


code: parser.add_argument('--use-lang', required=True, help="Output language")

rawDescription: argparse "compulsory" optional arguments

description: Argparse "compulsory" optional arguments


code:
source_file = open("myfile", "r")
file_data = list(source_file.read())
source_file.close()
file_data.insert(position, data)
open("myfile", "wb").write(file_data)

rawDescription: Writing in file's actual position in Python


code: fen.wm_attributes("-topmost", True)

rawDescription: UNIX - Tkinter Window always in the first plan


code: random.uniform(0, 1)

rawDescription: Random number between 0 and 1 in python

description: Random number between 0 and 1 in python


code:
import re

parts_to_remove = (
    r'@\w+',
    r'https?://[\da-z.-/]+'
)

with open('englishtweet.txt', 'r') as infile:
    for line in infile:

        for part in parts_to_remove:
            re.sub(part, '', line)

        if ':)' in line:
            cl.train(line, 'happy')
        elif ':(' in line:
            cl.train(line, 'sad')

rawDescription: Remove words from file in python and print line out by line


code:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import Subplot

left,bottom,width,height= -0.02 , 0.12, 1, 0.9
fig = plt.figure(figsize=(3,5))
ax1 = plt.Axes(fig,[left,bottom,width,height])
ax1.plot([1,2,3,4],'b') # plot on the first axes you created
fig.add_axes(ax1)

# using subplot you are acually using higher level objects

ax2 = Subplot(fig,111) # this addes another axis instance
fig.add_subplot(ax2)
ax2.axis["top"].set_visible(False)
ax2.axis["right"].set_visible(False)
ax2.plot([1,2,3,4,5],'r') # thos plots on the second

# now comment everything in ax2, and uncomment ax3
# you will get a crude, low level control of axes
# but both do what you want...

#ax3 = plt.Axes(fig,[left+0.2,bottom-0.2,width,height])
#ax3.plot([1,2,3,4],'g') # plot on the first axes you created

#for loc, spine in ax3.spines.iteritems():
#    if loc in ['left','bottom']:
#        spine.set_position(('outward',10)) # outward by 10 points
#    if loc in ['right','top']:
#        spine.set_color('none') # don't draw spine
#fig.add_axes(ax3)
plt.show()

rawDescription: Remove top and right axis in matplotlib after increasing margins?


code:
import time
t = time.time()
int(str(t-int(t))[2:])%100 #Keeping only the numbers after the decimal point, otherwise you would get the same "random" number each second

rawDescription: Alternative for random module in python

description: Alternative for random module in python


code:
counterup = Counter(upperseqs)
counterlow = Counter(lowerseqs)
countermc_up = counterup.most_common(500)

for k,v in countermc_up:
    print >> fh1, k, '\t', v, '\t', counterlow[k]

rawDescription: comparing two lists of different lengths generated from Counter() python

description: Comparing two lists of different lengths generated from Counter() python


code:
def timeout():
    time_label.config(text=time.time())
    window.after(500, timeout)

window = Tkinter.Tk()
window.title("Example")

time_label= Tkinter.Label(text='',
                    bg="black",fg="white")
time_label.grid(row=1,column=2)

timeout()
window.geometry("100x100+100+100")
window.mainloop()

rawDescription: How to get/print Updated Time per second in a Tkinter window

description: Get/print Updated Time per second in a Tkinter window


code:
from cStringIO import StringIO

imagefile = StringIO()  # writable object

# save to open filehandle, so specifying the expected format is required
animage.save(imageFile, format='PNG')
imagedata = imagefile.getvalue()

rawDescription: Python: process image and save to file stream


code: hashtags = re.findall(r'#(\w+)', str1, re.UNICODE)

rawDescription: How to account for accent characters for regex in Python?

description: Account for accent characters for regex in Python


code: combobox.SetSelection(0)  # select first item

rawDescription: How to Append data to a combobox

description: Append data to a combobox


code:
class AvgDict(dict):
    def __init__(self):
        self._total = 0.0
        self._count = 0

    def __setitem__(self, k, v):
        if k in self:
            self._total -= self[k]
            self._count -= 1
        dict.__setitem__(self, k, v)
        self._total += v
        self._count += 1

    def __delitem__(self, k):
        v = self[k]
        dict.__delitem__(self, k)
        self._total -= v
        self._count -= 1

    def average(self):
        if self._count:
            return self._total/self._count

a = AvgDict()
assert a.average() is None
a[1] = 1
assert a.average() == 1
a[2] = 10
assert a.average() == 5.5
assert a[2] == 10
a[1] = 5
assert a.average() == 7.5
del a[1]
assert a.average() == 10

rawDescription: Python - Fastest way to find the average value over entire dict each time it gets modified?


code:
from StringIO import StringIO
from fabric.api import get

fd = StringIO()
get(remote_path, fd)
content=fd.getvalue()

rawDescription: How to get the content of a remote file without a local temporary file with fabric

description: Get the content of a remote file without a local temporary file with fabric


code:
msg = "string in red"
self.showMessage(msg)

rawDescription: PyQt4 : can't change the color of my (html) message text


code:
def func(x):
    x[0] = 2 # Mutating the object affects the object outside the function
myList = [1]
func(myList)
myList # myList has changed
def func(x):
    x = 2 # rebinding name has no effect outside the function
myList = [1]
func(myList)
myList # myList is unaffected

rawDescription: Python - how does passing values work?

description: Python - how does passing values work


code:
import datetime
before = datetime.datetime.strptime('3/6/2011','%m/%d/%Y')
now = datetime.datetime.now()
type(now-before)
(now-before).days
float((now-before).days)/365

rawDescription: Python: Get number of years that have passed from date string


rawDescription: Python If-elif statement

description: Python If-elif statement


code:
i = 0
while i < 500000:
    line = FILE.readline()
    if line == "": # Cuts off if end of file reached
        break
    m = re.search('key=([^&]*)', line)
    count_words[m.group(1)]+=1
    i += 1

rawDescription: Parsing Gigantic Log File in Python

description: Parsing Gigantic Log File in Python


code:
from Tkinter import *

root = Tk()

text_good = [1,2,3,4,5,6,7,8,9]
text_wrong1 = [1,2,3,4,0,0,0,8,9]
text_wrong2 = [1,2,3,4," "," "," ",8,9]

def create_box(text_list, **grid_options):
    frame = Frame(root, bg="red")
    for i, text in enumerate(text_list):
        Label(frame, text=text, bg="red").grid(row=i//3, column=i%3)
    frame.grid(**grid_options)

create_box(text_good, row=0, column=0, padx=10)
create_box(text_wrong1, row=0, column=1, padx=10)
create_box(text_wrong2, row=0, column=2, padx=10)

root.mainloop()

rawDescription: How to arrange numbers in Label into grid in Tkinter?

description: Arrange numbers in Label into grid in Tkinter


code:
import datetime as dt

def draw_fft(self):
    ...
    outputfilename = 'output_{}.csv'.format( dt.datetime.now().strftime('%Y%m%d%H%M%S') )
    np.savetxt(outputfilename, output, delimiter=',')

rawDescription: How to check if a file exists, and if so append a number to the file name

description: Check if a file exists, and if so append a number to the file name


rawDescription: Making cells independent of each other in a Jupyter notebook


code:
with open("NC2010.txt") as NCFile:
    lines = NCFile.readlines()[1:]
    change = []
    for line in lines:
        row = line.split(",")
        country_name = row[1]
        population_2000 = float(row[6])
        population_2010 = float(row[8])
        pop_change = ((population_2010 / population_2000) - 1) * 100
        change.append((pop_change, country_name))

    change.sort()
    output_rows = []
    [output_rows.append("{0}, {1:.2f}\n".format(pair[1], pair[0]))
                        for pair in change]
    with open("Sorted_Population_Change_Output.txt", "w") as PopulationChange:
        PopulationChange.writelines(output_rows)

rawDescription: Trouble with sorting list and "for" statement snytax


code:
from Tkinter import *
import cv2
from PIL import Image, ImageTk

isrunning = 0
def Start():
    global isrunning
    if isrunning == 0:
        width, height = 800, 600
        cap = cv2.VideoCapture(0)
        cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, width)
        cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, height)
        isrunning = 1
        lmain.pack(side = RIGHT)

        def show_frame():
            _, frame = cap.read()
            frame = cv2.flip(frame, 1)
            cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
            img = Image.fromarray(cv2image)
            imgtk = ImageTk.PhotoImage(image=img)
            lmain.imgtk = imgtk
            lmain.configure(image=imgtk)
            if isrunning == 1:
                lmain.after(10, show_frame)

    show_frame()

def Stop():
    global isrunning
    isrunning = 0
    lmain.pack_forget()

root = Tk()
lmain = Label(root)

Button1 = Button(root, text = "Start", command = Start)
Button1.pack(side = LEFT)
Button2 = Button(root, text = "Stop", command = Stop)
Button2.pack(side = LEFT)

root.mainloop()

rawDescription: Python OpenCV output on Tkinter label deletion


code:
import re
test_str = 'ABC(XYZ)'
re.findall(r'\([^()]*\)|[^()]+', test_str)
[i for i in re.findall(r'(.*)(\([^()]*\))', test_str)[0]]

rawDescription: Python regular expression to extract the parenthesis


code:
# Import namespaces
from Spotfire.Dxp.Framework.ApplicationModel import ApplicationThread
from Spotfire.Dxp.Application import DocumentSaveSettings
from Spotfire.Dxp.Framework.Library import *

# Declaring the function which will run async
def g(app, folder, fileName, metaData, saveSettings):
   def f():
      app.SaveAs(folder, fileName, metaData, saveSettings)
   return f

# Set the folder path and file name
folderName = "/Spotfire Test Folder/Reports"
fileName = "Test File"

# Set up the LibraryMangager and ensure that we can
# access the folder path specified
libraryManager = Document.GetService(LibraryManager)
success, libraryFolder = libraryManager.TryGetItem(folderName, LibraryItemType.Folder)

# Executing the function on the application thread, and Save the document back to the Library
Application.GetService[ApplicationThread]().InvokeAsynchronously(g(Application, libraryFolder, fileName, LibraryItemMetadataSettings(), DocumentSaveSettings()))

rawDescription: Spotfire SaveAs using ironPython

description: Spotfire SaveAs using ironPython


code:
import numpy as np
x = range(1, 5)
x
y = np.cumsum(x)
y

rawDescription: Matplolib using lists making step graphs


code:
class MyModel(models.Model):
    # other fields
    my_file = models.FileField(upload_to='uploaddir')

    def save(self, *args, **kwargs):
        new_name = 'file_name-random-chars.ext'
        self.my_file.name = new_name
        super(MyModel, self).save(*args, **kwargs)

rawDescription: Modifying file name of a file in a Django ModelForm on save


code:
l = [(1, 2, 3, 4, 5)]
[item for tup in l for item in tup]

rawDescription: How to take a python list index containing multiple strings and split it

description: Take a python list index containing multiple strings and split it


code:
import StringIO

f = StringIO.StringIO() # create a file-like object

wbk = xlwt.Workbook()
earnings_tab = wbk.add_sheet('EARNINGS')

wbk.save(f) # write to stdout

rawDescription: xlwt write excel sheet on the fly

description: Xlwt write excel sheet on the fly


code:
f = window.GetFont()
dc = wx.WindowDC(window)
dc.SetFont(f)
width, height = dc.GetTextExtent("Text to measure")

rawDescription: How to get the width of a string in pixels?

description: Get the width of a string in pixels


code:
for i in p.imap(do, izip(Fastitr(seqsa, filetype='fastq'), \
        Fastitr(seqsb, filetype='fastq'))):
    pass

rawDescription: mutliprocessing.Pool.add_sync() eating up memory

description: Mutliprocessing.Pool.add_sync() eating up memory


code:
from time import time, sleep
end_time = time() + x_hours * 3600 # time() is calculated in seconds

while time() < end_time:
    do_your_work()
    sleep(y_seconds)

rawDescription: time loop in python

description: Time loop in python


rawDescription: Is there a limit to the size of a query that can be executed by a sqlalchemy session?


code: len(s) < 256 and '.' in s

rawDescription: How to create regular expression for domain name?

description: Create regular expression for domain name


code: numpy.apply_along_axis(lambda a: a.searchsorted(950), axis = 1, arr = air_pr)

rawDescription: numpy.searchsorted in a multidimensional array

description: Numpy.searchsorted in a multidimensional array


code:
class Numbers:
    def __init__(self):
       self.__sum=0
    def addNumber(self, number):
       self.__sum += number
    def currentSum(self):
       return self.__sum

a = ['3 2', '1 2']
for n in a:
  numbers = Numbers()
  for i in n.split():
      numbers.addNumber(int(i))
  print(numbers.currentSum())

rawDescription: How to find sum in a list using classes

description: Find sum in a list using classes


code:
import numpy as np

xdat = np.array([3,2,7,4])
ydat = np.array([2,4,4,9])

dat = np.vstack((xdat, ydat))
# array([[3, 2, 7, 4],
#        [2, 4, 4, 9]])

dat = np.cumsum(dat, axis=1)
# array([[ 3,  5, 12, 16],
#        [ 2,  6, 10, 19]], dtype=int32)

# optionally start at 0, 0 (can do this before or after cumsum)
dat = np.hstack([np.zeros((2, 1)), dat])
# array([[  0.,   3.,   5.,  12.,  16.],
#        [  0.,   2.,   6.,  10.,  19.]])

rawDescription: Drawing vector addition

description: Drawing vector addition


code:
import collections

key_value_pairs = [('zero', 0),
                   ('one', 0),
                   ('two', 0)]

dict = collections.OrderedDict(key_value_pairs)

rawDescription: for..in.. print dictionary in random order

description: For..in.. print dictionary in random order


code:
from pyPdf import PdfFileWriter, PdfFileReader
output_pdf = PdfFileWriter()

with open(r'input.pdf', 'rb') as readfile:
    input_pdf = PdfFileReader(readfile)
    total_pages = input_pdf.getNumPages()
    for page in xrange(total_pages - 1, -1, -1):
        output_pdf.addPage(input_pdf.getPage(page))
    with open(r'output.pdf', "wb") as writefile:
        output_pdf.write(writefile)

rawDescription: How do I reverse the order of the pages in a pdf file using pyPdf?

description: Reverse the order of the pages in a pdf file using pyPdf


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

conf_arr = [[33,2,0,0,0,0,0,0,0,1,3],
            [3,31,0,0,0,0,0,0,0,0,0],
            [0,4,41,0,0,0,0,0,0,0,1],
            [0,1,0,30,0,6,0,0,0,0,1],
            [0,0,0,0,38,10,0,0,0,0,0],
            [0,0,0,3,1,39,0,0,0,0,4],
            [0,2,2,0,4,1,31,0,0,0,2],
            [0,1,0,0,0,0,0,36,0,2,0],
            [0,0,0,0,0,0,1,5,37,5,1],
            [3,0,0,0,0,0,0,0,0,39,0],
            [0,0,0,0,0,0,0,0,0,0,38]]

norm_conf = []
for i in conf_arr:
    a = 0
    tmp_arr = []
    a = sum(i, 0)
    for j in i:
        tmp_arr.append(float(j)/float(a))
    norm_conf.append(tmp_arr)

fig = plt.figure()
plt.clf()
ax = fig.add_subplot(111)
ax.set_aspect(1)
res = ax.imshow(np.array(norm_conf), cmap=plt.cm.jet,
                interpolation='nearest')

width, height = conf_arr.shape

for x in xrange(width):
    for y in xrange(height):
        ax.annotate(str(conf_arr[x][y]), xy=(y, x),
                    horizontalalignment='center',
                    verticalalignment='center')

cb = fig.colorbar(res)
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
plt.xticks(range(width), alphabet[:width])
plt.yticks(range(height), alphabet[:height])
plt.savefig('confusion_matrix.png', format='png')

rawDescription: How can I plot a confusion matrix?

description: Plot a confusion matrix


code:
the_time= None
for f in FORMATS:
    try:
        the_time = time.mktime(time.strptime(t, f))
        return the_time # or break
    except ValueError:
        continue
if the_time is None:
    raise ValueError( "{0!r} is not a valid time".format(t) )

rawDescription: A better way to parse time strings

description: A better way to parse time strings


code:
import scipy.linalg as la

# Create arrays and set values
ab = np.zeros((3,m))
b = 2*ones(m)
ab[0] = 9
ab[1] = 8
ab[2] = 7

# Fix end points
ab[0,1] = 2
ab[1,0] = 1
ab[1,-1] = 4
ab[2,-2] = 3
b[0] = 1
b[-1] = 3

return la.solve_banded ((1,1),ab,b)

rawDescription: Optimize A*x = B solution for a tridiagonal coefficient matrix


code:
libncursesw5-dev
libssl-dev
libgdbm-dev
libsqlite3-dev
tk-dev

rawDescription: Ctrl+L won't clear Python3.3 terminal

description: Ctrl+L won't clear Python3.3 terminal


code:
from PIL import Image

image = request.FILES['new_photo']
if image:
    img = Image.open(image)
    img.save(path.join(app.config['UPLOAD_FOLDER'],
        secure_filename('upload-%d.jpg' % self.obj.id)), 'JPEG')
    img.thumbnail((200, 200), Image.ANTIALIAS)
    img.save(path.join(app.config['UPLOAD_FOLDER'],
        secure_filename('upload-%d.200.jpg' % self.obj.id)), 'JPEG')

rawDescription: Django/Python resize image

description: Django/Python resize image


code:
import multiprocessing
pool = multiprocessing.Pool(multiprocessing.cpu_count())
success = all(pool.imap_unordered(process, directories))

rawDescription: Fastest way to process large files in Python


code:
import lxml.etree as le
import cStringIO
content='''\
inside something
'''
doc=le.parse(cStringIO.StringIO(content))

xpath='//font[@face="verdana" and @color="#ffffff" and @size="2"]/child::*'
x=doc.xpath(xpath)
print(map(le.tostring,x))
# ['inside something']

rawDescription: how to get the full contents of a node using xpath & lxml?

description: Get the full contents of a node using xpath & lxml


code:
nums = str(12344444442)
from itertools import groupby as gby
if all (int(num) % 2 for num in nums):
    print("All are Odd numbers")
else:
    m_list=max((list(g) for n,g in gby(nums,key=lambda x:int(x)%2) if not n),key=len)
    # ['4', '4', '4', '4', '4', '4', '4', '2']   Longest even sequence
    print(nums.index("".join(m_list)))
    # 3   Starting index

rawDescription: Counting the largest sequence of even numbers


rawDescription: Slicing in mongoengine

description: Slicing in mongoengine


code:
query = "SELECT number_str, bnf_id, name FROM mytable WHERE "
for i, code in enumerate(codes):
    q = "(number_str ILIKE %s OR name ~* %s) "
    query += q
    if i < len(codes)-1:
        query += 'OR '

# create an interleaved list of '<code>%', '<code>' pairs:
qcodes1 = [s + '%' for s in codes]
qcodes2 = codes
qcodes = [code for p in zip(qcodes1, qcodes2) for code in p]

cursor.execute(query, qcodes)

rawDescription: Are these SQL input parameters vulnerable to injection?


code: sorted(your_tup, key=lambda x: [x[0], int(x[1]), int(x[2])])

rawDescription: How can I do Tuple sorting

description: Do Tuple sorting


code:
def do_something():
    # define a mapping from the choice value to a function name
    func_map = {
        "daily_choices": daily_choices,
        "value_at_risk": value_at_risk,
        "cumulative_return": cumulative_return,
    }
    # using the map, get the function
    function = func_map[var.get()]

    # call the function
    function()

...
Button(..., command=do_something)

rawDescription: Tkinter dynamic button that calls the function selected in a OptionMenu Widget


code: cmd_line = r'psexec \\{0} cmd /c "findstr /c:"{1}" "{2}" | find /v /c """'.format(address, findstr, file)

rawDescription: Issue using find with psexec

description: Issue using find with psexec


code:
time = input("what was your time? ")
time= time.split('.')
time
time= int(time[0])*60+int(time[1])
time

rawDescription: Splitting an integer in python

description: Splitting an integer in python


code:
def login_role_required(req_roles = None):
    if req_roles is None:
        req_roles = ['any']

    def decorator (f):
        def decorated_view(*args, **kwargs):
            # …
            return f(*args, **kwargs)
        return decorated_view

    return decorator

rawDescription: Wrapping Functions in Python 3.4 missing required positional argument


rawDescription: How to get an absolute file path in Python

description: Get an absolute file path in Python


code:
return {
    'type': 'ir.actions.report.xml',
    'report_name':'my.report.name',
    'datas': {
            'model':'my.model',
            'id': ids and ids[0] or False,
            'ids': ids and ids or [],
        }
}

rawDescription: How to print a report for each product independently?

description: Print a report for each product independently


code:
import cv2
import numpy as np

def nothing(x):
    pass

#image window
cv2.namedWindow('image')

#loading images
img = cv2.imread('leo-messi-pic.jpg',0)     # load your image with proper path

# create trackbars for color change
cv2.createTrackbar('th1','image',0,255,nothing)
cv2.createTrackbar('th2','image',0,255,nothing)

while(1):
    # get current positions of four trackbars
    th1 = cv2.getTrackbarPos('th1','image')
    th2 = cv2.getTrackbarPos('th2','image')
    #apply canny
    edges = cv2.Canny(img,th1,th2)
    #show the image
    cv2.imshow('image',edges)
    #press ESC to stop
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

rawDescription: Edge detection and histogram matching of two images using open CV python.


code:
import numpy as np
a = np.array([1,2,0,3,0,4])
b = np.array([1,2,3,4,5,6])
b[np.where(a)]
np.where(a)
a[np.where(a)]

rawDescription: Removing Array Elements in Python while keeping track of their position


code:
import pprint
pprint.pformat(thedict)

rawDescription: How to save a dictionary into a file, keeping nice format?

description: Save a dictionary into a file, keeping nice format


code:
def __init(self, request):
    ...
    self.id = { ... }

rawDescription: Python / Django - Class Dictionary Persistent in View?


code:
from django.db.models import fields
from south.modelsinspector import add_introspection_rules

class BigAutoField(fields.AutoField):
    def db_type(self, connection):
        if 'mysql' in connection.__class__.__module__:
            return 'bigint AUTO_INCREMENT'
        return super(BigAutoField, self).db_type(connection)

add_introspection_rules([], ["^MYAPP\.fields\.BigAutoField"])

rawDescription: Django BigInteger auto-increment field as primary key?


code:
old = None
for i in list:
    var = generate(i)
    do_stuff(var)
    if old is not None:
        do_other_stuff(old)
    old = var

rawDescription: Variable within for loop in python

description: Variable within for loop in python


code:
def request(context, flow):
    print(flow.request.timestamp_start)

rawDescription: mitmproxy, how to get the response time/duration of a call?

description: Mitmproxy, how to get the response time/duration of a call


code: doc2 = ET.SubElement(root, "product")

rawDescription: How to create multiple sub element under a root element in XML using python?

description: Create multiple sub element under a root element in XML using python


code:
a = set(list1)
b = set(list2)

companies_in_both = a & b

rawDescription: Checking for overlaps in two long lists of items in Python


code:
X = [['A', 'B', 'C'], ['A', 'B', 'D'],['W','X'],['W','Y','Z']]
d = {}

for path in X:
    current_level = d
    for part in path:
        if part not in current_level:
            current_level[part] = {}
        current_level = current_level[part]

rawDescription: How to turn a list into nested dict in Python

description: Turn a list into nested dict in Python


code:
class Foo(object):
    def __mul_(self, other):
        ''' multiply self with other, e.g. Foo() * 7 '''
    def __rmul__(self, other):
        ''' multiply other with self, e.g. 7 * Foo() '''

rawDescription: User defined __mul__ method is not commutative


code:
def fib3(n):
    if n < 3:
        return 1
    a = b = c = 1
    for i in range(3, n):
        # We "shift" a, b, and c to the next values of the sequence.
        a, b, c = b, c, (a + b + c)
    return c
fib3(4)
fib3(5)
fib3(6)
fib3(7)

rawDescription: Fibbonaci-like sequence of last 3 numbers


code:
from django.core.cache import cache

def get(request):
   value = cache.get('somekey')
   if not value:
      # The value in the cache for the key 'somekey' has expired
      # or doesn't exist, so we generate the value
      value = 42
      cache.set('somekey', value)

rawDescription: I wanna use Redis-Cache in my simple Django project. I'm not able to understand the implementation in django


code:
class DefaultHasher(dict):
    def __init__(self, default_factory, change_self=None):
        self.default_factory = default_factory
        self.change_self = change_self
    def change(self, key):
        def _change():
            x = self.default_factory()
            self[key] = x
            return x
        return _change
    def __missing__(self, key):
        self[key] = DefaultHasher(self.default_factory,
                                  self.change(key))
        return self[key]
    def __getattr__(self, name):
        result = self.change_self()
        return getattr(result, name)

foo = DefaultHasher(set)
foo[1][2][3][4][5].add(1)
print(foo)
# {1: {2: {3: {4: {5: set([1])}}}}}

foo[1][2][3].add(20)
print(foo)
# {1: {2: {3: set([20])}}}

foo[1][3] = foo[1][2]
print(foo)
# {1: {2: {3: set([20])}, 3: {3: set([20])}}}

foo[1][2].add(30)
print(foo)
# {1: {2: set([30]), 3: {3: set([20])}}}

rawDescription: Python Deeply Nested Dictionary of a Specific Type


code: df_together = pd.concat([df1, df2]).groupby('key').max()

rawDescription: Merging and Filling in Pandas DataFrames


code:
# basic_test.py
class BasicTest(unittest.TestCase):

  @staticmethod
  def main():
     # Do optparse stuff
     unittest.main()

if __name__ == '__main__':
  BasicTest.main()

# some_basic_test.py
class SomeBasicTest(BasicTest):
   ...

if __name__ == '__main__':
  BasicTest.main()

rawDescription: subclassing python unittest.Testcase, calling the same main

description: Subclassing python unittest.Testcase, calling the same main


code:
import numpy as np
from scipy.optimize import brentq

s = 10014.6
c = 6339.06
mu = 398600.0
dt = 780.0
def f(a):
    alpha = 2*np.arcsin(np.sqrt(s/(2*a)))
    beta = 2*np.arcsin(np.sqrt((s-c)/(2*a)))
    return alpha - beta - (np.sin(alpha)-np.sin(beta)) - np.sqrt(mu/a**3)*dt

a0 = max(s/2, (s-c)/2)
a = brentq(f, a0, 10*a0)

rawDescription: using python to solve a nonlinear equation

description: Using python to solve a nonlinear equation


code:
def foo(vals):
    def f(p,x):
        result=0
        for i,(av,ap) in enumerate(zip(vals,p)):
            result+=av*ap*(x**i)
        return result
    return f

print(foo([50])([2],3))
# f(p,x)=50*2
# 100
print(foo([50,60])([2,3],4))
# f(p,x)=50*2+60*3*x
# 820

rawDescription: Dynamic function building in Python

description: Dynamic function building in Python


rawDescription: Separate list of "letter number" (chess locations) into separate lists


rawDescription: How to round numbers

description: Round numbers


code:
class EditMenu(Tkinter.Menu):

    def __init__(self, parent, listboxes, **kw):
        self.commandhook = kw.get('postcommand', None)
        kw['postcommand'] = self.postcommand
        super(EditMenu, self).__init__(parent, **kw)
        self.listboxes = listboxes
        self.add_command(label="Move to right", command=self.move_to_right)
        self.add_command(label="Move to left", command=self.move_to_left)
        self.add_command(label="Exchange", command=self.exchange)

    def postcommand(self):
        for i in xrange(3):
            # do some checks for each entry
            # and set state to either Tkinter.DISABLED or Tkinter.NORMAL
            self.entryconfig(i, state=state)
        if self.commandhook is not None:
            self.commandhook()

    # Implement your three functions here

rawDescription: python tkinter: Custom menu while pulling down

description: Python tkinter: Custom menu while pulling down


code: list(itertools.islice(it, 0, n, 1))

rawDescription: How to get the n next values of a generator in a list (python)

description: Get the n next values of a generator in a list (python)


code:
from music21 import *

mymusic = stream.Stream()

notes = ["F4", "F4", "rest", "F4"]
durations = [0.25, 1, 0.25, 1]

for n,d in zip(notes, durations):
    if n == "rest":
        mymusic.append(note.Rest(d))
    else:
        mymusic.append(note.Note(n,d))

mymusic.show("midi")

rawDescription: data exchange between R and python (music21)

description: Data exchange between R and python (music21)


code: result1[:] = [x for x in map(func, l) if x is not None]

rawDescription: How to exclude cases from comprehension

description: Exclude cases from comprehension


code:
for elt in theList[ : ]:
    ...

rawDescription: Remove adjacent duplicate elements from a list


code:
EB-ABORTZ,True,False,False,0
EB-AGONCHAROVA,True,False,False,0
EB-AHART-1,True,False,False,0
EB-AHEIDENREICH,True,False,False,0
EB-ALOCKLEAR,True,False,False,0
EB-AMARGULIS,True,False,False,0
EB-ASKLAR,True,False,False,0
EB-ASKLAR-1,True,False,False,0
EB-ASKLAR-3,True,False,False,0
EB-BCHOW-1,True,False,False,0
EB-BJOHNSON,True,False,False,0
EB-BLYLE,True,False,False,0
EB-BRUSSUM,True,False,False,0
EB-CCLEARY,True,False,False,0

rawDescription: Export to CSV separating all chars into fields


code:
query = """
    select *
    from users
    where
        (%(age)s is null or %(age)s = age)
        and
        (%(name)s is null or %(name)s = name)
"""
parameters = dict(name = None, age = 35)
cursor.execute(query, parameters)

rawDescription: Querying on optional parameters

description: Querying on optional parameters


code:
import re

while True:
    name = input('Name(FN/MN/LN): ')
    if len(name) == 0:
        print ('Error! Please enter your real name!')
        continue #Try again
    break # len(name) is not 0, continue

while True:
    nickname = input('Preferred name/nickname: ')
    if len(nickame) == 0: #fixed this to nickname
        print ('Error! Please enter a nickname!')
        continue
    break

nickname=nickname.lower()
if not re.match('^[a-z]*$', nickname):
    print ('Error! Only letters allowed!')
    sys.exit()

rawDescription: How to I loop my program until they have filled it properly when I'm using an if statement?


rawDescription: Filling higher-frequency windows when upsampling with pandas


code:
from cStringIO import StringIO

# ...
def test_some_log_reading_scenario(self):
    log1 = '\n'.join([
        'log line',
        'another log line'
    ])
    log2 = '\n'.join([
        'another log another line',
        'lala blah blah'
    ])
    # ...
    result = myobj.read_log_files([StringIO(log1), StringIO(log2)])
    # assert result

rawDescription: Unit testing functions that access files


code:
#! /usr/bin/env python
import numpy as plotting
import matplotlib
from pylab import *
x = np.random.rand(20)
y = np.random.rand(20)
fig = figure(figsize=(6.5,12))
subplots_adjust(wspace=0.2,hspace=0.2)
iplot = 420
for i in range(7):
    iplot += 1
    if i == 6:
        ax = subplot2grid((4,8), (i/2, 2), colspan=4)
    else:
        # You can be fancy and use subplot2grid for each plot, which dosen't
        # require keeping the iplot variable:
        # ax = subplot2grid((4,2), (i/2,i%2))

        # Or you can keep using add_subplot, which may be simpler:
        ax = fig.add_subplot(iplot)
    ax.plot(x,y,'ko')
    ax.set_xlabel("x")
    ax.set_ylabel("y")
savefig("subplots_example.png",bbox_inches='tight')

rawDescription: Matplotlib: Repositioning a subplot in a grid of subplots


code:
class MyTable(db.Model):
    ...
    my_json_column = db.Column(MutableDict.as_mutable(JSON))

rawDescription: In SQLAlchemy, how does the dict update method interact with the ORM?


code:
from sqlalchemy import exists

session.query(KWViolations).filter(KWViolations.proj_id == project.id).\
    filter(
        ~exists().where(
                and_(
                    KWMethodMetrics.kw_id == KWViolations.kw_id,
                    KWMethodMetrics.checkpoint_id == checkpoint.id
                )
        )
    )

rawDescription: Using NOT EXISTS clause in sqlalchemy ORM query


code:
from subprocess import Popen, PIPE

process = Popen(["ls", "-la", "."], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()

rawDescription: How to call an external program in python and retrieve the output and return code?

description: Call an external program in python and retrieve the output and return code


rawDescription: Django: How can I tell if a certain quality of all objects in a RelatedManager is the same?


code:
from sqlalchemy.ext.hybrid import hybrid_property

class SomeClass(object):
    @hybrid_property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = value

rawDescription: SQLAlchemy Decomposing DateTime Fields

description: SQLAlchemy Decomposing DateTime Fields


code:
root.findall("/n:molpro/n:job",
             namespaces=dict(n="http://www.molpro.net/schema/molpro2006"))

rawDescription: python: xml.etree.ElementTree, removing "namespaces"

description: Python: xml.etree.ElementTree, removing "namespaces"


code:
from facepy import GraphAPI

graph = GraphAPI("CAAErZAZAHDByABAHtXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
graph.get('me/posts')

#if you want to get someone else's post: graph.get('{id}/posts')

rawDescription: Facebook python api documentation on all commands


code:
@classmethod
def function_b(cls):
    cls.function_a()

rawDescription: Python referencing static methods within a class - best practise


code:
class TagListView(ListView):
    def get_queryset(self):
        startdate = timezone.now() - datetime.timedelta(days=7)
        enddate = timezone.now()
        return Tag.objects.filter(last_view__range=[startdate, enddate]).order_by('-views')[:10]
    context_object_name='most_viewed_list'
    template_name='tags/index.html'

urlpatterns = patterns('',
    url(r'^$', TagListView.as_view(), name='index'),
)

rawDescription: Django querying on range of days with timezone.now and __range broken?


code:
import pandas as pd

import matplotlib.pyplot as plt
from matplotlib import dates

# Generate some random data and plot it

time = pd.date_range('07/11/2014', periods=1000, freq='5min')
ts = pd.Series(pd.np.random.randn(len(time)), index=time)

fig, ax = plt.subplots()

ax.plot_date(ts.index.to_pydatetime(), ts.data)

# Create your formatter object and change the xaxis formatting.

date_fmt = '%d/%m/%y %H:%M:%S'

formatter = dates.DateFormatter(date_fmt)
ax.xaxis.set_major_formatter(formatter)

plt.gcf().autofmt_xdate()

plt.show()

rawDescription: How to Customise Pandas Date Time Stamp @ x-axis


code:
endpoint1 = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(QOTDFactory("tweedledee"))
endpoint2 = TCP4ServerEndpoint(reactor, 8008)
endpoint2.listen(QOTDFactory("tweedledum"))

rawDescription: listening on multiple twisted endpoints

description: Listening on multiple twisted endpoints


code:
import urllib

x = "http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json"
tmp = urllib.unquote(x)
tmp2 = tmp % (foo, bar)
x = urllib.quote(tmp2)

rawDescription: How to do a string replace in a urlencoded string

description: Do a string replace in a urlencoded string


code:
TINYMCE_DEFAULT_CONFIG = {
    # your other settings
    'content_css': '/media/css/main.css',
}

rawDescription: Using TinyMCE for sites with a dark background


code:
def partition(number):
    answer = set()
    answer.add((number, ))
    for x in range(1, number):
        for y in partition(number - x):
            answer.add(tuple(sorted((x, ) + y)))
    return answer

partition(4)

rawDescription: Elegant Python code for Integer Partitioning


code:
from itertools import imap, repeat
import csv

fun = pow

with open('m.in', 'r') as input_file :
    with open('m.out', 'wb') as out_file:

        inpt = csv.reader(input_file, delimiter=' ')
        out = csv.writer(out_file, delimiter=' ')

        for row in inpt:
            row = [ int(e) for e in row] #conversion
            opt = repeat(2, len(row) ) # square power for every value

                    # write ( function(data, argument) )
            out.writerow( [ str(elem )for elem in imap(fun, row , opt ) ]  )

rawDescription: Input file, modify column, output file

description: Input file, modify column, output file


code:
from dateutil import parser
import pytz
FR = pytz.timezone('Europe/Paris') # there is the summer offset changing in this zone
date = parser.parse("2013-08-23T23:37:38+0000")
datefr = date.astimezone(FR)

rawDescription: Convert datetime to local python

description: Convert datetime to local python


code:
import wx, wx.calendar

class FoldableWindowContainer(wx.Panel):
    def __init__(self, parent, left, right):
        wx.Panel.__init__(self, parent)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.SetSizer(sizer)
        self.splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        left.Reparent(self.splitter)
        right.Reparent(self.splitter)
        self.left = left
        self.right = right
        self.splitter.SplitVertically(self.left, self.right)
        self.splitter.SetMinimumPaneSize(50)
        self.sash_pos = self.splitter.SashPosition
        sizer.Add(self.splitter, 1, wx.EXPAND)

        fold_button = wx.Button(self, size=(10, -1))
        fold_button.Bind(wx.EVT_BUTTON, self.On_FoldToggle)
        sizer.Add(fold_button, 0, wx.EXPAND)

    def On_FoldToggle(self, event):
        if self.splitter.IsSplit():
            self.sash_pos = self.splitter.SashPosition
            self.splitter.Unsplit()
        else:
            self.splitter.SplitVertically(self.left, self.right, self.sash_pos)

class FoldTest(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)

        left = wx.Panel(self, style=wx.BORDER_SUNKEN)
        right = wx.Panel(self, style=wx.BORDER_SUNKEN)

        left_sizer = wx.BoxSizer(wx.VERTICAL)
        left.SetSizer(left_sizer)
        left_sizer.Add(wx.calendar.CalendarCtrl(left), 1, wx.EXPAND | wx.ALL, 5)
        left_sizer.Add(wx.Button(left, label="Act"), 0, wx.EXPAND | wx.ALL, 5)

        right_sizer = wx.BoxSizer(wx.VERTICAL)
        right.SetSizer(right_sizer)
        right_sizer.Add(
            wx.StaticText(right, label="Fold panel", style=wx.BORDER_RAISED),
            1, wx.EXPAND | wx.ALL, 5
        )

        FoldableWindowContainer(self, left, right)

app = wx.PySimpleApp()
app.TopWindow = FoldTest()
app.TopWindow.Show()
app.MainLoop()

rawDescription: wxPython: A foldable panel widget

description: WxPython: A foldable panel widget


code:
class Brand(BaseModel):
    name = models.CharField(max_length=100, unique=True)
    website = models.URLField(max_length=500, blank=True, default='')

    def __unicode__(self):
        return self.name

rawDescription: Show a field name instead of the whole object for ManyToMany object in django admin site


rawDescription: python as a "batch" script (i.e. run commands from python)

description: Python as a "batch" script (i.e. run commands from python)


code:
from boto.s3 import connect_to_region
from boto.s3.connection import Location
from boto.s3.key import Key

conn = connect_to_region(Location.APSoutheast2,
                         aws_access_key_id=conf.Access_Key_ID,
                         aws_secret_access_key=conf.Secret_Key)
bucket = conn.lookup(bucket_name) # bucket is located in Location.APSoutheast2

k = Key(bucket)
k.key = 'akeynameformyfile'
k.set_contents_from_filename(source_path_of_file_to_upload)

rawDescription: Boto file upload to S3 failing on Windows [errno: 10054]


rawDescription: Django annotate by the objects name which is a ForeignKey


code:
from peewee import *
from playhouse.fields import CompressedField

# tell database that the longblob column type exists
db = MySQLDatabase('test', host='127.0.0.1', user='root',
                   fields={'longblob': 'longblob'})

# create a custom field, in this case subclassing the existing field
class LongCompressedField(CompressedField):
    db_field = 'longblob'  # <-- this matches our dictionary key above

class MyModel(Model):
    val = LongCompressedField()

    class Meta:
        db_table = 'test'
        database = db

db.connect()
db.create_table(MyModel, safe=True)

m = MyModel(val=''.zfill(200000000))
m.save()

rawDescription: Peewee CompressedField gets truncated on MySQL db


code:
string = 'sentence'
indices = range(len(string))        # Python 2
indices = list(range(len(string)))  # Python 3

rawDescription: The most time/space efficient way to list all indices in an object


code:
import wx
class  P:
    def __init__(self):
        """ Create main App """
        self._app = wx.App(redirect=False)

        #""" Load image """
        #png = wx.Image('show_work.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap()

        """ Create dialog """
        self._dialog = wx.Dialog(None, -1, 'Graphical Output', size = (500,500), style=wx.DEFAULT_DIALOG_STYLE & ~wx.RESIZE_BORDER)

        """ Bind image to dialog """
        #wx.StaticBitmap(self._dialog, -1, png, (10,5), (png.GetWidth(), png.GetHeight()))

        """ Create choice list """
        choice_list = []
        for number in xrange(10):
            choice_list.append(str(number +1))

        """ Create choice list """
        self._droplist = wx.Choice(self._dialog, -1, (280, 200), choices = choice_list)

        """ Show dialog """
        self._dialog.ShowModal()

        """ Start main App """
        self._app.MainLoop()

P()

rawDescription: How to use wxPython.Choice in a wxPython.Dialog?

description: Use wxPython.Choice in a wxPython.Dialog


code:
import numpy as np
import pylab as plt

# Your example data
A1 = np.zeros((3,3))
A2 = np.zeros((3,3))
A1[1,1] = 1
A2[2,2] = 1

# Apply a mask to filter out unused values
A1[A1==0] = None
A2[A2==0] = None

# Use different colormaps for each layer
pwargs = {'interpolation':'nearest'}
plt.imshow(A1,cmap=plt.cm.jet,**pwargs)
plt.imshow(A2,cmap=plt.cm.hsv,**pwargs)
plt.show()

rawDescription: Matplotlib imshow - Displaying different colours


code:
import urllib
import hashlib
import hmac
import base64
import urllib.request
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
account_name='****'
account_key='*****'
account_container='***'
file_name='**'
file_path='**'
request_url='https://myaccount.blob.core.windows.net/mycontainer/myblob?comp=appendblock'
#https://myaccount.blob.core.windows.net/mycontainer/myblob?comp=appendblock  Put
blobLength=0
blockID='**'
#create the authorization header
#how to encode and decode signtostring
def createAuthorizationHeader(canonicalizedString):
    storage_account_key = base64.b64decode(account_key)
    byte_canonicalizedString=canonicalizedString.encode('utf-8')
    signature = base64.b64encode(hmac.new(key=storage_account_key,msg=byte_canonicalizedString, digestmod=hashlib.sha256).digest())
    print(signature)
    authorization_str="SharedKey "+account_name+":"+signature.decode('utf-8')
    print(authorization_str)
    return authorization_str

#Construction Sign
def constructSTS(http_verb,Content_Encoding='',Content_Language='',Content_MD5='',Content_Type='',Date='',
                 If_Modified_Since='',If_Match='',If_None_Match='',length='',
                 If_Unmodified_Since='',Range='',CanonicalizedHeaders='',CanonicalizedResource=''):
    StringToSign=http_verb+'\n'+Content_Encoding+'\n'+Content_Language+'\n'+Content_MD5+'\n'+Content_Type+'\n'+Date+'\n'+If_Modified_Since+'\n'+If_Match+'\n'+If_None_Match+'\n'+length+'\n'+If_Unmodified_Since+'\n'+Range+'\n'+CanonicalizedHeaders+CanonicalizedResource;
    print(StringToSign)
    return StringToSign

#Construction Canonicalized headers
def constructCanonicalizedHeaders(date):
    CanonicalizedHeader="x-ms-date:"+date+"\nx-ms-version:2015-02-21\nx-ms-lease-id:"+blockID+"\nms-blob-condition-appendpos:"+youroffset+"\nx-ms-blob-condition-maxsize:4194304\n"
    print(CanonicalizedHeader)
    return CanonicalizedHeader

#Construction  Canonicalized Resource
def constructCanonicalizedResource():
    canonicalizedResource="/"+account_name+"/"+account_container+"/"+file_name+"\ncomp:appendblock"
    print(canonicalizedResource)
    return canonicalizedResource

#get current date
def getCurrentDate():
    now = datetime.now()
    stamp = mktime(now.timetuple())
    date=format_date_time(stamp)
    return date
#Create http request
def createHttpRequest():
    date=getCurrentDate()
    r=urllib.request.Request(request_url)
    canonicalizedString=constructSTS("PUT",CanonicalizedHeaders=constructCanonicalizedHeaders(date),CanonicalizedResource=constructCanonicalizedResource(),length=blobLength)
    print(canonicalizedString)
    r.add_header('x-ms-version','2015-02-21');
    r.add_header('Authorization',createAuthorizationHeader(canonicalizedString))
    r.add_header('x-ms-date',date)
    r.add_header('Content-Length',blobLength)
    r.add_header('x-ms-lease-id',blockID)
    r.add_header("x-ms-blob-condition-appendpos",youroffset)
    r.add_header("x-ms-blob-condition-maxsize",4194304)

rawDescription: Append block in blob service python

description: Append block in blob service python


code:
df1 = df1.reset_index()
pd.melt(df1, id_vars='index', value_vars=df1.columns.tolist()[1:])

rawDescription: Convert N by N Dataframe to 3 Column Dataframe


code:
import time
import getpass
import pexpect

karaf_port = 8101
karaf_id = 'user'
karaf_host = 'localhost'
log_file_name = 'karaf.log'

ssh_command = 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -p {} {}@{}'.format(karaf_port, karaf_id, karaf_host)

karaf_session = pexpect.spawn(ssh_command)

log_file = open(log_file_name, "wb")
karaf_session.logfile_read = log_file

try:
    karaf_session.expect('Password:', timeout=5)
    print('Got "Password:" prompt, sending password')
    karaf_session.sendline(getpass.getpass("Enter your Karaf password: "))
    # etc., etc.
except pexpect.EOF as e:
    print('Connection failed. Got EOF exception waiting for "Password:" prompt')
except pexpect.TIMEOUT as e:
    print('Timed out waiting for "Password:" prompt')

rawDescription: Python pexpect - spawn takes time to establish


rawDescription: Find all values such that .. from a density plot in Python


rawDescription: How can I get the list of registered atexit functions in Python3?

description: Get the list of registered atexit functions in Python3


code: test2 = set([x['TopicArn'] for x in test])

rawDescription: check if string exist inside a list

description: Check if string exist inside a list


code:
import requests
import json

r = requests.get('https://www.googleapis.com/plus/v1/people/me/people/connected')

input_log = json.loads(r.text)

rawDescription: How to get stream from Google+ REST API using python?

description: Get stream from Google+ REST API using python


rawDescription: How to add variables into a string?

description: Add variables into a string


rawDescription: Reverse dns lookup with scapy in python

description: Reverse dns lookup with scapy in python


code:
service.userUsageReport().get(userKey='all',
                              date='2013-12-02',
                              parameters='docs:num_docs_shared_outside_domain').execute()

rawDescription: Reports API - ADMIN SDK

description: Reports API - ADMIN SDK


code:
from itertools import product

my_dict = {'a':1, 'chk':{'b':2, 'c':3}, 'e':{'chk':{'f':5, 'g':6}} }

def process(d):
    to_product = []  # [[('a', 1)], [('b', 2), ('c', 3)], ...]
    for k, v in d.items():
        if k == 'chk':
            to_product.append([(k2, v2)
                              for d2 in process(v)
                              for k2, v2 in d2.items()])
        elif isinstance(v, dict):
            to_product.append([(k, d2) for d2 in process(v)])
        else:
            to_product.append([(k, v)])
    lst = [dict(l) for l in product(*to_product)]
    unique = []
    [unique.append(item) for item in lst if item not in unique]
    return unique

for i in process(my_dict):
    print(i)

# {'e': {'f': 5}, 'b': 2, 'a': 1}
# {'e': {'g': 6}, 'b': 2, 'a': 1}
# {'e': {'f': 5}, 'a': 1, 'c': 3}
# {'e': {'g': 6}, 'a': 1, 'c': 3}

rawDescription: How to split a python dictionary for its values on matching a key

description: Split a python dictionary for its values on matching a key


code:
pdf = pyPdf.PdfFileReader(file(path, "rb"))
content = pdf.getPage(1).extractText()

rawDescription: Is there a library that can open and search through a pdf file?


code:
import numpy
import pickle

RANDOM_STATE_FILE = 'random.bin'

def save_random_state():
    with open(RANDOM_STATE_FILE, 'wb') as f:
        pickle.dump(numpy.random.RandomState.get_state(), f)

def load_random_state():
    with open(RANDOM_STATE_FILE, 'rb') as f:
        numpy.random.RandomState.set_state(pickle.load(f))

rawDescription: Reading and writing a tuple to file (numpy.random.RandomState.get_state)


rawDescription: Numpy: Remove neighboring repeated subarrays in a 2x2 array?


code:
from collections import defaultdict

data = {(1,2,1,5),(1,2,7,2),(1,5,4,7),(4,7,7,5)}
output = defaultdict(list)

for a, b, c, d in data:
    output[a, b].append((c, d))

rawDescription: Adding Multiple Values to Single Key in Python Dictionary Comprehension


code: fruits = {'banana': {'color': 'yellow'}, 'potato': {'color': 'beige'}}

rawDescription: Python create variable for each item

description: Python create variable for each item


code:
im2 = cv2.imread(imgPath)
im = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)
surfDetector = cv2.FeatureDetector_create("SURF")
surfDescriptorExtractor = cv2.DescriptorExtractor_create("SURF")
keypoints = surfDetector.detect(im)
(keypoints, descriptors) = surfDescriptorExtractor.compute(im,keypoints)

rawDescription: Does anyone have any examples of using OpenCV with python for descriptor extraction?


code:
argv = ['-A', 'not slow and not valuations']
nose.main(argv=argv)

rawDescription: Specifying attributes from nose.run() or nose.main()


code:
idx = [slice(None)] * array.ndim
idx[axis] = slice(start, end)
myslice = array[tuple(idx)]

rawDescription: Python - how can I address an array along a given axis?


code:
from django.http import HttpResponse
import xlwt

def my_view(request):
    response = HttpResponse(mimetype="application/ms-excel")
    response['Content-Disposition'] = 'attachment; filename="foo.xls"'
    wb = xlwt.Workbook()
    wb.save(response)
    return response

rawDescription: Use pyExcelerator to generate dynamic Excel file with Django. Ensure unique temporary filename


rawDescription: Python using Selenium to click on a button based on type, value, and class


code:
path1 = "./base/folder1/subfolder"
path2 = "./base/folder2/"
import os
os.path.relpath(path1, path2)
os.path.relpath(path2, path1)

rawDescription: Python find difference between file paths


code:
import gtk

labels = []

def changeLabel(widget):
    l = p.get_children()[1]
    p.remove(l)
    nl = labels[l is l1]
    p.add2(nl)

w = gtk.Window()
w.connect('destroy', lambda w: gtk.main_quit())
p = gtk.HPaned()
w.add(p)
b = gtk.Button('change label')
b.connect('clicked', changeLabel)
p.add1(b)
l1 = gtk.Label('hello world')
l1.show()
p.add2(l1)
l2 = gtk.Label('ciao mondo')
l2.show()
labels = [l1, l2]
which = 0
w.show_all()
gtk.main()

rawDescription: PyGTK: adding text over widgets

description: PyGTK: adding text over widgets


rawDescription: How to use lxml in Python to get the following elements?

description: Use lxml in Python to get the following elements


code:
from selenium import webdriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.remote.command import Command

# monkey patch the click method :

def WebElement_click(self):
    """Clicks the element."""
    print("my click")
    self._execute(Command.CLICK_ELEMENT)

WebElement.click = WebElement_click

# usage example :

driver = webdriver.Chrome()
driver.get('https://stackoverflow.com')
driver.find_element_by_id("nav-questions").click()

rawDescription: Override .click() method of webElement in selenium using Python


code: from __builtin__ import hex

rawDescription: Directly Reference Python's Standard Library


code:
from docx import *
document = opendocx("document.doc")
body = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
body.append(paragraph('Appending this.'))

rawDescription: Read and Write .docx file with python

description: Read and Write .docx file with python


code: textwrap.wrap("This text will display on 3 LCD lines", 20)

rawDescription: chunk string in Python without breaking words

description: Chunk string in Python without breaking words


code:
import array
import numpy as np
a = array.array("d")
a.extend([0,1,2])
a.extend([3,4,5])
b = np.frombuffer(a, np.float).reshape(-1, 3)

rawDescription: efficient way to resize numpy or dataset?

description: Efficient way to resize numpy or dataset


code:
sorted(d, key=lambda k: -len(d[k]))
sorted(d, key=lambda k: len(d[k]), reverse=True)

rawDescription: Python : Best way to sort a python dictionary based on values ; values are lists


code:
for line in jack.split("\n"):
    print(line)

rawDescription: Python IDLE shell - How to make multiline strings


code:
filename = urlparse.urlparse(url).path.split('/')[-1]  # get file name
name = filename.rsplit('.', 1)[0] + '.html'  # change the extension

rawDescription: splitting a path with python

description: Splitting a path with python


code:
p = figure(...)
p.circle(...)
p.rect(...)

rawDescription: What happened to 'hold' in bokeh?

description: What happened to 'hold' in bokeh


code:
dc = filecmp.dircmp('dir1', 'dir2')
dc.diff_files

rawDescription: Diffing two folders (like the diff tool in Linux) with Python


code:
from subprocess import Popen, PIPE

p = Popen(['command', 'and', 'args'], stdout=PIPE, stderr=PIPE, stdin=PIPE)

output = p.stdout.read()
p.stdin.write(input)

rawDescription: Redirecting stdio from a command in os.system() in python


code:
class Candidate(models.Model):
    name = models.CharField(max_length=50)

class Step(model.Model):
    candidate = models.ForeignKey(Candidate)
    text = models.TextField(blank=True)

class Review(models.Model):
    reviewer = models.ForeignKey(User)
    step =  models.OneToOneField(Step)
    text = models.TextField(blank=True)

rawDescription: Django - Which model for a limited related data


rawDescription: How to calculate 3D object points from 2D image points using stereo triangulation?

description: Calculate 3D object points from 2D image points using stereo triangulation


code:
parser.add_argument('-n','--name',...,default=None)
parser.add_argument('-p','--password',...,default=None)
ns = parser.parse_args()

if len([x for x in (ns.name,ns.password) if x is not None]) == 1:
   parser.error('--name and --password must be given together')

name = ns.name if ns.name is not None else "default_name"
password = ns.password if ns.password is not None else "default_password"

rawDescription: python argparse - either both optional arguments or else neither one

description: Python argparse - either both optional arguments or else neither one


code:
import itertools

stuff1, stuff2 = itertools.tee(the_source_generator_or_iterator_or_whatever)

with open('file1.txt', 'w') as file1:
    for thing in stuff1:
        file1.write(thing + '\n')

with open('file2.txt', 'w') as file2:
    for thing in stuff2:
        file2.write(thing + '\n')

rawDescription: When I write to two files in python, the second one is always empty


code:
import re
matches = re.findall(r"\Bmyword", file_contents)

rawDescription: Regular Expression Word Boarder

description: Regular Expression Word Boarder


code:
import random

def get_secret_phrase():
    # Instead of using one long string and creating a list from it, just make a list!
    phrases = ["I like trains","Drop the bass","YouTube is funny","Ebola is dangerous","Python is cool","PHS is 116 years old","I am a person","Sleep is overrated","Programming is fun"]
    # We have a list, we can get its length by using `len()` so there is no need to hardcode a value of 10
    # We also know that lists are 0-indexed, so we can tell `randint()` to get an int between 0 and the length of the list - 1
    index = random.randint(0, len(phrases) - 1)
    # Now we get the phrase at the random `index` we just created
    secret_phrase = phrases[index]
    # An alternative, more pythonic way to do the previous 2 lines is to use `random.choice()` which does the same logic
    #secret_phrase = random.choice(phrases)
    # Finally, return `secret_phrase` and make it lowercase so we can use it in another method
    return secret_phrase.lower()

def get_user_guess():
    # We want to make this separate from `get_secret_phrase()` because this will be called every time we want the user to guess
    print("What is your guess? ")
    # Assign the user input to a variable
    guess = input().lower()
    print("You guessed: {}".format(guess))
    return guess

def get_phrase_progress(secret_phrase, guessed_letters):
    # We want to generate a string that will represent how many letters the user has gotten correctly
    # We will call this every time so that it is always accurate based on what was guessed
    blanks = ''
    for letter in secret_phrase:
        if letter == ' ' or letter in guessed_letters:
            blanks = blanks + letter
        else:
            blanks = blanks + '_'
    return blanks

def get_phrase_progress_pythonic(secret_phrase, guessed_letters):
    # Here's a really pythonic way to do this
    return ''.join(letter if letter == ' ' or letter in guessed_letters else '_' for letter in secret_phrase)

def main():
    guessed_letters = list() # First, create a `list` to store the guessed letters
    secret_phrase = get_secret_phrase() # Next, call `get_secret_phrase()` and assign it's value to a variable in the scope of `main()`

    # Uncomment the following to see that the pythonic version returns the same thing
    # print(get_phrase_progress(secret_phrase, guessed_letters))
    # print(get_phrase_progress_pythonic(secret_phrase, guessed_letters))

    guessed_phrase = get_phrase_progress(secret_phrase, guessed_letters)
    # We want to loop until the user guesses the whole phrase
    while guessed_phrase != secret_phrase:
        print(guessed_phrase)
        # We call `get_user_guess()` to prompt the user to enter a letter
        letter = get_user_guess()
        # Next we want to make sure they entered just 1 letter
        # We can use the built in `str.isalpha()` to check if the string entered by the user is alphabetical and at least 1 character long
        if not letter.isalpha():
            # However, we only want them to guess a single letter, so we also check that the length == 1
            if len(letter) != 1:
                print('You need to guess something...')
            else:
                print('You can only guess a single letter, you tried to guess: {}'.format(letter))
        # Next we check if the user already guessed the letter, if so, tell them!
        elif letter in guessed_letters:
            print('You already guessed {}'.format(letter))
        else:
            guessed_letters.append(letter)
        # Here we calculate `guessed_phrase` every loop to make sure it always takes into account what letters have been guessed
        guessed_phrase = get_phrase_progress(secret_phrase, guessed_letters)

    # If the user escapes the while loop, they won, they guessed the secret phrase
    # We can calculate a score based on how many letters they guessed, this isn't great but it works for a simple scoring method
    print('You won! It took you {} guesses to guess {}'.format(len(guessed_letters), secret_phrase))

main()

rawDescription: Python: Variable scope and parameters issue


code:
import os
os.makedirs('a/b/c', exist_ok=True)

rawDescription: Generating directories/sub-directories and files


code: np.transpose( np.expand_dims(A, axis=2), (2, 1, 0) )

rawDescription: what is an equivalent of matlab permute(A, [3 2 1]) in python?

description: What is an equivalent of matlab permute(A, [3 2 1]) in python


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

g = nx.Graph()
g.add_edges_from([(1,2), (2,3), (2,4), (3,4)])

d = nx.degree(g)

nx.draw(g, nodelist=d.keys(), node_size=[v * 100 for v in d.values()])
plt.show()

rawDescription: Node size dependent on the node degree on NetworkX


code:
import Image

#opens an image:
im = Image.open("1_tree.jpg")
#creates a new empty image, RGB mode, and size 400 by 400.
new_im = Image.new('RGB', (400,400))

#Here I resize my opened image, so it is no bigger than 100,100
im.thumbnail((100,100))
#Iterate through a 4 by 4 grid with 100 spacing, to place my image
for i in xrange(0,500,100):
    for j in xrange(0,500,100):
        #I change brightness of the images, just to emphasise they are unique copies.
        im=Image.eval(im,lambda x: x+(i+j)/30)
        #paste the image at location i,j:
        new_im.paste(im, (i,j))

new_im.show()

rawDescription: How do you merge images using PIL/Pillow?

description: Merge images using PIL/Pillow


code:
#Save a dictionary into a pickle file.
import pickle

favorite_color = { "lion": "yellow", "kitty": "red" }

pickle.dump( favorite_color, open( "save.p", "wb" ) )

# Load the dictionary back from the pickle file.

favorite_color = pickle.load( open( "save.p", "rb" ) )

rawDescription: python how to store a list in a file and get it back

description: Python how to store a list in a file and get it back


code: pos = mylist.index(max(mylist))

rawDescription: Efficient way to get the position info of the biggest item in a Python list


code:
import csv

with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

rawDescription: Write a list of sets to CSV - Python

description: Write a list of sets to CSV - Python


code:
n=10
for i in range(0, n):
    asci = (ord('z') - i + 1 )
    char = chr(asci)
    print (char*i)

rawDescription: How to make A reverse pyramid

description: Make A reverse pyramid


code:
from your_project import settings
from django.core.management import setup_environ
setup_environ(settings)

rawDescription: Django script to access model objects without using manage.py shell


code:
def writetocsv(l):
   #convert the set to the list
    b = list(l)
    #print b  #checking print b, it prints all values of b
    with open("eggs.csv",'wb') as f:
            w = csv.writer(f)

            for value in b:
                 w.writerow(value)

rawDescription: List to CSV Writer Python

description: List to CSV Writer Python


code:
answers = Answer.objects.all().prefetch_related('photos')

for answer in answers:
    result = extract_data(answer)
    for photo in answer.photos.all():
        result += photo.name + '\r'

    append_result_to_report(result)

rawDescription: Django how to make this query more efficient


code:
out_cc = env.Command('file.wave.cpp', 'file.cpp', 'wave command < $SOURCE > $TARGET')
env.Program('myprog', ['this.cc', 'that.cc', out_cc])

rawDescription: Scons - using custom preprocessor with scons cache


code:
import sys
from PyQt4 import QtGui, QtCore

class Widget(QtGui.QWidget):
    """ Here we add more buttons, if the size of the buttons exceeds the size of the widget scrolling starts. """
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.vbox = QtGui.QVBoxLayout()
        self.vbox.setSizeConstraint(QtGui.QLayout.SetMinAndMaxSize)
        self.setLayout(self.vbox)

    def add_button(self):
        tmp = QtGui.QPushButton("...", self)
        self.vbox.addWidget(tmp)

class ScrollArea(QtGui.QScrollArea):
    """ This scroll area only handles one widget for which scrolling should be provided. """
    def __init__(self, parent=None):
        QtGui.QScrollArea.__init__(self, parent)

        self.w = Widget()
        self.setWidget(self.w)    #set the widget to provide scrolling for here

    def add_button(self):
        self.w.add_button()

class MainWindow(QtGui.QWidget):
    """ Use this widget to arrange the QScrollArea and the QPushButton. """
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self)

        self.vbox = QtGui.QVBoxLayout()
        self.scroll = ScrollArea(self)
        self.vbox.addWidget(self.scroll)

        self.plus = QtGui.QPushButton("button", self)
        self.connect(self.plus, QtCore.SIGNAL("clicked()"), self.add_button)
        self.vbox.addWidget(self.plus)

        self.setLayout(self.vbox)

    def add_button(self):
        self.scroll.add_button()

app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())

rawDescription: QScrollArea is expanding instead of scrolling


rawDescription: make list separate values

description: Make list separate values


code:
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import matplotlib.animation as manim
from matplotlib.collections import PatchCollection

Nx = 30
Ny = 20
numtimes = 100

size = 0.5

x, y = np.ogrid[-1:1:30j, -1:1:20j]

data = np.zeros((numtimes, Nx, Ny))

for i in range(numtimes):
    data[i] = (x-i*0.02+1)**2 + y**2

colors = plt.cm.rainbow(data)

fig, ax = plt.subplots()

rects = []
for (i,j),c in np.ndenumerate(data[0]):
    rect = plt.Rectangle([i - size / 2, j - size / 2],size, size)
    rects.append(rect)

collection = PatchCollection(rects, animated=True)

ax.add_collection(collection)
ax.autoscale_view(True)

def animate(tind):
    c = colors[tind].reshape(-1, 4)
    collection.set_facecolors(c)
    return (collection,)

ani = manim.FuncAnimation(fig, animate, frames=numtimes,
        interval=10, blit=True, repeat=False)

plt.show()

rawDescription: Matplotlib funcanimation blit slow

description: Matplotlib funcanimation blit slow


code:
for k in fourB.keys():
    fourB[k].sort()

rawDescription: How do I sort a list in a dictionary

description: Sort a list in a dictionary


rawDescription: parsing id from text with python

description: Parsing id from text with python


code:
error = driver.find_element_by_xpath("""//*[@id="MemberNameError"]""")
with open("emails_available.txt", "a") as email_txt:
   if error.is_displayed():
      print(line.strip() + " is taken")
   else:
      print(line.strip() + " is available")
      email_txt.write(line.strip() + "@hormail.com" + "\n")

rawDescription: Python writing text files

description: Python writing text files


code: d = dict(zip(l, t))

rawDescription: Python Dictionary with List as Keys and Tuple as Values


code:
res = {"cmd": "echo \"Hello World\" ", "end": "2014-08-01 19:32:38.714584", "stdout": "Hello World", "changed": True, "start": "2014-08-01 19:32:38.707510", "delta": "0:00:00.007074", "stderr": "", "rc": 0, "invocation": {"module_name": "shell", "module_args": "echo \"Hello World\""}}

def json_log(res, host):
    if isinstance(res,dict) and 'verbose_override' not in res:
           res.update({"host": host})
           combined_json  = JSONEncoder().encode(res)
           print(combined_json)

In [73]: json_log(res,"centos")
{"cmd": "echo \"Hello World\" ", "end": "2014-08-01 19:32:38.714584", "stdout": "Hello World", "changed": true, "rc": 0, "start": "2014-08-01 19:32:38.707510", "host": "centos", "stderr": "", "delta": "0:00:00.007074", "invocation": {"module_name": "shell", "module_args": "echo \"Hello World\""}}

rawDescription: Better way of merging two json strings in Python for ansible callback_plugin


code:
rows = [row1,row2,row3,row4,row5]  # you'd generate rows in a cleaner way

cols = list(zip(*rows))

printedxrows = [ ("[X]","[X]","[X]","[X]","[X]","  <- V: {}   TOTAL: {}"
                                               .format(row.count(0), sum(row)))
                 for row in rows ]

rawDescription: Condensing Repetitive Code in Python?

description: Condensing Repetitive Code in Python


code: "%.3f" % math.pi

rawDescription: Getting a number of digits

description: Getting a number of digits


code:
import urllib
url = '/test/test?' + urllib.urlencode({
  'Monetization Source': mid,
  'Channel Id': cid,
})

rawDescription: String Interpolation in Python

description: String Interpolation in Python


code:
class ComboBox(QtGui.QComboBox):
    def showPopup(self):
        self.insertItem(0, 'Added')
        super(ComboBox, self).showPopup()

rawDescription: QComboBox mouse press event when combo box is initially pressed PyQt4


code:
operation = "x**4"
num_list = [4,3,2]
[eval(operation) for x in num_list]

rawDescription: Convert a math equation in string format to something workable in Python3


code: sum([True, True, False, False, False, True])

rawDescription: Counting the number of True Booleans in a Python List


code:
class Quiz(db.Model):
    # Data specific to your Quiz: number, name, times shown, etc
    questions = db.ListProperty(db.Key)

class Questions(db.Model):
    question = db.StringProperty()
    choices = db.StringListProperty() # List of possible anwsers
    correct = db.IntegerpProperty() # index of string in choices that is correct

rawDescription: Database Design Inquiry

description: Database Design Inquiry


code:
# Sometimes MCO gives us a ruby hash as a string, We can coerce this into json then into dictionary
def convert_hash_to_dict(self,ruby_hash):
    dict_str = ruby_hash.replace(":",'"')    # Remove the ruby object key prefix
    dict_str = dict_str.replace("=>",'" : ') # swap the k => v notation, and close any unshut quotes
    dict_str = dict_str.replace('""','"')    # strip back any double quotes we created to sinlges
    return json.loads(dict_str)

rawDescription: Converting a Ruby hash string to a Python dictionary


code:
from tkinter import ttk, messagebox, Toplevel, Tk
import time
import multiprocessing

def foo():
    for i in range(100):
        print(i)
        time.sleep(0.1)

class ProcessWindow(Toplevel):
    def __init__(self, parent, process):
        Toplevel.__init__(self, parent)
        self.parent = parent
        self.process = process

        terminate_button = ttk.Button(self, text="Cancel", command=self.cancel)
        terminate_button.grid(row=0, column=0)

        self.grab_set() # so you can't push submit multiple times

    def cancel(self):
        self.process.terminate()
        self.destroy()
        messagebox.showinfo(title="Cancelled", message='Process was terminated')

    def launch(self):
        self.process.start()
        self.after(10, self.isAlive)            # Starting the loop to check when the process is going to end

    def isAlive(self):
        if self.process.is_alive():                     # Process still running
            self.after(100, self.isAlive)               # Going again...
        elif self:
            # Process finished
            messagebox.showinfo(message="sucessful run", title="Finished")
            self.destroy()

class MainApplication(ttk.Frame):
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.button = ttk.Button(self, text = "foo", command = self.callback)
        self.button.grid(row = 0, column = 0)

    def callback(self):
        proc = multiprocessing.Process(target=foo)
        process_window = ProcessWindow(self, proc)
        process_window.launch()

def main():
    root = Tk()
    my_app = MainApplication(root, padding=(4))
    my_app.grid(column=0, row=0)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: How to run a cancellable function when a new Tkinter window opens

description: Run a cancellable function when a new Tkinter window opens


code:
separator=''
for e in dom('td.spgb-f')[:15]:
    for a in e('span.sptc-e'):
        ...
        print (separator + 'adding %s' %(plaintext(a.content)))
        separator = ', '

rawDescription: DOM parsing a document: adding and removing comma based on condition


code:
from django.template.loader import render_to_string
context = {'foo': 'bar'}
rendered_template = render_to_string('template.html', context)

rawDescription: Django include template tag alternative in python class


code:
for x in list:
   with classvar() as y:
       with open("test.csv", "w") as f:
           f.write(y)

rawDescription: Python run out of memory on mac

description: Python run out of memory on mac


code:
import gmpy2
gmpy2.set_context(gmpy2.ieee(32))
ctx=gmpy2.get_context()
ctx
gmpy2.const_pi().digits(2)
ctx.round=gmpy2.RoundDown
gmpy2.const_pi().digits(2)
ctx.round=gmpy2.RoundUp
gmpy2.const_pi().digits(2)

rawDescription: How do I access rounding modes defined in IEEE 754 in python?

description: Access rounding modes defined in IEEE 754 in python


code:
for subtree in tree.subtrees():
    s = subtree.label()
    subtree.set_label(re.sub('-.*', "", s))

rawDescription: How to iterate through all nodes of a tree?

description: Iterate through all nodes of a tree


code:
import sys
sys.path.append('/xyz')
import first
# eventually in you want to clean sys.path after the import
sys.path.remove('/xyz')

rawDescription: Calling one module into another if both modules are in diffrent directories


code:
import json
from collections import Counter
from operator import itemgetter

counter = None
state_getter = itemgetter('state')

with open('zips.json') as fh:
    zips_data = (json.loads(line) for line in fh)
    states_names = map(itemgetter('state'), zips_data)
    counter = Counter(states_names)

print(counter)

rawDescription: Problems with json file (Python)

description: Problems with json file (Python)


code:
with open("file.txt", "r") as in_file:
    buf = in_file.readlines()

with open("file.txt", "w") as out_file:
    for line in buf:
        if line == "; Include this text\n":
            line = line + "Include below\n"
        out_file.write(line)

rawDescription: Adding lines after specific line

description: Adding lines after specific line


code:
import types
def handle(self, *args, **options):
    if not args:
       do_something()
    # check if everything in args is a Int
    elif all( isinstance(s, types.IntType) for s in args):
       do_some_ather_thing()
    # as before with strings
    elif all( isinstance(s, types.StringTypes) for s in args):
       do_totally_different_thing()

rawDescription: How to check type of variable? Python

description: Check type of variable? Python


code:
ax = plt.gca()  # get the current axes
ax.relim()      # make sure all the data fits
ax.autoscale()  # auto-scale
# only needed mpl < 1.5
# ax.figure.canvas.draw_idle()       # re-draw the figure

rawDescription: Using Matplotlib and iPython, How to reset x and y axis limits to Autoscale?


code:
import numpy as np
import pylab as pl

Y, X = np.mgrid[-10:10:100j, -10:10:100j]

def f(x):
    return x**3 -3*x + 5

px = -2.0
py = -np.sqrt(f(px))

qx = 0.5
qy = np.sqrt(f(qx))

k = (qy - py)/(qx - px)
b = -px*k + py

poly = np.poly1d([-1, k**2, 2*k*b+3, b**2-5])

x = np.roots(poly)
y = np.sqrt(f(x))

pl.contour(X, Y, Y**2 - f(X), levels=[0])
pl.plot(x, y, "o")
pl.plot(x, -y, "o")

x = np.linspace(-5, 5)
pl.plot(x, k*x+b)

rawDescription: Python -- Matplotlib for elliptic curve with sympy solve()


code:
class View():
    def __init__(self, master, controller):
        self.canvas = Canvas(root)
        self.canvas.pack()
        self.canvas.bind("<Button-1>", controller.select)

class Controller():
    def __init__(self, master):
        self.model = model.Model()
        self.view = view.View(master, self)
    def select(self, event):
        canvas = event.widget
        # ...

rawDescription: tkinter binding event from controller

description: Tkinter binding event from controller


code:
distutils.core.setup(
      windows=[
            {'script': 'yourmodule.py',
             'icon_resources': [(1, 'moduleicon.ico')]
            }
      ],
      zipfile=None,
      options={'py2exe':{
                         'includes': ['tkinter'],
                         'bundle_files': 1
                        }
      }
  )

rawDescription: Create a standalone windows exe which does not require pythonXX.dll


code:
glob = "/home/spark-1.4.0/A/B_2{0}/Output/CSV.csv".format("[0-9]" * 8)
lines = sc.textFile(glob)

rawDescription: Regular expressions in PySpark textFile command


rawDescription: Faster method to get _set.all() values in m2m relationships with Django


code:
class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        layout = QGridLayout()
        self.sliders = []
        slider_amount = 3
        slider_precision = 10000 # sliders work only with ints, so large ints are used and mapped to floats
        for i in range(slider_amount):
            slider = QSlider(Qt.Horizontal)
            slider.setRange(0, slider_amount*slider_precision)
            slider.setSingleStep(slider.maximum()/100.0)
            slider.setPageStep(slider.maximum()/20.0)
            slider.valueChanged.connect(self.on_slider_value_changed)
            slider.float_value = (i+1)/((1+slider_amount)/2.0*slider_amount) # provide your own default values
            slider.label = QLabel()
            self.sliders.append(slider)
            layout.addWidget(slider, i, 0)
            layout.addWidget(slider.label, i, 1)
        self.update_slider_values()
        self.setLayout(layout)
        self.show()

    def on_slider_value_changed(self, value):
        changed_slider = self.sender()
        changed_slider.float_value = float(value)/changed_slider.maximum()
        delta = sum(slider.float_value for slider in self.sliders)-1
        while abs(delta)>0.00001:
            d = len(self.sliders)-1
            for slider in self.sliders:
                if slider is changed_slider:
                    continue
                old_value = slider.float_value
                slider.float_value = min(max(0, old_value-delta/d), 1)
                delta -= old_value-slider.float_value
                d -= 1
        self.update_slider_values()

    def update_slider_values(self):
        for slider in self.sliders:
            slider_signals_blocked = slider.blockSignals(True)
            slider.setValue(round(slider.float_value*slider.maximum()))
            slider.blockSignals(slider_signals_blocked)
            slider.label.setText('{:.2f}'.format(slider.float_value))

app = QApplication(sys.argv)
mw = MainWindow()
app.exec_()

rawDescription: How do you make linked sliders in Qt?

description: Make linked sliders in Qt


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''

Google

Example

''')
[a.get_text().strip() for a in soup.find_all('a')]
[a.get_text().strip() for a in soup.find_all('a', text=True)]

rawDescription: Retrieve contents from broken <a> tags using Beautiful Soup


code:
def remove_empty(l):
    return tuple(filter(lambda x:not isinstance(x, (str, list, tuple)) or x, (remove_empty(x) if isinstance(x, (tuple, list)) else x for x in l)))

rawDescription: Remove all empty nested lists

description: Remove all empty nested lists


code:
import csv
from itertools import groupby

for key, rows in groupby(csv.reader(open("foo.csv")),
                         lambda row: row[0]):
    with open("%s.txt" % key, "w") as output:
        for row in rows:
            output.write(",".join(row) + "\n")

rawDescription: How to split a huge csv file based on content of first column?

description: Split a huge csv file based on content of first column


code:
def recurse(A):
    if A.shape[0]>A.shape[1]:   #split longest axis first
        if not np.isnan( A[0,A.shape[1]//2]):
            return [rect for part in np.split(A, 2, axis=1) for rect in recurse(part)]
        if not np.isnan( A[A.shape[0]//2,0]):
            return [rect for part in np.split(A, 2, axis=0) for rect in recurse(part)]
    else:
        if not np.isnan( A[A.shape[0]//2,0]):
            return [rect for part in np.split(A, 2, axis=0) for rect in recurse(part)]
        if not np.isnan( A[0,A.shape[1]//2]):
            return [rect for part in np.split(A, 2, axis=1) for rect in recurse(part)]
    return [A]

rawDescription: Numpy -- Split 2D array into sub-arrays based on indices


code:
import urllib, cStringIO

file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)

rawDescription: How do I read image data from a URL in Python?

description: Read image data from a URL in Python