code:
import multiprocessing as m

manager = m.Manager()
starsdict = manager.dict()

process = Process(target=yourfunction, args=(starsdict,))
process.run()

rawDescription: Designing concurrency in a Python program


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

data = np.random.rand(10,4)

#creating a wide figure with 2 subplots in 1 row
fig, axes = plt.subplots(1, 2, figsize=(9,3))

for ax in axes.flatten():  # flatten in case you have a second row at some point
    img = ax.imshow(data, interpolation='nearest')
    ax.set_aspect('auto')

plt.colorbar(img)

rawDescription: Matplotlib: Getting subplots to fill figure


code:
df = pd.DataFrame(np.random.randint(0, 10, size=(10, 4)), columns=list("ABCD"))
df.ix[(df.A > 5) & (df.B < 8), ["A", "B"]] = -10, -10

rawDescription: pandas if conditions met assign values to two variables

description: Pandas if conditions met assign values to two variables


rawDescription: Conversion of Binary Float

description: Conversion of Binary Float


rawDescription: How can I generate a permutation of a list of lists while maintaining order on the highest level in Python?

description: Generate a permutation of a list of lists while maintaining order on the highest level in Python


rawDescription: how to connect between tow combo boxes

description: Connect between tow combo boxes


code:
import glob
import pandas as pd

combined = []
for filepath in glob.glob('path/to/your/files/*.exp'):
    combined.append(pd.read_table(filepath, sep='\t', header=None))
combined = pd.concat(combined, ignore_index=True)

rawDescription: Variable number of columns in Python data, multiple .exp files


code:
urlpatterns = patterns('django.views.generic.simple',
    (r'(.+\.html)$', 'direct_to_template'),
    # ...
)

rawDescription: Django urls straight to html template

description: Django urls straight to html template


code:
if sys.stdin.isatty():
    message = raw_input('Enter your message ')
else:
    message = sys.stdin.read()

rawDescription: Pipe text to Python script or prompt

description: Pipe text to Python script or prompt


rawDescription: Write UTF-8 strings to file with pprint

description: Write UTF-8 strings to file with pprint


code:
import wx

class Frame(wx.Frame):
  def __init__(self):
    wx.Frame.__init__(self, None)
    blah  = CustomWidget(self)
    self.Show(True)

class CustomWidget(wx.PyControl):
  def __init__(self, parent):
    wx.PyControl.__init__(self, parent=parent)
    text = wx.TextCtrl(parent=self)
    spin = wx.SpinButton(parent=self, style=wx.SP_VERTICAL)
    sizer = wx.GridBagSizer()
    self.layout(text, spin, sizer)
    self.OnInit(text, sizer)

  def OnInit(self, text, sizer):
    text.SetValue(u"0.000")

  def layout(self, text, spin, sizer):
    self.SetSizer(sizer)
    sizer.Add(text, pos=(0, 0), flag=wx.ALIGN_CENTER)
    sizer.Add(spin, pos=(0, 1), flag=wx.ALIGN_CENTER)
    self.Fit()
    self.Layout()
    self.CenterOnParent()

app = wx.App()
f = Frame()
app.MainLoop()

rawDescription: wxPython: Can a wx.PyControl contain a wx.Sizer?

description: WxPython: Can a wx.PyControl contain a wx.Sizer


code:
AUTOADDRESS = {'Demon Dogs':'944 W. Fullerton', 'Eat attack':'100 Green Meadows', 'Pizza Fast':'50 E. High Hill'}

class Restaurant(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)

    def clean(self):
        if not self.address:
            self.address = AUTOADDRESS.get(self.name, '')

rawDescription: Auto set field in Django Model, depending on another user submitted field


code:
import glob
path = '/home/kumarswamys/Adobe/download/*.py'
files=glob.glob(path)
for file in files:
    f=open(file, 'r')
    f.readlines()
    f.close()

rawDescription: Read all file from a directory (with different cwd)


code:
fig, (ax1,ax2,ax3) = plt.subplots(3,1)
f.plot(y= ['Adj_Close','Open'], title= ticker + " Close & Open", ax=ax1)
f.plot(y= ['High', 'Low'], title='High and Low', ax=ax2)
ax3.bar(f.index, f['Volume'], width = 1)
plt.tight_layout()

rawDescription: Subplots not showing up in plot - pyplots


code:
sums, bins = numpy.histogram(
    X, bins=numpy.arange(X.min(), X.max(), delta), weights=W)

rawDescription: Conditional sum over matrices in python/numpy


rawDescription: Python regular expression match with file extension


code:
from decimal import *
getcontext().prec = 100
Decimal(2).sqrt()
getcontext().prec = 1000
Decimal(2).sqrt()

rawDescription: program displaying to few digits

description: Program displaying to few digits


code:
X = 1
if var =='with_flag':
    ws.write(0, X, 'Country Flag')
    X += 1
ws.write(0, X, 'Country Name')

rawDescription: Export to excel with python and xlwt using condition in column number


rawDescription: python. pass function with some parameters specified

description: Python. pass function with some parameters specified


code:
# First import everthing you need
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D

# Create some random data, I took this piece from here:
# http://matplotlib.org/mpl_examples/mplot3d/scatter3d_demo.py
def randrange(n, vmin, vmax):
    return (vmax - vmin) * np.random.rand(n) + vmin
n = 100
xx = randrange(n, 23, 32)
yy = randrange(n, 0, 100)
zz = randrange(n, -50, -25)

# Create a figure and a 3D Axes
fig = plt.figure()
ax = Axes3D(fig)

# Create an init function and the animate functions.
# Both are explained in the tutorial. Since we are changing
# the the elevation and azimuth and no objects are really
# changed on the plot we don't have to return anything from
# the init and animate function. (return value is explained
# in the tutorial.
def init():
    x = np.linspace(0, 100, 100)
    y = np.linspace(0, 100, 100)
    ax.scatter(xx, yy, zz, marker='o', s=20, c="goldenrod", alpha=0.6)

def animate(i):
    ax.view_init(elev=10., azim=i)

# Animate
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=360, interval=20, blit=True)
# Save
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

rawDescription: Animate a rotating 3D graph in matplotlib


code:
dialogStatus = dlg.ShowModal()
if dialogStatus == wx.ID_OK:
    ...

rawDescription: What is the proper way to handle multiple conditionals in a wxpython file dialog?


code:
# change this to whatever a blank item is from the csv reader
# probably "" or None
blank_item = None

for row in csv.reader(input):
    # filter out all blank elements
    blanks = [x for x in row if x == blank_item]
    if len(blanks) < 5:
        writer.writerow(row)

rawDescription: Dump rows of a CSV file which contain a sequence of blank fields


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

fig = plt.figure()
for i, label in enumerate(('A', 'B', 'C', 'D')):
    ax = fig.add_subplot(2,2,i+1)
    ax.text(-0.1, 1.15, label, transform=ax.transAxes,
      fontsize=16, fontweight='bold', va='top', ha='right')

plt.show()

rawDescription: Matplotlib: panel label out of the box, above the ylabel


code:
db = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES)
c = db.cursor()
c.execute('create table foo (bar integer, baz timestamp)')
c.execute('insert into foo values(?, ?)', (23, datetime.datetime.now()))
c.execute('select * from foo')
c.fetchall()

rawDescription: How to read datetime back from sqlite as a datetime instead of string in Python?

description: Read datetime back from sqlite as a datetime instead of string in Python


code:
import itertools
def all_merges(a, b):
    # object guaranteed not to be in either input list
    sentinel = object()
    merged_length = len(a) + len(b)
    for a_positions in itertools.combinations(xrange(merged_length), len(a)):
        merged = [sentinel] * merged_length

        # Place the elements of a in their chosen positions.
        for pos, a_elem in zip(a_positions, a):
            merged[pos] = a_elem

        # Place the elements of b in the positions not taken.
        b_iter = iter(b)
        for pos in xrange(merged_length):
            if merged[pos] is sentinel:
                merged[pos] = next(b_iter)

        yield merged

rawDescription: All possible merges of lists in python

description: All possible merges of lists in python


code:
X = [1, 2, 3]
Y = [2, 5, 8]
Z = [6, 4, 5]
colors=["#0000FF", "#00FF00", "#FF0066"]

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

for i in range(len(X)):
    ax.scatter(X[i], Y[i], Z[i], color=colors[i])
plt.show()

rawDescription: Specify color of each point in scatter plot (matplotlib)


code:
from datatrans.models import KeyValue
from datatrans.utils import get_current_language, get_default_language

digest = KeyValue.objects.get(value=slug_from_url, language=get_current_language()).digest
value = KeyValue.objects.get(digest=digest, language=get_default_language()).value

# value now contains 'hello'
myobject = MyObject.objects.get(slug=value)

rawDescription: DJANGO translation - Translate models including "slugs" with django-datatrans


code:
from concurrent.futures import ThreadPoolExecutor
from tornado import gen
from tornado.web import RequestHandler

executor = ThreadPoolExecutor(8) # 8 Threads in the pool

class ThreadPoolHandler(RequestHandler):

    def _do_loop(self):
        x = 0
        for i in xrange(0,500000000):
            x = i

    @gen.coroutine
    def get(self):
        yield executor.submit(self._do_loop) # Run through the loop without blocking tornado
        self.render("page_temp.html",
                    title="Page"
                    )

rawDescription: Confusion about Python Tornado's blocking


code: rules = ( Rule(LinkExtractor(allow=('course-finder', ),restrict_xpaths=('//div[@class="pagination"]',)), callback='parse_items',follow=True), )

rawDescription: Scrapy Follow & Scrape next Pages

description: Scrapy Follow & Scrape next Pages


code:
import tornado.ioloop
import tornado.web
import tornado.gen
import time
from threading import Thread
from functools import wraps

def run_async(func):
  @wraps(func)
  def async_func(*args, **kwargs):
    func_hl = Thread(target = func, args = args, kwargs = kwargs)
    func_hl.start()
    return func_hl

  return async_func

@run_async
def login(username,password,callback=None):
  m = hashlib.md5()
  m.update(password)
  hashed = m.hexdigest()
  login = User.objects(UserName=username.lower(),Password=hashed).exclude("Password","Wall","FriendsRequested","Friends","FriendsRequesting")
  if login.first() is None:
    login = User.objects(Email=username.lower(),Password=hashed).exclude("Password","Wall","FriendsRequested","Friends","FriendsRequesting")
    if login.first() is None:
      return None
  logger.info(username + " has logged in")
  if callback != None:
    return callback(login.first())
  return login.first()

class AuthLoginHandler(BaseHandler):
  @tornado.web.asynchronous
  def get(self):
    self.render("login.html")

  @tornado.web.asynchronous
  @tornado.gen.coroutine
  def post(self):
    username = self.get_argument("UserName",strip = True)
    password = self.get_argument("Password",strip = True)
    user = yield tornado.gen.Task(auth_actions.login, username, password)
    if not user:
      self.redirect("/auth/login")
      return
    self.set_secure_cookie("userdata", tornado.escape.json_encode(dumps(user.to_mongo())))
    self.redirect("/")

rawDescription: How to convert a synchronous function to an asynchronous function in python using callbacks?

description: Convert a synchronous function to an asynchronous function in python using callbacks


code: sortedList = sorted(listToSort, key=lambda x: int(x[1].replace(',', '')), reverse=True)

rawDescription: Sorting list of tuples containing numbers as strings


code: posts = db.session.query(Post).filter(func.ST_DWithin(Post.location, point, 10))

rawDescription: GeoAlchemy ST_DWithin implementation

description: GeoAlchemy ST_DWithin implementation


