code:
def SendSSLPacket(self, hsMsg, seq, renegotiate):
        rec = hsMsg
        recLen = len(rec)
        rec_len_packed = pack('>H', recLen)

        self.seqNum = pack('>Q', seq)

        #
        # The following initIV is just for testing
        # Will be replaced by random number later
        #
        initIV = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02"

        m = hmac.new(self.sslStruct['wMacPtr'],
            digestmod=sha1)
        m.update(self.seqNum)
        m.update("\x16")
        m.update("\x03")
        m.update("\x02")
        m.update(rec_len_packed)
        m.update(rec)
        m = m.digest()

        self.HexStrDisplay("Final MAC", Str2HexStr(m))

        currentLength = len(rec + m) + 1
        blockLength = 16
        pad_len = blockLength - \
            (currentLength % blockLength)

        if pad_len == blockLength:
            pad_len = 0

        self.log("Padding Length: %s" % (str(pad_len)))

        padding = ''
        for iter in range(0, pad_len + 1):
            padding = padding + \
            struct.pack('B', pad_len)

        self.HexStrDisplay("Padding", Str2HexStr(padding))

        self.sslStruct['recordPlusMAC'] = \
            initIV + rec + m + padding
        self.HexStrDisplay("Final Packet", Str2HexStr(
            self.sslStruct['recordPlusMAC']))

        if renegotiate == 1:
            enc_hs_with_reneg = AES.new( self.sslStruct['wKeyPtr'], AES.MODE_CBC, self.sslStruct['wIVPtr'])
            encryptedData = enc_hs_with_reneg.encrypt(self.sslStruct['recordPlusMAC'])

        if renegotiate == 0:
            enc_hs_wo_reneg = AES.new( self.sslStruct['wKeyPtr'], AES.MODE_CBC, self.sslStruct['wIVPtr'] )
            encryptedData = enc_hs_wo_reneg.encrypt(self.sslStruct['recordPlusMAC'])

        packLen = len(encryptedData)

        self.sslStruct['encryptedRecordPlusMAC'] = \
            tls11RecHeaderDefault + \
            Pack2Bytes(packLen) + encryptedData
        self.HexStrDisplay("Encrypted Packet",
            Str2HexStr(self.sslStruct['encryptedRecordPlusMAC']))

        self.socket.send(
            self.sslStruct['encryptedRecordPlusMAC'])

rawDescription: TLS v 1.1 MAC calculation

description: TLS v 1.1 MAC calculation


code:
import lxml.etree
doc = lxml.etree.parse(xml)
count = doc.xpath('count(//author)')

rawDescription: Is there an elegant way to count tag elements in a xml file using lxml in python?


rawDescription: Python custom text to html syntax

description: Python custom text to html syntax


code:
import tkinter as tki # Tkinter -> tkinter in Python3

class App(object):

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

    # create a Frame for the Text and Scrollbar
        txt_frm = tki.Frame(self.root, width=600, height=400)
        txt_frm.pack(fill="both", expand=True)
        # ensure a consistent GUI size
        txt_frm.grid_propagate(False)

    # create first Text label, widget and scrollbar
        self.lbl1 = tki.Label(txt_frm, text="1")
        self.lbl1.grid(row=0,column=0,padx=2,pady=2)

        self.txt1 = tki.Text(txt_frm, borderwidth=3, relief="sunken", height=4,width=55)
        self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)

        scrollb1 = tki.Scrollbar(txt_frm, command=self.txt1.yview)
        scrollb1.grid(row=0, column=2, sticky='nsew')
        self.txt1['yscrollcommand'] = scrollb1.set

    # create second Text label, widget and scrollbar
        self.lbl2 = tki.Label(txt_frm, text="2")
        self.lbl2.grid(row=1,column=0,padx=2,pady=2)

        self.txt2 = tki.Text(txt_frm, borderwidth=3, relief="sunken",height=4,width=55)
        self.txt2.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt2.grid(row=1, column=1, sticky="nsew", padx=2, pady=2)

        scrollb2 = tki.Scrollbar(txt_frm, command=self.txt2.yview)
        scrollb2.grid(row=1, column=2, sticky='nsew')
        self.txt2['yscrollcommand'] = scrollb2.set

    # create third Text label, widget and scrollbar
        self.lbl3 = tki.Label(txt_frm, text="3")
        self.lbl3.grid(row=2,column=0,padx=2,pady=2)

        self.txt3 = tki.Text(txt_frm, borderwidth=3, relief="sunken",height=4,width=55)
        self.txt3.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt3.grid(row=2, column=1, sticky="nsew", padx=2, pady=2)

        scrollb3 = tki.Scrollbar(txt_frm, command=self.txt3.yview)
        scrollb3.grid(row=2, column=2, sticky='nsew')
        self.txt3['yscrollcommand'] = scrollb3.set

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

rawDescription: More than one text box on a gui

description: More than one text box on a gui


code:
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window

class TutorialApp(App):
    def build(self):
        sv = ScrollView(size=Window.size)
        l = Image(
            source='kivy.jpg',
            size_hint=(None, None),
            keep_ratio=True,
            size=Window.size
        )
        sv.add_widget(l)
        return sv

if __name__ == "__main__":
    TutorialApp().run()

rawDescription: Kivy: Image scrolling

description: Kivy: Image scrolling


code:
import random, string

key = "".join([random.choice(string.letters + string.digits + string.punctuation) for _ in xrange(64)])

rawDescription: My own API Key to my RPC server

description: My own API Key to my RPC server


code:
from __future__ import with_statement
import contextlib

with contextlib.closing(sftpClient.open('file.name', 'w')) as f:
   f.write('myData')

rawDescription: File-like operations without the file?

description: File-like operations without the file


code:
engine = create_engine(database_url)

def on_connect(conn, record):
    conn.execute('pragma foreign_keys=ON')

from sqlalchemy import event
event.listen(engine, 'connect', on_connect)

rawDescription: delete not cascaded to table in sqlalchemy

description: Delete not cascaded to table in sqlalchemy


code:
import numpy
mat = numpy.matrix("1 2 3; 4 5 6; 7 8 9")
mat.dump("my_matrix.dat")
mat2 = numpy.load("my_matrix.dat")

rawDescription: Saving and loading a Numpy Matrix in python


code:
class Program(db.Model):
    name = db.StringProperty("Title")
    slug = db.StringProperty("Slug")
    def put(self):
        if Program.get_by_key_name(self.slug):
            raise UniqueConstraintViolation("slug", self.slug)
        self._key_name = self.slug
        return db.Model.put(self)

class UniqueConstraintViolation(Exception):
    def __init__(self, scope, value):
        super(UniqueConstraintViolation, self).__init__("Value '%s' is not unique within scope '%s'." % (value, scope, ))

rawDescription: How do I create a unique property in python on google app engine?

description: Create a unique property in python on google app engine


code:
s = f['Adj Close'].to_json(date_format='iso',orient='split')
d = json.loads(s)  # import json
[{"index": date, "value": val} for date, val in zip(d['index'], d['data'])]
json.dumps([{"index": date, "value": val} for date, val in zip(d['index'], d['data'])])

rawDescription: How to convert Pandas Dataframe to the desired Json format

description: Convert Pandas Dataframe to the desired Json format


code:
l = [0, 1, 1, 2, 2]
d = {}
for i in l: d[i] = d.has_key(i)

[k for k in d.keys() if not d[k]]

rawDescription: Python filter a list to only leave objects that occur once


code:
class OrderPage(TemplateView):
    ...
    amount = None

    def post(self, request, *args, **kwargs):
        ...

        if form.is_valid():
            self.amount = form.cleaned_data['sum']
        ...

    def get_context_data(self, **kwargs):

        # Here you can use self.amount
        ...

rawDescription: Variable from post() to get_context_data() methods of TemplateView


code:
import os
import re

def replace_action(target, source, env):
    # NB. this is a pretty sloppy way to write a builder, but
    #     for things that are used internally or infrequently
    #     it should be more than sufficient
    assert( len(target) == 1 )
    assert( len(source) == 1 )
    srcf = str(source[0])
    dstf = str(target[0])
    with open(srcf, "r") as f:
        contents = f.read()
        # In cases where this builder fails, check to make sure you
        # have correctly added REPLST to your environment
        for old, new in env['REPLST']:
            contents = re.sub( old, new, contents )
        with open( dstf, "w") as outf:
            outf.write(contents)

replace_builder = Builder(action = replace_action)

env = Environment( ENV = os.environ )
env.Append( BUILDERS = {'Replace' : replace_builder } )
b = env.Replace( 'somefile', ['somefile.tmpl'], REPLST=[('A','b')] )
lib = env.SharedLibrary('lib', object + [b], extra_libs )

rawDescription: SCons: How to call a self defined python function in scons script and make right dependency


code:
if response == "st":
    st_search = raw_input("Search tracks: ")
    return [ t for t in tracks if st_search==t[1] ]
elif response == "sa":
    sa_search = raw_input("Search artists: ")
    return [ t for t in tracks if sa_search==t[0] ]

rawDescription: Searching through a 2D list?

description: Searching through a 2D list


code:
word_length = 3
file = 'practice.txt'
with open(file) as f:
    cnt = 0
    for word in f.read().replace('.','').split():
        if len(word) <= word_length:
            continue
        cnt += 1
print("There are {} words in {} that have over {} characters".format(
    cnt, file, word_length))

rawDescription: Count words over 3 characters using python?


code:
from sqlalchemy import literal
from sqlalchemy.dialects.mysql import SET

class MyTable(Model):

    letters = Column(SET('a', 'b', 'c', 'd', 'e'), server_default=literal('a,b'))

rawDescription: How do I set the server_default for a MySQL SET in SQLAlchemy?

description: Set the server_default for a MySQL SET in SQLAlchemy


