code:
LISTENERS = []

class RealtimeHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        LISTENERS.append(self)

    def on_close(self):
        LISTENERS.remove(self)

application = tornado.web.Application([
    (r'/', RealtimeHandler),
])

rawDescription: Keeping the ajax call alive when calling the Tornado server


code:
if request.method == 'POST':
    form = MyForm(request.POST, request.FILES)
    if form.is_valid():
        uploaded_file = request.FILES['html-file-attribute-name']

        # Write the file to disk
        fout = open("path/to/save/file/to/%s" % uploaded_file.name, 'wb')
        for chunk in uploaded_file.chunks():
            fout.write(chunk)
        fout.close()

rawDescription: Django Read/Upload a CSV

description: Django Read/Upload a CSV


code:
def fort_knox():
    # A very private variable
    gold = [0]

    class impl(object):
        def add_gold(self, amt):
            gold[0] += amt

        def remove_gold(self, amt):
            raise Exception('No withdrawals!')

        def count_gold(self):
            return gold[0]

    return impl()

rawDescription: information hiding in python

description: Information hiding in python


code:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        self.wfile.write("magic content goes here")

if __name__=="__main__":
    try:
        server = HTTPServer(("", 8080), Handler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

rawDescription: Python Django simple site

description: Python Django simple site


code:
import os
import cv2

img = cv2.imread(filename)
roi = img[row:row+height,column:column+width]
cv2.imshow('ROI',roi)
cv2.waitKey(0)

rawDescription: opencv using python - copy roi to new smaller image

description: Opencv using python - copy roi to new smaller image


code:
R1 = Radiobutton(root, text = "HOSTS", var = 'hosts', value = 1, command = sel, variable=var2)
R1.pack(anchor = W)

R2 = Radiobutton(root, text = "NETWORKS", var = 'networks', value = 2, command = selnet, variable=var2)
R2.pack(anchor = W)

rawDescription: Tkinter Radiobuttons autoselect and always on...Python 2.7


code:
import csv
import itertools

csvreader = csv.reader(open("Book1.csv", "r"))
lines = [line for line in csvreader]

#Sort
lines =  sorted(lines[1:], key = lambda x: (x[4], x[3], x[2]))

#Grouping
newRows = []
for grp in itertools.groupby(lines, key = lambda x: (x[2], x[3], x[4])):
    newRow = [0, 0] + list(grp[0]) + [0.0, 0.0, 0.0]
    for col in grp[1]:
        newRow[5] += float(col[5])
        newRow[6] += float(col[6])
        newRow[7] += float(col[5]) + float(col[6])
    newRows.append(newRow)

#Filtering and write csv
with open("Journal.csv", "w") as fp:
    csvwriter = csv.writer(fp)
    csvwriter.writerow(["Cost Centre", "Tax Rate", "Total Ex VAT", "VAT", "Total In VAT"])
    for r in filter(lambda x:x[2].strip() == "4200213", newRows):
        csvwriter.writerow(r[3:])

rawDescription: Grouping and Sub-Grouping CSV data in Python


code:
from pyramid.request import Request
from pyramid.request import Response

def request_factory(environ):
    request = Request(environ)
    if request.is_xhr:
        request.response = Response()
        request.response.headerlist = []
        request.response.headerlist.extend(
            (
                ('Access-Control-Allow-Origin', '*'),
                ('Content-Type', 'application/json')
            )
        )
    return request

config.set_request_factory(request_factory)

rawDescription: Pyramid CORS for Ajax requests

description: Pyramid CORS for Ajax requests


code: new_list = [ s[1:3] for s in your_list ]

rawDescription: Extracting a specified string in a list of strings in Python


code: min(ProdPrice.objects.filter(product=x['id']).aggregate(Min('price'))['price__min'] for x in c)

rawDescription: how to compare values in loop in python

description: Compare values in loop in python


code:
from sqlalchemy import select, func

col = getattr(obj_table.c, attr_name)
q = select([func.max(col)], obj_table)
with self._engine.connect() as conn:
    res = conn.execute(q)
    max_value = res.fetchone()[0]

rawDescription: Retrieve max of column using reflected table in SQLAlchemy


code:
class FooWrapper(object):
  def __init__(self, foo):
    self.foo = foo

  def __getattr__(self, name):
    return getattr(self.foo, name)

  def mymethod(self):
    ...

rawDescription: Can IronPython dynamically add methods to a C# class?


code:
import inspect

def foo(a,b,x='blah'):
    pass

print(inspect.getargspec(foo))
# ArgSpec(args=['a', 'b', 'x'], varargs=None, keywords=None, defaults=('blah',))

rawDescription: How can I read a function's signature including default argument values?

description: Read a function's signature including default argument values


code:
class PostResource(ModelResource):
    class Meta:
        queryset = Post.objects.all()

    def get_object_list(self, request):
        this_users_posts = super(PostResource, self).get_object_list(request).filter(user=User.objects.get(user=request.user))
        all_the_posts_this_user_follows = super(PostResource, self).get_object_list(request).filter(follower=User.objects.get(user=request.user))

        return this_users_posts | all_the_posts_this_user_follows

rawDescription: Advanced Filtering in Tastypie

description: Advanced Filtering in Tastypie


code:
def __getslice__(self, start, stop) :
    """This solves a subtle bug, where __getitem__ is not called, and all
    the dimensional checking not done, when a slice of only the first
    dimension is taken, e.g. a[1:3]. From the Python docs:
       Deprecated since version 2.0: Support slice objects as parameters
       to the __getitem__() method. (However, built-in types in CPython
       currently still implement __getslice__(). Therefore, you have to
       override it in derived classes when implementing slicing.)
    """
    return self.__getitem__(slice(start, stop))

rawDescription: Numpy __getitem__ delayed evaluation and a[-1:] not the same as a[slice(-1, None, none)]


code: outp = fun()

rawDescription: python 3.5.1 won't return strings from functions

description: Python 3.5.1 won't return strings from functions


code: s.groupby(s.index.weekday).transform(lambda x: pd.rolling_mean(x, window=n))

rawDescription: Get mean of last N weekdays for pandas dataframe


code:
# this is meant to follow on from the `os.makedirs` line...
foupath = os.path.join(realCSVdir, 'Movie-%s.csv' % var)
fou = open(foupath, 'wb')
writer = csv.writer(fou)

rawDescription: How do you write CSV files to a specific folder that you've recently created in python?

description: Write CSV files to a specific folder that you've recently created in python


code:
attributeList = (('Name',    'name',    'name'),
                 ('Version', 'version', 'revision'))

for title, obj_attribute, dict_key in attributeList:
    obj_value = getattr(obj, obj_attribute)
    adict_value = adict[dict_key]

    if obj_value == adict_value:
        msg.append('%s is the same' % (obj_value))
    else:
        msg.append('%s was updated from %s to %s' % (title, obj_value, adict_value))

        setattr(obj, obj_attribute, adict_value)

rawDescription: Pythonic way to avoid a mountain of if...else statements?


code: list = [ x[0] for x in values ]

rawDescription: Extracting first value of pair type in python


rawDescription: Min-Maxing / max-value of two slices in a list


code:
class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

rawDescription: Calling one method from another within same class in Python


code:
import winsound
import Tkinter
import threading

def create_frame():
    MessFrame = Tkinter.Tk()
    MessFrame.geometry('800x400+200+200')
    MessFrame.title('Main Frame')
    Framelabel = Tkinter.Label(MessFrame, text='Text Here', fg= 'red')
    Framelabel.place(x=10,y=10)
    MessFrame.mainloop()

t1 = threading.Thread(target=create_frame)
t1.start()

winsound.Beep(500,1000)

rawDescription: Tkinter frame pauses the program. Program wont move on until I close the frame


code:
return {
    'type': 'ir.actions.act_url',
    'url': '/forum/%s/question/%s' % (self.forum_id.id, self.id),
    'target': 'self',
    'res_id': self.id,
}

rawDescription: Odoo/Python how to redirect to a website


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

# two overlapping distributions
x1 = np.random.beta(2, 5, 500)
x2 = np.random.beta(5, 2, 500)

fig, ax = plt.subplots(1, 1)
ax.hold(True)

# plot the histograms as usual
bins = np.linspace(0, 1, 20)
counts1, edges1, bars1 = ax.hist(x1, bins)
counts2, edges2, bars2 = ax.hist(x2, bins)

# plot the histograms as lines as well for clarity
ax.hist(x1, bins, histtype='step', ec='k', ls='solid', lw=3)
ax.hist(x2, bins, histtype='step', ec='k', ls='dashed', lw=3)

# set the z-order of each bar according to its relative height
x2_bigger = counts2 > counts1
for b1, b2, oo in zip(bars1, bars2, x2_bigger):
    if oo:
        # if bar 2 is taller than bar 1, place it behind bar 1
        b2.set_zorder(b1.get_zorder() - 1)
    else:
        # otherwise place it in front
        b2.set_zorder(b1.get_zorder() + 1)

plt.show()

rawDescription: Matplotlib using layered histograms

description: Matplotlib using layered histograms


code:
def b():
    global a
    a = 5

a = 4
print(a)  # prints 4
b()
print(a)  # prints 5

rawDescription: Why is a variable able to be defined after definition of function using it?


code:
import collections
import random

delays=[0,2,30,180,365]

counter = collections.defaultdict(int)
while delays:
    condition = random.choice(delays)
    print(condition)
    counter[condition] += 1
    if counter[condition] == 20:
        delays.remove(condition)

rawDescription: Python - how do you select from variables when different conditions are met


code:
link = [l for l in br.links()][-1]
br.click_link(link)
response = br.follow_link(link)
open('asd.mp3', 'w').write(response.read())

rawDescription: Python Downloading a file without having a direct link on mechanize


code:
str='sdfsdfsdfdsfsdfcxvvdfvxcvsdcsdcs sdcsdcasd'
I=int.from_bytes(bytes([ord (i)for i in str]),byteorder='big')
print(I)
print(I.to_bytes(len(str),byteorder='big'))

rawDescription: Python strings as long number

description: Python strings as long number


rawDescription: stringified list to two separate lists

description: Stringified list to two separate lists


code:
idx = pandas.date_range(datetime(2015, 1, 1, 10, 0), datetime(2015, 1, 1, 12, 0), freq='30min')
df = pandas.DataFrame(numpy.nan, index=idx, columns=['val'])

testdf.set_index('t', inplace=True)
testdf.combine_first(df).fillna(method='ffill')

rawDescription: Keep original data points when padding a signal with pandas


code:
gridfunc = grid
grid = ximport("grid")

rawDescription: nodebox grid() vs. grid library

description: Nodebox grid() vs. grid library


code:
from bs4 import BeautifulSoup
def getGz():
    #http = httplib2.Http()
    #status, response = http.request('url/sitemap.xml')
    soup = BeautifulSoup(response, "lxml")
    links = [loc.text for loc in soup.find_all("loc")]

rawDescription: Use BeautifulSoup open .gz file in sitemap.xml


code:
def odd_or_even(num):
    if num % 2 == 0:
        print(num, 'is even')
    else:
        print(num, 'is not even')

lst = [random.randint(lower, upper) for x in range(20)]
for num in lst:
    print(even_or_odd(num))

rawDescription: how do you generate 20 random numbers in python

description: Generate 20 random numbers in python


code:
if url == "http://www.example.com":
    print("The URL is homepage")
else:
    print("The URL is not homepage")

rawDescription: Python Selenium if string contains exact match


code:
class Base(tornado.web.RequestHandler):
    def get_unique_id(self):
        return self.get_secure_cookie('unique_id')

    def set_unique_id(self, some_value):
        return self.set_secure_cookie('unique_id', some_value)

class ShowLogin(Base):
  def get(self):
    if get_unique_id():
       # Get stuff from Mongo using unique_id
       # mongo calls
       self.redirect('/dashboard')
    else:
       self.render('login.html')

class LoginLogin(Base):
  def post(self):
    self.set_unique_id(some_id)

rawDescription: Store Tornado ( Python ) session in MongoDB


code:
def getKey(row):
    return (row[0], row[7], row[9], row[10])

# create a set of all the keys you care about
lead_keys = {getKey(r) for r in Leads_rows}

# save this off due to reverse indexing gyration
len_ac_list = len(Acquisition_list)

for i, ac_row in enumerate(Acquisition_list[::-1]):
    ac_key = getKey(ac_row)
    if ac_key in lead_keys:   ## this look up is O(1)
        index = len_ac_list - i - 1
        Acquisition_list.pop(index)
        Leads_list.append(ac_row)
        ## maybe: lead_keys.add(ac_key)

rawDescription: Improving Run Time for deduping lists based on only certain columns in Python


code:
import json
json_data =  '{"a": "my data"}'
data = json.loads(json_data)
class AutoVar(object):
  def __init__(self, data):
      self.__dict__ = data

test = AutoVar(data)
test.a

rawDescription: Loading Class Variables from JSON?

description: Loading Class Variables from JSON


code:
from vtk.util.numpy_support import vtk_to_numpy

...

vtk_rw = vtk.vtkRenderWindow()

...

vtk_win_im = vtk.vtkWindowToImageFilter()
vtk_win_im.SetInput(vtk_rw)
vtk_win_im.Update()

vtk_image = vtk_win_im.GetOutput()

height, width, _ = vtk_image.GetDimensions()
vtk_array = vtk_image.GetPointData().GetScalars()
components = vtk_array.GetNumberOfComponents()

arr = vtk_to_numpy(vtk_array).reshape(height, width, components)

...

rawDescription: VTK render window image to numpy array

description: VTK render window image to numpy array


code:
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/")
def hello():
    all_args = request.args.lists()
    return jsonify(all_args)

rawDescription: How to process GET Query String with Flask

description: Process GET Query String with Flask


code:
for i, item in enumerate(my_list):
    item[0].append("#")
    my_list[i] = item[0], item[1] * 3

rawDescription: Appending to list of tuples

description: Appending to list of tuples


code:
import web
import json

class index:
    def GET(self):
        pyDict = {'one':1,'two':2}
        web.header('Content-Type', 'application/json')
        return json.dumps(pyDict)

rawDescription: webpy: How to serve JSON

description: Webpy: How to serve JSON


code:
df1 = pd.DataFrame.from_csv(filepath, index_col = None)

def find_peaks(grad, x_data, y_data):
    ...
    ...

for i in range(1,31):
    result = find_peaks(grad,df1['R'], df1['I {}'.format(i)])
    #Do whatever you want with the result

rawDescription: applying functions to multiple dataframe columns

description: Applying functions to multiple dataframe columns


code:
from PySide.QtCore import *
from PySide.QtGui import *
import sys

def createMask(size):
    w=size.width()
    h=size.height()
    img=QImage(size, QImage.Format_MonoLSB)
    qp=QPainter()
    qp.begin(img)
    qp.fillRect(QRect(QPoint(0, 0), size), QColor(255,255,255))
    path=QPainterPath()
    path.moveTo(0, h-1)
    path.lineTo(w-1,0)
    path.lineTo(h-1, 0)
    path.lineTo(0, h-1)
    qp.fillPath(path, QBrush(QColor(0, 0, 0)))
    qp.end()
    return img

def createRoundedRectRegion(rect, radius):
    r=QRegion(rect.adjusted(radius, 0, -radius, 0))
    r|=QRegion(rect.adjusted(0, radius, 0, -radius))
    r|=QRegion(rect.left(), rect.top(), 2*radius, 2*radius, QRegion.Ellipse)
    r|=QRegion(rect.right()-2*radius, rect.top(), 2*radius, 2*radius, QRegion.Ellipse)
    r|=QRegion(rect.left(), rect.bottom()-2*radius, 2*radius, 2*radius, QRegion.Ellipse)
    r|=QRegion(rect.right()-2*radius, rect.bottom()-2*radius, 2*radius, 2*radius, QRegion.Ellipse)
    return r

def createRegion(bubbleSize, pointSize, offset):
    r=createRoundedRectRegion(QRect(QPoint(0, 0), bubbleSize), 10)
    t=QRegion(QPixmap(createMask(pointSize)))
    t.translate(offset, bubbleSize.height())
    r|=t
    return r

class Callout(QWidget):
    def __init__(self, text, parent=None):
        super(Callout, self).__init__(parent)
        w=100+len(text)*5
        self.setMinimumSize(w, 100)
        self.setMaximumSize(w, 100)
        self.text=text
        self.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setMask(createRegion(QSize(w, 50), QSize(75, 50), 75))

    def paintEvent(self, event):
        qp=QPainter()
        qp.begin(self)
        qp.fillRect(0, 0, self.width(), 200, QColor(192, 192, 192))
        qp.drawText(QRect(0, 0, self.width(), 50), Qt.AlignCenter, self.text)
        qp.end()

def main():
    app=QApplication(sys.argv)
    w=Callout('Bla Bla Bla')
    w.move(200, 100)
    w.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: Implementing PySide callout

description: Implementing PySide callout


code:
import sqlalchemy
engine = sqlalchemy.create_engine("oracle+cx_oracle://user:pass@host:port/dbname", arraysize=50)
pd.read_sql("query ...", engine)

rawDescription: using the cx_Oracle arraysize parameter with pandas read_sql

description: Using the cx_Oracle arraysize parameter with pandas read_sql


code:
for t in my_threads:
    if not t.isAlive():
        # get results from thtead
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

rawDescription: Python - checking on a thread / remove from list


code:
from sklearn.utils.extmath import randomized_svd

U, Sigma, VT = randomized_svd(X, n_components=15,
                                      n_iter=5,
                                      random_state=None)

rawDescription: Get U, Σ, V* from Truncated SVD in scikit-learn


code:
while True:
        selected_piece = int(input("Which piece would you like to move? (1/2):  "))
        if selected_piece not in [1,2]:
            print("Invalid input, please try again.")
            continue
        else:
            break

rawDescription: Python - Try and Except not working

description: Python - Try and Except not working


rawDescription: How can I get 2 characters from the middle of a string?

description: Get 2 characters from the middle of a string


code:
import enum
DynamicEnum = enum.Enum('DynamicEnum', {'foo':42, 'bar':24})
type(DynamicEnum)
DynamicEnum.foo
DynamicEnum.bar
list(DynamicEnum)

rawDescription: Dynamically create an enum with custom values in Python?


code:
for num in xrange(3, n+1, 2):
    next_num = False
    for c in counted:
        if num % c == 0:
            next_num = True
            break
    if next_num:
        continue
    count += 1
    counted.append(num)

rawDescription: How can I continue the for loop of the outer side?

description: Continue the for loop of the outer side


code:
class ClassBasedDecorator():
    def __init__(self, fn):
        self.fn = fn
        functools.update_wrapper(self, fn)
    def __call__(self, *args, **kwargs):
        self.fn(*args, **kwargs)
    def __repr__(self):
        return repr(self.fn)

rawDescription: Class-based decorator and repr() conservation


code: client = mqtt.Client("python_pub")

rawDescription: Multiple MQTT Publish not Working

description: Multiple MQTT Publish not Working


code:
from rest_framework_jwt.settings import api_settings
from datetime import datetime

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

my_user = User.objects.get(pk=1) # replace with your existing logic

payload = jwt_payload_handler(my_user)

# Include original issued at time for a brand new token,
# to allow token refresh
if api_settings.JWT_ALLOW_REFRESH:
    payload['orig_iat'] = timegm(
        datetime.utcnow().utctimetuple()
    )

return {
    'token': jwt_encode_handler(payload)
}

rawDescription: How to do Django JSON Web Token Authentication without forcing the user to re-type their password?

description: Do Django JSON Web Token Authentication without forcing the user to re-type their password


code:
def MyUbberTuple(*args, **kwargs):
    if len(args) == 2:
        return Usual(*args)
    return Optimized(*args)

rawDescription: What's the best way of implementing from_iterable alternate c-tor?


code:
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': '/path/to/media'}),

rawDescription: Understanding of Django static files

description: Understanding of Django static files


code: R -= R.sum(0) / len(R)

rawDescription: Center of mass of a numpy array, how to make less verbose?


code:
from Tkinter import *

window = Tk()
window.geometry("300x300")

# Note the change to this line
my_frame = Frame(window, width=300, height=300)
my_frame.pack() # Note the parentheses added here

button1 = Button(my_frame, text="I am at (100x150)")
button1.place(x=100, y=150)

button2 = Button(my_frame, text="I am at (0 x 0)")
button2.place(x=0, y=0, width=100, height=50)

window.mainloop()

rawDescription: Tkinter code won't work

description: Tkinter code won't work


code:
def getMaxDeflection(self):
    a = s.fmin(lambda x: -self.getTotalDeflection(x), 0, full_output=1)
    return a[1], a[0][0]

rawDescription: Unpacking values of current function value and array from fmin scipy optimisation


code:
from tkinter import *
from tkinter.messagebox import *

def timerDone(window):
    showinfo('Alert','Alert')
    window.destroy()

window = Tk()
window.after(3000,lambda:timerDone(window))
window.mainloop()

rawDescription: tkinter issues in Python

description: Tkinter issues in Python


code:
wordcounter = collections.Counter(" ".join(v) for v in p)
print(wordcounter)
# gives
# Counter({'one two': 2, 'three four': 1, 'five six': 1})

rawDescription: How to count two word sequences in python

description: Count two word sequences in python


code:
import os
import os.path as _osp
import re
import subprocess
import io
import email.parser

env_forward = re.compile('^[A-Z][A-Z0-9_]*$')
header_match = re.compile(b'^(.*?\\n[ \\t\\r]*\\n)(.*)$', re.M | re.S)
env_whitelist = frozenset(('AUTH_TYPE', 'CONTENT_LENGTH', 'CONTENT_TYPE',
                           'DOCUMENT_ROOT', 'QUERY_STRING', 'PATH_INFO',
                           'PATH_TRANSLATED', 'REMOTE_ADDR', 'REMOTE_PORT',
                           'REMOTE_IDENT', 'REMOTE_USER', 'REQUEST_METHOD',
                           'REQUEST_URI', 'SCRIPT_NAME',
                           'SERVER_ADDR', 'SERVER_ADMIN', 'SERVER_NAME',
                           'SERVER_PORT', 'SERVER_PROTOCOL',
                           'SERVER_SIGNATURE', 'SERVER_SOFTWARE'))

class CGIApplication(object):
    def __init__(self, appfname):
        self._appfname = _osp.abspath(appfname)

    def __call__(self, environ, start_respose):
        appenv = {item[0]: item[1] \
                      for item in environ.items() \
                      if ((item[0] in env_whitelist) or
                          item[0].startswith('HTTP_'))}
        appenv['GATEWAY_INTERFACE'] = 'CGI/1.1'
        appenv['PATH'] = '/usr/local/bin:/usr/bin:/bin'
        appenv['SCRIPT_FILENAME'] = self._appfname
        nbytes_for_cgi = appenv.get('CONTENT_LENGTH', '')
        nbytes_for_cgi = (int(nbytes_for_cgi) if nbytes_for_cgi != '' else 0)

        args = [self._appfname]
        query = environ.get('QUERY_STRING', None)
        query = query.replace('+', ' ')
        if '=' not in query:
            args.append(query)
        proc = subprocess.Popen(args,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                env = appenv,
                                cwd = _osp.dirname(self._appfname))
        bytes_read = 0
        data_for_cgi = io.BytesIO()
        while bytes_read < nbytes_for_cgi:
            data = environ['wsgi.input'].read(nbytes_for_cgi - bytes_read)
            bytes_read += len(data)
            data_for_cgi.write(data)
            data = None
        data_for_cgi = data_for_cgi.getvalue()
        output, errdata = proc.communicate(data_for_cgi)
        data_for_cgi = None
        proc.stdin.close()
        proc.stdout.close()
        proc.stderr.close()
        try:
            errdata = errdata.decode('utf-8')
        except UnicodeDecodeError:
            errdata = errdata.decode('iso8859-1')
        environ['wsgi.errors'].write(errdata)
        errdata = None
        if proc.returncode != 0:
            start_respose('500 Internal Server Error',
                          [('Content-Type', 'text/plain')])
            return (b"CGI application died with non-zero return code.\n",)
        else:
            output_hdr = header_match.match(output)
            output_hdr, output = output_hdr.groups()
            parser = email.parser.HeaderParser()
            headers = parser.parsestr(output_hdr.decode('iso8859-1'))
            status = headers.get_all('Status', ['200 OK'])[-1]
            del headers['Status']
            start_respose(status, list(headers.items()))
            return (output,)

rawDescription: How do I launch a CGI script from a WSGI handler?

description: Launch a CGI script from a WSGI handler


code:
from tarfile import TarFile

tar = TarFile("the_tar.tar")
tar.extractall()

rawDescription: Untarring in python, interactive vs script call


code:
big = qrPIL.resize((1024, 1024))
big.save("bigger.png")
big.show()

rawDescription: How to change the image size of qrencode.encode?

description: Change the image size of qrencode.encode


code:
import re
randomText ="Enter your text"
randomText = randomText.replace('\n','')
wordFrequency = {}
randomText = randomText.split(' ')
for word in randomText:
    word = re.sub('[^A-Za-z0-9]+', '', word)
    currentWordLength = len(word)
    if(word):
        if  currentWordLength not in wordFrequency.keys():

            wordFrequency[currentWordLength]=1
        else:
            wordFrequency[currentWordLength]=      wordFrequency[currentWordLength]+1
for key in wordFrequency.keys():
    print("{0} --> {1}".format(key,wordFrequency[key]))

rawDescription: How to count words for each different length in python?

description: Count words for each different length in python


code:
def chunked_res():
    yield "Chunk 1"
    yield " " * 1024  # Encourage browser to render incrementally (either 1024 or 1024-7{length of "chunk 1"} = 1017)

    time.sleep(5)  # wait for 5 seconds

    yield "Chunk 2"

def myview(request):
    g = chunked_res()
    return HttpResponse(g)

rawDescription: Django return http early flush (chunked response)


code:
from threading import Thread
from time import sleep

class A(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.value = 1
        self.stop_flag = False

    def run(self):
        while not self.stop_flag:
            sleep(1)
            print(self.value)

    def set_value(self, value):
        self.value = value

    def stop(self):
        self.stop_flag = True

if __name__ == '__main__':
    a = A()
    a.start()
    try:
        while 1:
            r = raw_input()
            a.set_value(int(r))
    except:
        a.stop()

rawDescription: Multithreading (?): Manual interference in a loop


code:
import matplotlib.pyplot as plt
ax1 = plt.subplot(111, projection="polar")
ax1.get_rmin(), ax1.get_rmax()
ax1.set_rmin(0.5)
ax1.get_rmin(), ax1.get_rmax()
ax1.set_rscale('log')
ax1.get_rmin(), ax1.get_rmax()
ax1.set_rmin(0.5)
ax1.get_rmin(), ax1.get_rmax()
ax1.set_rmax(1); ax1.set_rmin(0.5)
ax1.get_rmin(), ax1.get_rmax()

rawDescription: Matplotlib: set_rmin not working for logarithmic polar projection


rawDescription: Combine lists by joining strings with matching index values


code: integral = integrate.simps(y*x*2*pi,x)

rawDescription: How can I integrate in cylindrical coordinates with Scipy?

description: Integrate in cylindrical coordinates with Scipy


code:
from collections import defaultdict

foo = defaultdict(int)
foo[bar] += 1

rawDescription: Python dictionary: add or increment entry


code:
sub1 = [s for s in l if not s.endswith('*')]
sub2 = [s for s in l if s.endswith('*')]

rawDescription: Division of a list to two sublists based on regex


code:
# api.py: your api flask application
from flask import Flask, jsonify, request

api_app = Flask(__name__)

big_gis_object = unpickle(...)

@api_app.route('/find_distance')
def find_distance():
    # grabbing the parameters for this request
    lat, lon = request.args['lat'], request.args['lon']

    # do your normal geo calculations here
    distance = big_gis_object.do_dist_calcs(lat, lon)

    # return the result as json to make things easy
    return jsonify(distance=distance)

# app.py: your main flask application
import requests
from flask import Flask, render_template

main_app = Flask(__name__)

@main_app.route('/')
def homepage():
    # this is how you ask the geo api app to do something for you
    # note that we're using the requests library do make it easier
    # - http://docs.python-requests.org/en/latest/user/quickstart/
    resp = requests.get('http://url_to_flask_app/find_distance', params=dict(lat=1.5, lon=1.7))
    distance = resp.json()['distance']
    return render_template('homepage.html', distance)

rawDescription: Is it feasible to unpickle large amounts of data in a Python web app that needs to be scalable?


code: sum(1 for result in results)

rawDescription: Get number of results from Django's raw() query function


code:
lst = r"""
\bigoplus
\bigotimes
\bigskip
\bigsqcup
\biguplus
\bigvee
\bigwedge
""".split()
lst.sort()      # necessary if lst is not already sorted
lst = [""] + lst + [""]
def cp(x): return len(os.path.commonprefix(x))

{ lst[i]: 1 + max(cp(lst[i-1:i+1]), cp(lst[i:i+2])) for i in range(1,len(lst)-1) }

rawDescription: how would i look for the shortest unique subsequence from a set of words in python?

description: How would i look for the shortest unique subsequence from a set of words in python


code:
def on_click(event):
    plt.plot(event.xdata, event.ydata, 'ro')
    global fig
    fig.canvas.draw()

rawDescription: Drawing on top of an existing graph Python Matplotlib


code:
def jtheta_dq(n, z, q):
    # cf. http://functions.wolfram.com/EllipticFunctions/EllipticTheta2/13/01/0002/
    return -mpmath.jtheta(n, z, q, 2)/(4*q)

rawDescription: Implementation of derivatives of Jacobi theta function


code:
tview = gtk.TextView()
# background
tview.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse('#000000'))
# foreground
tview.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('#FFFFFF'))
# bonus font
tview.modify_font(pango.FontDescription('Monospace 11'))