code:
if column[1][0] == '\x01':
    print('hello')

rawDescription: Control characters in CSV file and python


code:
if __name__ == "__main__":
    import mamapackage
    mamapackage.register("thisdriver",
               os.path.abspath(__file__),
               "A description of this driver")

rawDescription: Delayed loading of modules in python

description: Delayed loading of modules in python


rawDescription: Python multiprocessing and database access with pyodbc "is not safe"?


code:
class B(A):
    __tablename__ = 'b'

    id = Column(Integer, ForeignKey('a.id'), primary_key=True)

    __mapper_args__ = {
        'polymorphic_identity': 'b',
        'inherit_condition': id == A.id

    }

    a_id = Column(Integer, ForeignKey('a.id'))
    a = relationship(
        'A',
        backref='b', primaryjoin=A.id == a_id, remote_side=A.id)

rawDescription: Polymorphic self referential foreign key in sqlalchemy


code:
from concurrent.futures import Future, Executor
from threading import Lock

class DummyExecutor(Executor):

    def __init__(self):
        self._shutdown = False
        self._shutdownLock = Lock()

    def submit(self, fn, *args, **kwargs):
        with self._shutdownLock:
            if self._shutdown:
                raise RuntimeError('cannot schedule new futures after shutdown')

            f = Future()
            try:
                result = fn(*args, **kwargs)
            except BaseException as e:
                f.set_exception(e)
            else:
                f.set_result(result)

            return f

    def shutdown(self, wait=True):
        with self._shutdownLock:
            self._shutdown = True

if __name__ == '__main__':

    def fnc(err):
        if err:
            raise Exception("test")
        else:
            return "ok"

    ex = DummyExecutor()
    print(ex.submit(fnc, True))
    print(ex.submit(fnc, False))
    ex.shutdown()
    ex.submit(fnc, True) # raises exception

rawDescription: `DummyExecutor` for Python's `futures`

description: `DummyExecutor` for Python's `futures`


code:
selected_values = (e_data > (no_data + eps)) & (e_data < (no_data - eps))
pyplot.hist(e_data[selected_values])

rawDescription: matplotlib hist while ignoring a particular no data value

description: Matplotlib hist while ignoring a particular no data value


code:
class Classes(models.Model):
    classcode = models.CharField(max_length=15)
    classname = models.TextField()
    students = models.ManyToManyField(User)

    def __str__(self):
        return "{0}: {1}".format(self.classcode, self.classname)

rawDescription: Pre-populate form field with data from table linked via foreign key


code:
from PyQt4 import QtGui

class MyQGroupBoxes(QtGui.QGroupBox):
    def __init__(self, parent):
        QtGui.QGroupBox.__init__(self, parent)

        self.button_export = QtGui.QPushButton("Export", self)
        self.button_import = QtGui.QPushButton("Import", self)

        layout = QtGui.QVBoxLayout(self)
        self.setLayout(layout)

        layout.addWidget(self.button_export)
        layout.addWidget(self.button_import)

    def config_export(self):
        # config your button
        pass

    def config_import(self):
        # config your button
        pass

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)

    my_box1 = MyQGroupBoxes(None)
    my_box2 = MyQGroupBoxes(None)

    my_boxes = [my_box1, my_box2]

    # Config all the boxes
    for my_box in my_boxes:
        my_box.config_export()
        my_box.config_import()

        my_box.show()

    app.exec_()

rawDescription: pyQt - how to make a widgets selection based on QGroupBox

description: PyQt - how to make a widgets selection based on QGroupBox


rawDescription: Adding multiple user inputs to a dictionary and writing them to csv, python tkinter


code:
from __future__ import print_function
import os
import SimpleHTTPServer
import SocketServer

class MySimpleHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    def do_GET(self):
        """Serve a GET request."""
        f = self.send_head()
        if f:
            try:
                self.copyfile(f, self.wfile)
            finally:
                if(os.path.isfile(self.translate_path(self.path))):
                    print("Log this download:", self.translate_path(self.path))
                f.close()

PORT = 8000

Handler = MySimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print("serving at port", PORT)
httpd.serve_forever()

rawDescription: SimpleHTTPServer, Detecting when file transfer is finished?


code:
from glob import glob  # or iglob, see documentation

for f in glob("*.recode.vcf"):
    os.remove(f)

rawDescription: Efficient way of removing a specific file


code:
f = open("template.txt", "r")
g = open("data.txt", "w")
lines = f.readlines()
new_value_1 = "Whatever"
new_value_2 = "Whatever else"
for each in lines:
    if each.strip().startswith("$DS_activation_energy"):
        split_val = each.split("=")
        split_val[-1] = new_value_1
        new_val = "= ".join(split_val) + "\n"
        g.write(new_val)
    elif each.strip().startswith("$DS_arrhenius_constant"):
        split_val = each.split("=")
        split_val[-1] = new_value_2
        new_val = "= ".join(split_val) + "\n"
        g.write(new_val)
    else:
        g.write(each)

rawDescription: Copying text changing some variables

description: Copying text changing some variables


code:
0x41
"\x41"
"\x01" # a non printable character

rawDescription: Meaning of 0x and \x in python hex strings?


code:
import numpy as np
import scipy.interpolate as interp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

#define your data as you did in your question: a, b and betaTab

ip = interp.interp2d(a,b,betaTab)           # original interpolator

aplotv = np.linspace(a.min(),a.max(),100)   # to interpolate at
bplotv = np.linspace(b.min(),b.max(),100)   # to interpolate at
aplot,bplot = np.meshgrid(aplotv,bplotv)    # mesh to interpolate at

# actual values from interp2d:
betainterp2d = ip(aplotv,bplotv)

# actual values from griddata:
betagriddata = interp.griddata(np.array([a.ravel(),b.ravel()]).T,betaTab.ravel(),np.array([aplot.ravel(),bplot.ravel()]).T)
# ^ this probably could be written in a less messy way,
# I'll keep thinking about it

#plot results
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(aplot,bplot,betainterp2d,cmap='viridis',cstride=1,rstride=1)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(aplot,bplot,betagriddata,cmap='viridis',cstride=1,rstride=1)

rawDescription: scipy.interp2d warning and different result than expected

description: Scipy.interp2d warning and different result than expected


code:
method = getattr(myPotatoHead, 'play_' + toy)
method()

rawDescription: Variables as a part of calling a method in python


code:
"""
This module implements Obj-C-style categories for classes for Python

Copyright 2009 Ulrik Sverdrup <ulrik.sverdrup@gmail.com>
License: Public domain
"""

def Category(toclass, clobber=False):
    """Return a class decorator that implements the decorated class'
    methods as a Category on the class @toclass

    if @clobber is not allowed, AttributeError will be raised when
    the decorated class already contains the same attribute.
    """
    def decorator(cls):
        skip = set(("__dict__", "__module__", "__weakref__", "__doc__"))
        for attr in cls.__dict__:
            if attr in toclass.__dict__:
                if attr in skip:
                    continue
                if not clobber:
                    raise AttributeError("Category cannot override %s" % attr)
            setattr(toclass, attr, cls.__dict__[attr])
        return cls
    return decorator

rawDescription: How to do Obj-C Categories in Python?

description: Do Obj-C Categories in Python


code:
import itertools as it
def vecAdd(v1, v2): return tuple(it.imap(add, v1, v2))
def vecMul(v1, f): return tuple(it.imap(mul, v1, it.repeat(f)))

rawDescription: Python: some function for args -> *args (similar like those in functools)


code:
from collections import Counter
from operator import itemgetter

word = input('Enter a word: ')
c = Counter(word)

letter_arr, num_arr = zip(*sorted(c.items(), key=itemgetter(1,0)))
print(letter_arr)
print(num_arr)

rawDescription: Getting key values from a list of dictionaries


code:
def __eq__(self, other):
    return self.attrfoo == other.attrfoo # change that to your needs

rawDescription: Equality of objects in Python

description: Equality of objects in Python


code:
import urllib2
import cookielib

# load cookies from file
saved_cookies = cookielib.MozillaCookieJar('cookie_file_name')
saved_cookies.load()

opener = urllib2.build_opener() # your opener director

# do something...
opener.add_handler(urllib2.HTTPCookieProcessor(saved_cookies))

rawDescription: how do I insert a cookie into a urllib2 openerdirector object?

description: Insert a cookie into a urllib2 openerdirector object


rawDescription: using BeautifulSoup to insert an element before closing body

description: Using BeautifulSoup to insert an element before closing body


code:
browser = spynner.Browser()
browser.debug_level = spynner.DEBUG
browser.create_webview()
browser.show()
# now maximize the webview
browser.webview.showMaximized()

rawDescription: How can I set GUI size of spynner python module?

description: Set GUI size of spynner python module


code:
dict_a = {'verbs': ['run', 'go', 'eat'], 'nouns':['dog', 'cat', 'bear']}
dict_b = {'verbs': ['jump'], 'nouns': ['human']}

def foo(dict_a, dict_b):
  for k,v in dict_b.iteritems():
    for word in v[:]:
      if word in dict_a.get(k, []):
        dict_b[k].remove(word)

rawDescription: Deleting items from a list that is in a dictionary


code:
myregex=re.compile('{} is (not)? very good at python'.format(mystring))

myregex=re.compile('{s} is (not)? very good at python'.format(s=mystring))

myregex=re.compile('%s is (not)? very good at python'% (mystring))

myregex=re.compile('%(mystring)s is (not)? very good at python' % locals())

myregex=re.compile(mystring+' is (not)? very good at python')

myregex=re.compile(' '.join([mystring,'is (not)? very good at python']))

rawDescription: How do I insert a string element into a regular expression in Python?

description: Insert a string element into a regular expression in Python


code:
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt

m = Basemap(projection='cyl', lon_0=0, resolution='c')

m.fillcontinents(color='coral',lake_color='aqua')
m.drawmapboundary(fill_color='aqua')

places = {'Mexico City': (19.05, -99.366667),
          'London': (51.507222, -0.1275),
          'Sydney': (-33.859972, 151.211111),
          'Cape Town': (-33.925278, 18.423889),
          'Delhi': (28.61, 77.23),
          }

network = [
           ('London', 'Delhi'),
           ('Mexico City', 'Sydney'),
           ]

for source, target in network:
    lat1, lon1 = places[source]
    lat2, lon2 = places[target]
    line, = m.drawgreatcircle(lon1, lat1, lon2, lat2, lw=3)

    p = line.get_path()
    # find the index which crosses the dateline (the delta is large)
    cut_point = np.where(np.abs(np.diff(p.vertices[:, 0])) > 200)[0]
    if cut_point:
        cut_point = cut_point[0]

        # create new vertices with a nan inbetween and set those as the path's vertices
        new_verts = np.concatenate(
                                   [p.vertices[:cut_point, :],
                                    [[np.nan, np.nan]],
                                    p.vertices[cut_point+1:, :]]
                                   )
        p.codes = None
        p.vertices = new_verts

plt.show()

rawDescription: Python Basemap drawgreatcircle function

description: Python Basemap drawgreatcircle function


code:
@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignupForm(request.form)
    if request.method == 'POST':
        # maybe call form.validate()
        app.logger.info(form.data)
        return redirect(url_for('signup'))
    elif request.method == 'GET':
        return render_template('signup.html', form=form)

rawDescription: Flask/WTForms - post request doesnt send input


code:
import datetime
from threading import Timer

# dummy timestamp for testing, gong should be the
# timestamp of the last keepAlive signal
gong = datetime.datetime(2012, 8, 16, 16, 3, 18, 341121)

#seconds before kill check is performed
idle = 5