rawDescription: Python datetime conversions from one local timezone to another (+ bonus DST's)


code:
def createDailyAvg(p):  # The method
    dailyAvg = []   # this creates the initial empty array for this method below
    i = 0
    while i < 35140:    # I have 35140 data points in my array
        dailyAvg.append(np.mean(p[i:i+96]))  #Creates the avg of the 96, 15 minute avg
        i += 96
    return dailyAvg

dailyAvgWind = createDailyAvg(Wind) # Wind is the array of 15 minute avg's.
dailyAvgDemand = createDailyAvg(M) # M is the array of demand avg's

rawDescription: Generalizing a method in Python

description: Generalizing a method in Python


code:
def make_lists():
    return ['Hello']  # Your are creating the list with a single value,
                      # and return it

def print_list(ls):
    for i in ls:      # You are iterating thru the list,
        print(i)      # which is the input of this function

def main():
    print_list(make_lists())  # In your main function you call the make_list()
                              # which will return the newly created list, and
                              # pass it to print_list, which will iterate thru
                              # the list and prints your values out

if __name__ =="__main__":
    main()

rawDescription: Passing list Between Functions

description: Passing list Between Functions


code:
from operator import itemgetter
from collections import Counter
c = Counter({'A': 10, 'C':5, 'H':4})
sorted(c.items(), key=itemgetter(0))

rawDescription: sorting a counter in python by keys

description: Sorting a counter in python by keys


code:
while curr_row < num_rows: # for each row
    curr_row += 1
    row = worksheet.row(curr_row)
    if curr_row > 0: # don't want the first row because those are labels
        for col_ind, el in enumerate(row):
            inputData[curr_row - 1, col_ind] = el.value

rawDescription: Python: Convert xlrd sheet to numpy matrix (ndarray)


code:
def clean_images(self):
    files = self.files.getlist('images')
    for file in files:
        if file:
            if file._size > 15*1024*1024:
                raise forms.ValidationError("Image file is too large ( > 15mb ).")
        else:
            raise forms.ValidationError("Could not read the uploaded file.")
    return files

rawDescription: Django: How to write a clean method for a field that allows mutiple file uploads?


code:
from tkinter import Tk, Message

root = Tk()
m = Message(text="This is a Tkinter message widget. Pretty exiting, huh? I enjoy Tkinter. It is very simple.")
m.pack(expand=True, fill='x')
m.bind("<Configure>", lambda e: m.configure(width=e.width-10))
root.mainloop()

rawDescription: How to make Tkinter message expand when I resize the window?

description: Make Tkinter message expand when I resize the window


code:
Ts = [T0]
Tx = []
counter = 1
for T in Ts:
    for t in T:
        Ts.append([s[0] * s[1] + s[2] for s in izip(Ts[-1], C, QIN)])

rawDescription: Looping through lists with different number of elements


code:
query = Docs.query()
multi_future = query.map_async(lambda entity: P(...).callback(entity))

rawDescription: App engine Python NDB map_async using callback, objects and inheritance pattern


code:
cursor.execute ("""
        INSERT INTO dailylog
        (emp, content, entrytime, shift, shiftday, containingweek)
        VALUES (%s, %s, %s, %s, %s, %s)
        """, (emp, content1, entrytime, shift, shiftday, containingweek))

rawDescription: python mysql is this a parameterized statement? choking on special characters

description: Python mysql is this a parameterized statement? choking on special characters


rawDescription: Pandas: How to unstack a series

description: Pandas: How to unstack a series


code:
def connectionMade(self):
    self.factory.clients.append(self)
    self.setRawMode()
    startClock(self)

rawDescription: running only one twisted looping call

description: Running only one twisted looping call


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

data = np.loadtxt('data.txt')

# Resample your data grid by a factor of 3 using cubic spline interpolation.
data = scipy.ndimage.zoom(data, 3)

plt.contour(data)
plt.show()

rawDescription: How to smooth matplotlib contour plot?

description: Smooth matplotlib contour plot


code:
@ndb.tasklet
def defer_fetch_document(user_key, document_key):
    queue = taskqueue.Queue("process-documents")
    task = taskqueue.Task(url="<url for worker>",
                          params={"document_key": document_key.urlsafe()})
    yield queue.add_async(task)  #this returns a rpc which you can yield on
    raise ndb.Return(True)

rawDescription: Defer multiple tasks in google app engine asynchronously


code:
import inspect

def first():
    return second()

def second():
    return inspect.getouterframes( inspect.currentframe() )[1]

first()[3] # 'first'

rawDescription: Get parent function

description: Get parent function


code:
im = np.array([[2, 3, 2], [3, 4, 1], [6, 1, 5]])
mask = np.array([[False, False, True], [False, True, True], [False, False, False]])

# note that the mask is inverted (~) to show color where mask equals true
im_ma = np.ma.array(im, mask=~mask)

# some default keywords for imshow
kwargs = {'interpolation': 'none', 'vmin': im.min(), 'vmax': im.max()}

fig, ax = plt.subplots(1,3, figsize=(10,5), subplot_kw={'xticks': [], 'yticks': []})

ax[0].set_title('"Original" data')
ax[0].imshow(im, cmap=plt.cm.Greys_r, **kwargs)

ax[1].set_title('Mask')
ax[1].imshow(mask, cmap=plt.cm.binary, interpolation='none')

ax[2].set_title('Masked data in color (jet)')
ax[2].imshow(im, cmap=plt.cm.Greys_r, **kwargs)
ax[2].imshow(im_ma, cmap=plt.cm.jet, **kwargs)

rawDescription: Applying different color map to mask

description: Applying different color map to mask


code:
import lxml.html
from lxml.cssselect import CSSSelector
str = """
'<input type="radio" name="rd1" value="E" checked="checked" />Employee
<input type="radio" name="rd2" value="o" />Other'
"""
input_sel = CSSSelector('input[name="rd1"]')
lx = lxml.html.fromstring(str)
input_sel(lx)

rawDescription: Select radio buttons with scrapy

description: Select radio buttons with scrapy


code:
def intersect(recta, rectb):
    a=(rectb[1]+rectb[3]<recta[1]) or (recta[1]+recta[3]<rectb[1]) #up, down
    b=(rectb[0]+rectb[2]<recta[0]) or (recta[0]+recta[2]<rectb[0]) #left, right
return not(a or b)

def onplatform(self):
    for i in plist:
        if intersect(i[0]+[i[1].get_width(), 1], [bodyc[0], bodyc[1]+47, 50, 3]):
            return True, plist.index(i)

onplat=self.onplatform()
if yvelocity!=-13:
    bodyc[1]-=yvelocity
    for i in plist:
        temp=i[0][0]<bodyc[0]+50<i[0][0]+i[1].get_width()
        temp2=i[0][0]<bodyc[0]<i[0][0]+i[1].get_width()
        if prevcoords[1]+50<=i[0][1]<=bodyc[1]+50 and (temp or temp2):
            bodyc[1]=i[0][1]-50
            yvelocity=-13
            break
if yvelocity>-12: yvelocity-=1
if yvelocity==-13 and not onplat[0]: yvelocity=-1
if pressed[pygame.K_UP] and yvelocity==-13:
    yvelocity=13
prevcoords=bodyc[:]

rawDescription: (Python) Platformer - character skips over/incorrectly placed


code:
ax = plt.gca()
legend = ax.get_legend()
legend.legendHandles[0].set_color('red')
legend.legendHandles[1].set_color('yellow')

rawDescription: Manually set color of points in legend

description: Manually set color of points in legend


code:
def start_requests(self):
    for i in range(1, 101):
        yield Request(url='http://www.somesite.com/details.html?pageId={0}'.format(i), callback=self.my_callback)

rawDescription: Scrapy + Change in request parameter

description: Scrapy + Change in request parameter


code:
def OneOverF(N):
    import numpy as np
    N2 = N/2; #N has to be even!
    x = np.hstack((1, np.arange(1, N2+1), np.arange(N2-1, 0, -1)))
    hf = 1/(2*np.pi*x/N2)
    ht = np.real(np.fft.ifft(hf)) # discard tiny imag part from numerical error
    htrot = np.roll(ht, N2)
    htwin = htrot * np.hamming(N)
    return ht, htrot, htwin

rawDescription: Fourier space filtering

description: Fourier space filtering


code: [m.group(0) for m, _ in zip(re.finditer(r"\w", "abcdef"), range(3))]

rawDescription: Python Regular Expressions - Limit Results?


code:
from collections import defaultdict

OUTF = "{0}.txt".format

def sortWords(wordList):
    d = defaultdict(list)
    for word in wordList:
        d[len(word)].append(word)
    return d

def readWords(fname):
    with open(fname) as inf:
        return [word for word in (line.strip() for line in inf.readlines()) if word]

def writeWords(fname, wordList):
    wordList.sort()
    with open(fname, 'w') as outf:
        outf.write('\n'.join(wordList))

def main():
    for wordLen,wordList in sortWords(readWords('words.txt')).iteritems():
        writeWords(OUTF(wordLen), wordList)

if __name__=="__main__":
    main()

rawDescription: Python: Sort text file twice and split to different files?


code:
s = 'abcdefghijklmnopqrstuvwxyz'
b = buffer(s, 2, 10)
b
b[:]

rawDescription: slices to immutable strings by reference and not copy

description: Slices to immutable strings by reference and not copy


rawDescription: Search preceding and following characters of re


code: sorted(mydict.items(), key=lambda x: (-x[1], x[0]))

rawDescription: Sort by values (descending) and then keys (ascending) in Python dictionary


code: rawlossDF['damage_description'] = rawlossDF['damage_description'].map(lambda x: x.strip())

rawDescription: Stripping all trailing empty spaces in a column of a pandas dataframe


code:
class B(object):
    def __init__(self, previous):
        self.previous = previous
    def __del__(self):
        self.previous = None
        self = None

l = []
prev = None
for i in range(1000000):
    b = B(prev)
    l.append(b)
    prev = b

del l[:]
prev
b
b.previous
import gc
sum(1 for ob in gc.get_objects() if isinstance(ob, B))
del b, prev
sum(1 for ob in gc.get_objects() if isinstance(ob, B))

rawDescription: Garbage collector doesn't deallocate linked objects (Linked Lists memory leak)


code: path = os.path.join(sys.argv[1], '1.exe')

rawDescription: What is 'subdir' defined var in python 3 for all OS?


code:
import matplotlib.pyplot as plt
import numpy as np
from pandas import DataFrame
df = DataFrame(np.random.randn(5, 3), columns=['A', 'B', 'C'])

fig, ax = plt.subplots()
ax2, ax3 = ax.twinx(), ax.twinx()
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.25))
ax3.set_frame_on(True)
ax3.patch.set_visible(False)
fig.subplots_adjust(right=0.75)

df.A.plot(ax=ax, style='b-')
df.B.plot(ax=ax2, style='r-', secondary_y=True)
df.C.plot(ax=ax3, style='g-')

rawDescription: PANDAS plot multiple Y axes

description: PANDAS plot multiple Y axes


code:
import datetime, time, pytz
tz = pytz.FixedOffset(-60)
dt = datetime.datetime(1990, 1, 1, tzinfo=pytz.utc)
tm = dt.astimezone(tz).timetuple(); tm
time.mktime(tm)

rawDescription: Boost / Python unix timestamps don't match


code:
import re
html = getHTMLText()
mp3s = []
other = []
for match in re.findall('<reexpression>',html):
    if match.endswith('.mp3'):
        mp3s.append(match)
    else:
        other.append(match)

rawDescription: Extracting links from HTML in Python

description: Extracting links from HTML in Python


code:
nreceive = True#nreceive = Not Received
ticks = 0
f = None
while nreceive and ticks < 101:#try to get the info 100 times or until it's received
    ticks+=1
    try:
        f = mysocket.makefile('rb')
        if not f == None:
            nreceive = False
    except:
        pass
data = f.read(1024)

rawDescription: Client Not Receiving Data in Python

description: Client Not Receiving Data in Python


code:
left = QtGui.QVBoxLayout()
# This makes the label take as little space as possible
# since QLabel's sizeHint is Minimum.
left.addWidget(label1, 0)
left.addWidget(self.mainList, 1)

right = QtGui.QVBoxLayout()
right.addWidget(label2, 0)
right.addWidget(self.descList, 1)

main = QtGui.QHBoxLayout()
main.addLayout(left, 1)    # Both sides take the same amount of space.
main.addLayout(right, 1)

rawDescription: Python PyQt widget positioning in grid

description: Python PyQt widget positioning in grid


code:
import csv
import struct

fieldwidths = (-4, 24, -4, 40,-4,64,-1,1,25)  # negative widths represent ignored padding fields
fmtstring = ' '.join('{}{}'.format(abs(fw), 'x' if fw < 0 else 's')
                        for fw in fieldwidths)
fieldstruct = struct.Struct(fmtstring)
parse = fieldstruct.unpack_from

c = csv.writer(open("/home/ulrich/Desktop/disertation/sample_parsed_blch1.csv", "wb"))
fields = parse("    Sat Jan  3 18:15:05 2009    62e907b15cbf27d5425399ebf6f0fb50ebb88f18    4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b +              50.00000000")

c.writerow(fields)

rawDescription: Python fixed delimited text file to csv using struct


rawDescription: Python: List initialization differences

description: Python: List initialization differences


code:
from __future__ import print_function
from pyspark import SparkConf, SparkContext

conf = SparkConf().setMaster("local").setAppName("My Test")
sc = SparkContext(conf = conf)

lines = sc.textFile("file:///home/hduser/spark-1.5.2-bin-hadoop2.6/README.md")

print(lines.count())
print(lines.first())

rawDescription: Cannot output result at Python lines.first() from SparkContext