rawDescription: gtk.TextBuffer color

description: Gtk.TextBuffer color


code:
def offset(coordinates, distance):
    coordinates = iter(coordinates)
    x1, y1 = coordinates.next()
    z = distance
    points = []
    for x2, y2 in coordinates:
        # tangential slope approximation
        try:
            slope = (y2 - y1) / (x2 - x1)
            # perpendicular slope
            pslope = -1/slope  # (might be 1/slope depending on direction of travel)
        except ZeroDivisionError:
            continue
        mid_x = (x1 + x2) / 2
        mid_y = (y1 + y2) / 2

        sign = ((pslope > 0) == (x1 > x2)) * 2 - 1

        # if z is the distance to your parallel curve,
        # then your delta-x and delta-y calculations are:
        #   z**2 = x**2 + y**2
        #   y = pslope * x
        #   z**2 = x**2 + (pslope * x)**2
        #   z**2 = x**2 + pslope**2 * x**2
        #   z**2 = (1 + pslope**2) * x**2
        #   z**2 / (1 + pslope**2) = x**2
        #   z / (1 + pslope**2)**0.5 = x

        delta_x = sign * z / ((1 + pslope**2)**0.5)
        delta_y = pslope * delta_x

        points.append((mid_x + delta_x, mid_y + delta_y))
        x1, y1 = x2, y2
    return points