def bringOutYourDead():
    """If the last keep alive time stamp is more than 5 minutes ago, I am Audi 500."""
    stoneDeadIn =  5
    if datetime.datetime.now() - datetime.timedelta(minutes=stoneDeadIn) >= gong:
        # I used print for whatever command for testing
        print('save_state_or_whatever()')
        print('gtk_main_quit()')
    else:
        print("I'm not dead yet!'")
    # recurse this as you see fit

dung = Timer(idle, bringOutYourDead)
dung.start()

rawDescription: Processes launched from wsgi are still running after restarting/reloading the server


code:
if area > 1000:
    with open(output_file, "r+") as f:
        linecount = sum(1 for _ in output_file)
        f.write("%s %s %s\n" % (linecount + 1, a, b))

rawDescription: Add line number when adding line to a file


code: scipy.misc.factorial(12345, exact=True)

rawDescription: What is the fastest way to find the exact value of the factorial of a large number in python?


code:
from operator import itemgetter
from itertools import groupby

#input file
f=open('mytxt','rb')
#output file
f_out=open('out','w')

#skip the first line
header=f.readline()

# read every line
lines=f.readlines()
lines=[i.split(';')  for i in lines if i != '\n']

#grouping
groups=[]
for k,g in groupby(lines,itemgetter(1)):
    groups.append(list(g))

#iterate and write to a file
for j in range(len(groups)):
    headers=[[i[0],i[2]]  for i in groups[j]]
    final_headers=["PLZ"+'\t'] + [i[0]+'\t' for i in headers]
    final_values=[str(j+1)+'\t']+[i[1].strip()+'\t' for i in headers]
    f_out.write("".join(final_headers))
    f_out.write("\n")
    f_out.write("".join(final_values))
    f_out.write("\n")

rawDescription: Writing value just once to file in for loop


code:
def recdup(seq):
    if not seq:
        return seq
    head, tail = seq[0:1], seq[1:]
    return (head * 2) + recdup(tail)

rawDescription: Write a recursive function in python that duplicates each character in a string


code: variable_name = raw_input('please enter variable name (TimeStamp, Temperature or Humidity):')

rawDescription: how do i ask user for input of datetime & a variable before plotting

description: Ask user for input of datetime & a variable before plotting


code: sns.barplot(x='group', y='Values', data=df, estimator=lambda x: sum(x==0)/len(x)*100)

rawDescription: Python: Plotting percentage in seaborn bar plot


code:
started_23 = 0
while True:
    if GPIO.input(23) and time.time() - started_23 > 10:
        started_23 = time.time()
        print("Button 23 Pressed")
        os.system('omxplayer -o both /root/1.mp3 &')
    time.sleep(0.200)

rawDescription: Raspberry PI with GPIO Input buttons

description: Raspberry PI with GPIO Input buttons


code:
time = pd.DatetimeIndex(df['time taken'])
time.hour * 60 + time.minute

rawDescription: Convert hh:mm:ss to minutes using python pandas


code:
def module_exists(module_name):
    try:
        mod = __import__(module_name)
    except ImportError:
        return False
    else:
        return True

if module_exists('simplejson'):
    import simplejson as json
elif module_exists('json'):
    import json
elif module_exists('django.utils'):
    from django.utils import simplejson as json
else:
    raise ImportError('Requires either simplejson, Python 2.6 or django.utils')

rawDescription: Tidier way of trying to import a module from multiple locations?


code:
from sqlalchemy.orm.collections import MappedCollection, \
                    collection_adapter, collection

class MySubMagicDict(dict):
    def __init__(self, parent, key):
        self.parent = parent
        self.key = key

    def __setitem__(self, key, value):
        self.parent.__setitem__(self.key,
                            Value(type=self.key, name=key, value=value))

class MyMagicDict(MappedCollection):
    def __missing__(self, key):
        d = MySubMagicDict(self, key)
        dict.__setitem__(self, key, d)
        return d

    def __getitem__(self, key):
        d = MySubMagicDict(self, key)
        d.update(
            (v.name, v.value) for v in dict.__getitem__(self, key).values()
        )
        return d

    @collection.internally_instrumented
    def __setitem__(self, key, value, _sa_initiator=None):

        if _sa_initiator is not False:
            executor = collection_adapter(self)
            if executor:
                value = executor.fire_append_event(value, _sa_initiator)

        dict.__setitem__(
            dict.__getitem__(self, key), value.name, value)

    @collection.converter
    def _convert(self, dictlike):
        for incoming_key, value in dictlike.items():
            for name, subvalue in value.items():
                yield Value(type=incoming_key, name=name, value=subvalue)

    @collection.iterator
    def _all_items(self):
        for value in self.values():
            for subvalue in value.values():
                yield subvalue

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

values = Table('values', Base.metadata,
    Column("id", Integer, primary_key=True),
    Column('person_id', Integer, ForeignKey('persons.id')),
    Column('type', Text, nullable=False),
    Column('name', Text, nullable=False),
    Column('value', String)
)
class Value(Base):
    __table__ = values

class Person(Base):
    __tablename__ = 'persons'

    id = Column(Integer, primary_key=True)
    values = relationship("Value", collection_class=
                            lambda: MyMagicDict(lambda item: item.type),
                            cascade="all, delete-orphan"
                        )

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

s = Session(e)

p = Person(values={
    't1': {
        'n1': 't1n1',
        'n2': 't1n2'
    },
    't2': {
        'n1': 't2n1',
        'n2': 't2n2'
    }
})
s.add(p)
s.commit()

assert p.values['t2']['n2'] == 't2n2'
assert p.values['t1']['n1'] == 't1n1'

p.values['t1']['n2'] = 't1n2mod'

s.commit()

assert p.values['t1']['n2'] == 't1n2mod'
assert p.values['t1']['n1'] == 't1n1'

rawDescription: How do I create a multi-level dictionary backed by a single table in SQLAlchemy?

description: Create a multi-level dictionary backed by a single table in SQLAlchemy


code:
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
console_handler.setLevel(logging.ERROR)
logger.addHandler(console_handler)

rawDescription: Python logging messages appears in stdout when script is launched


code:
from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_active and u.is_superuser)
def my_view(request):
    ...

rawDescription: @permission-required argument in django

description: @permission-required argument in django


code:
from sqlalchemy import event, Integer, Column, String
from sqlalchemy.orm import scoped_session, sessionmaker, mapper
from sqlalchemy.ext.declarative import declarative_base

Session = scoped_session(sessionmaker())

@event.listens_for(mapper, 'init')
def auto_add(target, args, kwargs):
    Session.add(target)

Base = declarative_base()

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)
    data = Column(String)

a1 = A(data="foo")
assert a1 in Session()

rawDescription: How to automatically add a SQLAlchemy object to the session?

description: Automatically add a SQLAlchemy object to the session


rawDescription: Sending specific hex data using scapy

description: Sending specific hex data using scapy


code:
start_urls = ['http://www.e3050.com/Items.aspx?cat=SON']
pro_urls = [] # all product Urls

def parse(self, response): # select 50 products on each page
    yield FormRequest.from_response(response,
        formdata={'ctl00$ctl00$ContentPlaceHolder1$ItemListPlaceHolder$pagesddl': '50',
                  'ctl00$ctl00$ContentPlaceHolder1$ItemListPlaceHolder$sortddl': 'Price(ASC)'},
        meta={'curr': 1, 'total': 0, 'flag': True},
        dont_click=True,
        callback=self.page_rs_50)

def page_rs_50(self, response): # paginate the pages
    hxs = HtmlXPathSelector(response)
    curr = int(response.request.meta['curr'])
    total = int(response.request.meta['total'])
    flag = response.request.meta['flag']
    self.pro_urls.extend(hxs.select(
        "//td[@class='name']//a[contains(@id,'ctl00_ctl00_ContentPlaceHolder1_ItemListPlaceHolder_itemslv_ctrl')]/@href"
    ).extract())
    if flag:
        total = hxs.select(
            "//span[@id='ctl00_ctl00_ContentPlaceHolder1_ItemListPlaceHolder_lbl_pagesizeBtm']/text()").re('\d+')[0]
    if curr < total:
        curr += 1
        yield FormRequest.from_response(response,
            formdata={'ctl00$ctl00$ContentPlaceHolder1$ItemListPlaceHolder$pagesddl': '50',
                      'ctl00$ctl00$ContentPlaceHolder1$ItemListPlaceHolder$sortddl': 'Price(ASC)',
                      'ctl00$ctl00$ScriptManager1': 'ctl00$ctl00$ScriptManager1|ctl00$ctl00$ContentPlaceHolder1$ItemListPlaceHolder$pager1$ctl00$ctl01'
                , '__EVENTTARGET': 'ctl00$ctl00$ContentPlaceHolder1$ItemListPlaceHolder$pager1$ctl00$ctl01',
                      'ctl00$ctl00$ContentPlaceHolder1$ItemListPlaceHolder$hfVSFileName': hxs.select(
                          ".//input[@id='ctl00_ctl00_ContentPlaceHolder1_ItemListPlaceHolder_hfVSFileName']/@value").extract()[
                                                                                0]},
            meta={'curr': curr, 'total': total, 'flag': False},
            dont_click=True,
            callback=self.page_rs_50
        )
    else:
        for pro in self.pro_urls:
            yield Request("http://www.e3050.com/%s" % pro,
                callback=self.parse_product)

def parse_product(self, response):
    pass
    #TODO Implementation Required For Parsing

rawDescription: using scrapy to scrap asp.net website with javascript buttons and ajax requests

description: Using scrapy to scrap asp.net website with javascript buttons and ajax requests


code:
from Tkinter import *
import Tkinter
root = Tk()

class PaintBox( Frame ):
    def __init__( self, root ):
        Frame.__init__( self, root )
        self.pack( expand = YES, fill = BOTH )
        self.master.title( "Color Draw v0.2.63.23 open closed beta (Still in Alpha) greenlight edition" )
        self.master.geometry( "600x600" )

        self.message = Label( self, text = "Drag the mouse SLOWLY to draw" )
        self.message.pack( side = TOP )

        self.myCanvas = Canvas( self )
        self.myCanvas.pack( expand = YES, fill = BOTH )
        self.bd = (2)

        self.myCanvas.bind( "<B1-Motion>", self.paint )
        button = Button(root, text = "Clear", command = self.delete)
        button.pack()

    def paint( self, event ):
        x1, y1 = ( event.x - 4 ), ( event.y - 4 )
        x2, y2 = ( event.x + 4 ), ( event.y + 4 )
        self.myCanvas.create_rectangle( x1, y1, x2, y2, fill = "black", tags="box")

    def delete(self):
        items = self.myCanvas.find_all()
        for item in items:
            self.myCanvas.delete(item)

PaintBox(root).mainloop()

rawDescription: Tkinter name "delete" not defined

description: Tkinter name "delete" not defined