code:
from Tkinter import *
import ttk

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = ttk.Combobox(master, textvariable=variable, values=["Carrier 19EX 4667kW/6.16COP/Vanes", "Carrier 19EX 4997kW/6.40COP/Vanes", "Carrier 19EX 5148kW/6.34COP/Vanes", "Carrier 19EX 5208kW/6.88COP/Vanes", "Carrier 19FA 5651kW/5.50COP/Vanes", "Carrier 19XL 1674kW/7.89COP/Vanes", "Carrier 19XL 1779kW/6.18COP/Vanes", "Carrier 19XL 1797kW/5.69COP/Vanes", "Carrier 19XL 1871kW/6.49COP/Vanes", "Carrier 19XL 2057kW/6.05COP/Vanes", "Carrier 19XR 1076kW/5.52COP/Vanes", "Carrier 19XR 1143kW/6.57COP/VSD", "Carrier 19XR 1157kW/5.62COP/VSD", "Carrier 19XR 1196kW/6.50COP/Vanes", "Carrier 19XR 1213kW/7.78COP/Vanes", "Carrier 19XR 1234kW/5.39COP/VSD", "Carrier 19XR 1259kW/6.26COP/Vanes", "Carrier 19XR 1284kW/6.20COP/Vanes", "Carrier 19XR 1294kW/7.61COP/Vanes", "Carrier 19XR 1350kW/7.90COP/VSD", "Carrier 19XR 1403kW/7.09COP/VSD", "Carrier 19XR 1407kW/6.04COP/VSD", "Carrier 19XR 1410kW/8.54COP/VSD", "Carrier 19XR 1558kW/5.81COP/VSD", "Carrier 19XR 1586kW/5.53COP/VSD", "Carrier 19XR 1635kW/6.36COP/Vanes", "Carrier 19XR 1656kW/8.24COP/VSD", "Carrier 19XR 1723kW/8.32COP/VSD", "Carrier 19XR 1727kW/9.04COP/Vanes", "Carrier 19XR 1758kW/5.86COP/VSD", "Carrier 19XR 1776kW/8.00COP/Vanes", "Carrier 19XR 1801kW/6.34COP/VSD", "Carrier 19XR 2391kW/6.44COP/VSD", "Carrier 19XR 2391kW/6.77COP/Vanes", "Carrier 19XR 742kW/5.42COP/VSD", "Carrier 19XR 823kW/6.28COP/Vanes", "Carrier 19XR 869kW/5.57COP/VSD", "Carrier 19XR 897kW/6.23COP/VSD", "Carrier 19XR 897kW/6.50COP/Vanes", "Carrier 19XR 897kW/7.23COP/VSD", "Carrier 23XL 1062kW/5.50COP/Valve", "Carrier 23XL 1108kW/6.92COP/Valve", "Carrier 23XL 1196kW/6.39COP/Valve", "Carrier 23XL 686kW/5.91COP/Valve", "Carrier 23XL 724kW/6.04COP/Vanes", "Carrier 23XL 830kW/6.97COP/Valve", "Carrier 23XL 862kW/6.11COP/Valve", "Carrier 23XL 862kW/6.84COP/Valve", "Carrier 23XL 865kW/6.05COP/Valve", "Carrier 30RB100 336.5kW/2.8COP", "Carrier 30RB110 371kW/2.8COP", "Carrier 30RB120 416.4kW/2.8COP", "Carrier 30RB130 447.7kW/2.8COP", "Carrier 30RB150 507.8kW/2.8COP", "Carrier 30RB160 538kW/2.9COP", "Carrier 30RB170 585.5kW/2.8COP", "Carrier 30RB190 662.9kW/2.8COP", "Carrier 30RB210 710kW/2.9COP", "Carrier 30RB225 753.3kW/2.8COP", "Carrier 30RB250 836.2kW/2.8COP", "Carrier 30RB275 915kW/2.8COP", "Carrier 30RB300 993.8kW/2.8COP", "Carrier 30RB315 1076.1kW/2.9COP", "Carrier 30RB330 1123.6kW/2.8COP", "Carrier 30RB345 1170.7kW/2.8COP", "Carrier 30RB360 1248.4kW/2.8COP", "Carrier 30RB390 1325.8kW/2.8COP", "Carrier 30RB90 303.8kW/2.9COP", "Carrier 30XA100 330.1kW/3.1COP", "Carrier 30XA110 359.9kW/3COP", "Carrier 30XA120 389kW/3COP", "Carrier 30XA140 466.7kW/3.1COP", "Carrier 30XA160 535.1kW/3.1COP", "Carrier 30XA180 601.9kW/3.1COP", "Carrier 30XA200 681.7kW/3.1COP", "Carrier 30XA220 743.7kW/3.1COP", "Carrier 30XA240 801.6kW/3COP", "Carrier 30XA260 881.7kW/3.1COP", "Carrier 30XA280 943.4kW/3.1COP", "Carrier 30XA300 1010.2kW/3.1COP", "Carrier 30XA325 1077.4kW/3.1COP", "Carrier 30XA350 1138.7kW/3COP", "Carrier 30XA400 1348kW/3COP", "Carrier 30XA450 1499.5kW/2.9COP", "Carrier 30XA500 1609.4kW/2.9COP", "Carrier 30XA80 265.5kW/2.9COP", "Carrier 30XA90 297.8kW/3.1COP", "DOE-2 Centrifugal/5.50COP", "DOE-2 Reciprocating/3.67COP", "McQuay AGZ010BS 34.5kW/2.67COP", "McQuay AGZ013BS 47.1kW/2.67COP", "McQuay AGZ017BS 54.5kW/2.67COP", "McQuay AGZ020BS 71kW/2.67COP", "McQuay AGZ025BS 78.1kW/2.67COP", "McQuay AGZ025D 96kW/2.81COP", "McQuay AGZ029BS 95.7kW/2.67COP", "McQuay AGZ030D 111.1kW/2.81COP", "McQuay AGZ034BS 117.1kW/2.61COP", "McQuay AGZ035D 122.7kW/2.93COP", "McQuay AGZ040D 133.3kW/2.96COP", "McQuay AGZ045D 149.8kW/3.02COP", "McQuay AGZ050D 169.2kW/2.96COP", "McQuay AGZ055D 181.5kW/2.93COP", "McQuay AGZ060D 197.3kW/2.87COP", "McQuay AGZ065D 204.3kW/3.02COP", "McQuay AGZ070D 225.4kW/2.84COP", "McQuay AGZ075D 257.1kW/2.93COP", "McQuay AGZ080D 285.2kW/2.87COP", "McQuay AGZ090D 313.7kW/2.87COP", "McQuay AGZ100D 351kW/2.81COP", "McQuay AGZ110D 373.1kW/2.87COP", "McQuay AGZ125D 411.8kW/2.87COP", "McQuay AGZ130D 455.8kW/2.81COP", "McQuay AGZ140D 479kW/2.99COP", "McQuay AGZ160D 539.1kW/2.93COP", "McQuay AGZ180D 605.6kW/2.81COP", "McQuay AGZ190D 633.4kW/2.96COP", "McQuay PEH 1030kW/8.58COP/Vanes", "McQuay PEH 1104kW/8.00COP/Vanes", "McQuay PEH 1231kW/6.18COP/Vanes", "McQuay PEH 1635kW/7.47COP/Vanes", "McQuay PEH 1895kW/6.42COP/Vanes", "McQuay PEH 1934kW/6.01COP/Vanes", "McQuay PEH 703kW/7.03COP/Vanes", "McQuay PEH 819kW/8.11COP/Vanes", "McQuay PFH 1407kW/6.60COP/Vanes", "McQuay PFH 2043kW/8.44COP/Vanes", "McQuay PFH 2124kW/6.03COP/Vanes", "McQuay PFH 2462kW/6.67COP/Vanes", "McQuay PFH 3165kW/6.48COP/Vanes", "McQuay PFH 4020kW/7.35COP/Vanes", "McQuay PFH 932kW/5.09COP/Vanes", "McQuay WDC 1973kW/6.28COP/Vanes", "McQuay WSC 1519kW/7.10COP/Vanes", "McQuay WSC 1751kW/6.73COP/Vanes", "McQuay WSC 471kW/5.89COP/Vanes", "McQuay WSC 816kW/6.74COP/Vanes", "Multistack MS 172kW/3.67COP/None", "Trane CGAM100 337.6kW/3.11COP", "Trane CGAM110 367.2kW/3.02COP"])
w.pack()

master.mainloop()

rawDescription: how to attatch scrollbar to dropdown list in tkinter?

description: Attatch scrollbar to dropdown list in tkinter


code:
import argparse

# Use nargs to specify how many arguments an option should take.
ap = argparse.ArgumentParser()
ap.add_argument('-a', nargs=2)
ap.add_argument('-b', nargs=3)
ap.add_argument('-c', nargs=1)

# An illustration of how access the arguments.
opts = ap.parse_args('-a A1 A2 -b B1 B2 B3 -c C1'.split())

print(opts)
print(opts.a)
print(opts.b)
print(opts.c)

# To require that at least one option be supplied (-a, -b, or -c)
# you have to write your own logic. For example:
opts = ap.parse_args([])
if not any([opts.a, opts.b, opts.c]):
    ap.print_usage()
    quit()

print("This won't run.")

rawDescription: Python argparse example?

description: Python argparse example


rawDescription: How to set Plone to redirect to came_from after logout

description: Set Plone to redirect to came_from after logout


code:
import random
import sys
import time

def slowprint(s):
    for c in s + '\n':
        sys.stdout.write(c)
        sys.stdout.flush() # defeat buffering
        time.sleep(random.random() * 0.1)

slowprint('Hello, world.')

rawDescription: Slow, word-by-word terminal printing in Python?


code:
import os
path = "abc/def/ghi"
a = path.split("/")
[os.path.join(*a[:i]) for i in range(1, len(a)+1)]

rawDescription: Python: How to do this string manipulation


code:
def newfunction(*args):
    return oldfunction(10, *args)

rawDescription: Generate new function from old function with only one argument set


code:
import logging
logging.basicConfig(filename = log_filename, level = logging.DEBUG)

rawDescription: Selenium unit tests in Python -- where is my log file?


code:
def stripper(self, data):
    new_data = {}
    for k, v in data.items():
        if isinstance(v, dict):
            v = stripper(v)
        if not v in (u'', None, {}):
            new_data[k] = v
    return new_data

rawDescription: Remove empty dicts in nested dictionary with recursive function


rawDescription: Strip in Python

description: Strip in Python


code:
import matplotlib.pyplot as plt
from PyQt4.QtCore import Qt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10),range(10))

#get the parent window of the canvas and set the flags
fig.canvas.parent().setWindowFlags(
    Qt.WindowSystemMenuHint|
    Qt.WindowMinimizeButtonHint|
    Qt.WindowCloseButtonHint)

plt.show()

rawDescription: Disable window maximilization in matplotlib figure window


code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

cmap = ListedColormap(['b', 'r', 'b'])
norm = BoundaryNorm([0, 1, 1.5, 2], cmap.N)

line = LineCollection([], cmap=cmap, norm=norm,lw=2)
line.set_array(np.linspace(0, 2, 1000))
ax.add_collection(line)

# initialization function: plot the background of each frame
def init():
    line.set_segments([])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    line.set_segments(segments)
    return line,

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

rawDescription: Animate a line with different colors

description: Animate a line with different colors


code:
import numpy as np

def spectral_centroid(x, samplerate=44100):
    magnitudes = np.abs(np.fft.rfft(x)) # magnitudes of positive frequencies
    length = len(x)
    freqs = np.abs(np.fft.fftfreq(length, 1.0/samplerate)[:length//2+1]) # positive frequencies
    return np.sum(magnitudes*freqs) / np.sum(magnitudes) # return weighted mean

rawDescription: Python: Spectral Centroid for a .wav file?


code:
import numpy as np
import matplotlib
matplotlib.use("Qt4Agg") # This program works with Qt only
import pylab as pl
fig, ax1 = pl.subplots()

t = np.linspace(0, 10, 200)

line, = ax1.plot(t, np.sin(t))

### control panel ###
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtCore import Qt

def update():
    freq = float(textbox.text())
    y = np.sin(2*np.pi*freq*t)
    line.set_data(t, y)
    fig.canvas.draw_idle()

root = fig.canvas.manager.window
panel = QtGui.QWidget()
hbox = QtGui.QHBoxLayout(panel)
textbox = QtGui.QLineEdit(parent = panel)
textbox.textChanged.connect(update)
hbox.addWidget(textbox)
panel.setLayout(hbox)

dock = QtGui.QDockWidget("control", root)
root.addDockWidget(Qt.BottomDockWidgetArea, dock)
dock.setWidget(panel)
######################

pl.show()

rawDescription: Interactive matplotlib plots via textboxes


code:
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self, parent = None):
        super(Window, self).__init__(parent)

        # Create a QTabWidget where all the tabs will be held
        self.myTabs = QtGui.QTabWidget()

        # Loop through our animal names
        setNames = ['Cat', 'Dog', 'Bird', 'Tiger']
        for tabName in setNames:
            # Each tab needs its own widget, so let's create one with a label
            tabWidget = QtGui.QWidget()
            tabLabel = QtGui.QLabel('Hello! I am a {0}.'.format(tabName) )

            # Set the tab widget's layout
            tabLayout = QtGui.QVBoxLayout()
            tabLayout.addWidget(tabLabel)
            tabWidget.setLayout(tabLayout)

            # Create the tab
            self.myTabs.addTab(tabWidget, tabName)

        # Set the main layout
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.myTabs)
        self.setLayout(mainLayout)

        # Resize our window and show it
        self.resize(300, 300)
        self.show()

win = Window()

rawDescription: Creating tabs for each name in a list

description: Creating tabs for each name in a list


code:
import gzip
with gzip.open('/sample.gz', 'rb') as my_gz:
    file_content = my_gz.read()
    with open('/sample.csv', 'wb') as my_csv:
        my_csv.write(file_content)

rawDescription: Need to extract a csv file to a new file


code:
import sqlite3

db = sqlite3.connect('sampledb')
c = db.cursor()

new_set = []

c.execute('select * from main')

temp_value = []
for row in c:
     for item in row:
          temp_value.append(item[1:-1])
     new_set.append(temp_value)
     temp_value = []

# place it back into the database