def add_semicircle(x_origin, y_origin, radius, num_x = 50):
    points = []
    for index in range(num_x):
        x = radius * index / num_x
        y = (radius ** 2 - x ** 2) ** 0.5
        points.append((x, -y))
    points += [(x, -y) for x, y in reversed(points)]
    return [(x + x_origin, y + y_origin) for x, y in points]

def round_data(data):
    # Add infinitesimal rounding of the envelope
    assert data[-1] == data[0]
    x0, y0 = data[0]
    x1, y1 = data[1]
    xe, ye = data[-2]

    x = x0 - (x0 - x1) * .01
    y = y0 - (y0 - y1) * .01
    yn = (x - xe) / (x0 - xe) * (y0 - ye) + ye
    data[0] = x, y
    data[-1] = x, yn
    data.extend(add_semicircle(x, (y + yn) / 2, abs((y - yn) / 2)))
    del data[-18:]

from pylab import *

with open('ah79100c.dat', 'rb') as f:
    f.next()
    data = [[float(x) for x in line.split()] for line in f if line.strip()]

t = [x[0] for x in data]
s = [x[1] for x in data]

round_data(data)

parallel = offset(data, 0.1)
t2 = [x[0] for x in parallel]
s2 = [x[1] for x in parallel]

plot(t, s, 'g', t2, s2, 'b', lw=1)

title('Wing with envelope')
grid(True)

axes().set_aspect('equal', 'datalim')

savefig("test.png")
show()

rawDescription: Python. How to get the x,y coordinates of a offset spline from a x,y list of points and offset distance


code:
def question1_UI(self):
    # ...
    label1 = Label(self, image=gif1)
    label1.image = gif1
    label1.grid(row = 0, column = 0, columnspan = 2, sticky=NW)

    questionAButton = Button(self, text='Submit',font=('MS', 8,'bold'))
    questionAButton.grid(row = 1, column = 0, sticky = S)
    questionBButton = Button(self, text='Submit',font=('MS', 8,'bold'))
    questionBButton.grid(row = 1, column = 1, sticky = S)
    questionCButton = Button(self, text='Submit',font=('MS', 8,'bold'))
    questionCButton.grid(row = 2, column = 0, sticky = S)
    questionDButton = Button(self, text='Submit',font=('MS', 8,'bold'))
    questionDButton.grid(row = 2, column = 1, sticky = S)

rawDescription: Tkinter: Getting an image above buttons in grid layout


code:
sample=[[1,[1,0]],[1,1]]
from itertools import chain
print [1,0]  in chain(*sample)

rawDescription: How do I search a list that is in a nested list (list of list) without loop in Python?

description: Search a list that is in a nested list (list of list) without loop in Python


code:
import os
import sys

stdin_no = sys.stdin.fileno()
some_bytes = os.read(stdin_no, 1024)

rawDescription: Python pipe in binary file from command line -u option


code:
from sqlalchemy.ext.hybrid import hybrid_property

class Person(Base):
    # ...
    @hybrid_property
    def name(self):
        return '{0} {1}'.format(self.first_name, self.last_name)

    @name.setter
    def name(self, value):
        self.first_name, self.last_name = value.split(' ', 1)

    @name.expression
    def name(cls):
        return db.func.concat(cls.first_name, ' ', cls.last_name)

rawDescription: Return two SqlAlchemy Columns concatenated


code:
import sys
sys.stdout = open("mylog.txt", "w")

rawDescription: Can I get the output of "print" statement in pythonw?

description: Get the output of "print" statement in pythonw


code:
import mock

from mymodule import my_method_under_test

class MyTest(TestCase):

    def test_request_get(self):
        with patch('requests.get') as patched_get:
            my_method_under_test()
            # Ensure patched get was called, called only once and with exactly these params.
            patched_get.assert_called_once_with("https://ec2.amazonaws.com/", params={'Action': 'GetConsoleOutput', 'InstanceId': 'i-123456'})

rawDescription: Unit-testing python-requests?

description: Unit-testing python-requests


code:
from Tkinter import *

# Esempio di GUI

def main():
    w1=Tk()
    w1.title("Finestra 1")
    # Width, height in pixels
    f1=Frame(w1, height=50, width=50)
    f1.pack()
    w1.mainloop()

main()

rawDescription: Window doesn't appear using Tkinter

description: Window doesn't appear using Tkinter


code:
if form.is_valid():
    comment = form.save(commit=False)
    comment.story = story_details
    comment.save()
    return ...

rawDescription: Recommended way to populate foreign key?

description: Recommended way to populate foreign key


code:
options = pax_two_ob_meal.options # get all the options into list
index = randint(0, len(options) - 1) # get random number from 0 to list size - 1
pax_two_ob_meal.select_by_index(index)

rawDescription: How to count options in a drop down list and then randomly select

description: Count options in a drop down list and then randomly select


code:
import struct
struct.pack(">i", 336)