code:
with open('/path/to/file.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        ID, x1, y1, x2, y2 = row

rawDescription: Extracting data from a list using a for loop


code: string = string.replace(i, '', 1)

rawDescription: Why isn't this Python replace function working?


rawDescription: parsing a string based on specified identifiers

description: Parsing a string based on specified identifiers


code:
name = fields.Char(
    string='Name',
    default=lambda self: self._get_default_name(),
)

@api.model
def _get_default_name(self):
    return "test"

rawDescription: How to set default values with methods in Odoo 8?

description: Set default values with methods in Odoo 8


rawDescription: Pandas: adding "diagonally"

description: Pandas: adding "diagonally"


code:
pygame.display.init()
surface = pygame.display.set_mode((0,0),pygame.FULLSCREEN,0)

rawDescription: Which display manager for a non interactive Python app and mplayer?


code:
points = PointOfInterest.objects.filter(geom__distance_lte=(pnt, D(km=10)), events__start__range=(start_date, end_date)).extra(select={'event_pk': 'SELECT event.id FROM app name_event AS event where event.venue_pk=appname_pointofinterest.id ORDER BY start LIMIT 1'}).extra(select={'event_start': 'SELECT event.start_date FROM app name_event AS event where event.venue_pk=appname_pointofinterest.id ORDER BY start LIMIT 1'}).order_by('event_start')[:10]
ids = []
for point in points:
    ids.append(point.event_pk)
events = Event.objects.select_related('venue').filter(pk__in=ids)

rawDescription: django: order_by and distinct OK; then order_by another field... HowTo?

description: Django: order_by and distinct OK; then order_by another field... HowTo


code:
from pywinauto import application
app = application.Application()
app.Form1.CheckedListBox1.Select('item1')
app.Form1.CheckedListBox1.Select('item1')

rawDescription: CheckedListBox used from Python(pywin32)


code:
class UserProfileResource(ModelResource):
    fullname = fields.CharField(attribute='_get_full_name', readonly=True)
    class Meta:
        queryset = models.UserProfile.objects.all()
        authorization = DjangoAuthorization()
        fields = ['gender',]

rawDescription: How to expose a property (virtual field) on a Django Model as a field in a TastyPie ModelResource

description: Expose a property (virtual field) on a Django Model as a field in a TastyPie ModelResource


code:
def fopen():
    file = input("Open: ")
    print("")
    with open(file, 'r') as f:
        for line in f:
            print(line)
            print("")   # new line?
    editredirect()

def editredirect():
    print("You can edit this file with the 'edit' command.")
    dcmdLvl2()

rawDescription: How can I print more than one line of a file using python?

description: Print more than one line of a file using python


rawDescription: Python regex replace space from string if surrounded by numbers, but not letters


rawDescription: Parsing from Shakespeare text in Python

description: Parsing from Shakespeare text in Python


code: objective = (price[channel_id] * is_channel_assigned[channel_id])

rawDescription: pulp (python) - objective function depends on the result

description: Pulp (python) - objective function depends on the result


code:
from itertools import permutations
len([x for x in permutations((1, 3, 5, 0, 9)) if x[0]!=0])

rawDescription: Number of permutations of a set with an element limited to some positions


code:
class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['text', 'tags']}),
    ]
    filter_horizontal = ['tags']
    ...

rawDescription: How to create objects inline for many to many relationships in Django?

description: Create objects inline for many to many relationships in Django


code:
import numpy as np

# number of highest label:
labmax = np.max(labels)

# maximum and minimum positions along each axis (initialized to very low and high values)
b_first = np.iinfo('int32').max * np.ones((3, labmax + 1), dtype='int32')
b_last = np.iinfo('int32').max * np.ones((3, labmax + 1), dtype='int32')

# run through all dimensions making 2D slices and marking all existing labels to b
for dim in range(3):
    # create a generic slice object to make the slices
    sl = [slice(None), slice(None), slice(None)]

    bf = b_first[dim]
    bl = b_last[dim]

    # go through all slices in this dimension
    for k in range(arr.shape[dim]):
        # create the slice object
        sl[dim] = k
        # update the last "seen" vector
        bl[arr[sl].flatten()] = k

        # if we have smaller values in "last" than in "first", update
        bf[:] = np.clip(bf, None, bl)

rawDescription: Fastest way to get bounding boxes around segments in a label map


code:
g=graph.graphxy(width=8,y=graph.axis.linear(title=r"Fraction of DM halos"),
   x=graph.axis.linear(min=1,
       title=u"Mass ($10^{11}M_\u2609$)"))

rawDescription: How to do the astronomical symbol "\sun" in PyX

description: Do the astronomical symbol "\sun" in PyX


code:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

firefox = webdriver.Firefox()
firefox.get('http://foo.bar')
element_to_hover_over = firefox.find_element_by_id("baz")

hover = ActionChains(firefox).move_to_element(element_to_hover_over)
hover.perform()

rawDescription: Is there a way to perform a mouseover (hover over an element) using Selenium and Python bindings?


code:
import csv

names = ['control', 'control', 'control', 'vinc', 'vinc', 'vinc']
area = [20.3, 23.4, 24.5, 65.45, 76.45, 34.65]
mean = [123, 232, 132, 65, 34, 65]

op_file = open('output', 'w')
csv_writer = csv.writer(op_file, delimiter=',')
csv_writer.writerow(['names', 'area', 'mean']) #print the header
for row in zip(names, area, mean):
    csv_writer.writerow(row) # write each row by zipping the three lists
op_file.close()

rawDescription: Create a results table from lists

description: Create a results table from lists


code:
# Having a LazyUser means we don't have to get the actual User object
# for each request before it's actually accessed.
class LazyUser(object):
    # Define the __get__ operation for the descripted object.
    # According to the docs, "descr.__get__(self, obj, type=None) --> value".
    # We don't need the type (obj_type) for anything, so don't mind that.
    def __get__(self, request, obj_type=None):
        # This particular request doesn't have a cached user?
        if not hasattr(request, '_cached_user'):
            # Then let's go get it!
            from django.contrib.auth import get_user
            # And save it to that "hidden" field.
            request._cached_user = get_user(request)
        # Okay, now we have it, so return it.
        return request._cached_user

class AuthenticationMiddleware(object):
    # This is done for every request...
    def process_request(self, request):
        # Sanity checking.
        assert hasattr(request, 'session'), "blah blah blah."
        # Put the descriptor in the class's dictionary. It can thus be
        # accessed by the class's instances with `.user`,  and that'll
        # trigger the above __get__ method, eventually returning an User,
        # AnonymousUser, or what-have-you.
        # Come to think of it, this probably wouldn't have to be done
        # every time, but the performance gain of checking whether we already
        # have an User attribute would be negligible, or maybe even negative.
        request.__class__.user = LazyUser()
        # We didn't mess with the request enough to have to return a
        # response, so return None.
        return None

rawDescription: What's the trick in Django's AuthenticationMiddleware


code:
def log_chunker(log_lines):
    batch = []
    for line in log_lines:
        if batch and has_timestamp(line):
            # detected a new log statement, so yield the previous one
            yield batch
            batch = []
        batch.append(line)
    yield batch

rawDescription: Merging and sorting multiline logs in Python


code:
lstNeedOrder = ['a/b','c/d','f/d','a/e','c/d','a/c']
lst = ['a','b','c']
order = {ch: i for i, ch in enumerate(lst)} # {'a': 0, 'b': 1, 'c': 2}
def sort_key(x):
    # 'a/b' -> (0, 1), 'c/d' -> (2, 3), ...
    a, b = x.split('/')
    return order.get(a, len(lst)), order.get(b, len(lst))

sorted(lstNeedOrder, key=sort_key)

rawDescription: python group by and ordered a list by another list

description: Python group by and ordered a list by another list


code:
import re
regex = re.compile(r'.+_\d+_svm\.pkl')
regex.search('anytext_1_svm.pkl') != None

rawDescription: Python and regex - how to find anytext_NUMBER_svm.pkl


code:
class Foo:

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

  def __eq__(self, other):
    """Implements ==."""
    return self.foo == other.foo

  def __repr__(self):
    # if you eval the return value of this function,
    # you'll get another Foo instance that's == to self
    return "Foo(%r)" % self.foo

rawDescription: what's the meaning of %r in python

description: What's the meaning of %r in python


code:
import wsgiref
from wsgiref.simple_server import make_server

def my_app(environ,start_response):
    from io import StringIO
    stdout = StringIO()
    host = environ["HTTP_HOST"].split(":")[0]
    if host == "127.0.0.1":
        print("This is virtual host 1", file=stdout)
    elif host == "localhost":
        print("This is virtual host 2", file=stdout)
    else:
        print("Unknown virtual host", file=stdout)

    print("Hello world!", file=stdout)
    print(file=stdout)
    start_response(b"200 OK", [(b'Content-Type',b'text/plain; charset=utf-8')])
    return [stdout.getvalue().encode("utf-8")]

def test1():
    httpd = make_server('', 8000, my_app)
    print("Serving HTTP on port 8000...")

    # Respond to requests until process is killed
    httpd.serve_forever()

rawDescription: Python3 Http Web Server: virtual hosts

description: Python3 Http Web Server: virtual hosts


code:
from setuptools import setup, Extension

sources = ['src/units.c']
ext_opts = {'extra_compile_args': ['-Wl,-soname,units.so', '-Isrc']}

setup(
    name='units',
    ext_modules = [Extension('units', sources, **ext_opts)]
    )

rawDescription: Python library release best practices

description: Python library release best practices


code:
{{ appointment.teachers|join:", " }}
{{ appointment.subjects|join:", " }}

rawDescription: removing [u''] in the django template

description: Removing [u''] in the django template


code:
root = etree.XML('<root></root>')
etree.tostring(root)
print(etree.tostring(root, xml_declaration=True))
print(etree.tostring(root, encoding='iso-8859-1'))
print(etree.tostring(root, pretty_print=True))

rawDescription: How can I view a text representation of an lxml element?

description: View a text representation of an lxml element


code:
import itertools

class count(object):

    def __init__(self, start=0, step=1):
        self.start = start
        self.step = step

    def __eq__(self, other):
        return self.start == other.start and self.step == other.step

    def __iter__(self):
        return itertools.count(self.start, self.step)

rawDescription: Equality of itertools.count in Python

description: Equality of itertools.count in Python


code:
apinv = map(lambda n: np.linalg.pinv(n), a)
apinv = np.asarray(apinv,dtype=dt)

rawDescription: broadcasting linalg.pinv on a 3D matrix

description: Broadcasting linalg.pinv on a 3D matrix


code:
import os.path

def location(filename, pL):
    if pL == 'ab1234':
        filename = os.path.join(r'C:\dropbox', filename)
    else:
        filename = os.path.join(r'C:\dropbox', pL, filename)
    with open(filename, 'r') as f:
        return f.read()

rawDescription: Opening a file from a location and getting its text


code:
for itemID in itemsArray:
    avgQuantity = getJitaQuantity(itemID)
    lowestJitaSell = getJitaLowest(itemID)
    candidateArray = findLowestPrices(itemID, lowestJitaSell, candidateArray, avgQuantity)
    multiCandidateArray.append(sorted(candidateArray))

rawDescription: A list of lists of lists in Python

description: A list of lists of lists in Python


code:
def mycount(s):
        i = 0
        res = []
        while i<len(s):
                j = i+1
                while j<len(s) and s[i] == s[j]:
                        j += 1
                res.append( (s[i],j-i) )
                i = j
        return res

rawDescription: Count of repeated characters including the non-repeated ones in a string python


code:
import shutil, os

target = raw_input("Target directory: ")

# Make sure the target dir exists!
assert(os.path.exists(target))

for f in os.listdir('.'):
    b = raw_input("Press y to move file %s to %s: " %(f,target))
    if b.lower() == 'y':
        shutil.move(f, target)

rawDescription: Moving files using Python

description: Moving files using Python


code:
import numpy
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
# fake data
xdata = numpy.random.rand(100,100)
ydata = numpy.random.rand(100,100)
# set up figure
fig = plt.figure()
ax = fig.add_subplot(111)
ax.autoscale(True)
plt.subplots_adjust(left=0.25, bottom=0.25)

# plot first data set
frame = 0
ln, = ax.plot(xdata[frame],ydata[frame])