rawDescription: modifying the contents of the sqlilte database

description: Modifying the contents of the sqlilte database


code:
import string
def Validate(self, win):
    """
    Enter your code here...
    """
    return True

def OnChar(self, event):
    txtObj = event.GetEventObject()
    txt = txtObj.GetValue()
    if txt == "": txt = '0'
    key = chr(event.GetKeyCode())

    if key in string.digits:
        if int(txt+str(key)) < 150:
            event.Skip()
        else:
            msg = "You have entered an age greater than 150!"
            wx.MessageBox(msg, "Improbable entry", style=wx.OK|wx.ICON_ERROR)

            # PROBLEM ARISES HERE
            # ===================
            MyDialog().ageWarning_ST.Show()
            MyDialog().mainSizer.Fit(MyDialog())

            return False

    key = event.GetKeyCode()
    if key in(wx.WXK_RETURN, wx.WXK_DELETE, wx.WXK_BACK):
        event.Skip()

    elif (chr(key)).isdigit():
        event.Skip()
    else:
        return

rawDescription: wxPython: using Show() and Hide()

description: WxPython: using Show() and Hide()


code:
"" or 12
27 or 9
None or "default"

rawDescription: Python Version of Perl = || (= Or)

description: Python Version of Perl = || (= Or)


code:
import sys
sys.path.insert(0, './')

rawDescription: Tab completion not seeing my modules in IPython 0.12


code:
class Class(object):
    def __init__(self):
        self.value = False

c = Class()
c.value                # False
c.value = True
c.value                # True

rawDescription: why doesn't the Python property set the attribute value

description: Why doesn't the Python property set the attribute value


code:
import memcache

memc = memcache.Client(['127.0.0.1:11211'], debug=1);
memc.set('top10candytypes', {1 : 2, "3" : [4,5,6]})

bestCandy = memc.get('top10candytypes')
print(bestCandy)

rawDescription: I need an efficient shared dictionary in a Python multiprocessing environment


code:
from numpy import array
a = array([1, 2, 3, 4, 5])
new_max = 6
a / max(a)            # This is probably what happens to you
a / float(max(a))     # Convert that integer to a float and it'll work
a / float(max(a)) * new_max

rawDescription: Numpy: How to scale an integer array by an integer value?


rawDescription: How to select a post with no comments?

description: Select a post with no comments


code:
import json

json_keyboard = json.dumps({'keyboard': [["A button"], ["B button"]],
                            'one_time_keyboard': False,
                            'resize_keyboard': True})

TelegramAPI.post(TELEGRAM_URL + "sendMessage",
                 data=dict(chat_id=CHAT_ID,
                           text="Has to be non-empty",
                           reply_markup=json_keyboard))

rawDescription: Telegram bot api keyboard

description: Telegram bot api keyboard


code:
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((300, 300))

currtile_x = 0
currtile_y = 0
with open('townhall.map') as f:
    for line in f:
        for character in line:
            if character == '\n':
                currtile_y += 10
                currtile_x = 0
            elif character == 'x':
                pygame.draw.rect(screen, (0,0,0), (currtile_x, currtile_y, 10, 10), 0)
                currtile_x += 10
            elif character == 'a':
                pygame.draw.rect(screen, (0,255,255), (currtile_x, currtile_y, 10, 10), 0)
                currtile_x += 10

running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
    pygame.display.update()

rawDescription: PyGame not rendering shapes?

description: PyGame not rendering shapes


code: s = near_city + "," + str(state)

rawDescription: How to concatenate two variable of which one is string and other is not

description: Concatenate two variable of which one is string and other is not


code:
import sys

while True:
    line = sys.stdin.readline()    # readline will return "" on EOF
    if line:
        do_something_with(line)    # * if user just pressed Enter line will
                                   #   be "\n", i.e. still True
    else:                          # * user pressed C-D, i.e. stdin has been
        sys.exit(0)                #   closed readline call must have returned ""

rawDescription: Python - Handle CTRL+D with 'import signal'


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

img_xsize, img_ysize = 20, 20 # size of single image
mx, my = 10, 10 # x/y grid of sites per well
nx, ny = 12, 8 # x/y grid of wells per plate
wgap = 20 # pixels gap between wells
stitched_x, stitched_y = (wgap+mx*img_xsize)*nx, (wgap+my*img_ysize)*ny

img_stitched = np.zeros((stitched_y, stitched_x), dtype=np.uint8)

def add_img(mxi, myi, nxi, nyi, img):
    assert img.shape == (img_ysize, img_xsize)
    xi = nxi*(mx*img_xsize + wgap) + mxi*img_xsize
    yi = nyi*(my*img_ysize + wgap) + myi*img_ysize
    img_stitched[yi:yi+img_ysize,xi:xi+img_xsize] = img

for nxi in range(nx):
    for nyi in range(ny):
        for mxi in range(mx):
            for myi in range(my):
                # ... get image data
                img = np.random.randint(0,255) * np.ones((img_ysize, img_xsize), dtype=np.uint8)
                add_img(mxi, myi, nxi, nyi, img)

plt.imshow(img_stitched)
plt.colorbar()
plt.show(block=False)
raw_input("Enter")

rawDescription: Most pythonic way to stitch an array of images together


code:
import re
files = ["C:\\MyDir\\some_file.txt",
     "C:\\MyDir\\another_file.txt",
     "C:\\MyDir\\some_file.old"]

patern = re.compile(r"\\some[^\\]*\.txt$", re.I)
filtered_files = [f for f in files if pattern.search(f)]

rawDescription: SFTP full file path for a set of files

description: SFTP full file path for a set of files


code:
class Root(object):
    __name__ = None
    __parent__ = None

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

    def __getitem__(self, key):
        if key == 'articles':
            dispatch =  ArticleDispatcher(self.request)
            dispatch.__name__ = key
            dispatch.__parent__ = self
            return dispatch
        raise KeyError(key)

class ArticleDispatcher(object):
    __name__ = None
    __parent__ = None

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

    def __getitem__(self, key):
        # Get a hold of the database here:
        db = findDatabase(self.request)
        if db.exists(key):
            data = db.load(key)
            art = Article(data)
            art.__name__ = key
            art.__parent__ = self
            return art
        raise KeyError(key)

class Article:
    __name__ = None
    __parent__ = None

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

rawDescription: Pyramid traversal is doing my head in

description: Pyramid traversal is doing my head in


code:
with open('/etc/hosts', 'rt') as f:
    s = f.read() + '\n' + '127.0.0.1\t\t\thome_sweet_home\n'
    with open('/tmp/etc_hosts.tmp', 'wt') as outf:
        outf.write(s)

os.system('sudo mv /tmp/etc_hosts.tmp /etc/hosts')

rawDescription: IOError: 13, 'Permission denied' when writing to /etc/hosts via Python


code:
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.edit = QtGui.QLineEdit(self)
        self.edit.setProperty('warning', False)
        self.edit.setStyleSheet("""
           /* other rules go here */
           QLineEdit[warning="true"] {background-color: yellow};
           QLineEdit[warning="false"] {background-color: palette(base)};
            """)
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.button)

    def handleButton(self):
        self.edit.setProperty(
            'warning', not self.edit.property('warning'))
        self.edit.style().unpolish(self.edit)
        self.edit.style().polish(self.edit)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: Pyside: Modifying widget colour at runtime without overwriting stylesheet.


code:
from __future__ import division
import numpy as np
import math
import matplotlib.pyplot as plt

def generate_data(n):
    """Make random, correlated x & y arrays"""
    points = np.random.multivariate_normal(mean=(0,0),
        cov=[[0.4,9],[9,10]],size=int(n))
    return points

if __name__ =='__main__':

    color_map = plt.cm.Spectral_r
    n = 1e4
    points = generate_data(n)

    xbnds = np.array([-20.0,20.0])
    ybnds = np.array([-20.0,20.0])
    extent = [xbnds[0],xbnds[1],ybnds[0],ybnds[1]]

    fig=plt.figure(figsize=(10,9))
    ax = fig.add_subplot(111)
    x, y = points.T
    # Set gridsize just to make them visually large
    image = plt.hexbin(x,y,cmap=color_map,gridsize=20,extent=extent,mincnt=1,bins='log')
    # Note that mincnt=1 adds 1 to each count
    counts = image.get_array()
    ncnts = np.count_nonzero(np.power(10,counts))
    verts = image.get_offsets()
    for offc in xrange(verts.shape[0]):
        binx,biny = verts[offc][0],verts[offc][1]
        if counts[offc]:
            plt.plot(binx,biny,'k.',zorder=100)
    ax.set_xlim(xbnds)
    ax.set_ylim(ybnds)
    plt.grid(True)
    cb = plt.colorbar(image,spacing='uniform',extend='max')
    plt.show()

rawDescription: get bins coordinates with hexbin in matplotlib

description: Get bins coordinates with hexbin in matplotlib


code:
def local_ephemeral_UTC_offset(epoch_time=None):
  u"Returns a datetime.timedelta object representing the local time offset from UTC at the moment"
  if epoch_time == None:
    epoch_time = time()
  return datetime.fromtimestamp(epoch_time) - datetime.utcfromtimestamp(epoch_time)

rawDescription: Python: get timezone based on DST for a timestamp


code: sort = sorted(row[1:4], reverse=True)

rawDescription: Where can I put `reverse=true` to reverse sorting order?


code: [m for m in abc if 'on' in m]

rawDescription: 'LIKE' function for Lists

description: 'LIKE' function for Lists


code:
for pattern in ("".join(seq) for seq in itertools.product("01", repeat=3)):
    ...

rawDescription: Python: Getting binary permutations, but controlling loop flow


code:
# context menu requested signal handler
def display_context_menu(point):
    global line_edit

    # grab the standard context menu
    menu = line_edit.createStandardContextMenu()

    # search through the actions i nthe menu to find undo
    for action in menu.actions():
        if action.text() == '&Undo  Ctrl+Z':
            # set undo as disabled
            action.setDisabled(True)
            break

    # show context menu where we right clicked
    menu.exec_(line_edit.mapToGlobal(point))

# create line edit, set it to use a custom context menu, connect the context menu signal to handler
line_edit = QLineEdit()
line_edit.setContextMenuPolicy(Qt.CustomContextMenu)
line_edit.customContextMenuRequested.connect(display_context_menu)

line_edit.show()

rawDescription: Prevent undo in a particular text box

description: Prevent undo in a particular text box


code:
with open(filename, 'r') as f:
    content = f.read().replace('\n', '\r\n')

rawDescription: Python : How to email attached Unix file in DOS format


rawDescription: Why is a comma captured in this group?

description: Why is a comma captured in this group


code:
scoreLst = []

print("The list ends when user inputs -999")
scoreLst.append(int(input("Enter the test score: ")))

while True:
    scoreLst.append(int(input("Enter another test score: ")))
    if scoreLst[-1] == -999:
        scoreLst.pop()
        break

rawDescription: Breaking out of user inputs in a list

description: Breaking out of user inputs in a list


code:
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset
fig, ax = plt.subplots()
time_list = np.linspace(0, 7, 1000)
data = np.random.random(1000) - .5
plt.plot(time_list, data, color='red')

plt.axvline(x=0, color='black')
plt.axhline(y=0, color='black')

axins = zoomed_inset_axes(ax, 4.5, loc=4)
axins.plot(time_list, data, color='red')
axins.axvline(x=0, color='black')
axins.axhline(y=0, color='black')
axins.axis([2, 3, -0.01, 0.01])
plt.yticks(visible=False)
plt.xticks(visible=False)
mark_inset(ax, axins, loc1=3, loc2=1, fc="none", ec="0.0", zorder = 3)
plt.show()

rawDescription: How can I make matplotlib mark_inset display line on top of the graph?

description: Make matplotlib mark_inset display line on top of the graph


code:
list_1_sorted, list_2_sorted = zip(*sorted(zip(list_1, list_2),
  key=operator.itemgetter(0), reverse=True))

rawDescription: Sorting a list in Python using the result from sorting another list


code:
import os, multiprocessing, time

sem1 = multiprocessing.Semaphore(1)
sem2 = multiprocessing.Semaphore(0)

pid1 = os.fork()
pid2 = -1

if pid1 != 0:
    pid2 = os.fork()
for i in range(1,20):
    time.sleep(1)
    if (i%2) == 1 and pid1==0:
            sem1.acquire()
            print("sem1: %d" %i)
            sem2.release()
            #time.sleep(1)
    elif (i%2) == 0 and pid2==0:
            sem2.acquire()
            print("sem2: %d" %i)
            sem1.release()
            #time.sleep(1)