rawDescription: convert decimal to hex python

description: Convert decimal to hex python


code:
'''
Created on May 8, 2016

@author: Billal Begueradj
'''
import Tkinter as Tk

class Begueradj(Tk.Frame):
    '''
    Dislay a Label spanning over 3 columns of checkbuttons
    '''
    def __init__(self, parent):
        '''Inititialize the GUI
        '''
        Tk.Frame.__init__(self, parent)
        self.parent=parent
        self.initialize_user_interface()

    def initialize_user_interface(self):
        """Draw the GUI
        """
        self.parent.title("Billal BEGUERADJ")
        self.parent.grid_rowconfigure(0,weight=1)
        self.parent.grid_columnconfigure(0,weight=1)
        self.parent.config(background="lavender")

        # Create a Frame on which other elements will be attached to
        self.frame = Tk.Frame(self.parent, width = 500, height = 207)
        self.frame.pack(fill=Tk.X, padx=5, pady=5)

        # Create the checkbuttons and position them on the second row of the grid
        self.alpha_button = Tk.Checkbutton(self.frame, text = 'Alpha', font = ('Arial', 20))
        self.alpha_button.grid(row = 1, column = 0)

        self.beta_button = Tk.Checkbutton(self.frame, text = 'Beta', font = ('Arial', 20))
        self.beta_button.grid(row = 1, column = 1)

        self.gamma_button = Tk.Checkbutton(self.frame, text = 'Gamma', font = ('Arial', 20))
        self.gamma_button.grid(row = 1, column = 2)

         # Create the Label widget on the first row of the grid and span it over the 3 checbbuttons above
        self.label = Tk.Label(self.frame, text = 'Even', bd = 5, fg = 'black', font = ('Arial', 70), width = 8, relief = 'groove')
        self.label.grid(row = 0, columnspan = 3)

# Main method
def main():
    root=Tk.Tk()
    d=Begueradj(root)
    root.mainloop()

# Main program
if __name__=="__main__":
    main()

rawDescription: Adding frame over lable on python

description: Adding frame over lable on python


code:
class Order(DirtyFieldsMixin, models.Model):
    ...

def order_pre_save(sender, instance):
    if "status" in instance.get_dirty_fields():
        instance.t_status = datetime.datetime.now()

pre_save.connect(order_pre_save, sender=Order)

rawDescription: How to set a timestamp in Django when the class's attribute is set or changed

description: Set a timestamp in Django when the class's attribute is set or changed


code:
tablename='Querysummary Data'
table=Document.Data.Tables[tablename]

topiccolname='TOPIC_ID'
topiccol=table.Columns[topiccolname]
topiccursor=DataValueCursor.Create[str](topiccol)

docscolname='DOC_IDS'
doccol=table.Columns[docscolname]
doccursor=DataValueCursor.Create[str](doccol)

myPanel = Document.ActivePageReference.FilterPanel
idxSet =  myPanel.FilteringSchemeReference.FilteringSelectionReference.GetSelection(table).AsIndexSet()

# build a string representing the data in tab-delimited text format
textData = "TOPIC_ID;DOC_IDS\r\n"

keys=dict()
topdoc=dict()
for row in table.GetRows(idxSet,topiccursor,doccursor):
   keys[topiccursor.CurrentValue]=doccursor.CurrentValue

for key in keys:
    str = keys[key].split(",")

    for i in str:
        textData += key + ";" +  i + "\r\n"

dataSet = DataSet()
dataTable = DataTable("DOCIDS")
dataTable.Columns.Add("TOPIC_ID", System.String)
dataTable.Columns.Add("DOC_IDS", System.String)

dataSet.Tables.Add(dataTable)

# make a stream from the string
stream = MemoryStream()
writer = StreamWriter(stream)
writer.Write(textData)
writer.Flush()
stream.Seek(0, SeekOrigin.Begin)

# set up the text data reader
readerSettings = TextDataReaderSettings()
readerSettings.Separator = ";"
readerSettings.AddColumnNameRow(0)
readerSettings.SetDataType(0, DataType.String)
readerSettings.SetDataType(1, DataType.String)
readerSettings.SetDataType(2, DataType.String)

# create a data source to read in the stream
textDataSource = TextFileDataSource(stream, readerSettings)

# add the data into a Data Table in Spotfire
if Document.Data.Tables.Contains("Querysummary Mapping"):
    Document.Data.Tables["Querysummary Mapping"].ReplaceData(textDataSource)
else:
    newTable = Document.Data.Tables.Add("Querysummary Mapping", textDataSource)
    tableSettings = DataTableSaveSettings (newTable, False, False)
    Document.Data.SaveSettings.DataTableSettings.Add(tableSettings)

rawDescription: How to split a comma-delimited list in IronPython (Spotfire)?

description: Split a comma-delimited list in IronPython (Spotfire)


code:
from fabric.api import task
from fabric.tasks import Task

class CustomTask(Task):
    def __init__(self, func, *args, **kwargs):
        super(CustomTask, self).__init__(*args, **kwargs)
        self.func = func
        self.foo = "one"

    def run(self, *args, **kwargs):
        return self.func(self.foo, *args, **kwargs)

@task(task_class=CustomTask)
def one(foo):
    print(cyan('Using FOO %s' % foo))

rawDescription: Implicitly called task / function on python Fabric startup?


code:
def startDrag(self, sender, event):
    self.root.drag.Visibility = Visibility.Visible
    self.root.dragText.Text = sender.Text

    self.root.CaptureMouse()
    self._captured = True
    self.root.MouseLeftButtonUp += self.stopDrag
    self.root.MouseLeave += self.stopDrag
    self.onDrag(sender, event)

def onDrag(self, sender, event):
    if self._captured:
        position = event.GetPosition(self.root.layout_root)
        self.root.drag.Margin = Thickness(position.X, position.Y, 0, 0)
        self.root.drag.UpdateLayout()

rawDescription: TranslateTransform for drag and drop in Silverlight


rawDescription: How to omit all the last elements of a numpy ndarray in python?

description: Omit all the last elements of a numpy ndarray in python


code:
import ast
import numpy
a = numpy.array(["{'foo':123}","{'foo':234}"])
numpy.fromiter((ast.literal_eval(s)['foo'] for s in a), numpy.int_)

rawDescription: Implementing ast.literal_eval on a numpy array


code:
import re

data = "billg@microsoft.com;steve@apple.com;  dhh@37signals.com"
stuff = re.split(r"\s*[,;]\s*", data.strip())

rawDescription: String of values separated by commas or semicolons into a Python list


code:
def resizeConsoleEvent(self, resizeObject):
    if not self.keyPressDown and not self.blockResizing:
        # calculate maximum columns and lines based on a '|' character
        font = self.ui.console.currentFont()
        fmetric = QtGui.QFontMetrics(font)
        fontPixelWidth = fmetric.width("|")
        fontPixelHeight = fmetric.height()
        availableWidthPixels = int(self.ui.console.geometry().width())
        availableHeightPixels = int(self.ui.console.geometry().height())
        # Calculate columns and lines w/ adjustments for rounding
        self.consoleColumns = int(availableWidthPixels / fontPixelWidth) + 1
        self.consoleLines = int(availableHeightPixels / fontPixelHeight) - 3

        # resize the pyte screen I'm using with the calculated information
        self.shell.resizeConsole(self.consoleLines, self.consoleColumns)

        # block double resize event
        self.keyPressDown = False
        return False
    else:

        return True

rawDescription: How do I convert width and height (in pixels) to columns for use with the python library pyte?

description: Convert width and height (in pixels) to columns for use with the python library pyte


code:
try:
    from .settings_local import *  # noqa
except ImportError:
    pass

rawDescription: Update sensitive code on Github and server?


code:
arr = np.array([[9], [2], [4], [1], [8]])
arr_ = np.zeros((arr.size, arr.max()))
arr_[np.arange(arr.size), arr[:,0]-1] = 1
arr_

rawDescription: transform a numpy array of dimensions nx1 into a numpy array of dimensions nx10

description: Transform a numpy array of dimensions nx1 into a numpy array of dimensions nx10


code:
import cherrypy

class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())

rawDescription: How can one process POST requests with a basic Python CGI script on Apache?


code:
from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPFound
from paste.httpserver import serve

config = Configurator()

config.add_route('redirect', '/{arg}')

def redirect_view(request):
    dst = 'http://mydomain2.com/register.php?id={id}&from={host}'
    args = {
        'id': request.matchdict['arg'],
        'host': request.host,
    }
    return HTTPFound(dst.format(**args))
config.add_view(redirect_view, route_name='redirect')

serve(config.make_wsgi_app(), host='0.0.0.0', port=80)

rawDescription: Creating a dynamic redirect by using any of Flask, Pyramid, or Bottle?


rawDescription: Plotting line segments from the set of startpoints and endpoints


code:
def Pole(request, pole, nazwa):

    try:
        criteria = {pole: nazwa}
        entry = Entry.objects.get(**criteria)
        return HttpResponse(entry.wpis)
    except Entry.DoesNotExist:
        return HttpResponse("Nuffin")

rawDescription: Use variable as field in ORM query

description: Use variable as field in ORM query


code:
from collections import defaultdict
nesteddict = lambda: defaultdict(nesteddict)
test = nesteddict()
test['SYSTEM']['home']['GET'] = True
test['SYSTEM']['home']['POST'] = False
test['SYSTEM']['home']['GET']
test['SYSTEM']['home']['POST']

rawDescription: Multi dimensional python dictionary

description: Multi dimensional python dictionary


rawDescription: Multiplying two 2D numpy arrays to a 3D array


code:
import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style="ticks", color_codes=True)

tips = sns.load_dataset("tips")

g = sns.FacetGrid(tips, col="time",  hue="smoker")
g = g.map(plt.scatter, "total_bill", "tip", edgecolor="w")

g.axes[0,0].set_xlabel('axes label 1')
g.axes[0,1].set_xlabel('axes label 2')

plt.show()

rawDescription: Python Seaborn Facetgrid change xlabels

description: Python Seaborn Facetgrid change xlabels


rawDescription: imread in pylab vs opencv: returning completely different array values

description: Imread in pylab vs opencv: returning completely different array values


code:
from __future__ import division
from collections import Counter
from itertools import product
from toolz.curried import sliding_window, map, pipe, concat
from toolz.dicttoolz import merge

# Generate all possible transitions
defaults = sc.broadcast(dict(map(
    lambda x: ("".join(concat(x)), 0.0),
    product(product("HNL", "NL", "HNL"), repeat=2))))

rdd = sc.parallelize(["500, HNL, LNH, NLH, HNL", "600, HNN, NNN, NNN, HNN, LNH"])

def process(line):
    """
    >>> process("000, HHH, LLL, NNN")
    ('000', {'LLLNNN': 0.5, 'HHHLLL': 0.5})
    """
    bits = line.split(", ")
    transactions = bits[1:]
    n = len(transactions) - 1
    frequencies = pipe(
        sliding_window(2, transactions), # Get all transitions
        map(lambda p: "".join(p)), # Joins strings
        Counter, # Count
        lambda cnt: {k: v / n for (k, v) in cnt.items()} # Get frequencies
    )
    return bits[0], frequencies

def store_partition(iter):
    for (k, v) in iter:
        db_insert(k, merge([defaults.value, v]))

rdd.map(process).foreachPartition(store_partition)

rawDescription: Algorithmic / coding help for a PySpark markov model


code:
def CreateLink():
    excel.Worksheets(1).Cells(1,1).Value = '=HYPERLINK(A21,"Cell A21")'

rawDescription: Error when using Python to create hyperlink within a worksheet in Excel


code:
search_str =  self.text_to_find.get_text()
start_iter =  textbuffer.get_start_iter()
# don't need these lines anymore
#match_start = textbuffer.get_start_iter()
#match_end =   textbuffer.get_end_iter()
found =       start_iter.forward_search(search_str,0, None)
if found:
   match_start,match_end = found #add this line to get match_start and match_end
   textbuffer.select_range(match_start,match_end)

rawDescription: Find text in gtk.TextView

description: Find text in gtk.TextView