# make the slider
axframe = plt.axes([0.25, 0.1, 0.65, 0.03])
sframe = Slider(axframe, 'Frame', 0, 99, valinit=0,valfmt='%d')

# call back function
def update(val):
    frame = numpy.floor(sframe.val)
    ln.set_xdata(xdata[frame])
    ln.set_ydata((frame+1)* ydata[frame])
    ax.set_title(frame)
    ax.relim()
    ax.autoscale_view()
    plt.draw()

# connect callback to slider
sframe.on_changed(update)
plt.show()

rawDescription: Creating a scrollable multiplot with python's pylab


code:
import unittest
import time

expectedOutput = range(5)
class UnitTest(unittest.TestCase):

    def test_while(self):
        # Put your code here.
        timer = 5
        while timer > 0:
            timer = timer - 1
            self.assertTrue(timer == expectedOutput[timer])

if __name__ == "__main__":
    suite = unittest.TestLoader().loadTestsFromTestCase(UnitTest)
    unittest.TextTestRunner(verbosity=2).run(suite)

rawDescription: Python Unit testing for While Loops

description: Python Unit testing for While Loops


code:
import random
n = 10
random.sample(xrange(n), n)

rawDescription: Choosing randomly all the elements in the the list just once


code:
def function(n):
    stored  = n
    print(stored)
    while stored > 0:
        stored = stored - 1
        print(stored)
    while stored < n:
        stored = stored + 1
        print(stored)

function(10)

rawDescription: How to store a variable in python?

description: Store a variable in python


rawDescription: Matplotlib: change background color of colorbar (when using transparent colors)


code:
from threading import Timer

def make_api_with_interval(*arg, **kwargs):
    # BODY of make api call
    make_call_to_api()
    Timer(30.0, make_api_with_interval, ["args"], {'kwarg': 'kwarg'}).start()

Timer(30.0, make_api_with_interval).start() # after 30 seconds, api call would be performed.

rawDescription: How to politely make massive amounts of api calls?

description: Politely make massive amounts of api calls


code:
from django.db import models
from django.template import Template, Context

class YourModel(models.Model):
    body = models.TextField()

    def render_body(self, context=None):
        template = Template(self.body)
        context = context or {}
        context['object'] = self
        return template.render(Context(context))

rawDescription: Render django application within TextField


code: dict_list = [{} for x in xrange(3)]

rawDescription: Python: How to create a dictionary named after a list entry?


code:
#cython: boundscheck=False, wraparound=False
import cython

@cython.locals(end=cython.Py_ssize_t, i=cython.Py_ssize_t)
def remove_inplace_senderle2(L, keep):
    end = 0
    for i in range(len(L)):
        x = L[end] = L[i]
        if keep(x):
           end += 1

    del L[end:]

rawDescription: Is it simple to implement a simple python function in C?


rawDescription: Numpy: Index 3D array with index of last axis stored in 2D array


code: plt.grid(True, which='minor')

rawDescription: change the position (move) of tick labels when plotting with matplotlib

description: Change the position (move) of tick labels when plotting with matplotlib


code:
with open('O:/py_files/countlines.txt', 'rb') as infile,\
open('O:/py_files/countlines_out.txt', 'wb') as outfile:
   counter = 1
   for line in infile:
        if line[0].isdigit():
                counter = 1

        out = str(counter)+' '+line
        outfile.write(out)
        counter += 1

rawDescription: python increment counter if character in list and then if character not in list

description: Python increment counter if character in list and then if character not in list


code:
from itertools import product
bases = ["A","C","G","T"]
map(''.join, product(bases, repeat=4))

rawDescription: How to use List comprehension to create strings of different sizes from specific characters

description: Use List comprehension to create strings of different sizes from specific characters


code: "".join(str(i) for i in l)

rawDescription: What's the best way to convert an array of ints into a string?


code:
from functools import reduce

def flip(f):
    if not callable(f):
        raise TypeError("Cannot filp a non-callable object")
    def result(*args, **kw):
        args = list(args)
        args.reverse()
        return f(*args, **kw)
    return result

def ilast(i):
    return reduce(lambda _, x: x, i)

def iscanl(f, v, seq):
    yield v
    for a in seq:
        v = f(v, a)
        yield v

def scanl(*args, **kw):
    return list(iscanl(*args, **kw))

def foldl(*args, **kw):
    return ilast(iscanl(*args, **kw))
# Or using reduce
#def foldl(f, v, seq):
#    return reduce(f, seq, v)

def iscanr_reverse(f, v, seq):
    return iscanl(flip(f), v, seq)

def scanr(*args, **kw):
    result = list(iscanr_reverse(*args, **kw))
    result.reverse()
    return result

def foldr(*args, **kw):
    return ilast(iscanr_reverse(*args, **kw))

rawDescription: compose function and functional module

description: Compose function and functional module


code:
import wx
import os
import sys, csv
import wx.grid
from csv1 import MyFrame3

class MyFrame(MyFrame3):
    def __init__(self, parent, size = wx.Size(900,600)):
        MyFrame3.__init__ (self, parent)

        self.dirname = os.getcwd()

    # Import/Open CSV

    def ImportFunc( self, event ):
        '''THIS IMPORTED CSV WILL NEVER EXPAND TO FIT INTO THE FRAME, PLEASE HELP?'''

        dlg=wx.FileDialog(self, 'Choose a file', self.dirname, '','CSV files (*.csv)|*.csv|All files(*.*)|*.*',wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.dirname=dlg.GetDirectory()
            self.filename=os.path.join(self.dirname,dlg.GetFilename())
            self.file=file(self.filename, 'r')

            #check for file format with sniffer
            dialect = csv.Sniffer().sniff(self.file.read(1024))
            self.file.seek(0)

            csvfile=csv.reader(self.file,dialect)
            filedata = [] #put contents of csvfile into a list
            filedata.extend(csvfile)
            self.file.seek(0)

            #grab a sample and see if there is a header
            sample=self.file.read(2048)
            self.file.seek(0)
            if csv.Sniffer().has_header(sample): #if there is a header
                colnames=csvfile.next() # label columns from first line
                datalist=[] # create a list without the header
                datalist.extend(filedata[1:len(filedata)]) #append data without header

            else:
                row1=csvfile.next() #if there is NO header
                colnames=[]
                for i in range(len(row1)):
                    colnames.append('col_%d' % i) # label columns as col_1, col_2, etc
                self.file.seek(0)
                datalist=filedata #append data to datalist

        self.file.close()
        self.createGrid(datalist, colnames)
        grid_sizer = wx.BoxSizer(wx.VERTICAL)
        grid_sizer.Add(self.grid, 1, wx.EXPAND)
        self.Right_Panel.SetSizer(grid_sizer)
        self.Right_Panel.Layout()

    #create the grid

    def createGrid(self, datalist, colnames):
        if getattr(self, 'grid', 0): self.grid.Destroy()
        self.grid=wx.grid.Grid(self.Right_Panel, 0)
        self.grid.CreateGrid(len(datalist), len(colnames)) #create grid, same size as file (rows, cols)

        #fill in headings
        for i in range(len(colnames)):
            self.grid.SetColLabelValue(i, colnames[i])

        #populate the grid
        for row in range(len(datalist)):
            for col in range(len(colnames)):
                try:
                    self.grid.SetCellValue(row,col,datalist[row][col])
                except:
                    pass

        self.grid.AutoSizeColumns(False) # size columns to data (from cvsomatic.py)
        self.twiddle()

    def twiddle(self): # from http://www.velocityreviews.com/forums/t330788-how-to-update-window-after-wxgrid-is-updated.html
        x,y = self.GetSize()
        self.SetSize((x, y+1))
        self.SetSize((x,y))

    def Exit(self, event):
        if getattr(self, 'file',0):
            self.file.close()
            self.Close(True)

import wx.lib.mixins.inspection
app = wx.App(0)
Frame_02 = MyFrame(None)
Frame_02.Show()
wx.lib.inspection.InspectionTool().Show()
app.MainLoop()

rawDescription: Python/wxPython: Importing CSV file onto wxGrid not displaying to fit on frame


code:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

rawDescription: How to display full output in Jupyter, not only last result?

description: Display full output in Jupyter, not only last result


code:
file=open('new_file.txt','r')
new_user=input(str('NEW: '))
flag = False
for line in file:
    line=str(line)
    if new_user in line:
        print('yes its in here: ',line)
        flag = True
if not flag:
    print('Word: ',new_user,' not in here')
file.close()

rawDescription: For loop in Python and reading input from file


code:
import networkx as nx

G = nx.DiGraph()
G.add_node(1,level=1)
G.add_node(2,level=2)
G.add_node(3,level=2)
G.add_node(4,level=3)

G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,4)

import pylab as plt
nx.draw_graphviz(G, node_size=1600, cmap=plt.cm.Blues,
                 node_color=range(len(G)),
                 prog='dot')
plt.show()

rawDescription: in NetworkX draw the graph dividing the plot area in 3

description: In NetworkX draw the graph dividing the plot area in 3


code: [x for x in my_list if not x.startswith('#')]

rawDescription: What is the most pythonic way to exclude elements of a list that start with a specific character?


code:
import csv

with open("wakhawakha.csv", 'rt') as f:
    data = f.read()
new_data = data.replace('"', '')
for row in csv.reader(new_data.splitlines(), delimiter=' ', skipinitialspace=True):
    print ('|'.join(row))

rawDescription: Python strip every double quote from csv


code: linspace(min, max, n+1)

rawDescription: How can I make a list of n + 1 values with constant increment between two numbers?

description: Make a list of n + 1 values with constant increment between two numbers


code:
myList = [1,9,16,24]

num = int(input("Enter a number: "))

condition = True

for index, x in enumerate(myList):
    if condition and num < x:
        myList.insert(index, num)
        condition = False

if condition:
    myList.append(num)

print(myList)

rawDescription: python - an alternative way to not have repetitive elements print without break command?

description: Python - an alternative way to not have repetitive elements print without break command


rawDescription: Regex for string matching with special escaping rule


rawDescription: How to extract array entries for method call in python

description: Extract array entries for method call in python


rawDescription: Best Way to Add Implied Multiplication (*) to a Python String?


code: map (list, zip(*[['What if?', ' 2014', ' Randall Munroe'], ['Thing Explainer', ' 2015', ' Randall Munroe'], ['Alan Turing: The Enigma', ' 2014', ' Andrew Hodges']]))

rawDescription: Nested list manipulation, double forloop needed?


code:
class Record(object):
    """docstring for Record"""
    def __init__(self, FNAME, SNAME, M1, M2, M3, M4):
        super(Record, self).__init__()
        self.FNAME = FNAME
        self.SNAME = SNAME
        self.M1 = M1
        self.M2 = M2
        self.M3 = M3
        self.M4 = M4

with open('your_file_name') as f:
    LIST = [Record(*(line.split(':'))) for line in f]

rawDescription: Python: Read line from file, split it and change object


code:
idx = pd.IndexSlice
df.loc[:, idx[:, ['j', 'k']]]

rawDescription: how to select multiple values from a single level of a dataframe multiindex

description: Select multiple values from a single level of a dataframe multiindex


rawDescription: How to add the missing keys in this dictionary with values as empty string using python

description: Add the missing keys in this dictionary with values as empty string using python


code:
class LastMonthFeed(Feed):

    def items(self):
        ts = datetime.datetime.now() - datetime.timedelta(days=30)
        return sol.object.filter(date__gte=ts).order_by('-date')

rawDescription: Reusing a Django RSS Feed for different Date Ranges


code:
from Spotfire.Dxp.Application.Visuals import VisualContent