rawDescription: Semaphore output is wrong

description: Semaphore output is wrong


code:
import socketserver

class MyTCPHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        while True:
            self.data = self.rfile.readline()
            if not self.data:
                break
            self.data = self.data.strip()
            ...

rawDescription: Python Socket - handling client disconnect


code:
import itertools

for item in itertools.chain(r, p):
    do_some_stuff(item)

rawDescription: Python for loop with two dicts

description: Python for loop with two dicts


code:
def sanity_check( test, name='undefined', ontrue=None, onfalse=None ):
    if test:
        log.debug(name)
        if ontrue is not None:
            ontrue()
    else:
        log.warn( name )
        if onfalse is not None:
            onfalse()

def sanity_checks():
    sanity_check(sanity_access(PATH['userhome'], os.F_OK), 'test home',
        onfalse=sys.exit)

rawDescription: Passing 'None' as function parameter (where parameter is a function)


code:
from pandas import DataFrame
from scipy.stats import uniform
from scipy.stats import randint
import numpy as np
import matplotlib.pyplot as plt

# some sample data
df = DataFrame({'gene' : ['gene-%i' % i for i in np.arange(10000)],
'pvalue' : uniform.rvs(size=10000),
'chromosome' : ['ch-%i' % i for i in randint.rvs(0,12,size=10000)]})

# -log_10(pvalue)
df['minuslog10pvalue'] = -np.log10(df.pvalue)
df.chromosome = df.chromosome.astype('category')
df.chromosome = df.chromosome.cat.set_categories(['ch-%i' % i for i in range(12)], ordered=True)
df = df.sort_values('chromosome')

# How to plot gene vs. -log10(pvalue) and colour it by chromosome?
df['ind'] = range(len(df))
df_grouped = df.groupby(('chromosome'))

fig = plt.figure()
ax = fig.add_subplot(111)
colors = ['red','green','blue', 'yellow']
x_labels = []
x_labels_pos = []
for num, (name, group) in enumerate(df_grouped):
    group.plot(kind='scatter', x='ind', y='minuslog10pvalue',color=colors[num % len(colors)], ax=ax)
    x_labels.append(name)
    x_labels_pos.append((group['ind'].iloc[-1] - (group['ind'].iloc[-1] - group['ind'].iloc[0])/2))
ax.set_xticks(x_labels_pos)
ax.set_xticklabels(x_labels)
ax.set_xlim([0, len(df)])
ax.set_ylim([0, 3.5])
ax.set_xlabel('Chromosome')

rawDescription: How to create a Manhattan plot with matplotlib in python?

description: Create a Manhattan plot with matplotlib in python


code:
import sys
sys.path.insert(0, 'specific/site-packages')

rawDescription: Execute script ignoring user's PYTHONPATH


code:
import numpy as np
a=[1,2]
b=[2,2]
c=[3,3]
d=np.rec.fromarrays([a, b, c], names='x,y,z')
d
d.astype([(k, float) for k in d.dtype.names])

rawDescription: numpy convert 2D Integer Record to 2D floating point Record

description: Numpy convert 2D Integer Record to 2D floating point Record


code:
ar = numpy.array([1,17,1])
numpy.bitwise_or.reduce(ar)

rawDescription: bitwise operations between elements in a list

description: Bitwise operations between elements in a list


code: map(int, mystring.split(','))

rawDescription: String to list without using regex

description: String to list without using regex


code:
if __name__ == "__main__":
    bottle_app = bottle.default_app()
    bottle_handler = tornado.wsgi.WSGIContainer(bottle_app)
    HTTPServer(Application([(r"/ws", WSHandler),
                            (r"/css/(.*)", StaticFileHandler, {"path": "./css/"}),
                            (r"/js/(.*)", StaticFileHandler, {"path": "./js/"}),
                            (r"/img/(.*)", StaticFileHandler, {"path": "./img/"}),
                            ("/(.*)", bottle_handler)])
                         ).listen(1024)
    IOLoop.instance().start()

rawDescription: Tornado - mount Bottle app

description: Tornado - mount Bottle app


code:
import hmac
import hashlib
import base64
dig = hmac.new(b'1234567890', msg=your_bytes_string, digestmod=hashlib.sha256).digest()
base64.b64encode(dig).decode()      # py3k-mode
'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg='

rawDescription: Calculating a SHA hash with a string + secret key in python


code:
#!/usr/bin/env python
from __future__ import print_function
import re
import struct
import sys
try:
    import urllib2
except ImportError:  # Python 3
    import urllib.request as urllib2

url = 'http://pool.cdn.lagardere.cz/fm-evropa2-128'  # radio stream
request = urllib2.Request(url, headers={'Icy-MetaData': 1})  # request metadata
response = urllib2.urlopen(request)
print(response.headers, file=sys.stderr)
metaint = int(response.headers['icy-metaint'])
response.read(metaint)  # skip to metadata
metadata_length = struct.unpack('B', response.read(1))[0] * 16  # length byte
metadata = response.read(metadata_length).rstrip(b'\0')
print(metadata, file=sys.stderr)
# extract title from the metadata
title = re.search(br"StreamTitle='([^']*)';", metadata).group(1)
print(title.decode(errors='replace'))

rawDescription: Python 3 get song name from internet radio stream


code: pl.imshow(image1, cmap=pl.gray())

rawDescription: using pylab or matplotlib to display an image from file

description: Using pylab or matplotlib to display an image from file


code:
if len(sys.argv) == 1:
    parser.print_help()

rawDescription: Make python display help screen if no action is given


code:
import numpy as np
import vtk
from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
from PyQt4 import QtGui
import sys

class ViewerWithScrollBar(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(ViewerWithScrollBar, self).__init__(parent)
        # Define the renderer and Qt window ------------------------
        self.frame = QtGui.QFrame()

        self.hl = QtGui.QHBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.hl.addWidget(self.vtkWidget)

        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
        self.ren.ResetCamera()

        self.frame.setLayout(self.hl)
        self.setCentralWidget(self.frame)

        # Point coordinate data ---------------------------------
        self.coordData = {}
        self.coordData[0] = np.array([[0,0,0], [1,0,0], [1,1,0]])
        self.coordData[1] = self.coordData[0] + np.array([[0.2, 0.1, -0.05], [0,0,0], [0,0,0]])
        self.coordData[2] = self.coordData[1] + np.array([[0.2, 0.1, -0.05], [0,0,0], [0,0,0]])

        # Define the slider bar and add it to the window ---------------
        slider = QtGui.QSlider()
        slider.setAccessibleName('Time index')
        slider.setRange(0, len(self.coordData)-1)
        slider.valueChanged.connect(self.sliderCallback)

        self.hl.addWidget(slider)

        # Create the polydata object -----------------------------
        points = vtk.vtkPoints()
        points.SetNumberOfPoints(len(self.coordData[0]))
        self.polydata = vtk.vtkPolyData()

        for i in range(len(self.coordData[0])):
            points.SetPoint(i, self.coordData[0][i])
        self.polydata.SetPoints(points)

        ptsFilter = vtk.vtkVertexGlyphFilter()
        ptsFilter.SetInputData(self.polydata)
        ptsMapper = vtk.vtkPolyDataMapper()
        ptsMapper.SetInputConnection(ptsFilter.GetOutputPort())
        ptsActor = vtk.vtkActor()
        ptsActor.SetMapper(ptsMapper)
        ptsActor.GetProperty().SetPointSize(10)

        self.ren.AddActor(ptsActor)

        self.show()
        self.iren.Initialize()

    def sliderCallback(self):
        index = self.sender().value() # The index that the slider bar is currently on
        points = self.polydata.GetPoints()
        for i in range(len(self.coordData[index])):
            points.SetPoint(i, self.coordData[index][i])
        self.polydata.Modified()
        self.iren.Render()
        return

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)

    window = ViewerWithScrollBar()

    sys.exit(app.exec_())

rawDescription: Python VTK polydata not updating

description: Python VTK polydata not updating


code: [c.run() for c in objs]

rawDescription: Pythonic Way To Call A Class Function If I have A List of Instances


code: self.EIG2D = numpy.vectorize(complex)(EIG2Dtmp[...,0], EIG2Dtmp[...,1])

rawDescription: How to pass complex arguments in netcdf python

description: Pass complex arguments in netcdf python


code:
import Tix
from Tkinter import *

def build_ui(root):
    sw = Tix.ScrolledWindow(root, scrollbar=Tix.AUTO)
    sw.pack(side=LEFT, fill=Tix.BOTH, expand=1)
    for i in range(300):
        label1 = Label(sw.window, text="foo")
        label1.grid(row=i, column=0)
    button = Button(root, text="Quit", command=root.quit)
    button.pack(side=RIGHT)

root = Tix.Tk()
build_ui(root)
root.mainloop()

rawDescription: How do you keep a widget in view while scrolling?

description: Keep a widget in view while scrolling


code:
data = create_dataset() # List of data to be sampled

n_samples = 100000
samples = random.sample(data,n_samples)

rawDescription: Python Get Random Sample of List of Tuples


code: pybot.bat --version

rawDescription: Not able to run pybot batch file in cygwin in windows environment


code:
import urllib
from cStringIO import StringIO

png_output = StringIO()
canvas.print_png(png_output)
data = png_output.getvalue().encode('base64')
data_url = 'data:image/png;base64,{}'.format(urllib.quote(data.rstrip('\n')))

rawDescription: generate image -> embed in flask with a data uri

description: Generate image -> embed in flask with a data uri


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.canvas = tk.Canvas(width=300, height=150,borderwidth=1)
        self.canvas.pack(side="top", fill="both", expand=True)
        points = (20,20,20,100,70,100)
        self.canvas.create_line(points, fill="red")

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

rawDescription: Python Equivalent of HTML5 Canvas

description: Python Equivalent of HTML5 Canvas


code:
import os
import subprocess

if platform.system() == "Windows" :
    subprocess.Popen("taskkill /F /T /PID %i" % process_pid , shell=True)
else :
    os.killpg( process_pid, signal.SIGKILL)

rawDescription: How to terminate a process without os.kill() - OSGeo4W Python 2.5

description: Terminate a process without os.kill() - OSGeo4W Python 2.5


code:
import md5
hashed = raw_input("Hash:")
with open(raw_input("Wordlist Path: ")) as f:
    for line in f:
        if md5.new(line.strip()).hexdigest() == hashed:
            print(line.strip())
            break
    else:
        print("The hash was not found. Please try a new wordlist.")

    raw_input("Press ENTER to close.")

rawDescription: Read from a file and remove \n and spaces


code:
with open("test.csv","wa") as f:
    f.write("name\tnum\n")
    for k, v in tripo.items():
        if v:
            f.write("1\t")
            f.write("{}\n".format(k.split('.')[0]))
            for s in v:
                f.write("1\t{}\n".format(s.split('.')[0]))

rawDescription: How to add new column to output file in Python?

description: Add new column to output file in Python


code:
from AccessControl import allow_module
allow_module('json')

rawDescription: How do I allow through-the-web Controller Python Scripts to import otherwise restricted modules? Plone4

description: Allow through-the-web Controller Python Scripts to import otherwise restricted modules? Plone4


code:
import json

import pymongo

pipeline = json.load(open('filename.json'))
collection = pymongo.MongoClient().db.collection
for doc in collection.aggregate(pipeline):
    print(doc)

rawDescription: MongoDB server-side aggregate queries shared between multiple scripts


code:
d = {"SPORTS": {"data": [["Bball", "10", 3]], "columns": ["SPORT", "MATCHES", "WINS"]}, "GRAMMY": {"data": [["Billy Joel", "Rock", 1], ["Elton John", "FUnk", 2]], "columns": ["ARTIST", "GENRE", "ID"]}, "SONGS": {"data": [], "columns": ["NAME", "ARTIST", "SONG_ID"]}}
newd = OrderedDict(sorted(d.iteritems(), key=lambda x: len(x[1]['data']), reverse=True))
# change iteritems to items if python 3
# newd holds the sorted dictionaries

rawDescription: Sorting a dictionary according to values in sub dictionary


code:
import os
def calc_sig_num(a, b):
    lcp = os.path.commonprefix([a,b])
    a, b = a[len(lcp):], b[len(lcp):]       # we now have a[0] < b[0]
    if a == "0"*len(a) and b == "9"*len(b): # base case, range is X00.. - X99..
        yield lcp
        return
    da, db = int(a[0]), int(b[0])
    size = len(a) - 1
    for d in range(da, db + 1):  # we iterate over 1 digit prefix extensions
        suffixes = calc_sig_num(a[1:] if d == da else "0"*size,
                                b[1:] if d == db else "9"*size)
        for suffix in suffixes:
            yield lcp + str(d) + suffix