code:
filename = "filewithcontents.csv"
# opening the file with w+ mode truncates the file
f = open(filename, "w+")
f.close()

rawDescription: python clear csv file

description: Python clear csv file


code:
def _is_min_heap(L, i):
    l, r = 2 * i + 1, 2 * i + 2

    if r < len(L): # has left and right children
        if L[l] < L[i] or L[r] < L[i]: # heap property is violated
            return False

        # check both children trees
        return _is_min_heap(L, l) and _is_min_heap(L, r)
    elif l < len(L): # only has left children
        if L[l] < L[i]: # heap property is violated
            return False

        # check left children tree
        return _is_min_heap(L, l)
    else: # has no children
        return True

rawDescription: Is Min Heap Function

description: Is Min Heap Function


code:
from PIL import Image, ImageDraw

W, H = (300,200)
msg = "hello"

im = Image.new("RGBA",(W,H),"yellow")
draw = ImageDraw.Draw(im)
w, h = draw.textsize(msg)
draw.text(((W-w)/2,(H-h)/2), msg, fill="black")

im.save("hello.png", "PNG")

rawDescription: Center-/middle-align text with PIL?

description: Center-/middle-align text with PIL


code:
vowels = set(['a', 'e', 'i', 'o', 'u'])
inp = "foobar"
bool(vowels.intersection(inp))
bool(vowels.intersection('qwty'))

rawDescription: How to check if a string contains a string from a list?

description: Check if a string contains a string from a list


code:
def fromdeg(d):
    r = d * np.pi / 180.
    return np.array([np.cos(r), np.sin(r)])

np.linalg.norm(fromdeg(1) - fromdeg(359))
np.linalg.norm(fromdeg(1) - fromdeg(180))
np.linalg.norm(fromdeg(90) - fromdeg(270))

rawDescription: Periodic Data with Machine Learning (Like Degree Angles -> 179 is 2 different from -179)


code:
now = timezone.now()
qs = Event.objects.filter(start__lte=now, end__gte=now)

rawDescription: How to get current events in queryset?

description: Get current events in queryset


code:
from django import forms
from django.db import models
from django.contrib import admin

class Foo(models.Model):
    pass

class Bar(models.Model):
    foo = models.ForeignKey(Foo)

class FooForm(forms.ModelForm):
    class Meta:
        model = Foo

    bars = forms.ModelMultipleChoiceField(queryset=Bar.objects.all())

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['bars'].initial = self.instance.bar_set.all()

    def save(self, *args, **kwargs):
        # FIXME: 'commit' argument is not handled
        # TODO: Wrap reassignments into transaction
        # NOTE: Previously assigned Foos are silently reset
        instance = super(FooForm, self).save(commit=False)
        self.fields['bars'].initial.update(foo=None)
        self.cleaned_data['bars'].update(foo=instance)
        return instance

class FooAdmin(admin.ModelAdmin):
    form = FooForm

rawDescription: one-to-many inline select with django admin

description: One-to-many inline select with django admin


code:
from pyzipcode import ZipCodeDatabase
zcdb = ZipCodeDatabase()
zipcode = zcdb[54115]
zipcode.zip
zipcode.city
zipcode.state
zipcode.longitude
zipcode.latitude
zipcode.timezone

rawDescription: Good Python library for plotting points on a U.S. map by zip code


code:
import numpy
import matplotlib.delaunay
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
import copy

# Unique points
points = numpy.random.randint(0,2000, (1000, 2))
points = numpy.vstack([numpy.array(u) for u in set([tuple(p) for p in points])])

# Delaunay edges
centers, edges, tris, neighb = matplotlib.delaunay.delaunay(points[:,0], points[:,1])

# LineCollection of edges
lc_edges = LineCollection(points[edges])
lc_edges2 = copy.copy(lc_edges)
# 1x2 subplots
fig,(ax) = plt.subplots(1, 2, figsize=(12,16))

ax1 = plt.subplot(211, aspect='equal', xlim=[points[:,0].min()- 100, points[:,0].max() + 100], ylim=[points[:,1].min() - 100, points[:,1].max() + 100])
plt.title("First plot")
plt.gca().add_collection(lc_edges)
plt.scatter(points[:,0], points[:,1])

ax2 = plt.subplot(212, aspect='equal', xlim=[points[:,0].min()- 100, points[:,0].max() + 100], ylim=[points[:,1].min() - 100, points[:,1].max() + 100])
plt.title("Second plot")

plt.gca().add_collection(lc_edges2)
plt.scatter(points[:,0], points[:,1])

plt.show()

rawDescription: Displaying LineCollections in matplotlib subplots


code:
import collections
subpq = collections.defaultdict(dict)
for (number, type), value in pq.values()[0].items():
 subpq[number][type] = value

subpq

rawDescription: Collect values together in subdicts by the first value in a tuple key


code:
output = np.empty(indices[0].shape)
x_indices = indices[0]
y_indices = indices[1]
z_indices = indices[2]

x0 = x_indices.astype(np.integer)
y0 = y_indices.astype(np.integer)
z0 = z_indices.astype(np.integer)
x1 = x0 + 1
y1 = y0 + 1
z1 = z0 + 1

#Check if xyz1 is beyond array boundary:
x1[np.where(x1==input_array.shape[0])] = x0.max()
y1[np.where(y1==input_array.shape[1])] = y0.max()
z1[np.where(z1==input_array.shape[2])] = z0.max()

x = x_indices - x0
y = y_indices - y0
z = z_indices - z0
output = (input_array[x0,y0,z0]*(1-x)*(1-y)*(1-z) +
             input_array[x1,y0,z0]*x*(1-y)*(1-z) +
             input_array[x0,y1,z0]*(1-x)*y*(1-z) +
             input_array[x0,y0,z1]*(1-x)*(1-y)*z +
             input_array[x1,y0,z1]*x*(1-y)*z +
             input_array[x0,y1,z1]*(1-x)*y*z +
             input_array[x1,y1,z0]*x*y*(1-z) +
             input_array[x1,y1,z1]*x*y*z)

return output

rawDescription: 3D interpolation of NumPy arrays without SciPy


code:
def to_url(self):
    d = {'ass_cls': self.model.__class__.__name__}
    d.update({local.name: getattr(self.model.src, remote.name)
        for local, remote in self.model.__class__.src.property.local_remote_pairs})
    d.update({k: v for k, v in self.model.__dict__.items()
        if not k.startswith('_') and k != 'src'})
    return d

rawDescription: converting PEP 448 Python 3.5 code to Python 3.4-compatible

description: Converting PEP 448 Python 3.5 code to Python 3.4-compatible


code:
img
M,N = img.shape
Y,X = np.meshgrid(np.arange(N),np.arange(M))
np.vstack((X,Y,img)).reshape(3,-1).T

rawDescription: Creating a label dataset from a segmented image using Python


code:
...
listener = socket(AF_INET, SOCK_STREAM)
listener.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
listener.bind((HOST, PORT))
listener.listen(32)
...

rawDescription: python SimpleHTTPRequestHandler server leaves socket in TIME_WAIT state after exit

description: Python SimpleHTTPRequestHandler server leaves socket in TIME_WAIT state after exit


code:
from collections import Sequence

class MyList(Sequence):
    ...

rawDescription: How do __getitem__, __setitem__, work with slices?


code:
L = ['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']
def mysort(x):
    temp = x.split(',')
    return (-int(temp[1]), temp[0])

sorted(L, key=mysort)

rawDescription: alphabetical tie-breakers in lists python

description: Alphabetical tie-breakers in lists python


code:
from __future__ import division
import string

def istext(filename):
    s=open(filename).read(512)
    text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
    _null_trans = string.maketrans("", "")
    if not s:
        # Empty files are considered text
        return True
    if "\0" in s:
        # Files with null bytes are likely binary
        return False
    # Get the non-text characters (maps a character to itself then
    # use the 'remove' option to get rid of the text characters.)
    t = s.translate(_null_trans, text_characters)
    # If more than 30% non-text characters, then
    # this is considered a binary file
    if float(len(t))/float(len(s)) > 0.30:
        return False
    return True

rawDescription: How to identify binary and text files using Python?

description: Identify binary and text files using Python


code:
with open('lsn_log.txt', 'a') as f:
    while 1:
        time.sleep(0.5)
        clientSocket_sen.send(get.encode('utf-8'))
        print('LSN BP1')
        num = clientSocket_sen.recv(1024)
        test = int(num)
        print("Data Received from LSN:")
        print(test)

        if test > 210:
            if status == 'on':
                #clientSocket_act.send(off.encode('utf-8'))
                status = 'off'

        elif test < 100:
            if status == 'off':
                #clientSocket_act.send(on.encode('utf-8'))
                status = 'on'

        logvar += 1
        if logvar == 5:
            print("BP2 LSN")
            f.write("{} {}  The Lights are:  {}\n".format(time.strftime("%I:%M:%S"), time.strftime("%d/%m/%Y"), status))

rawDescription: Logging data from a subprocess (python,linux)


code:
#!/usr/bin/python

import matplotlib.pyplot as plt
import time
import numpy as np
from scipy.interpolate import spline

# Local variables
x = []
y = []

# Open the data file for reading lines
datafile = open('testdata1.txt', 'r')
sepfile = datafile.read().split('\n')
datafile.close()

# Create a canvas to place the subgraphs
canvas = plt.figure()
rect = canvas.patch
rect.set_facecolor('white')

# Iterate through the lines and parse them
for datapair in sepfile:
    if datapair:
        xypair = datapair.split(' ')
        x.append(int(xypair[1]))
        y.append(int(xypair[3]))

x_sm = np.array(x)
y_sm = np.array(y)

x_smooth = np.linspace(x_sm.min(), x_sm.max(), 200)
y_smooth = spline(x, y, x_smooth)

# Define the matrix of 1x1 to place subplots
# Placing the plot1 on 1x1 matrix, at pos 1
sp1 = canvas.add_subplot(1,1,1, axisbg='w')
#sp1.plot(x, y, 'red', linewidth=2)
sp1.plot(x_smooth, y_smooth, 'red', linewidth=1)

# Colorcode the tick tabs
sp1.tick_params(axis='x', colors='red')
sp1.tick_params(axis='y', colors='red')

# Colorcode the spine of the graph
sp1.spines['bottom'].set_color('r')
sp1.spines['top'].set_color('r')
sp1.spines['left'].set_color('r')
sp1.spines['right'].set_color('r')

# Put the title and labels
sp1.set_title('matplotlib example 1', color='red')
sp1.set_xlabel('matplot x label', color='red')
sp1.set_ylabel('matplot y label', color='red')

# Show the plot/image
plt.tight_layout()
plt.grid(alpha=0.8)
plt.savefig("example6.eps")
plt.show()

rawDescription: Generating smooth line graph using matplotlib


code:
f = open('programa.txt','r')
grab_next = False
for line in f:
    if grab_next:
        print(line)
    grab_next = line == "[Height of the board]\n"

rawDescription: How to jump to the next element when iterating in a list in python?

description: Jump to the next element when iterating in a list in python


code:
import urllib
response = urllib.urlopen('http://freegeoip.net/json/1.2.3.4').read()
print(response)

rawDescription: What API, package or library is easiest to find the location of an IP address?


code:
import logging
import time
import pymongo
import hashlib
import random

DEBUG_MODE = True

class logger(object):

        def __new__(cls, *args, **kwargs):
                if DEBUG_MODE:
                        return object.__new__(cls, *args, **kwargs)
                else:
                        return args[0]

        def __init__(self, foo):
                self.foo = foo
                logging.basicConfig(filename='exceptions.log', format='%(levelname)s %(asctime)s: %(message)s')
                self.log = logging.getLogger(__name__)

        def __call__(self, *args, **kwargs):
                def _log():
                        try:
                                t = time.time()
                                func_hash = self._make_hash(t)
                                col = self._make_db_connection()
                                log_record = {'func_name':self.foo.__name__, 'start_time':t, 'func_hash':func_hash}
                                col.insert(log_record)
                                res = self.foo(*args, **kwargs)
                                log_record = {'func_name':self.foo.__name__, 'exc_time':round(time.time() - t,4), 'end_time':time.time(),'func_hash':func_hash}
                                col.insert(log_record)
                                return res
                        except Exception as e:
                                self.log.error(e)
                return _log()

        def _make_db_connection(self):
                connection = pymongo.Connection()
                db = connection.logger
                collection = db.log
                return collection

        def _make_hash(self, t):
                m = hashlib.md5()
                m.update(str(t)+str(random.randrange(1,10)))
                return m.hexdigest()