#"visual" is the name of the parameter found in the "Script Parameter" dialog below the editor which points to the visualization I want to change.
vc = visual.As[VisualContent]()
exp="["+Document.Properties["DocPropertyNameHere"]+"]"
vc.YAxis.Expression =exp

rawDescription: How do I set the x-axis (xaxis) on a Bar Graph in Spotfire with IronPython?

description: Set the x-axis (xaxis) on a Bar Graph in Spotfire with IronPython


code:
import csv
import os

with open('names.csv') as csvfile:
     reader = csv.reader(csvfile)
     for row in reader:
         oldPath = row[0]
         newPath = row[1]
         os.rename(oldPath, newPath)

rawDescription: How to rename file names using text file in python

description: Rename file names using text file in python


code:
import tkinter as tk

def click(row, col):
    label.configure(text="you clicked row %s column %s" % (row, col))

root = tk.Tk()
for row in range(10):
    for col in range(10):
        button = tk.Button(root, text="%s,%s" % (row, col),
                           command=lambda row=row, col=col: click(row, col))
        button.grid(row=row, column=col, sticky="nsew")
label = tk.Label(root, text="")
label.grid(row=10, column=0, columnspan=10, sticky="new")

root.grid_rowconfigure(10, weight=1)
root.grid_columnconfigure(10, weight=1)

root.mainloop()

rawDescription: TkInter button coordinates on a grid

description: TkInter button coordinates on a grid


code:
import collections

list1 = [1,1,1,-1,-1]
p = min(collections.Counter(list1).values())*1.0/len(list1)
print(p)
# Output
0.4

rawDescription: Python - Get percentage of minority class in a list


code:
def main():
    while True:
        all_files = getFiles(LOC_DIR)
        files = []
        for f in all_files:
            if checkExt(f):
                files.append(f)
        if len(files) == 1:
            printLog('<<< Found %s matching file >>>' % len(files))
        elif len(files) > 1:
            printLog('<<< Found %s matching files >>>' % len(files))
        for f in files:
            if checkSize(f):
                rsyncFile(f)
        printLog('No files found.  Checking again in %s seconds' % RUN_INT)
        time.sleep(RUN_INT)
        printLog('Checking for files')

if __name__ == "__main__":
    main()

rawDescription: Python recursion limit

description: Python recursion limit


code:
import csv
with open('titanic.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for i,row in enumerate(reader):
        print(row['survived'], row['pclass'], row['name'], row['sex'], row['age'])
        if(i >= 9):
            break

rawDescription: How do I print only the first 10 lines from a csv file using Python?

description: Print only the first 10 lines from a csv file using Python


code: result = filter (None, map (expensive, mylist))

rawDescription: How do I efficiently filter computed values within a Python list comprehension?

description: Efficiently filter computed values within a Python list comprehension


code:
from flask import Flask, request
app = Flask(__name__)

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        f.save('/var/www/uploads/uploaded_file.txt')

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

rawDescription: How can I store the value of an HTTP Post to my server?

description: Store the value of an HTTP Post to my server


code:
string = "hello world"
string.startswith("hello")

rawDescription: Checking whether a string starts with XXXX


code:
# Note: Untested code follows
with open(input_file) as f_in:
    np.genfromtxt(itertools.islice(f_in,2,None,4),dtype=None,delimiter=",")

    f_in.seek(0)  # Set the file pointer back to the beginning
    low = np.genfromtxt(itertools.islice(f_in,3,None,4),dtype=str)

    f_in.seek(0)  # Set the file pointer back to the beginning
    up = np.genfromtxt(itertools.islice(f_in,4,None,4),dtype=str)

rawDescription: Using multiple genfromtxt on a single file


rawDescription: How to generate random number of given decimal point between 2 number in Python?

description: Generate random number of given decimal point between 2 number in Python


code:
conn = session.connection()
conn.execute(Review.__table__
                .update()
                .values(artist_id=artist_id)
                .where(Review.id.in_(review_ids))
            )

rawDescription: SQLAlchemy: add a relationship using id instead of object?


code:
s1 = "The cat Went to The store To get Some food doNotMatch"
r1 = re.compile('\\b[A-Z]\w+')
r1.sub('',s1)
' cat  to  store  get  food doNotMatch'

rawDescription: Add stop_words while performing TF-IFcosine similarity


code:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.carousel import Carousel
from kivy.uix.image import Image
from kivy.factory import Factory
from kivy.clock import Clock

class Logo(App):

    def build(self):

        main_layout = GridLayout(cols=1, rows=2)
        top_row = GridLayout(cols=3, rows=1)
        bottom_row = GridLayout(cols=1)

        logo = Image(source='bird.jpg')
        title = Label(text='Just three birds.',font_size='40sp')
        ip = Label(text='tweet\ntweet\ntweet',font_size='20sp')

        carousel = Carousel(direction='right', loop=True, size_hint=(.5,.5),pos=(0,180))

        for i in range(1,4):
            src = "bird%s.jpg" % str(i)
            image = Factory.AsyncImage(source=src, allow_stretch=True)
            carousel.add_widget(image)
        Clock.schedule_interval(carousel.load_next, 1.0)

        top_row.add_widget(logo)
        top_row.add_widget(title)
        top_row.add_widget(ip)
        bottom_row.add_widget(carousel)

        main_layout.add_widget(top_row)
        main_layout.add_widget(bottom_row)

        return main_layout

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

rawDescription: How to return a widget inside a Layout in Kivy?

description: Return a widget inside a Layout in Kivy


code:
allocation = parent_widget.get_allocation()
desired_width = allocation.width
desired_height = allocation.height

pixbuf = gtk.gdk.pixbuf_new_from_file('your_image.png')
pixbuf = pixbuf.scale_simple(desired_width, desired_height, gtk.gdk.INTERP_BILINEAR)
image = gtk.image_new_from_pixbuf(pixbuf)

rawDescription: PyGTK: How do I make an image automatically scale to fit it's parent widget?


code:
import time

for img in [image, image1, image2]:
    screen.fill((200, 200, 200))
    screen.blit(img, (320, 240))
    time.sleep(1)    # sleep 1 second before continuing

rawDescription: How to cycle image sprite in pygame

description: Cycle image sprite in pygame


code:
job_admin = admin.site._registry[Job]
# save old values so that you can go back to them later
old_list_display = job_admin.list_display
old_list_filter = job_admin.list_filter
old_ordering = job_admin.model._meta.ordering
job_admin.list_editable = ("time", "what", "approved")
cl = ChangeList(request, job_admin.model, job_admin.list_display, job_admin.list_display_links, job_admin.list_filter, job_admin.date_hierarchy, job_admin.search_fields, job_admin.list_select_related, job_admin.list_per_page, job_admin.list_editable,job_admin.admin_site, job_admin)
# options.py from django framework lines 1181-1208 (v. 1.4)
if request.POST:
    FormSet = job_admin.get_changelist_formset(request)
    formset =FormSet(request.POST, request.FILES, queryset=cl.result_list)
    if formset.is_valid():
        changecount = 0
        for form in formset.forms:
            if form.has_changed():
                obj = job_admin.save_form(request, form, change=True)
                job_admin.save_model(request, obj, form, change=True)
                job_admin.save_related(request, form, formsets=[], change=True)
                change_msg = job_admin.construct_change_message(request, form, None)
                job_admin.log_change(request, obj, change_msg)
                changecount += 1

        if changecount:
            if changecount == 1:
                name = force_unicode(job_admin.model._meta.verbose_name)
            else:
                name = force_unicode(job_admin.model._meta.verbose_name_plural)
            msg = ungettext("%(count)s %(name)s was changed successfully.",
                                "%(count)s %(name)s were changed successfully.",
                                changecount) % {'count': changecount,
                                                'name': name,
                                                'obj': force_unicode(obj)}
            job_admin.message_user(request, msg)
        # call function that sets admin with original values
        fix_old_job_admin(job_admin, old_list_display, old_ordering, old_list_filter)
        return HttpResponseRedirect(request.get_full_path())

FormSet = job_admin.get_changelist_formset(request)
cl.formset = FormSet(queryset=cl.result_list)

context = Context({
    'app_label': ContentType.objects.get_for_model(Lawyer).app_label,
    'verbose_name_plural': Job._meta.verbose_name_plural.title(),
    "cl": cl,
    'request': request,

                   })
# call function that sets admin with original values
fix_old_job_admin(job_admin, old_list_display, old_ordering, old_list_filter)
return render_to_response('yourtemplate/similar_to_changelist.html', context, RequestContext(request))

rawDescription: django formset update existing

description: Django formset update existing


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

def make_lines(x,y):
    ax = plt.gca()
    for j in range(len(x)):
        for i in range(j,len(x)):
            distance = np.sqrt((x[i]-x[j])**2+(y[i]-y[j])**2)
            if distance < 0.2 and distance > 0:
                ax.annotate('', xy=(x[i], y[i]), xytext=(x[j], y[j]),
                            arrowprops=dict(facecolor='black',
                                            shrink=0.1,
                                            width=1),
                            textcoords='data',
                            )
n = 30
x,y = np.random.rand(n), np.random.rand(n)

fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111)

make_lines(x,y)

ax.plot(x,y,'ro',markersize=10)
plt.show()

rawDescription: Matplotlib, how to connect with a line annotations if a condition is met?


code:
# sample
import googleDriveAccess
ci = googleDriveAccess.readClientId(basedir)
ds = googleDriveAccess.second_authorize(basedir, ci, script=True)
id, fileobj = googleDriveAccess.script_download(ds, folder, SCRIPT_ID)

rawDescription: Useing python to download a file in google drive that is created by a google app script


code:
class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)
        self.label = wx.StaticText(self.panel, label="Test", style=wx.ALIGN_CENTRE)
        self.button = wx.Button(self.panel, label="Change")

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.label, 1)
        self.sizer.Add(self.button)

        self.button.Bind(wx.EVT_BUTTON, self.OnButton)

        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

    def OnButton(self, e):
        self.label.SetLabel("Oh, this is very looooong!")
        self.sizer.Layout()
        # self.panel.Layout()  #Either works

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: What is the correct way to change StaticText label?


code:
p = html5lib.HTMLParser(tokenizer=sanitizer.HTMLSanitizer, tree=treebuilders.getTreeBuilder("dom"))
dom_tree = p.parseFragment(value)
walker = treewalkers.getTreeWalker("dom")
stream = walker(dom_tree)
s = serializer.htmlserializer.HTMLSerializer(quote_attr_values=True)
return s.render(stream)

rawDescription: How to prevent BeautifulSoup from self-closing things that look like tags but aren't?

description: Prevent BeautifulSoup from self-closing things that look like tags but aren't


code:
query = User.select().where(User.username == 'charlie')
if query.exists():
    # A user named "charlie" exists.
    cool()

rawDescription: check if query exists using peewee

description: Check if query exists using peewee


code:
def getNextWeek(week):
  nextWeek = {};
  nextWeek['start'] = week['end'] + timedelta(days=1)
  nextWeek['end'] = nextWeek['start'] + timedelta(days=6)
  return nextWeek

rawDescription: get the start and the end date of every week leading up to the current date

description: Get the start and the end date of every week leading up to the current date


rawDescription: Sorting Tweepy Status objects?

description: Sorting Tweepy Status objects


code:
version, type, length = struct.unpack("cch", packed[:4])
content, = struct.unpack("%ds" % length, packed[4:])

rawDescription: Unspecified byte lengths in Python

description: Unspecified byte lengths in Python


code:
# What you are doing
random_array[[2, 3, 3]]  # semantics: [arr[2], arr[3], arr[3]]

# What you want to be doing
random_array[(2, 3, 3)]  # semantics: arr[2][3][3], same as arr[2,3,3]