rawDescription: Calculating significant number (or greatest common prefix)


rawDescription: Komodo Python auto complete: type inference by variable metadata?


code: cursor.execute("select Count(TeacherID) from TeacherInfo where TeacherInitials = ?",(TeacherInitials,))

rawDescription: getting multiple values out of an SQL statement

description: Getting multiple values out of an SQL statement


code: theta_c = list(a_t)

rawDescription: (Python) One variable becomes zero while assigning the value to another variable


code:
test1 = "name"
test2 = "value"

bare = soup.find("bare")

if bare.find("key", {"name": test1, "value": test2}) is None:
    new_key = soup.new_tag("key")
    new_key["name"] = test1
    new_key["value"] = test2

    bare.append(new_key)

rawDescription: How to check/add keys with beautifulsoup?

description: Check/add keys with beautifulsoup


rawDescription: how to convert string from known encoding to utf-8 on the fly in python?

description: Convert string from known encoding to utf-8 on the fly in python


code:
from BeautifulSoup import BeautifulSoup
# if the file is on your computer use this
#file = open('/path/to/the/file')
# and if the file is on the internet use this
#import urllib
#file = urllib.urlopen('http://www.the.com/path/to/the/file')
html = file.read()
file.close()
soup = BeautifulSoup(html)
trueimages = [image for image in soup.findAll('img') if image['id'].lower() == 'true']

rawDescription: Look for img and id tag, store URL in variable if both are true


code: [L if i else False for i in A ]

rawDescription: How to define list/array as a scalar in Python

description: Define list/array as a scalar in Python


code:
import sublime, sublime_plugin

def copy_line(view):
    sels = view.sel()
    # Do some stuff
    return line_region

class CopyLineCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        line_region = copy_line(self.view)
        # Do some stuff

class CutLineCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        line_region = copy_line(self.view)
        # Do some stuff

rawDescription: Python inheritance dilemma for plugin

description: Python inheritance dilemma for plugin


code:
def in_giant(G):
    cl = G.components()
    cl_sizes = cl.sizes()
    giant_component_index = cl_sizes.index(max(cl_sizes))
    return [x == giant_component_index for x in cl.membership]

rawDescription: Identity of nodes in the giant component, in igraph with Python


Add 2 to list [[23,34],[34,23]]


code:
def func(request):
    url  = request.META['HTTP_REFERER']
    if request.META['QUERY_STRING']:
        url += '?%s' % request.META['QUERY_STRING']
    return redirect_to(request, url, **kwargs)

rawDescription: How to pass an absolute url in django

description: Pass an absolute url in django


code:
object_1 = Object.objects.get(pk=id)

# Count how many items have more votes than this one
# This effectively tells you the position in your ordered list
position = Object.objects.filter(votes__gt=object_1.votes).count()

# Now generate your list of nearby objects
objects = Object.objects.order_by('-votes')[position-4:position+2]

rawDescription: Django query ordered objects given position


code: is_retired = models.CharField(max_length=50, null=True, blank=True)

rawDescription: Can I change the type of Model Field?

description: Change the type of Model Field


code:
text = 'Some text where the words should be'
words = ['text', 'string', 'letter', 'words']
[i for i, x in enumerate(words) if x in text]

rawDescription: Python - How to check whether a string contains an item from a list, and when returns true, have the item from the list as index usable in the loop


code:
img = cv2.imread("D:\\img.jpg")
gray = cv2.cvtColor(img, cv.CV_BGR2GRAY)

img2 = np.zeros_like(img)
img2[:,:,0] = gray
img2[:,:,1] = gray
img2[:,:,2] = gray

cv2.circle(img2, (10,10), 5, (255,255,0))
cv2.imshow("colour again", img2)
cv2.waitKey()

rawDescription: How to convert a 1 channel image into a 3 channel with opencv2?

description: Convert a 1 channel image into a 3 channel with opencv2


rawDescription: Sig fig formatting display with variable sig figs


code:
import json
import urllib2
json.load(urllib2.urlopen("url"))

rawDescription: How do I get JSON data from RESTful service using Python?

description: Get JSON data from RESTful service using Python


code:
import numpy as np
import scipy.stats as ss
import matplotlib.pyplot as plt

means = -1., 0., 3.
stdevs = 1.5, 1., 0.5
weights = 0.3, 0.5, 0.2

x = np.arange(-5., 5., 0.01)

pdfs = [p * ss.norm.pdf(x, mu, sd) for mu, sd, p in zip(means, stdevs, weights)]

density = np.sum(np.array(pdfs), axis=0)
plt.plot(x, density)

rawDescription: How to construct and plot uni-variate Gaussian Mixture using its parameters in Python

description: Construct and plot uni-variate Gaussian Mixture using its parameters in Python


code:
SMALL_CHUNK = 100000

def write_chunk(source_file, start, end, dest_name):
    pos = start
    source_file.seek(pos)
    with open(dest_name, 'w') as dest_file:
        for chunk_start in range(start, end, SMALL_CHUNK):
            chunk_end = min(chunk_start + SMALL_CHUNK, end)
            dest_file.write(source_file.read(chunk_end - chunk_start))

rawDescription: Divide .csv file into chunks with Python


code:
@celery.task
def task():
    RealTask.apply_async(countdown=30)

rawDescription: deferred execution celery task

description: Deferred execution celery task


code:
@classmethod
def get_all(cls, session, query):
    _filters = []
    for prop in class_mapper(cls).iterate_properties:
        if isinstance(prop, ColumnProperty):
            _col = prop.columns[0]
            _attr = getattr(cls, _cls.name)

            _filters.append(cast(_attr, String).match(query))

    result = session.query(cls)
    result = result.filter(or_(*_filters))

    # get the subclasses
    subclasses = set()
    for child in cls.__subclasses__():
        if child not in subclasses:
            subclasses.add(child)
            # join the subclass
            result = result.outerjoin(child)
            # recurse to get the columns from the subclass
            result = subclass.get_all(session, result)

    # return a query, not a result to allow for the recursion.
    # you might need to tweak this.
    return result

rawDescription: SQLAlchemy inheritance filter on all columns


code:
from lxml import etree

with open(filename, 'r') as xmlfile:
    tree = etree.parse(xmlfile)
    if tree.docinfo.encoding == 'utf-8':
        # already in correct encoding, abort
        return

rawDescription: Reading XML header encoding

description: Reading XML header encoding


code:
def quotedStringOrWord(pattern):
    return quotedString(pattern) | Word(pattern)

rawDescription: Something like optionalQuotedString in pyparsing?


code:
class BaseResume(models.Model):
    class Meta:
        abstract = True

    owner = models.ForeignKey(Member)
    realname = models.CharField(max_length=30)
    sex = models.IntegerField(blank=False, choices=SEX_CHOICES, default=1)
    education = models.IntegerField(blank=False, choices=EDUCATION_CHOICES)

    expierence = models.IntegerField(blank=False, choices=EXPERIENCE_CHOICES)
    expect_post = models.IntegerField(blank=False, choices=POST_CHOICES)
    expect_salary = models.IntegerField(blank=False, choices=SALARY_CHOICES)
    city = models.ForeignKey(City)
    location = models.ForeignKey(Location, null=True)

class Resume(BaseResume):
    pass

class ResumeCopy(BaseResume):
    pass

rawDescription: How to create a ModelCopy in correct way (django)

description: Create a ModelCopy in correct way (django)


code:
fig, ax = plt.axes()
plt.hold(True)
polarity_godzilla.plot(ax=ax, style="k-o", label="Godzilla")
polarity_henry_kissinger(ax=ax, style="b-*", label="Kissinger")
#etc.
plt.legend()  #to draw a legend with the labels you provided
plt.show() #or plt.savefig(filename)

rawDescription: autoscaling in matplotlib, plotting different time series in same chart

description: Autoscaling in matplotlib, plotting different time series in same chart


code:
import sys  # probably near the top of the file
sys.stdout.flush()  # after printing

rawDescription: generator with sleep method couldn't work?

description: Generator with sleep method couldn't work


rawDescription: Pandas Missing Data

description: Pandas Missing Data


code:
{
        "query": {
            "function_score": {
                "score_mode": "sum",
                "boost_mode": "replace",
                "query": {
                    "match": {
                        "title": {
                            "query":  "iphone 6",
                            "operator": "and"
                        }
                    }
                },

                "functions": [{
                    "script_score": {
                        "script": "def score = 1000 - _source.title.size(); score",
                        "lang": "groovy"
                    }
                }]
            }
        },
        "track_scores": True,
        "sort": [
            {
                "_score": {
                    "order": "desc"
                }
            }
        ],
        "size": 1
    }

rawDescription: ElasticSearch match query score

description: ElasticSearch match query score


code:
lqt.lqt_write_text.argtypes = [ctypes.c_void_p,ctypes.c_int,ctypes.c_char_p,ctypes.c_int64]
lqt.lqt_write_text.restype = None
lqt.lqt_write_text(qth, 1, 'test message', 123)

rawDescription: Seg faults on c dataypes in python using ctypes


code:
import numpy
import theano
import theano.tensor as tt
import theano.ifelse

def scan_range_step(x_tm1, step):
    return x_tm1 + step

def compile_theano_range():
    tt.arange
    symbolic_start = tt.lscalar()
    symbolic_stop = tt.lscalar()
    symbolic_step = tt.lscalar()
    n_steps = tt.cast(
        tt.ceil(tt.abs_(symbolic_stop - symbolic_start) / tt.cast(tt.abs_(symbolic_step), theano.config.floatX)),
        'int64') - 1
    outputs, _ = theano.scan(scan_range_step, outputs_info=[symbolic_start], n_steps=n_steps,
                             non_sequences=[symbolic_step], strict=True)
    outputs = theano.ifelse.ifelse(tt.eq(n_steps, 0), tt.stack(symbolic_start), outputs)
    f = theano.function([symbolic_start, symbolic_stop, symbolic_step],
                        outputs=tt.concatenate([[symbolic_start], outputs]))

    def theano_range(start, stop=None, step=1):
        assert isinstance(start, int)
        assert isinstance(step, int)
        if step == 0:
            raise ValueError()
        if stop is None:
            stop = start
            start = 0
        else:
            assert isinstance(stop, int)
        if start == stop:
            return []
        if stop < start and step > 0:
            return []
        if stop > start and step < 0:
            return []
        return f(start, stop, step)

    return theano_range

def main():
    theano_range = compile_theano_range()
    python_range = range

    for start in [-10, -5, -1, 0, 1, 5, 10]:
        for stop in [-10, -5, -1, 0, 1, 5, 10]:
            for step in [-3, -2, -1, 1, 2, 3]:
                a = theano_range(start, stop, step)
                b = python_range(start, stop, step)
                assert numpy.all(numpy.equal(a, b)), (start, stop, step, a, b)

main()

rawDescription: Scanning without sequences in theano? (emulating range())


code:
from pylab import *
for (x, y) in clusters:
    plot(x, y, '+')
show() # or savefig(<filename>)

rawDescription: How to plot a set of points in python?

description: Plot a set of points in python


code:
class House:
    # other methods
    def __str__(self):
        return "%d %s" % (self.street_number, self.street_name)

rawDescription: Python Returns on calling class object

description: Python Returns on calling class object


code:
from PySide import QtGui, QtCore

# special GraphicsRectItem that is aware of its position and does something if the position is changed
class MovableGraphicsRectItem(QtGui.QGraphicsRectItem):

    def __init__(self, callback=None):
        super(MovableGraphicsRectItem, self).__init__()
        self.setFlags(QtGui.QGraphicsItem.ItemIsMovable | QtGui.QGraphicsItem.ItemSendsScenePositionChanges)
        self.setCursor(QtCore.Qt.PointingHandCursor)
        self.callback = callback

    def itemChange(self, change, value):
        if change == QtGui.QGraphicsItem.ItemPositionChange and self.callback:
            self.callback(value)

        return super(MovableGraphicsRectItem, self).itemChange(change, value)

    def activate(self):
        self.setFlags(QtGui.QGraphicsItem.ItemIsMovable | QtGui.QGraphicsItem.ItemSendsScenePositionChanges)
        self.setCursor(QtCore.Qt.PointingHandCursor)

    def deactivate(self):
        self.setFlags(not QtGui.QGraphicsItem.ItemIsMovable | QtGui.QGraphicsItem.ItemSendsScenePositionChanges)
        self.setCursor(QtCore.Qt.ArrowCursor)