rawDescription: How can I trace a multi-thread software?

description: Trace a multi-thread software


code: my_iterable = lambda: iter(())

rawDescription: What is the simplest way to create an empty iterable using yield in Python?


code:
clf = GridSearchCV(LogisticRegression(), {'C': [1, 2, 3]})
clf.fit(np.random.randn(10, 4), np.random.randint(0, 2, 10))
from pprint import pprint
pprint(clf.grid_scores_)

rawDescription: How to print out an accuracy score for each combination within Gridsearch?

description: Print out an accuracy score for each combination within Gridsearch


code:
from collections import Counter
d = {1: 7, 2: 8, 3: 9, 4: 7, 5: 8, 6: 9, 7: 7, 8: 8, 9: 9, 10: 9}
Counter(d.values())
Counter(d.values()).most_common()

rawDescription: transform a dictionary from key:value to value:number of occurences

description: Transform a dictionary from key:value to value:number of occurences


code:
from tlslite.utils import keyfactory
private_key = keyfactory.parsePrivateKey(rsa_key)
signed = private_key.hashAndSign(data)

rawDescription: Signing a string with RSA private key on Google App Engine Python SDK


code:
import importlib

qual_name = "my.module.MyClass"
splitted = qual_name.split(".")
class_name = splitted[-1]
module_name = ".".join(splitted[:-1])

module_obj = importlib.import_module(module_name)
class_obj = getattr(module_obj, class_name)
class_inst = class_obj()   # this is instance of my.module.MyClass; assuming that this class has no-argument constructor; in other case use constructor arguments here

rawDescription: How to instance objects from a unicode string in Python

description: Instance objects from a unicode string in Python


code:
class ItemUpdateView(UpdateView):
    form_class = ItemForm

rawDescription: How to add css in django Updateview or Create view form

description: Add css in django Updateview or Create view form


code:
import csv

links = ['http://www.amazon.com/dp/B00064NZCK',
         'http://www.amazon.com/dp/B000CIU7F8',
         'http://www.amazon.com/dp/B000H5839I',
         'http://www.amazon.com/dp/B000LTLBHG',
         'http://www.amazon.com/dp/B000SDLXKU',
         'http://www.amazon.com/dp/B000SDLXNC',
         'http://www.amazon.com/dp/B000SPHPWI',
         'http://www.amazon.com/dp/B000UUMHRE']

with open('existing.csv', 'r') as f_input:
    csv_input = csv.reader(f_input)

    # Read in the existing CSV file
    headers = next(csv_input) + ["Date_time", "price", "Merchant", "Sellers_count"]
    rows = list(csv_input)

    # Create an index just in case the order changes or there are other entries
    url_indexes = {row[3] : index for index, row in enumerate(rows)}

    for url in links:
        # Insert your existing code here to get the actual data

        Date_time = "2015-08-27_12-34-56"
        price = "123.45"
        Merchant = "Def"
        Sellers_count = "42"

        rows[url_indexes[url]].extend([Date_time, price, Merchant, Sellers_count])

# Write the updated CSV to a new file

with open('updated.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(headers)
    csv_output.writerows(rows)

rawDescription: Write to csv python Horizontally append Each time


code:
class Person(models.Model):
  name = models.CharField(max_length=30)

  class Meta:
    db_table = 'core_Person'

rawDescription: Creating alias for the db tableD Django

description: Creating alias for the db tableD Django


code:
import os
directory = "C:/"
extension = ".tga"
list_of_files = [file for file in os.listdir(directory) if file.lower().endswith(extension)]

rawDescription: How do I list all tga files in a directory (non recursive) in Python?

description: List all tga files in a directory (non recursive) in Python


code:
def update_level(username, new_level):
   inpath = "/path/to/your/file"
   outpath = "path/to/tmpfile"
   with open(inpath) as infile:
       with open(outpath, "w") as outfile:
           for line in infile:
               line = line.strip()
               name, level = line.split()
               if name == username:
                   line = " ".join((username, new_level))
               outfile.write("%s\n" % line)
   os.rename(outpath, inpath)

rawDescription: How to delete a specific line and replace it in python

description: Delete a specific line and replace it in python


code:
import operator

map(operator.not_, (True, False, False))

rawDescription: What is python's not? A special function type?


code:
class Station(Base):
    __tablename__ = 'stations'
    ...
    station_logo_url = Column('STATION_LOGO_URL', NVARCHAR)
    ...

...

stations = session.query(Station).all()
for station in stations:
    logo_url = get_logo_url(station)
    station.station_logo_url = logo_url
session.commit()

rawDescription: What is pythonic way with SQLAchemy to update dataset?


code:
def builditem():
   d = collections.OrderedDict()
   d['batteryLevel'] = random.randint(0, 100)
   ...
   d['status'] = random.choice([OPEN, LOCKED])
   return d

json.dumps([builditem() for n in range(10)])

rawDescription: python create multiple json objects

description: Python create multiple json objects


code:
def highest_score():

    with open('my_file.txt') as myfile:
        values = myfile.readlines()

    values.sort(key=lambda s: int(s.split(':')[1].strip()), reverse=True)

    return values

rawDescription: Python: Sort by numbers within a list of strings?


code:
from getpass import getpass
password = getpass()

rawDescription: Is it possible to make user input invisible as a 'sudo' password input?


code:
kafka = ['Das ist ein schöner Tag.', '>>I would like some ice cream and a big cold orange juice!',...]
s = ''.join(kafka)

rawDescription: How to transform elements of a list into one string?

description: Transform elements of a list into one string


rawDescription: Python: would this leave me with a clean environment?


code:
f = ['sum_','count_','per_']
d = ['fav_genre','sum_fav_event','count_fav_type','per_fav_movie']
[s[len(([p for p in f if s.startswith(p)]+[""])[0]):] for s in d]

rawDescription: python--recursive list comprehension to apply lstrip on a list

description: Python--recursive list comprehension to apply lstrip on a list


code:
def get_variable_and_sizes(var_string):
    result = re.search(r'(.*?)((?:\[\d*])*)$', var_string)
    var_name = result.group(1)
    numbers = re.findall(r'\[(\d+)]', result.group(2))
    return [var_name] + numbers

rawDescription: Using Regex in Python to get array sizes


code:
import numpy
desc = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')}
a = numpy.array([('M',64.0,75.0),('F',25.0,60.0)], dtype=desc)
numpy.hstack((a,a))

rawDescription: Combining two record arrays

description: Combining two record arrays


code:
def clean(self):
    file_field = self.cleaned_data.get('file_field')
    image_field = self.cleaned_data.get('image_field')

    if file_field and image_field:
        raise forms.ValidationError("You should only provide one of File or Image")
    elif not file_field and not image_field:
        raise forms.ValidationError("You must provide either File or Image")

    return self.cleaned_data

rawDescription: Python/Django Model overriding the cleaned data


code:
def myDecorate(something):
    # do work here
    def decorate(f):
        def _wrapper(self, arg1, myOtherArg):
            # do something with myOtherArg
            return f(self, arg1)
        return _wrapper
    return decorate

rawDescription: Python decorate class method with arguments


code:
# tempfiles is a list of file handles to your temp files. Order them however you like
f = open("bigfile.txt", "w")
for tempfile in tempfiles:
    f.write(tempfile.read())

rawDescription: Python append multiple files in given order to one big file


code:
word_dic = {}
for i in top_25:
    word_dic[i] = random.choice(o)+random.choice(q)
print(word_dic)

rawDescription: Dictionary keeps getting overwritten in each iteration of for-loop


code:
item=0
while True:
    menu = int(input (""" ----- Heart Attacks On A Bun ----------
          1.    The Big MOO Combo . . . . 5.99
          2.    Big MOO . . . . . . . . . 3.99
          3.    Spring Surprise . . . . . 1.99
          4.    Fries . . . . . . . . . . 1.29
          5.    Pop . . . . . . . . . . . 1.19
          6.    Exit
          ________________________________________

          What would you like? one for combo, two for Big MOO etc.
          """))

    if menu == 1:
        item+=5.99
    elif menu == 2:
        item+=3.99
    elif menu == 3:
        item+=1.99
    elif menu == 4:
        item+=1.29
    elif menu == 5:
        item+=1.19
    elif menu == 6:
        print("Your total is $" + str(item))
        break

rawDescription: Trying to create a menu in python but loop won't exit


rawDescription: Pymongo return data without _id

description: Pymongo return data without _id


code:
import os
import sys

filename = 'logo.txt'
# Use join instead of hard-coding file separators
path = os.path.join(os.getcwd(), filename)
# You need to specify some kind of delimiter so you know
# where the logo ends. I couldn't think of a better way to
# only print part of the file.
delimiter = '------'

with open(path, 'r') as f:
    for line in f:
        if delimiter in line:
            sys.stdout.write('Press any key to continue...')
            raw_input()
        else:
            sys.stdout.write(line)

rawDescription: How to open a text file in python and write only the first visible portion to the screen?

description: Open a text file in python and write only the first visible portion to the screen


code:
bpPetrol = 099.9
bpDiesel = 100.9

shellPetrol = 102.9
shellDiesel = 103.9

texacoPetrol = 100.9
texacoDiesel = 101.9

gulfPetrol = 098.9
gulfDiesel = 102.9

tescoPetrol = 100.9
tescoDiesel = 102.9

namelist=['bp', 'shell', 'texaco', 'gulf', 'tesco']
list1= [bpPetrol, shellPetrol, texacoPetrol, gulfPetrol, tescoPetrol]
list2= [bpDiesel, shellDiesel, texacoDiesel, gulfDiesel, tescoDiesel]

fuelType="Petrol"

if fuelType == "Petrol":
    minPetrolPrice=min(list1)
    minPetrolPriceIndex=list1.index(min(list1))
    minPetrolPriceName=namelist[minPetrolPriceIndex]
    print("The cheapest price of petrol today is: ", minPetrolPrice)
    print("")

    print("This can be found at the position ", minPetrolPriceIndex, "in list1 and petrol station name is ", minPetrolPriceName)
    print("The average price of petrol at all the stations today is:", (sum(list1)/float(len(list1))))
    print("Just in case you were intersted, the average price of d diesel today is:", (sum(list2)/float(len(list2))))

rawDescription: Find the name of a specific python variable and print it out- Python


code:
self.listview.bind(on_touch_down=self.press)
self.scatter.bind(on_touch_up=self.release)
self.adapter.bind(on_selection_change=self.selectionChange)

def selectionChange(self, adapter):
    if adapter.selection: #Sometimes the selection was [], so a check doesn't hurt
        names = adapter.data
        self.scatter.children[0].text = adapter.selection[0].text #My scatter has a label as it's first and only child. Here, I'm changing the label's text
        for j in adapter.data:
            if j == adapter.selection[0].text:
                break
        names.pop(names.index(j))
        self.listview.adapter.data = names
        if(hasattr(self.listview, '_reset_spopulate')): #This is used to reset the ListView
            self.listview._reset_spopulate()

def press(self, view, touch):
    if view.collide_point(touch.x, touch.y) and not touch.is_mouse_scrolling:
        self.scatter.center = touch.pos
        self.floatLayout.add_widget(self.scatter) #The scatter appears on the click
        self.scatter.on_touch_down(touch) #Needs to be called to get the scatter to be dragged

def release(self, scatter, touch):
    if scatter.collide_point(touch.x, touch.y) and touch.grab_current: #Because Kivy's on_touch_up doesn't work like I think it does

        #Do whatever you want on the release of the scatter

        self.floatLayout.remove_widget(self.scatter) #Remove the scatter on release

rawDescription: Kivy drag and drop from ListView

description: Kivy drag and drop from ListView


code:
with open(..., 'w') as f:
    s = f.read()
    for src, dest in replacements:
        s = s.replace(src, dest)
    f.seek(0)
    f.write(s)

rawDescription: Multiple string replacements on a 100mb file in python 2.6


rawDescription: Calculating the number of specific consecutive equal values in a vectorized way in pandas


rawDescription: How to delete a table in SQLAlchemy?

description: Delete a table in SQLAlchemy


code:
# -*- coding: utf-8 -*-

import os

from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/some/path/'

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('uploaded_file', filename=filename))
    return '''<!doctype html>
              <title>Upload new File</title>

Upload new File

              <form action="" method=post enctype=multipart/form-data>

<input type=file name=file>
                <input type=submit value=Upload>
              </form>'''

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