rawDescription: Using itertools to index an array

description: Using itertools to index an array


code:
from phpserialize import loads, phpobject

python_object = loads(php_serialized_string, object_hook=phpobject)

rawDescription: Decoding StdClass in Python

description: Decoding StdClass in Python


rawDescription: Function(x,y) that returns x number of @ separated by y number of spaces


code:
import datetime
datetime.datetime.strptime(str(datetime.datetime.now().year) +
'/' + '06/18-19:31:05.688344', '%Y/%m/%d-%H:%M:%S.%f')

rawDescription: Convert Snort string to Python timestamp


rawDescription: How do I stop Count Vectorizer of Python Sci-kit library from doing any kind of word filtering?

description: Stop Count Vectorizer of Python Sci-kit library from doing any kind of word filtering


code:
streamerIP = "192.168.0.53"
dump = PacketList()

def filterStreamer(pkt):
    global streamerIP, dump
    if pkt.src == streamerIP or pkt.dst == streamerIP:
        dump.append(pkt)

dump.summary()

rawDescription: How to specify a scapy startup file?

description: Specify a scapy startup file


code:
from collections import defaultdict

tuples = [('Tim', 'PageFoo'), ('Jen','PageBar'), ('Tim', 'PageBaz')]
result = defaultdict(list)
for key, value in tuples:
    result[key].append(value)
result
# Out[8]: defaultdict(<type 'list'>, {'Tim': ['PageFoo', 'PageBaz'], 'Jen': ['PageBar']})
dict(result)
# Out[9]: {'Jen': ['PageBar'], 'Tim': ['PageFoo', 'PageBaz']}
result.items()
# Out[10]: [('Tim', ['PageFoo', 'PageBaz']), ('Jen', ['PageBar'])]

rawDescription: Mapping (key, value) (key, value) to (key, (value1, value2)) in Python


code:
def update(self, instance, validated_data):
    instance.account = validated_data['account']
    instance.password = validated_data['password']
    instance.username = validated_data['username']
    instance.gender = validated_data['gender']
    instance.score = validated_data['score']
    instance.photo = validated_data['photo']

    Friends_Datas = User_Datas.get('FriendsDatas')
    for friend in Friends_Datas:
        friendsdatas, _ = FriendsData.objects.update_or_create(
            {'friend_name': friend.get('friend_name')},
            friend_account = friend.get('friend_account'),
            usersData_id = instance)

    Task_Datas = User_Datas.get('TaskDatas')
    for task in Task_Datas:
        taskdatas, _  = TaskData.objects.update_or_create(
            {
            'task_is_group' : task.get('task_is_group'),
            'task_time' : task.get('task_time'),
            'task_score' : task.get('task_score'),
            'task_member_list' : task.get('task_member_list'),
            'task_bulletin' : task.get('task_bulletin'),   },
            task_name = task.get('task_name'),
            userData_id = instance
                                    )
        Subtask_Datas = task.get('SubtaskDatas')
        for subtask in Subtask_Datas:
            subtaskdatas = SubtaskData.objects.update_or_create(
                {'subtask_deadline' : subtask.get('subtask_deadline'),
                'subtask_completion' : subtask.get('subtask_completion'),
                'subtask_importance' : subtask.get('subtask_importance'),
                'subtask_item' : subtask.get('subtask_item'), }
                ,subtask_name = subtask.get('subtask_name'),
                taskData_id = taskdatas
                                    )

    Chatroom_Datas = User_Datas.get('ChatroomDatas')
    for chatroom in Chatroom_Datas:
        chatroomdatas, _  = ChatroomData.objects.update_or_create(
            {'chatroom_contents' : chatroom.get('chatroom_contents'),},
            chatroom_member = chatroom.get('chatroom_member'),
            userdata_cid = instance
             )

    return instance

rawDescription: Django REST: How to PUT Data in Nested ModelSerializer (Update)


rawDescription: Matching strings and extracting parts

description: Matching strings and extracting parts


code:
class RulesAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.TextField: {'widget': Textarea(
                           attrs={'rows': 1,
                                  'cols': 40,
                                  'style': 'height: 1em;'})},
    }

rawDescription: Control the size TextArea widget look in django admin


code:
import unittest

class MyTest(unittest.TestCase):
    def test_example(self):
        self.assertTrue(x)

rawDescription: python 2.6. unittest framework, asserts: help required

description: Python 2.6. unittest framework, asserts: help required


code:
class CleanForm(forms.ModelForm):
    def clean_slug(self):
        return "something"

class BlogCreateForm(CleanForm):
    class Meta:
        model   = Blog
        exclude = ('author',)

class BlogEditForm(CleanForm):
    class Meta:
        model   = Blog
        exclude = ('author', 'slug')

rawDescription: Django Form inheritance on Google App Engine


rawDescription: Dictionary with values as lists to pandas dataframe frame


code: sourcefile = __file__.rstrip('cd')

rawDescription: Why does basename return the compiled filename?


code:
from django.core.serializers.json import DjangoJSONEncoder

def myview(request):
    file_dict = File.objects.filter(pk=1).values()[0]
    folder_dict = Folder.objects.filter(pk=file.folder.pk).values()[0]
    folder_dict.update(file_dict)
    response = json.dumps({'file': folder_dict}, cls=DjangoJSONEncoder)
    return HttpResponse(response, content_type="application/json")

rawDescription: Django - serialize polymorphic model

description: Django - serialize polymorphic model


rawDescription: Using Imap - Mail encoding weirdness

description: Using Imap - Mail encoding weirdness


rawDescription: How to set the precision on str(numpy.float64)?

description: Set the precision on str(numpy.float64)


rawDescription: python: escape all escaped characters

description: Python: escape all escaped characters


code:
from itertools import groupby
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()
class Stuff(Base):
    __tablename__ = 'stuff'
    id = Column(Integer, primary_key=True)
    column1 = Column(String(10))
    column2 = Column(String(10))

    def __repr__(self):
        return '({}, {})'.format(self.column1, self.column2)

db_url = 'sqlite:////tmp/test.db'
engine = create_engine(db_url)
Base.metadata.bind = engine
session = sessionmaker(bind=engine)()

for k, g in groupby(session.query(Stuff).order_by(Stuff.column1, Stuff.column2),
                    key=lambda stuff: stuff.column1):
    print('{}: {}'.format(k, ','.join(stuff.column2 for stuff in g)))

rawDescription: How to iterate a column to get the sub list in sqlalchemy?

description: Iterate a column to get the sub list in sqlalchemy


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

N = 100

fig, ax = plt.subplots()
x = np.arange(N).astype('<i8').view('M8[s]').tolist()
y = (np.random.random(N)-0.5).cumsum()
ax.plot(x, y)

seclocator = matdates.SecondLocator(bysecond=[20, 40])
minlocator = matdates.MinuteLocator(byminute=range(60))  # range(60) is the default

seclocator.MAXTICKS  = 40000
minlocator.MAXTICKS  = 40000

majorFmt = matdates.DateFormatter('%Y-%m-%d, %H:%M:%S')
minorFmt = matdates.DateFormatter('%H:%M:%S')

ax.xaxis.set_major_locator(minlocator)
ax.xaxis.set_major_formatter(majorFmt)
plt.setp(ax.xaxis.get_majorticklabels(), rotation=90)

ax.xaxis.set_minor_locator(seclocator)
ax.xaxis.set_minor_formatter(minorFmt)
plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)

plt.subplots_adjust(bottom=0.5)
plt.show()

rawDescription: matplotlib how to specify time locator's start-ticking timestamp?

description: Matplotlib how to specify time locator's start-ticking timestamp


code:
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Question(models.Model):
# ...
    def __str__(self):              # __unicode__ on Python 2
        return self.question_text

@python_2_unicode_compatible
class Choice(models.Model):
# ...
    def __str__(self):              # __unicode__ on Python 2
        return self.choice_text

rawDescription: Using __str__() method in Django on Python 2


code:
K = abs(A - C) < abs(B - C)  # create array of bool
D = where(K, A, B)     # get elements of A and B respectively

rawDescription: select closest values from two different arrays

description: Select closest values from two different arrays


code:
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("https://www.google.com")

# open a link in a new window
actions = ActionChains(driver)
about = driver.find_element_by_link_text('About')
actions.key_down(Keys.CONTROL).click(about).key_up(Keys.CONTROL).perform()

driver.switch_to.window(driver.window_handles[-1])
driver.get("https://stackoverflow.com")

rawDescription: Selenium won't open a new url in a new tab (Python & Chrome)


code:
regex_search_string = re.compile(r"[+-]>\s\[HELP\.SELECTOR\]")
for data in repo.pull_request(prs.number).files():
    match_text = regex_search_string.search(data.patch)
    if match_text:
        search_string_found = 'True'
        break

rawDescription: Python regex statement not returning correct results


code:
@patch('module_under_test.get_complex_data_structure')
def test_function_to_test(self, mocked_function):
    foo_mock = mocked_function.return_value

rawDescription: Mock variable in function

description: Mock variable in function


code:
urllib.request.urlretrieve ("http://bogoroditsa.tk/Grant's%20Libraries/",
                                             "/home/foo/ExtraFunctionality.py")

rawDescription: How to specify the file path in which to download using python

description: Specify the file path in which to download using python


code:
import re
re.split('\n\n+', text)

rawDescription: Python: Regex needed

description: Python: Regex needed


code:
def wtf(some, thing, fields = None):
  if fields is None:
    fields = []

rawDescription: Optional Parameters in Python with List Append


code:
class FilterValue(models.Model):
    name = models.CharField('Name', max_length=255)
    filter = models.ForeignKey(Filter)

    class Meta:
        unique_together = (("name", "filter"),)

rawDescription: How to define django foreign key limit_choices_to constraint which has reference to it's own model?

description: Define django foreign key limit_choices_to constraint which has reference to it's own model


code:
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
    i = bisect(breakpoints, score)
    return grades[i]
[grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]

rawDescription: Hash a Range of Values

description: Hash a Range of Values


code:
import os
import fnmatch

for path,dirs,files in os.walk('.'):
    for f in fnmatch.filter(files,'*.txt'):
        fullname = os.path.abspath(os.path.join(path,f))
        print(fullname)

rawDescription: navigate folders with python

description: Navigate folders with python


code:
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

x = range(10)
plt.plot(x)

plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%d km'))

plt.show()

rawDescription: Add unit to yaxis labels in MatPlotLib

description: Add unit to yaxis labels in MatPlotLib


rawDescription: Why is there a performance difference between the order of a nested loop?


code:
import os
import time

source = 'D:\\backup_original'

target_dir = 'E:\\backup_copied'

target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'

zip_command = "7za a {0} {1}".format(target, ''.join(source))

if os.system(zip_command) == 0:
    print('Success')
else:
    print('Backup Failed')

rawDescription: Python Backup script not working on windows


code:
import networkx as nx
def my_bipartite_geom_graph(a, b, radius, dim):

    G=nx.Graph()
    G.add_nodes_from(range(a+b))
    for n in range(a):
        G.node[n]['pos']=[random.random() for i in range(0,dim)]
        G.node[n]['type'] = 'A'

    for n in range(a, a+b):
        G.node[n]['pos']=[random.random() for i in range(0,dim)]
        G.node[n]['type'] = 'B'

    nodesa = [(node, data) for node, data in G.nodes(data=True) if data['type'] == 'A']
    nodesb = [(node, data) for node, data in G.nodes(data=True) if data['type'] == 'B']

    while nodesa:
        u,du = nodesa.pop()
        pu = du['pos']
        for v,dv in nodesb:
            pv = dv['pos']
            d = sum(((a-b)**2 for a,b in zip(pu,pv)))
            if d <= radius**2:
                G.add_edge(u,v)
    return G