class MouseInsideFilterObj(QtCore.QObject):#And this one
    def __init__(self, enterCallback, leaveCallback):
        QtCore.QObject.__init__(self)
        self.enterCallback = enterCallback
        self.leaveCallback = leaveCallback

    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.Type.Enter:
            self.enterCallback(obj)

        if event.type() == QtCore.QEvent.Type.Leave:
            self.leaveCallback(obj)

        return True

class TestClass:

    def __init__(self):

        self.app = QtGui.QApplication([])

        # the scene with some rectangles
        self.scene = QtGui.QGraphicsScene()
        self.scene.addRect(30, 30, 100, 50, pen=QtGui.QPen(QtCore.Qt.darkGreen))
        self.scene.addRect(150, 0, 30, 80, pen=QtGui.QPen(QtCore.Qt.darkYellow))
        self.scene.addRect(80, 80, 100, 20, pen=QtGui.QPen(QtCore.Qt.darkMagenta))
        self.scene.addRect(200, 10, 30, 80, pen=QtGui.QPen(QtCore.Qt.darkRed))

        self.window = QtGui.QWidget()

        # put two graphicsviews into the window with different scaling for each
        self.layout = QtGui.QVBoxLayout(self.window)
        self.v1 = QtGui.QGraphicsView(self.scene)
        self.v1.setFixedSize(500, 100)
        self.v1.scale(0.5, 0.5)
        self.v1.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.v1.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.layout.addWidget(self.v1)
        self.v2 = QtGui.QGraphicsView(self.scene)
        self.v2.setFixedSize(500, 500)
        self.v2.scale(5, 5)
        self.v2.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.v2.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.layout.addWidget(self.v2)

        mouseFilter = MouseInsideFilterObj(self.enterGV, self.leaveGV)
        self.v1.installEventFilter(mouseFilter)

        # the tracker rectangle
        self.tracker = MovableGraphicsRectItem(lambda pos: self.v2.setSceneRect(pos.x(), pos.y(), 100, 100))
        self.tracker.setRect(0, 0, 100, 100)
        self.v2.setSceneRect(0, 0, 100, 100)
        self.tracker.setPen(QtGui.QPen(QtCore.Qt.darkCyan))
        self.scene.addItem(self.tracker)

        self.window.show()
        self.app.exec_()

    def leaveGV(self, gv):
        if gv is self.v1:
            self.tracker.deactivate()

    def enterGV(self, gv):
        if gv is self.v1:
            self.tracker.activate()

TestClass()

rawDescription: Make QGraphicsItem only selectable in one graphicsview


code:
def start(self):
    ...
    self.new_window = name_w
    ...

def quit_window(self):
    self.Q1()
    self.new_window.destroy()

rawDescription: Closing a window and opening a new one via a button in Tkinter


code:
from django.db.models import Avg
Table.objects.extra(select={'month':"strftime('%m',date)"}).values('month').annotate(Avg('value'))

rawDescription: Django Monthly/quartarly grouping of DateField() data


code:
existingEpisodeIDs = [row[0] for row in c.fetchall()] #this will end up just being a list of id's
id = 22528819
existingEpisodeIDs.remove(id)

rawDescription: Correct syntax to remove list elements by value from MySQL array


code:
from collections import defaultdict
from fractions import Fraction
from math import factorial
from operator import itemgetter

def binomial(n, k):
    return factorial(n) // (factorial(k) * factorial(n - k))

def find_path(graph, s, t):
    stack = [s]
    predecessor = {s: t}
    while stack:
        v = stack.pop()
        for u in graph[v]:
            if u not in predecessor:
                stack.append(u)
                predecessor[u] = v
    assert t in predecessor
    path = [t]
    while path[-1] != s:
        path.append(predecessor[path[-1]])
    path.reverse()
    return path

def round_flow(flow):
    while True:
        capacities = []
        for (u, v), x in flow.items():
            z = x - x.numerator // x.denominator
            if z:
                capacities.append(((v, u), z))
                capacities.append(((u, v), 1 - z))
        if not capacities:
            break
        (t, s), delta = min(capacities, key=itemgetter(1))
        graph = defaultdict(list)
        for (v, u), z in capacities:
            if (v, u) not in [(s, t), (t, s)]:
                graph[v].append(u)
        path = find_path(graph, s, t)
        for i, v in enumerate(path):
            u = path[i - 1]
            if (u, v) in flow:
                flow[(u, v)] += delta
            else:
                flow[(v, u)] -= delta

def baranyai(n, k):
    m, r = divmod(n, k)
    assert not r
    M = binomial(n - 1, k - 1)
    partition = [[()] * m for i in range(M)]
    for l in range(n):
        flow = defaultdict(Fraction)
        for i, A_i in enumerate(partition):
            for S in A_i:
                flow[(i, S)] += Fraction(k - len(S), n - l)
        round_flow(flow)
        next_partition = []
        for i, A_i in enumerate(partition):
            next_A_i = []
            for S in A_i:
                if flow[(i, S)]:
                    next_A_i.append(S + (l,))
                    flow[(i, S)] -= 1
                else:
                    next_A_i.append(S)
            next_partition.append(next_A_i)
        partition = next_partition
    assert len(partition) == M
    classes = set()
    for A in partition:
        assert len(A) == m
        assert all(len(S) == k for S in A)
        assert len({x for S in A for x in S}) == n
        classes.update(map(frozenset, A))
    assert len(classes) == binomial(n, k)
    return partition

if __name__ == '__main__':
    print(baranyai(9, 3))
    print(baranyai(20, 2))

rawDescription: Find unique compositions of k-distinct-element subsets for a set of n elements


code:
# only make the figure and axes once
fig, ax = plt.subplots(figsize=(2, 2))
# set the aspect to be equal
ax.set_aspect('equal')
# do the looping
for x_list,label_list,title in lists:
    # clear the axes
    ax.cla()
    # make the pie graph
    ax.pie(x_list, labels=label_list, autopct="%1.1f%%")
    # set the title
    ax.set_title(title)
    # save the figure
    fig.savefig(pp, format='pdf')

rawDescription: Matplotlib overlapping multiple charts in one pdf


code:
url = "http://www.example.com/site/section1/VAR1/VAR2"
url.split("/")[-2:]

rawDescription: Python - Split url into its components

description: Python - Split url into its components


code:
import csv

total = count = 0

with open('3114644b.csv', newline='') as f:
    reader = csv.reader(f)
    next(reader, None)  # skip the first row of headers

    for row in reader:
        total += float(row[4])
        count += 1

if count:
    # only calculate the average if there was actually anything in the file
    average = total / count
    print('The average of the values is {}'.format(average))

rawDescription: Finding The Average on Python

description: Finding The Average on Python


code:
s="""                              SPY
Date
2015-02-02 00:00:00+00:00  201.92"""
s.split()
from itertools import repeat
repeat(s.split()[-1],10)
list(repeat(float(s.split()[-1]),10))

rawDescription: Python convert a list of strings in a nested list to list


code:
import scipy.io.wavfile
fs1, y1 = scipy.io.wavfile.read(filename)
l1 = numpy.array([  [7.2,19.8], [35.3,67.23], [103,110 ] ])
l1 = ceil(l1*fs1)#get integer indices into the wav file - careful of end of array reading with a check for greater than y1.shape
newWavFileAsList = []
for elem in l1:
  startRead = elem[0]
  endRead = elem[1]
  if startRead >= y1.shape[0]:
    startRead = y1.shape[0]-1
  if endRead >= y1.shape[0]:
    endRead = y1.shape[0]-1
  newWavFileAsList.extend(y1[startRead:endRead])

newWavFile = numpy.array(newWavFileAsList)

scipy.io.wavfile.write(outputName, fs1, newWavFile)

rawDescription: Trimming audio in python

description: Trimming audio in python


code:
# Defines a list of `num_steps` variables, each 1-D with length `batch_size`.
weights = [tf.get_variable("w", [batch_size]) for _ in range(num_steps)]

loss = seq2seq.sequence_loss_by_example([logits_1, ..., logits_n],
                                        [targets_1, ..., targets_n],
                                        weights,
                                        vocab_size_all)

rawDescription: Trainable weight for TensorFlow sequence_loss_by_example()


code:
# No teamNews here.

def getTeamNews(team_to_query):
    # Since you don't do any other things, directly assign it is enough, right?
    # No need for a list comprehension or a for loop here.
    teamNews = teams.select().where(teams.Nba == team_to_query)
    return teamNews

rawDescription: Can't remove objects from list after MySQL query with peewee in Flask


code:
def isSpaceFree(bin, row, column, block):
    if row + block > len(bin):
        return False
    if column + block > len(bin):
        return False
    else:  # YOU PROBABLY DON'T WANT THIS HERE
        return False #DITTO

    ## Nothing from here or below ever gets reached because of above commented lines
    if bin[row][column] == 0 :  ## you dont want this
        return True  ##because this is bad too and aborts and its already covered below
    for r in range(row, row+block):
        for c in range(column, column + block):
            if bin[r][c] != 0:
                return False
    return True

rawDescription: binary 2d dimension and packing

description: Binary 2d dimension and packing


code:
def request(context, flow):
    if flow.request.method == "POST":
        form = flow.request.get_form_urlencoded()
        real_post = form.get_first("phony_param")
        if real_post:
            flow.request.content = real_post

rawDescription: Use mitmproxy to translate a form key/value to a body post


code: from gravatar.templatetags.gravatar import _get_gravatar_id, gravatar_for_email

rawDescription: Django - Get gravatar from view

description: Django - Get gravatar from view


code:
#!python3
import collections
import time