rawDescription: Is there a simple way to process an html form upload with python?


code: frames = int(clip.fps * clip.duration)

rawDescription: Get number of frames in clip with Moviepy


code:
class Woman(models.Model):
    age = models.IntegerField()
    ...

class Man(models.Model):
    age = models.IntegerField()
    woman = models.OneToOneField(Woman)
    ...

rawDescription: How to filter occupied models in one-to-one relationship in django admin

description: Filter occupied models in one-to-one relationship in django admin


code:
from itertools import izip_longest
[float(sum(col)) / sum(cmp(x,0) for x in col) for col in izip_longest(*B, fillvalue=0)]

rawDescription: How do I calculate the mean of elements in a list across columns?

description: Calculate the mean of elements in a list across columns


code:
class YourAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {
            'fields': ('name',)
        }),
        ('Address', {
            'fields': ('Add1', 'Add2', 'city', 'zipcode',)
        }),
    )

rawDescription: how to add a custom label and content in django admin form

description: Add a custom label and content in django admin form


code:
import urllib
from HTMLParser import HTMLParser

class FeedParser(HTMLParser):

    def __init__(self, *args, **kwargs):
        self.feeds = set()
        HTMLParser.__init__(self, *args, **kwargs)

    def handle_starttag(self, tag, attrs):
        if tag == 'link':
            try:
                href = [attr[1] for attr in attrs if attr[0] == 'href'][0]
            except IndexError:
                return None
            else:
                if ('type', 'application/atom+xml') in attrs or ('type', 'application/rss+xml') in attrs:
                    self.feeds.add(href)

def get_all_feeds_from_url(url):
    f = urllib.urlopen(url)
    contents = f.read()
    f.close()

    parser = FeedParser()
    parser.feed(contents)
    parser.close()

    return list(parser.feeds)

rawDescription: Extract feeds from web page

description: Extract feeds from web page


code:
l = [u'This is a test', u' ', u'Something', u' ', u'Something more', u' ', u'Another test', u' ', u' Test test']
sans_whitespace = [s for s in l if s.strip()]
sans_whitespace

rawDescription: How to remove items with whitespace in array

description: Remove items with whitespace in array


code:
def company_user_count(self):
    return self.users.count()

rawDescription: How to count all users in reverse relationship

description: Count all users in reverse relationship


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
np.random.seed(1977)

def main():
    x, y = generate_data()
    fig, axes = plt.subplots(nrows=3, sharex=True)
    for ax in axes.flat:
        ax.xaxis_date()
    fig.autofmt_xdate()

    axes[0].set_title('Scatterplot of all data')
    axes[0].scatter(x, y, marker='.')

    axes[1].set_title('"Chunk" plot of data')
    chunkplot(x, y, chunksize=1000, ax=axes[1],
              edgecolor='none', alpha=0.5, color='gray')

    axes[2].set_title('Hexbin plot of data')
    axes[2].hexbin(x, y)

    plt.show()

def generate_data():
    # Generate a very noisy but interesting timeseries
    x = mdates.drange(dt.datetime(2010, 1, 1), dt.datetime(2013, 9, 1),
                      dt.timedelta(minutes=10))
    num = x.size
    y = np.random.random(num) - 0.5
    y.cumsum(out=y)
    y += 0.5 * y.max() * np.random.random(num)
    return x, y

def chunkplot(x, y, chunksize, ax=None, line_kwargs=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    if line_kwargs is None:
        line_kwargs = {}
    # Wrap the array into a 2D array of chunks, truncating the last chunk if
    # chunksize isn't an even divisor of the total size.
    # (This part won't use _any_ additional memory)
    numchunks = y.size // chunksize
    ychunks = y[:chunksize*numchunks].reshape((-1, chunksize))
    xchunks = x[:chunksize*numchunks].reshape((-1, chunksize))

    # Calculate the max, min, and means of chunksize-element chunks...
    max_env = ychunks.max(axis=1)
    min_env = ychunks.min(axis=1)
    ycenters = ychunks.mean(axis=1)
    xcenters = xchunks.mean(axis=1)

    # Now plot the bounds and the mean...
    fill = ax.fill_between(xcenters, min_env, max_env, **kwargs)
    line = ax.plot(xcenters, ycenters, **line_kwargs)[0]
    return fill, line

main()

rawDescription: How can I plot ca. 20 million points as a scatterplot?

description: Plot ca. 20 million points as a scatterplot


code:
parser = argparser.ArgumentParser
subparsers = parser.add_subparsers('-bowtie')
subparser = subparsers.add_parser()
subparser.add_argument('new argument')

rawDescription: Python argparse conditional arguments

description: Python argparse conditional arguments


code:
Teams = ['Boston Americans','World Series Not Played in 1904','New York Giants',
         'Chicago White Sox','Chicago Cubs','Chicago Cubs','Pittsburgh Pirates',
         'Philadelphia Athletics']
Year = [1903,1904,1905,1906,1907,1908,1909,1910]

l = zip(Teams, Year)
d = {}
for e in l:
    if e[0] not in d:
        d[e[0]] = [e[1]]
    else:
        d[e[0]].append(e[1])

#Max Item
s = sorted(d.items(), key=lambda x: len(x[1]))[-1]
print("%s - %s" % (s[0], len(s[1])))

# Entire list
for k, v in sorted(d.items(), key=lambda x: -len(x[1])):
    print("%s - %s" % (k, len(v)))

rawDescription: Dictionary: Print entire list from max to min items in a dictionary


code:
#! /usr/bin/env python3

def main():
    print(find_mismatch('Hello, world!', 'Hello, world'))
    print(find_mismatch('Hello, world!', 'Hello, world!'))
    print(find_mismatch('Hello, world!', 'Hallu, world!'))
    print(find_mismatch('Hello, world!', 'Hello, world.'))

def find_mismatch(string_a, string_b):
    if len(string_a) != len(string_b):
        return 2
    folded_a, folded_b = string_a.casefold(), string_b.casefold()
    if folded_a == folded_b:
        return 0
    found_difference = False
    for character_a, character_b in zip(folded_a, folded_b):
        if character_a != character_b:
            if found_difference:
                return 2
            found_difference = True
    return 1

def find_mismatch(a, b):
    """Find mismatches in strings a and b.

    Returns 0 when strings are the same.
    Returns 1 when strings differ in one character.
    Returns 2 any other time (different lengths or more mismatches)."""
    if len(a) != len(b):
        return 2
    a, b = a.casefold(), b.casefold()
    if a == b:
        return 0
    error = False
    for a, b in zip(a, b):
        if a != b:
            if error:
                return 2
            error = True
    return 1

if __name__ == '__main__':
    main()

rawDescription: Mismatched strings in Python -- how to continue process?


rawDescription: regular expression to parse option string in python

description: Regular expression to parse option string in python


code:
t1 = np.resize(table1, list(table1.shape)+n2)
t2 = np.resize(table2, n1+list(table2.shape))
return t1, t2

rawDescription: Numpy resize without modifying original object


code:
def foo():
    import sys
    flocals = sys._getframe(1).f_locals
    flocals['ham'] = 'eggs'

class Bar:
    foo()

dir(Bar)
Bar.ham

rawDescription: Getting class reference from function in Python


code:
def get_likes(strategy, details, response, *args, **kwargs):
    if strategy.backend.name == 'facebook':
        likes = strategy.backend.get_json(
            'https://graph.facebook.com/%s/likes' % response['id'],
            params={'access_token': response['access_token']}
        )
        for like in likes['data']:
            pass  # Process and save likes here

rawDescription: Get Facebook user likes in Python Social Auth


code:
print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

rawDescription: python numpy machine epsilon

description: Python numpy machine epsilon


code:
from PyQt5 import QtCore, QtWidgets

class ColorDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        widget = QtWidgets.QColorDialog()
        widget.setWindowFlags(QtCore.Qt.Widget)
        widget.setOptions(
            QtWidgets.QColorDialog.DontUseNativeDialog |
            QtWidgets.QColorDialog.NoButtons)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(widget)
        hbox = QtWidgets.QHBoxLayout()
        hbox.addWidget(QtWidgets.QPushButton('No Color'))
        hbox.addWidget(QtWidgets.QPushButton('Cancel'))
        hbox.addWidget(QtWidgets.QPushButton('Ok'))
        layout.addLayout(hbox)

if __name__ == '__main__':

    import sys
    app = QtWidgets.QApplication(sys.argv)
    dialog = ColorDialog()
    dialog.show()
    sys.exit(app.exec_())

rawDescription: PyQt5: "No Fill" in Color Dialog?

description: PyQt5: "No Fill" in Color Dialog


code:
prev_Status = None

while True:
    if sensor > 1.60:
        Status = 'ON'
    else:
        Status = 'OFF'

    if Status != prev_Status:
        print("Status : {}".format(Status))
        prev_Status = Status

rawDescription: How to print for once (no multiple) if status change?

description: Print for once (no multiple) if status change


code:
import csv, json

li = []
with open('myfile.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ')
    for location_id, name, latitude, longitude in reader:
        li.append({
           "location_id": location_id,
           "name": name,
           "latitude": latitude,
           "longitude": longitude,
           "geo": {
                "__type": "GeoPoint",
                "latitude": latitude,
                "longitude": longitude,
            }
        })
with open("outfile.geo", "w") as f:
    json.dump(li, f)

rawDescription: Convert CSV with Headers to JSON with GeoLocation


code:
import imp,sys,string
magic = string.join(["\\x%.2x" % ord(c) for c in imp.get_magic()],"")
reg = ':pyc:M::%s::%s:' % (magic, sys.executable)
open("/proc/sys/fs/binfmt_misc/register","wb").write(reg)

rawDescription: How to execute *.pyc file directly in linux terminal

description: Execute *.pyc file directly in linux terminal


code: "SELECT interest FROM User"

rawDescription: Is it possible to access index directly?

description: Is it possible to access index directly


code:
def recurseDecrMap(l):
    if not l:
        return []
    else:
        return [l[0]-1] + recurseDecrMap(l[1:])

rawDescription: Recursively decrement a list by 1

description: Recursively decrement a list by 1


code:
# Produces all possible RPN layouts with n values and n-1 binary operators,
# representing values as '#' and operators as '+'
def RPN(n):
  if n == 1:
    yield '#'
  for i in range(1,n):
    for left in RPN(i):
      for right in RPN(n - i):
        yield left + right + '+'

rawDescription: all possible numerical expressions

description: All possible numerical expressions


code:
import numpy

INDENT = 3
SPACE = " "
NEWLINE = "\n"

def to_json(o, level=0):
    ret = ""
    if isinstance(o, dict):
        ret += "{" + NEWLINE
        comma = ""
        for k,v in o.iteritems():
            ret += comma
            comma = ",\n"
            ret += SPACE * INDENT * (level+1)
            ret += '"' + str(k) + '":' + SPACE
            ret += to_json(v, level + 1)

        ret += NEWLINE + SPACE * INDENT * level + "}"
    elif isinstance(o, basestring):
        ret += '"' + o + '"'
    elif isinstance(o, list):
        ret += "[" + ",".join([to_json(e, level+1) for e in o]) + "]"
    elif isinstance(o, bool):
        ret += "true" if o else "false"
    elif isinstance(o, int):
        ret += str(o)
    elif isinstance(o, float):
        ret += '%.7g' % o
    elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.integer):
        ret += "[" + ','.join(map(str, o.flatten().tolist())) + "]"
    elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.inexact):
        ret += "[" + ','.join(map(lambda x: '%.7g' % x, o.flatten().tolist())) + "]"
    elif o is None:
        ret += 'null'
    else:
        raise TypeError("Unknown type '%s' for json serialization" % str(type(o)))
    return ret