rawDescription: bip geom graph attempt in python

description: Bip geom graph attempt in python


code:
from django.contrib.auth.views import redirect_to_login
from django.core.urlresolvers import reverse
import functools

def login_required(fn):
    @functools.wraps(fn)
    def _decorated(request, *args, **kwargs):
        if request.user.is_authenticated():
            return fn(request, *args, **kwargs)

        path = request.get_full_path()
        login_url = reverse('login')
        return redirect_to_login(path, login_url)

rawDescription: @login_required is losing the current specified language


code:
location, created = Location.objects.get_or_create(pk=pk)
if created:
   num_of_new_locs+=1 #number of new locations increased
else:
   location.url= loc_fields['url']
   location.locationname = loc_fields['locationname']
   location.desc = loc_fields['desc']
   location.str_hnr = loc_fields['str_hnr']
   location.save()

rawDescription: how to update only one field instead creating another object - django 1.4

description: Update only one field instead creating another object - django 1.4


code:
def upload_to_path(instance, filename):
    return '{upload_dir}/{filename}'.format(
        upload_dir=instance.upload_dir,
        filename=filename
    )

class Image(models.Model):
    """
    Images base class
    """
    upload_dir = "uploads/images"
    image = models.ImageField(upload_to=upload_to_path)

class ActivityThumbnail(Image):
    """
    Thumbnail images for activities
    """
    upload_dir = "uploads/images/thumbnails/activities"

rawDescription: Override hardcoded value Python Django class


code:
import logging

logging.getLogger("httpstream").setLevel(Logging.WARNING)

rawDescription: How do I stop py2neo watch()?

description: Stop py2neo watch()


code:
import sys
myFile=sys.stdout
myFile.write("Hello!\n")

rawDescription: Is there such thing as File name or handle to write to console?


code:
def remove_items(item,quantity):
    global inventory
    if item not in inventory: #make sure the item is in the inventory first
        return
    inventory[item] -= quantity
    if inventory[item] <= 0: #remove item if the quantity is less than 0
        inventory.pop(item,None)

rawDescription: removing items from an inventory(dictionary) if the value is zero

description: Removing items from an inventory(dictionary) if the value is zero


code:
header, output = client.request(twitterRequest, method="GET", body=None,
                            headers=None, force_auth_header=True)

# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()

rawDescription: Need to Pretty-Print Twitter JSON Data to a File using Python


code:
from random import randint
print(randint(0,9))

rawDescription: Generate random integers between 0 and 9


code:
def find_difference(list_of_files, block_size=1000):
    fs=[open(f,'rb') for f in list_of_files]
    while True:
        first=True
        for f in fs:
            if first:
                first=False
                s1=f.read(block_size)
                end=(s1==b'')
                continue
            s2=f.read(block_size)
            if s1!=s2:
                return True
            if end and (s2!=b''):
                end=False
        if end:
            return False

rawDescription: Comparing more than 2 files in python3

description: Comparing more than 2 files in python3


code: ["#{val}FF{val}".format(val=hex(i)[2:].zfill(2)) for i in range(55, 255, 50)]

rawDescription: Creating hex color series

description: Creating hex color series


code:
import ast
ast.literal_eval(d)

rawDescription: Is string to dict conversion possible in python?


code:
class Team(models.Model):
    team_name = ...
    # Whatever other attributes.

class Player(models.Model):
    first_name = ...
    last_name = ...
    # Assign players to a team.
    team = models.ForeignKey(Team)
    # Whatever stats you want to keep on the players

rawDescription: Django - Generating New Classes Automatically


rawDescription: Fastest way to get elements from a numpy array and create a new numpy array


code:
d = t1 - t0
d.total_seconds()

rawDescription: I want to measure time passed between action in the code


code: conn.index({"name":"Joe Tester", "parsedtext":"Joe Testere nice guy", "uuid":"11111", "position":1}, "test-index", "test-type", 1)

rawDescription: django-haystack elasticsearch as backend and searchengine

description: Django-haystack elasticsearch as backend and searchengine


code:
x = file.readline()
file.seek(len(x), 0)
file.write(text) #write the text

rawDescription: Why does readline() put the file pointer at the end of the file in Python?


code:
import re

origional_string = "makeup of organisms.[10] In 1997, while working at the University of Tennessee, Pigliucci received the Theodosius Dobzhansky Prize,[11]"

result = re.sub(r'\[ *[0-9]+ *\]', '', origional_string)

print(result)

rawDescription: Python regex to remove all occurances of [Number]


code: age + subtract(height, multiply(weight, devide(iq, 2)))

rawDescription: learn python the hard way exercise 21 help

description: Learn python the hard way exercise 21 help


code:
class State(models.Model):
    title = models.CharField(max_length=50)

    def __unicode__(self):
        return self.title

class Transaction(models.Model):
    ...
    state = models.ForeignKey(State)

rawDescription: Option or state Field like a boolean field in a django model


rawDescription: Python and numpy - converting multiple values in an array to binary


code:
for task in tasks:
    result=np.array([])
    for subject in subjects:
        f=np.load('%d/%s.npy' % (subject,event))
        result=np.append(result,f)
    mu=np.mean(result)
    sav=np.save('%s' %(task),mu)

rawDescription: python - numpy create array from multiple files

description: Python - numpy create array from multiple files


code:
with open('test.txt') as infile, open('test_2.txt', 'w') as outfile:
  for line in infile:
    if not line.startswith("I want"):
      outfile.write(line.strip())

rawDescription: Can't properly remove line from text file


code:
import sys
from PySide import QtGui, QtCore

class myQTabBar(QtGui.QTabBar):
    def __init__(self, *args, **kargs):
        super(myQTabBar, self).__init__(*args, **kargs)

        self.setMovable(True)
        self.installEventFilter(self)

    def eventFilter(self, source, event):

        if event.type() == QtCore.QEvent.Type.MouseMove:

            if source.currentIndex() == 0: # Block MouseMove for first tab.
                return True

            else: # For remaining tabs:

                  # block MouseMove if the left edge of the moving tab goes
                  # farther to the left than the right edge of first tab.

                moving_leftEdge = event.pos().x() - self.edge_offset
                fixed_rightEdge = self.tabRect(0).width()

                if moving_leftEdge < fixed_rightEdge:
                    return True

        elif event.type() == QtCore.QEvent.Type.MouseButtonPress:

            # Get mouse click horizontal position.
            xclick = event.pos().x()

            # Get the left edge horizontal position of the targeted tab.
            xleft = self.tabRect(self.tabAt(event.pos())).x()

            # Compute and store offset between mouse click horizontal
            # position and the left edge of the targeted tab
            self.edge_offset = xclick - xleft

        return QtGui.QWidget.eventFilter(self, source, event)

class myQTabWidget(QtGui.QTabWidget):
    def __init__(self, *args, **kargs):
        super(myQTabWidget, self).__init__(*args, **kargs)

        tab_bar = myQTabBar()
        self.setTabBar(tab_bar)

        self.addTab(QtGui.QWidget(), 'Tab1')
        self.addTab(QtGui.QWidget(), 'Tab2')
        self.addTab(QtGui.QWidget(), 'Tab3')

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    instance1 = myQTabWidget()
    instance1.show()
    sys.exit(app.exec_())

rawDescription: PySide Qt4 - Qtabwidget - Disable drag and drop of a single q tab widget


code:
# create everything that will be inside the canvas
...

# next, cause the window to be drawn, so the frame will auto-size
self.update_idletasks()

# now, tell the canvas to scroll everything that is inside it
self.mastercanvas.configure(scrollregion=self.mastercanvas.bbox("all"))

rawDescription: Horizontal Scrollbar not working in Python TKinter Frame


code: add = functools.partial(map, lambda obj : obj.value + 1)

rawDescription: How to add value to attribute of all objects which are in list

description: Add value to attribute of all objects which are in list


code:
def callback(source=source):
    data = source.get('data')
    f = cb_obj.get('value')
    data['x'] = [0.9, 0.8, 0,7]
    data['y'] = [1,   2,   3  ]
    source.trigger('change')

rawDescription: Interactive browser plot in Python 3.5 using bokeh/flexx pyscript


code:
from datetime import datetime
from django.utils import formats
date_joined = datetime.now()
formatted_datetime = formats.date_format(date_joined, "SHORT_DATETIME_FORMAT")

rawDescription: Django: how to get format date in views?

description: Django: how to get format date in views


code:
from django.contrib.sessions.models import Session
class SessionAdmin(ModelAdmin):
    def _session_data(self, obj):
        return obj.get_decoded()
    list_display = ['session_key', '_session_data', 'expire_date']
admin.site.register(Session, SessionAdmin)

rawDescription: Django, how to see session data in the admin interface


code:
def reportCSV(t):
    result = []
    for t_key, t_value in t.iteritems():
        for p_key, p_value in t_value.iteritems():
            for w_key, w_value in p_value.iteritems():
                row_data = t_key, p_key, w_key, w_value
                result.append(','.join(row_data))
    return '\n'.join(result)

rawDescription: Pythonic / itertools way to go through a dict?


code:
sentence = "I do not like sentences like this sentence"
unique = list()
idx = list()

for word in sentence.split():
   if not word in unique:
      unique.append(word)
   i = unique.index(word)
   idx.append(i)

s = "" # the reconstructed sentence
for i in idx:
   s = s + unique[i] + " "

print(s)

rawDescription: How to recreate a sentence from the list of unique words and the position

description: Recreate a sentence from the list of unique words and the position


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons

x = [50, 50]

fig, axarr = plt.subplots(3)

# draw the initial pie chart
axarr[0].pie(x,autopct='%1.1f%%')
axarr[0].set_position([0.25,0.4,.5,.5])

# create the slider
axarr[1].set_position([0.1, 0.35, 0.8, 0.03])
risk = Slider(axarr[1], 'Risk', 0.1, 100.0, valinit=x[0])

# create some other random plot below the slider
axarr[2].plot(np.random.rand(10))
axarr[2].set_position([0.1,0.1,.8,.2])

def update(val):
    axarr[0].clear()
    axarr[0].pie([val, 100-val],autopct='%1.1f%%')
    fig.canvas.draw_idle()

risk.on_changed(update)

plt.show()

rawDescription: refresh my piechart using matplotlib?

description: Refresh my piechart using matplotlib


code:
import pygame
import math
import random
pygame.init()

screen=pygame.display.set_mode((300,300))
screen.fill((255,255,255))

pos1=random.randrange(300), random.randrange(300)
pos2=random.randrange(300), random.randrange(300)

pygame.draw.line(screen, (0,0,0), pos1, pos2)

arrow=pygame.Surface((50,50))
arrow.fill((255,255,255))
pygame.draw.line(arrow, (0,0,0), (0,0), (25,25))
pygame.draw.line(arrow, (0,0,0), (0,50), (25,25))
arrow.set_colorkey((255,255,255))

angle=math.atan2(-(pos1[1]-pos2[1]), pos1[0]-pos2[0])
##Note that in pygame y=0 represents the top of the screen
##So it is necessary to invert the y coordinate when using math
angle=math.degrees(angle)

def drawAng(angle, pos):
    nar=pygame.transform.rotate(arrow,angle)
    nrect=nar.get_rect(center=pos)
    screen.blit(nar, nrect)

drawAng(angle, pos1)
angle+=180
drawAng(angle, pos2)
pygame.display.flip()

rawDescription: Rotation based on end points

description: Rotation based on end points