class FuturesContract:
    Commodity = collections.namedtuple('Commodity',
            'symbol future exchange delivery_months')

    Commodities = [
        # Source: http://www.mrci.com/web/online-explanation-pages/symbols-a-codes.html
        # !IMPORTANT! Sorted by length of symbol!!!
        Commodity('ITCO', 'Brent Crude', 'ICE', 'F,G,H,J,K,M,N,Q,U,V,X,Z'),
        Commodity('AD', 'Australian Dollar', 'CME', 'H,M,U,Z'),
        Commodity('BP', 'British Pound', 'CME', 'H,M,U,Z'),
        Commodity('CD', 'Canadian Dollar', 'CME', 'H,M,U,Z'),
        Commodity('DX', 'US Dollar Index', 'ICE', 'H,M,U,Z'),
        Commodity('EU', 'EuroFx', 'CME', 'H,M,U,Z'),
        Commodity('JY', 'Japanese Yen', 'CME', 'H,M,U,Z'),
        Commodity('SF', 'Swiss Franc', 'CME', 'H,M,U,Z'),
        Commodity('CL', 'Crude Oil', 'NYM', 'F,G,H,J,K,M,N,Q,U,V,X,Z'),
        Commodity('HO', 'NY Harbor ULSD/Heating Oil', 'NYM', 'F,G,H,J,K,M,N,Q,U,V,X,Z'),
        Commodity('HU', 'Unleaded Gas', 'NYM', 'F,G,H,J,K,M,N,Q,U,V,X,Z'),
        Commodity('NG', 'Natural Gas', 'NYM', 'F,G,H,J,K,M,N,Q,U,V,X,Z'),
        Commodity('RB', 'RBOB Gasoline', 'NYM', 'F,G,H,J,K,M,N,Q,U,V,X,Z'),
        Commodity('BO', 'Soybean Oil', 'CBOT', 'F,H,K,N,Q,U,V,Z'),
        Commodity('KW', 'Kansas City Wheat', 'KCBT', 'H,K,N,U,Z'),
        Commodity('MW', 'Minneapolis Wheat', 'MGE', 'H,K,N,U,Z'),
        Commodity('SM', 'Soybean Meal', 'CBOT', 'F,H,K,N,Q,U,V,Z'),
        Commodity('DJ', 'Dow Jones Industrials', 'CBOT', 'H,M,U,Z'),
        Commodity('KV', 'Value Line (Discontinued)', 'KCBT', 'H,M,U,Z'),
        Commodity('MV', 'Value Line (Mini)', 'KCBT', 'H,M,U,Z'),
        Commodity('ND', 'Nasdaq-100', 'CME', 'H,M,U,Z'),
        Commodity('RL', 'Russell 2000 (Discontinued)', 'CME', 'H,M,U,Z'),
        Commodity('SP', 'S & P 500', 'CME', 'H,M,U,Z'),
        Commodity('YU', 'NYSE Composite (Discontinued)', 'NYFE', 'H,M,U,Z'),
        Commodity('ED', 'Eurodollars', 'CME', 'H,M,U,Z'),
        Commodity('FV', '5-Yr T-Notes', 'CBOT', 'H,M,U,Z'),
        Commodity('MB', 'Municipal Bonds', 'CBOT', 'H,M,U,Z'),
        Commodity('TU', '2-Yr T-Notes', 'CBOT', 'H,M,U,Z'),
        Commodity('TY', '10-Yr T-Notes', 'CBOT', 'H,M,U,Z'),
        Commodity('US', '30-Yr T-Bonds', 'CBOT', 'H,M,U,Z'),
        Commodity('FC', 'Feeder Cattle', 'CME', 'F,H,J,K,Q,U,V,X'),
        Commodity('LC', 'Live Cattle', 'CME', 'G,J,M,Q,V,Z'),
        Commodity('LH', 'Lean Hogs', 'CME', 'G,J,K,M,N,Q,V,Z'),
        Commodity('LE', 'Lean Hogs', 'CME', 'G,J,K,M,N,Q,V,Z'),
        Commodity('PB', 'Pork Bellies', 'CME', 'G,H,K,N,Q'),
        Commodity('DA', 'Milk Class III', 'CME', 'F,G,H,J,K,M,N,Q,U,V,X,Z'),
        Commodity('GC', 'Gold', 'CMX', 'G,J,M,Q,V,Z'),
        Commodity('HG', 'Copper', 'CMX', 'H,K,N,U,Z'),
        Commodity('PL', 'Platinum', 'NYM', 'F,J,N,V'),
        Commodity('SI', 'Silver', 'CMX', 'H,K,N,U,Z'),
        Commodity('RR', 'Rice', 'CBOT', 'F,H,K,N,U,X'),
        Commodity('CC', 'Cocoa', 'ICE', 'H,K,N,U,Z'),
        Commodity('CT', 'Cotton', 'ICE', 'H,K,N,V,Z'),
        Commodity('KC', 'Coffee', 'ICE', 'H,K,N,U,Z'),
        Commodity('LB', 'Lumber', 'CME', 'F,H,K,N,U,X'),
        Commodity('JO', 'Orange Juice', 'ICE', 'F,H,K,N,U,X'),
        Commodity('SB', 'Sugar #11', 'ICE', 'H,K,N,V'),
        Commodity('C', 'Corn', 'CBOT', 'F,H,K,N,U,X,Z'),
        Commodity('O', 'Oats', 'CBOT', 'H,K,N,U,Z'),
        Commodity('S', 'Soybeans', 'CBOT', 'F,H,K,N,Q,U,X'),
        Commodity('W', 'Wheat', 'CBOT', 'H,K,N,U,Z'),
    ]

    Months = {
        1: 'January',
        2: 'February',
        3: 'March',
        4: 'April',
        5: 'May',
        6: 'June',
        7: 'July',
        8: 'August',
        9: 'September',
        10: 'October',
        11: 'November',
        12: 'December',
        'F': 'January',
        'G': 'February',
        'H': 'March',
        'J': 'April',
        'K': 'May',
        'M': 'June',
        'N': 'July',
        'Q': 'August',
        'U': 'September',
        'V': 'October',
        'X': 'November',
        'Z': 'December',
    }

    MonthCodes = {
        'January': 'F',
        'February': 'G',
        'March': 'H',
        'April': 'J',
        'May': 'K',
        'June': 'M',
        'July': 'N',
        'August': 'Q',
        'September': 'U',
        'October': 'V',
        'November': 'X',
        'December': 'Z',
    }

    def __init__(self, details=None):
        if details is None:
            now = time.localtime()
            month = now.tm_mon
            year = now.tm_year
            self.commodity = None
        else:
            for c in self.Commodities:
                if details.startswith(c.symbol):
                    self.commodity = c
                    symlen = len(c.symbol)
                    month = details[symlen:symlen+1]
                    year = details[symlen+1:]
                    if len(year) == 2:
                        year = '20'+year
                    year = int(year)
                    break
            else:
                raise ValueError("Unparseable details given: "+details)

        month = self.Months[month]
        if self.commodity is not None:
            month_code = self.MonthCodes[month]
            if month_code not in self.commodity.delivery_months:
                raise ValueError('Invalid delivery month for commodity: '+month)

        self.month = month
        self.year = year

    def __str__(self):
        c = self.commodity
        return 'Unspecified' if c is None else c.symbol + self.MonthCodes[self.month] + str(self.year)

    def explain(self):
        c = self.commodity
        return [ 'A FuturesContract for:',
                '\t{}: {} (on the {} exchange)'.format(c.symbol, c.future, c.exchange),
                '\tDated: {} ({}), {}'.format(self.month, self.MonthCodes[self.month], self.year),
                ]

cz2016 = FuturesContract('CZ2016')

print('\n'.join(cz2016.explain()))
print('\n')
print('Commodity:', cz2016.commodity)
print('Month:', cz2016.month)
print('Year:', cz2016.year)

print("\nHas __str__:", cz2016)

print("\n\n")
print("Future LBQ2014: (should be invalid, because Q):")
fc = FuturesContract('LBQ2014')

rawDescription: Python Custom Formatters

description: Python Custom Formatters


code:
class Matrix:

    def __init__(self, matrix):
        self.matrix = matrix
        self.n = len(matrix)

    def __getitem__(self, index):
        index -= 1
        return self.matrix[int(index%self.n)][int(index/self.n)]

a = [[1,5,9,13],
     [2,6,10,14],
     [3,7,11,15],
     [4,8,12,16]]

mtx = Matrix(a)
print([ mtx[i] for i in range(1,17) ])
# [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

rawDescription: How can I chage the index count in a matrix? (Python)

description: Chage the index count in a matrix? (Python)


code:
src = lxml.etree.parse('real.xml')
ix = dict()
for n in src.getroot().iterdescendants():
    ix[n.tag] = n

dest = lxml.etree.parse('template.xml')
for n in dest.getroot().iterdescendants():
    if n.tag in ix:
        n.text = ix[n.tag].text

rawDescription: python lxml: copy values from one xml file to another where elements match

description: Python lxml: copy values from one xml file to another where elements match


code:
def empty_generator():
    return
    yield

rawDescription: How to write Python generator function that never yields anything

description: Write Python generator function that never yields anything


code:
def callback(event):
    text = inputfield.get()
    if 'weather:' in text:
        weather()
    if 'open:' in text:
        program()

# ...
inputfield.bind('<Return>', callback)

rawDescription: Calling Different Functions tkinter

description: Calling Different Functions tkinter


code:
def obj_get(self, bundle, **kwargs):
    try:
        obj = super(self, ResourceClass).obj_get(bundle, **kwargs)
        obj.counter_field += 1
        obj.save()
        return obj
    except NotFound:
        raise

rawDescription: Overriding get logic in tastypie

description: Overriding get logic in tastypie


code:
class ModelName(models.Model):
    created = models.DateTimeField()
    expired = models.DateTimeField(blank=True, null=True)

    def save(self, *args, **kwargs):
        if not self.pk:
            self.expired = self.created + datetime.timedelta(days=30)
        super(ModelName, self).save(*args, **kwargs)

rawDescription: Calculate DateField until days in Django


rawDescription: Build list in Python

description: Build list in Python


code:
def test_build_url(self):
    """ If only endpoint is supplied should default to settings"""

    with patch.object(build_url, 'func_defaults', ('domain',)):
      result = build_url('/end')
      expected = 'domain/end'

    self.assertEqual(result,expected)

rawDescription: Python unittest mock: Is it possible to mock the value of a method's default arguments at test time?


code:
max_row = ws.get_highest_row() # find last row of worksheet
reff = "A1:A" + str(max_row) # build an Excel range covering the data
values = [cell.value for cell in ws.range(reff)] # collect the data
ws.cell('A' + str(max_row + 1)).value = ' '.join(values) # write values

rawDescription: concatenate data in excel using openpyxl in Python

description: Concatenate data in excel using openpyxl in Python


code:
import os.path

package_dir = os.path.abspath(os.path.dirname(__file__))
database_path = os.path.join(package_dir, 'database.db')

rawDescription: Access SQLite3 database that is located up one directory from application folders


code:
cntent = re.sub('<[^>]+>',"\n", str(cntent))
with open(os.path.join('/Users/Brian/Documents/test', titles), "wb") as f:
    f.writelines(line for line in cntent.splitlines(True) if line.strip())

rawDescription: python removing lines from file

description: Python removing lines from file


code:
def to01(array):
    a = array.min()
    # ignore the Runtime Warning
    with numpy.errstate(divide='ignore'):
        b = 1. /(array.max() - array.min())
    if not(numpy.isfinite(b)):
        b = 0
    return numpy.vectorize(lambda x: b * (x - a))(array)

rawDescription: NumPy array to bounded by 0 and 1?

description: NumPy array to bounded by 0 and 1


code: Hits = p.starmap(calc, ((rules, record) for record in Records))

rawDescription: Why aren't my Python Multiprocessing worker processes using multiple cores?


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

fig = plt.figure()

ax = fig.add_subplot(111)
ax.plot(np.arange(300))

# Get current tick locations and append 271 to this array
x_ticks = np.append(ax.get_xticks(), 271)

# Set xtick locations to the values of the array `x_ticks`
ax.set_xticks(x_ticks)

plt.show()

rawDescription: showing specific xtick in matplotlib

description: Showing specific xtick in matplotlib


rawDescription: Python: telling a raw string (r'') from a string ('')


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = [0.15, 0.11, 0.06, 0.06, 0.12, 0.56]
y = [x, x, x, x, x, x]
boxes = plt.boxplot(y,
                    flierprops={'alpha':0.6,
                                'markersize': 40,
                                'markeredgecolor': 'None',
                                'marker': '.'
                                })

cols = ['green', 'red', 'blue', 'orange', 'purple', 'black']

for f, fc in zip(boxes['fliers'], cols):
    f.set_markerfacecolor(fc)

plt.show()

rawDescription: matplotlib: Fliers in boxplot object not setting correctly

description: Matplotlib: Fliers in boxplot object not setting correctly


code:
def ccovf(x, y, unbiased=True, demean=True):
    n = len(x)
    if demean:
        xo = x - x.mean()
        yo = y - y.mean()
    else:
        xo = x
        yo = y
    if unbiased:
        xi = np.ones(n)
        d = np.correlate(xi, xi, 'full')
    else:
        d = n
    return (np.correlate(xo, yo, 'full') / d)[n - 1:]

def ccf(x, y, unbiased=True):
    cvf = ccovf(x, y, unbiased=unbiased, demean=True)
    return cvf / (np.std(x) * np.std(y))

rawDescription: numpy and statsmodels give different values when calculating correlations, How to interpret this?

description: Numpy and statsmodels give different values when calculating correlations, How to interpret this


code:
def search_orders(self):
    headers = {'Authorization':'Bearer %s' % self.token,'Content-Type':'application/json',}
    url = "https://api.flipkart.net/sellers/orders/search"
    filter = {"filter": {"states": ["APPROVED","PACKED"],},}
    s = requests.Session()
    response = s.post(url, data=json.dumps(filter), headers=headers)
    orderList = []
    resp_json = response.json()
    orderList.append(resp_json["orderItems"])
    while resp_json.get('hasMore') == True:
        response = s.get('"https://api.flipkart.net/sellers{0}'.format(resp_json['nextPageUrl']))
        resp_json = response.json()
        orderList.append(resp_json["orderItems"])
    return orderList

rawDescription: Fetch all pages using python request

description: Fetch all pages using python request


code:
def getAvgValues(data, avgSampleTime):
  lastTime = 0
  prevValsBuf = []
  prevValsStart = 0
  tot = 0
  for t, v in data:
    avgStart = t - avgSampleTime
    # remove too old values
    while prevValsStart < len(prevValsBuf):
      pt, pv = prevValsBuf[prevValsStart]
      if pt > avgStart:
        break
      tot -= pv
      prevValsStart += 1
    # add new item
    tot += v
    prevValsBuf.append((t, v))
    # yield result
    numItems = len(prevValsBuf) - prevValsStart
    yield (t, tot / numItems)
    # clean prevVals if it's time
    if prevValsStart * 2 > len(prevValsBuf):
      prevValsBuf = prevValsBuf[prevValsStart:]
      prevValsStart = 0
      # recalculate tot for not accumulating float precision error
      tot = sum(v for (t, v) in prevValsBuf)

rawDescription: smoothing irregularly sampled time data

description: Smoothing irregularly sampled time data


code:
s = "ERTYHGFYUUHGFREDFYAAAAAAAAAA"
endings = ['AAAAA', 'AAAAAA', 'AAAAAAA', 'AAAAAAAA', 'AAAAAAAAA']
max([i for i in endings if s.endswith(i)],key=len)

rawDescription: Get the actual ending when testing with .endswith(tuple)