rawDescription: python JSON array newlines

description: Python JSON array newlines


code:
import datetime
def next_weekday(d, weekday):
    days_ahead = weekday - d.weekday()
    if days_ahead <= 0: # Target day already happened this week
        days_ahead += 7
    return d + datetime.timedelta(days_ahead)

d = datetime.date(2011, 7, 2)
next_monday = next_weekday(d, 0) # 0 = Monday, 1=Tuesday, 2=Wednesday...
print(next_monday)

rawDescription: Python: Find the date for the first Monday after a given a date


code:
from selenium import webdriver
from time import sleep

# Startup the web-browser
browser = webdriver.Firefox()
current_url = browser.current_url

while True:
    try:
        # If we have a url, identify and download your items
        if browser.current_url != current_url:
            # Download the stuff here
            current_url = browser.current_url
    # Triggered once you close the web-browser
    except:
        break
    # Sleep for half a second to avoid demolishing your machine from constant polling
    sleep(0.5)

rawDescription: how to convert IP address into http for urllib

description: Convert IP address into http for urllib


code:
item=self.model.item(1,1)
thestring = str(item.text())

rawDescription: How to get a Value from a Qtable

description: Get a Value from a Qtable


code: [WordsUsed.index(word) for word in Phrase]

rawDescription: Referencing List Positions of Words

description: Referencing List Positions of Words


code:
import pygame
from itertools import cycle
pygame.init()
screen = pygame.display.set_mode((300, 300))
s_r = screen.get_rect()
player = pygame.Rect((100, 100, 50, 50))
player2 = pygame.Rect((200, 100, 50, 50))
timer = pygame.time.Clock()
speed = 5
up, down, left, right = (0, -speed), (0, speed), (-speed, 0), (speed, 0)

dirs1 = cycle([up, right, down, left])
dirs2 = cycle([up, right, down, left])

dir1 = next(dirs1)
dir2 = next(dirs2)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise

    # move player
    player.move_ip(dir1)
    player2.move_ip(dir2)
    # if it's outside the screen
    if not s_r.contains(player):
    # put it back inside
        player.clamp_ip(s_r)
        # and switch to next direction
        dir1 = next(dirs1)

    if not s_r.contains(player2):
        # put it back inside
        player2.clamp_ip(s_r)
        # and switch to next direction
        dir2 = next(dirs2)

    screen.fill(pygame.color.Color('Black'))
    pygame.draw.rect(screen, pygame.color.Color('Grey'), player)
    pygame.draw.rect(screen, pygame.color.Color('Grey'), player2)
    pygame.display.flip()
    timer.tick(25)

rawDescription: Repeat the rectangular object in pygame

description: Repeat the rectangular object in pygame


code:
class Profile(models.Model):
    '''
    Teacher or  Parent
    '''
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
    primary_key=True)

    students = models.ManyToManyField(Student)

rawDescription: Associate Python / Django model objects with users


code:
class C: pass

type(C)
isinstance(C, type)
isinstance('string', type)

rawDescription: What happened to types.ClassType in python 3?


code:
import time
import multiprocessing as mp

def myWait(wait, resultQueue):
    startedAt = time.strftime("%H:%M:%S", time.localtime())
    time.sleep(wait)
    endedAt = time.strftime("%H:%M:%S", time.localtime())
    name = mp.current_process().name
    resultQueue.put(
        (name, wait, startedAt, endedAt))

# queue initialisation
resultQueue = mp.Queue()

# process creation arg: (process number, sleep time, queue)
proc =  [
    mp.Process(target=myWait, name = '0', args=(2, resultQueue,)),
    mp.Process(target=myWait, name = '1', args=(1, resultQueue,))
    ]

# starting processes
for p in proc:
    p.start()

for p in proc:
    p.join()

# print results
for p in proc:
    name, wait, startedAt, endedAt = resultQueue.get()
    print('Process %s started at %s wait %s ended at %s' %
          (name, startedAt, wait, endedAt))

rawDescription: multiprocess: identify process in queue

description: Multiprocess: identify process in queue


code:
from collections import Counter

d = {"harley": ["apple", "apple", "banana"]}
for k,v in d.items():
    print("%s has %s" %(k, ', '.join("%s x %s"%(k,v) for k,v in Counter(v).items())))

rawDescription: How to get how many of each item is in a list?

description: Get how many of each item is in a list


code:
a = cls.query().fetch()
b = list(a)
j = []
k = 0
for p in b:
    j.append(p.From)

rawDescription: How to fetch a column in non sql database

description: Fetch a column in non sql database


code:
class Breakfast:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name

spam = Breakfast("Spam")
eggs = Breakfast("Eggs")
G2 = nx.Graph()
G2.add_nodes_from([spam, eggs])
G2.add_edge(spam, eggs)
nx.draw_networkx(G2, with_labels=True)
plt.show()

rawDescription: Labeling nodes in a networkx graph when nodes are objects


code:
# in this example, current_id and recvd_event are global variables, since global variables
#  are generally considered a bad coding practice they also could be wrapped in a class and
#  passed in.

def multipleClients():
    conn, addr = s.accept()

    # the number of clients at this moment is unique, so we can use it as an id
    client_id = len(all_clients)
    all_clients.append(conn)

    # .. do other stuff ..

    while True:
        if client_id == current_id:
            # receive, retransmit, etc..
            recvd_event.set()

def main():
    global current_id
    # .. set up server ..
    current_id = 0
    recvd_event = threading.Event()
    while True:
        # .. select incoming connection ..
            # .. create thread ..
        if recvd_event.isSet():
            # received a message, next thread's turn
            # increments current_id and wraps around at end of client list
            current_id = (current_id + 1) % len(all_clients)
            recvd_event.clear()

rawDescription: How to know which client is sending message to the server

description: Know which client is sending message to the server


code:
pathbytes= path.encode(encoding, errors= 'replace')
sys.stdout.buffer.write(pathbytes)

rawDescription: Converting between charsets in python

description: Converting between charsets in python


code:
import re
s = "[AA BB, CC, DD, EE] [PP QQ, RR] [WW XX, YY, ZZ]"
response = re.findall('(?<![[\w])\w+', s)

rawDescription: Remove every word of after a bracket and append remaining words to Python list


code:
with open(file) as inf:
    if inf.read(15) == "//StackOverflow":
        inf.seek(0)
        matches.append(inf.readlines())

rawDescription: Faster way of getting files with certain text in them in Python?


code:
#!python3

def FORMAT_DOC(f):
    """Decorator to format docstring of a function. Supplies
    `defaults` dictionary, positional values, and argname:value
    pairs to format - use {defaults[a]} or {a} or {0} to access
    the 0th default value, etc.
    """
    defaults = f.__defaults__
    docs = f.__doc__

    if docs and defaults:
        nargs = f.__code__.co_argcount
        argnames = f.__code__.co_varnames[nargs-len(defaults):nargs]
        argdefaults = dict(zip(argnames, defaults))
        f.__doc__ = docs.format(defaults=argdefaults, *defaults, **argdefaults)

    return f

@FORMAT_DOC
def f(a):
    pass

@FORMAT_DOC
def f(a,b,c=1,d=2):
    """Docstring

    By default, c = {} and d = {}
    """
    v=a+c
    w=b+d
    x=w/v
    return x+1

@FORMAT_DOC
def f(a=0, b="foo", c="bar"):
    """Docstring: a={0}, b={defaults[b]}, c={c}"""
    pass

rawDescription: Python docstrings templated

description: Python docstrings templated


code: print([[x[3] for x in y] for y in matrix])

rawDescription: Using Python, extract and print items from a matrix containing list elements


code:
import numpy as np
import cv2

# details of rectangle to be drawn.
x, y, h, w = (493, 305, 125, 90)

cap = cv2.VideoCapture(0)

while 1:
  ret, frame = cap.read()

  if not ret or not frame:
    # camera didn't give us a frame.
    continue

  # draw a rectangle.
  cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

  # show it ;)
  cv2.imshow('img', frame)

rawDescription: Why does cv2.rectangle return None instead of an image?


code:
writing = False
html_file = open('my_file.html', 'a')
with open(origpath) as f:
    for line in f:
        # find start indicator
        if line == start:
            writing = True
        if writing:
            html_file.write(line + '\n')
        # yield lines until stop indicator found
        if line == stop:
            writing = False

html_file.close()

rawDescription: Python: Grab all sections between <html> and </html> from a txt file


code: re.sub(r'(?<=[^eyioae])ill[eyioae]', 'y', 'ville', re.I)

rawDescription: Using re.sub but keeping some letters from search pattern?


code:
math.ceil(1e23)
int(math.ceil(1e23))

rawDescription: Why does math.ceil return a float?

description: Why does math.ceil return a float


code:
cur_window = the_display.get_input_focus().focus
cur_class = None
while cur_class is None:
    cur_name = cur_window.get_wm_name()
    cur_class = cur_window.get_wm_class()
    if cur_class is None:
        cur_window = cur_window.query_tree().parent

rawDescription: Why do some (e.g Emacs and Chrome) X windows report no name and class?


code:
# Haystack search settings
HAYSTACK_SITECONF = 'project.search_sites'
HAYSTACK_INCLUDE_SPELLING = True
# Haystack backend settings
HAYSTACK_SEARCH_ENGINE = 'solr' # Switch this to 'whoosh' to use that backend instead
if DEBUG:
    HAYSTACK_SOLR_URL = 'solr.development.url'
else:
    HAYSTACK_SOLR_URL = 'solr.production.url'
HAYSTACK_WHOOSH_PATH = os.path.join(PROJECT_ROOT, 'search_index', 'whoosh')

rawDescription: Does anyone have examples of integrating Haystack/Solr with Django?


code:
import sys
def decorator(cls):
    mod = __import__(cls.__module__)
    mod.root = cls

rawDescription: Using python decorator functions from a different module


code:
from Tkinter import *

fen =Tk()

class test_Tk_class:
    def __init__(self):
        self.make_title() # <------------

    def make_title(self):
        fen.title("Test")

a = test_Tk_class()
fen.mainloop()

rawDescription: Class functions and Tkinter

description: Class functions and Tkinter


code:
class Config(object):
    setting1 = "default_value"
    setting2 = "default_value"

    @staticmethod
    def load_config(json_file):
        """ load settings from config file """
        with open(json_file) as f:
            config = json.load(f)
        for k, v in config.iteritems():
            setattr(Config, k, v)

rawDescription: Pythonic way to set module-wide settings from external file


code: python -V

rawDescription: Which version of Python do I have installed?


code:
a = abs( LAT-chosen_lat ) + abs( LONG-chosen_lon )

i,j = np_unravel_index(a.argmin(), a.shape)

rawDescription: find (i,j) location of closest (long,lat) values in a 2D array

description: Find (i,j) location of closest (long,lat) values in a 2D array


rawDescription: Serve dynamically generated file instead of htm


code:
from flask import Flask, Blueprint, current_app

test = Blueprint('user', __name__, url_prefix='/')

@test.route('/')
def home():
    return str(current_app.debug)

def create_app():
    app = Flask(__name__)
    app.register_blueprint(test)
    return app

rawDescription: Get debug status out of Flask Script Manager


code:
f1 = lambda x: x
f2 = lambda y: y
def f3(z):
    return z
dis.dis(f1)
dis.dis(f2)
dis.dis(f3)
inspect.getsource(f1)
inspect.getsource(f2)
inspect.getsource(f3)

rawDescription: Check if two Python functions are equal

description: Check if two Python functions are equal


code:
from mock import MagicMock
lst = [1, 2]
mock = MagicMock(side_effect=lst)
mock(), mock()
mock.side_effect = lst  # <-------
mock(), mock()

rawDescription: Can a mock side_effect iterator be reset after it has been exhausted?