code:
request = webapp.Request({
    "wsgi.input": StringIO.StringIO(),
    "CONTENT_LENGTH": 0,
    "METHOD": "GET",
    "PATH_INFO": "/",
})
response = webapp.Response()
handler = MainHandler()
handler.initialize(request, response)
handler.get()
self.assertEqual(response.out.getvalue(), "Home Page")

rawDescription: UnitTesting the webapp.RequestHandler in GAE - Python


code:
def my_sort(a_list):
    changes_exist = True
    while changes_exist:
         changes_exist = False
         for i in range(len(a_list)-1):
             if a_list[i] > a_list[i+1]:
                a_list = do_swap(a_list,i,i+1)
                changes_exist = True
    return a_list

rawDescription: Python, Arranging lists in list without using .sort()


code:
def edit_notification(request):
    foo = request.GET.get('foo')
    ...

rawDescription: django view method signature is it possible to match GET parameters?

description: Django view method signature is it possible to match GET parameters


code:
uri = self.calendar.GetAlternateLink().href
batch_uri = uri + u'/batch'
calendar_service.ExecuteBatch(request_feed, batch_uri)

rawDescription: Using ExecuteBatch from Python on Google Calendars API


code:
import re

pattern = 'CCNNNGG'
regex = re.compile(pattern.replace('N', '[ACGT]'))
for record in SeqIO.parse(...):
    if re.search(regex, record.seq) is not None:
        my_sequences.append(record)

rawDescription: Filtering a FASTA file based on restriction-sequence with BioPython


code:
class NotebookWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="FlowBox Test")

        #Create Application Window
        self.set_border_width(10)
        self.set_default_size(400, 400)
        self.set_position(Gtk.WindowPosition.CENTER)

        #Add tabbed window
        self.nbook = Gtk.Notebook()
        self.add(self.nbook)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        club_box = Gtk.FlowBox()
        club_box.set_valign(Gtk.Align.START)
        club_box.set_max_children_per_line(30)
        club_box.set_selection_mode(Gtk.SelectionMode.SINGLE)
        club_box.set_activate_on_single_click(True)

        self.buttons = []
        for club in range(0, 55):
            button = Gtk.Button(label=club)
            club_box.add(button)
            button.connect('clicked', self.on_button_clicked)  # new callback
            self.buttons.append(button)

        vbox.pack_start(club_box, True, True, 0)

        self.out_message = Gtk.Label(label="\n")
        vbox.pack_start(self.out_message, True, True, 0)

        label = Gtk.Label()
        label.set_markup("<b><big>Clubs</big></b>")
        self.nbook.append_page(vbox, label)

    def on_button_clicked(self, button):
        for i in range(len(self.buttons)):
            if self.buttons[i] == button:
                print('button at index {}'.format(i))
                break

win = NotebookWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()

Gtk.main()

rawDescription: Gtk FlowBox - buttons in box clickable area tiny


code:
bisect.bisect(x, y)
x[:bisect.bisect(x, y)]
x[bisect.bisect(x, y):]

rawDescription: Finding values from a list that are higher and lower than a certain value


rawDescription: Python sort dictionary of Lat / Lons for Footprint


code:
def permCount(permList):
    condition = ' OR '.join(['(A=? AND B=? AND C=?)'
                             for row in permList])
    sql = "SELECT Count(*) FROM Table WHERE {c}".format(
        c=condition)
    args = sum(permList, [])
    cursor.execute(sql, args)

rawDescription: Dynamically Generating SQL Queries with Python and SQLite3


rawDescription: regex named group starting with but not ends with

description: Regex named group starting with but not ends with


code:
for root, dirs, files in os.walk('A Folder'):
    for f in files:
        fname = os.path.join(root, f)
        new_path = os.path.normpath(fname.replace('A Folder', ''))
        myzip.write(fname, new_path)

rawDescription: Python - os.walk certain file types into an existing ZipFile


rawDescription: Code like this in Python: a_list[i, j] = 3


code:
n = 257
n_bytes = n.to_bytes(2, "little")
n_again = int.from_bytes(n_bytes, "little")
n_again == n

rawDescription: Python 3 how to convert a large number expressed as bytes into an integer?


code:
kinds = (("p_audio", ".mp3"), ("p_video", ".flv"), ("p_swf", ".swf"))
extra_context.update((key, False) for key, _ in kinds)

for key, ext in kinds:
    entries = plate.parts.filter(content__iendswith=ext)
    if entries:
        extra_context[key] = entries[0]
        break

rawDescription: can this python be shorter

description: Can this python be shorter


code:
f1 = open('fileInput', 'r')
f2 = open('fileInput+".tmp"', 'w')
for line in f1:
    if line[:-1].endswith("invalid"):
        f2.write("\t".join(line.split("\t")[:2] + ["reviewed", "rd"]) + "\n")
    else:
        f2.write(line)
f1.close()
f2.close()

rawDescription: find and replace whole line python

description: Find and replace whole line python


code: total_profiles = persons.objects.all().exclude(id__in = blocked_list.values_list('id', flat=True))

rawDescription: exclude a query result in another query

description: Exclude a query result in another query


code:
import itertools
import operator

def code_counter(table, codes):
    for key, group in itertools.groupby(table, key=operator.itemgetter('ID')):
        group_codes = [item['CODE'] for item in group]

        yield [group_codes.count(code) for code in codes]

if __name__ == '__main__':
    cursor.execute("SELECT * FROM table1")
    table1 = cursor.fetchall()

    cursor.execute("SELECT CODE FROM table2")
    codes = [code.get('code') for code in cursor.fetchall()]

    for chunk in code_counter(table1, codes):
        print(chunk)

rawDescription: Efficient counting of word occurrences in Python


code:
arr = np.array([0,0,0,0,0,1,1,1,1,1])
want_frac = 0.2
n = int(round(arr.sum() - want_frac * len(arr)))
indices_to_flip = np.random.choice(arr.nonzero()[0], n, replace=False)
arr[indices_to_flip] = 0
arr
arr.mean()

rawDescription: Randomly re-assign 1's to 0's to reach a specified ratio


rawDescription: N dimensional arrays - Python/Numpy

description: N dimensional arrays - Python/Numpy


code:
hmag = np.array(hmag)
jmag = np.array(jmah)

colorjh = jmag - hmag
idx_c = (colorjh > 0) & (colorjh < 1) # where condition on c is met
idx_h = (hmag > 10) & (hmag < 13) # where condition on h is met
idx = idx_c & idx_h # where both conditions are met

plt.scatter(colorjh[idx], hmag[idx], c='g', s=1, alpha=0.05)

rawDescription: How to slice up a numpy array with inequalities?

description: Slice up a numpy array with inequalities


code:
row = "Power Density,=,(n - 232) * 4.182e-005 W/cm^2".split(',')
expr = row[2].replace( ' W/cm^2', '')
# f = eval("lambda n:" + expr)  # based on your original idea
exec("def f(n): return " + expr)  # more flexible
print(f(0))
# -0.00970224

rawDescription: How can I convert a string into a function in Python?

description: Convert a string into a function in Python


code:
from django.db.models import Sum

def list_invoices(request):
    invoices = Item.objects.all().annotate(subtotal=Sum('invoiceline__price'))

rawDescription: Django sub queries

description: Django sub queries


code:
b = tk.Button(root, text="bla")
b.grid(row=0, column=0, sticky="nwes")
root.columnconfigure(0, weight=1)

rawDescription: (Python 3.4 Tkinter) Button grid filling issue


code: min((idx for idx in indexes if not visited[idx]), key=lambda idx: dist[idx])

rawDescription: In python, find minimum subject to a constraint?


code:
matching_objects = News.objects.filter(title="SomeText")
# this means the query returned at least one result
self.assertNotEqual(matching_objects.count(), 0)

rawDescription: Django queryset - get created object from database and equal the values


rawDescription: Edit the value of every Nth item in a list


code:
for i, (word, frequency) in enumerate(top_words, start=1):
    print("%s %d %d" % (word, i, frequency))

rawDescription: How to print out the rank number of a word?

description: Print out the rank number of a word


code: count_list.sort(key=lambda x: (-x[1], x[0]))

rawDescription: Sorting a list of two element tuples numerically and alphabetically


code:
def delete(request):
    if request.method != 'POST':
        raise HTTP404 # don't forget to import
    else:
        docId = request.POST.get('doc-id', None)

    if docId is not None:
        docToDel = Document.objects.get(pk=docId)

        # delete the file using docToDel.docfile

        docToDel.delete()

    return HttpResponse('Whatever message you want.')

rawDescription: django python document object listing even deleted files

description: Django python document object listing even deleted files


rawDescription: Pandas: Check if row exists with certain values


code:
import re
re.search('name', 'Name', re.IGNORECASE)
re.search('name', 'nAMe', re.IGNORECASE)
re.search('name', 'NAme', re.IGNORECASE)

rawDescription: How to use regular expressions in python to search for all capitalization combinations

description: Use regular expressions in python to search for all capitalization combinations


code: a, b, c = s.split('\n\n')

rawDescription: parsing a string of ascii text into separate variables

description: Parsing a string of ascii text into separate variables


code:
from django.contrib.auth.models import User

def validate_for_fs(value): # <-- If the value string doesn't meet a condition required to be a name on the filesystem then throw a ValidationError
    if foo_condition_not_met:
        raise ValidationError(u'foo is not true for %s' % value)
    if bar_condition_not_met:
        raise ValidationError(u'bar is not true for %s' % value)

for field in [f for f in User._meta.fields if f.name in ['first_name','last_name','email']]:
    field.validators.append(validate_for_fs)

rawDescription: Django User model validators

description: Django User model validators


code:
m = myModel(**jsondata)
m.full_clean()

rawDescription: Django/ python validate JSON

description: Django/ python validate JSON


code:
def call_by_name(self, method_name):
    method = getattr(self, method_name)
    method()

rawDescription: How to eval a member function name to a function object?

description: Eval a member function name to a function object


code:
demo_page = '''
    data:text/html,
    <!doctype html>

        <meta charset="utf-8">
        <title>Test "How to load up PhantomJS with a Python string"</title>

        How to load up PhantomJS with a Python string

'''

driver = webdriver.PhantomJS()
driver.get(demo_page)

driver.save_screenshot('screenshot.png')
driver.quit()

description: Load up PhantomJS with a Python string


rawDescription: parsing words in string prefaced by 'password' with regex

description: Parsing words in string prefaced by 'password' with regex


code:
def initialise_cache(vertices, s):
    cache = empty(vertices)
    cache[:] = float("inf")
    cache[s] = 0
    return cache

adjacency_matrix = zeros((vertices, vertices))
adjacency_matrix[:] = float("inf")
for line in file.readlines():
    tail, head, weight = line.split(" ")
    adjacency_matrix[int(head)-1][int(tail)-1] = int(weight)

n = vertices
shortest_paths = []
s=2

cache = initialise_cache(vertices, s)
for i in range(1, vertices):
    previous_cache = cache
    combined = (previous_cache.T + adjacency_matrix).min(axis=1)
    cache = minimum(previous_cache, combined)

shortest_paths.append([s, cache])

rawDescription: Using vectorisation with numpy for the Bellman-Ford algorithm


code:
import numpy as np
collection = [(1, 200, 9),
              (2, 300, 8),
              (3, 400, 7)]
collection = np.array(collection)
def f(d, c, v):
    # d: collection, c: column, v: value
    if np.any(d[:, c]==v): return d[d[:, c]==v]
    return 'None'
f(collection, 0, 1)
f(collection, 1, 300)
f(collection, 2, 250)

rawDescription: Efficient data structure of objects in python for lookup based on any object member variable


code:
def xyz():
    if not messagebox.askyesno("Title","Some text"):
        exit()
root.after(10,xyz) #show the messagebox after root.mainloop()
root.mainloop()

rawDescription: Python Tkinter entry widget won´t accept input


code:
import sys
sys.path.append("/path/to/lab03")
from lab import TT

rawDescription: importing module

description: Importing module


code:
msg = bytearray()  # New empty byte array
# Append data to the array
msg.extend(b"blah")
msg.extend(b"foo")

rawDescription: Python 3 How do I 'declare' an empty `bytes` variable


code:
class AdvertismentAdmin(admin.ModelAdmin):
   def save_model(self, request, obj, form, change):
      if obj.category:
        category_list=[]
        category = obj.category
        category_list.append(category)
        for parent in category.get_ancestors():
            if parent not in category_list:
                category_list.append(parent)
        form.cleaned_data['all_categories'] = category_list
        super(AdvertismentAdmin, self).save_model(request, obj, form, change)

rawDescription: Django, Add value to ManyToManyField when save changes of the model


code:
smtp = smtplib.SMTP(mailhost)
smtp.starttls()

rawDescription: Sending mail with SSL with Python 2.3

description: Sending mail with SSL with Python 2.3


code:
class Question(models.Model):

    def can_answer(self, user):
        return Answer.filter(question=self, user=user).count() < 3

rawDescription: In Django, how to limit entries from each user to a specific number N (N > 1)?


code:
mpa = dict.fromkeys(range(32))
'abc\02de'.translate(mpa)

rawDescription: Removing control characters from a string in python


code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

class Group(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    group_id = db.Column(db.ForeignKey(Group.id))
    group = db.relationship(Group, backref='users')

db.create_all()
db.session.add(User(group=Group()))
db.session.commit()
u = User.query.get(1)
print(u.group)

rawDescription: Access SQLAlchemy model linked with foreign key


code:
...
lock = Lock()
...
with (lock):
  # This code will only be executed by one single thread at a time
  # the lock is released when the thread exits the 'with' block
  ...

rawDescription: Monitor thread synchronization in python


code:
xRng = range(a[0],b[0]+1)
yRng = range(a[1],b[1]+1)
zRng = range(a[2],b[2]+1)
g = [(a,b,c) for a in xRng for b in yRng for c in zRng]

rawDescription: Create 3D Grid from opposite vector coordinates


code: [[w for w in L if len(w) == num] for num in set(len(i) for i in L)]

rawDescription: Python: split list of strings to a list of lists of strings by length with a nested comprehensions


code:
class ResponseCreate(CreateView):
    model = Response
    form_class = ResponseForm

rawDescription: Excluding Fields in Django Class Based Views Not Working


code:
from itertools import groupby, count
nums = [1, 2, 3, 4, 8, 10, 11, 12, 17]
[list(g) for k, g in groupby(nums, key=lambda n, c=count(): n - next(c))]

rawDescription: Python - find incremental numbered sequences with a list comprehension


rawDescription: Python, pygame - gamepad with 8 way d-pad


code:
from cStringIO import StringIO
f = StringIO('foo')
f.read()

rawDescription: How do I wrap a string in a file in Python?

description: Wrap a string in a file in Python


code:
class FileDialog(QtGui.QFileDialog):
    def __init__(self, *args):
        QtGui.QFileDialog.__init__(self, *args)
        self.setOption(self.DontUseNativeDialog, True)
        self.setFileMode(self.ExistingFiles)
        btns = self.findChildren(QtGui.QPushButton)
        self.openBtn = [x for x in btns if 'open' in str(x.text()).lower()][0]
        self.openBtn.clicked.disconnect()
        self.openBtn.clicked.connect(self.openClicked)
        self.tree = self.findChild(QtGui.QTreeView)

    def openClicked(self):
        inds = self.tree.selectionModel().selectedIndexes()
        files = []
        for i in inds:
            if i.column() == 0:
                files.append(os.path.join(str(self.directory().absolutePath()),str(i.data().toString())))
        self.selectedFiles = files
        self.hide()

    def filesSelected(self):
        return self.selectedFiles

rawDescription: Multiple files AND folder selection in a QFileDialog?


code:
import re
s="abc123abcfndfabc1234drfabc"
re.findall(r'(?<=abc).*?(?=abc)', s)

rawDescription: How do I get lines between same pattern using python regex

description: Get lines between same pattern using python regex


code:
InfoJson = json.loads(response)
assetInfoJson = InfoJson["assets"]["730"]["2"]
listingInfoJson = InfoJson["listinginfo"]

for key, value in listingInfoJson.iteritems():
    listingId = key
    try:
        subTotal = value["converted_price"]
        feeAmount = value["converted_fee"]
        asset = value["asset"]["id"]
    except KeyError:
      continue

    if asset in assetInfoJson:
        # Get asset details if it's present in the assetInfoJson dict
        assetInfo = assetInfoJson[asset]
        try:
            image = assetInfo["icon_url"]
            item = assetInfo["market_hash_name"]
        except KeyError:
          continue

        print ("Found Matching asset :",assetId)
        print ("Found Matching name : %s, listingid : %s, subtotal : %s" % (item, listingId, subTotal))

rawDescription: Python, comparing JSON iterations with multiple keys and values


code:
import sublime, sublime_plugin

class PositionListener(sublime_plugin.EventListener):
  def on_selection_modified(self,view):
    text = "Position: "
    sels = view.sel()
    for s in sels:
        text += " " + str(s.begin())
        if not s.empty():
            text += "-" + str(s.end()) + " "
    view.set_status('exact_pos', text)

rawDescription: Is it possible to show the exact position in Sublime Text 2?


code:
class Foo(object):
  def f(x): return x * x

dis.dis(Foo)

rawDescription: How to Disassemble an object creation in Python?


code: max(my_dict.items(), key=lambda x: x[1]['last_event'])[0]

rawDescription: In python - Find the maximum date in a nested dictionary


code:
from django.core import mail

assert len(mail.outbox) == 1
assert mail.outbox[0].subject == 'Subject here'

rawDescription: Using lettuce, how can I verify that an email sent from a Django web application has the correct contents?


code:
if '4.2.1' in pl.values():
   print ("We're good!")
else:
   print ("No good")

rawDescription: Looking for one dict value, if it isn't there - run another module


code:
import numpy as np
import matplotlib.pylab as pl

a = np.random.random((10,10))
b = np.random.random((10,10))
c = np.random.random((10,10))
x = np.linspace(0,1,10)
y = np.linspace(0,1,10)

fig = pl.figure()

# Adjust the axis position, to create sufficient room for two colorbars:
#                   L    B    R    T    ws  hs
fig.subplots_adjust(0.09,0.19,0.87,0.94,0.04,0.3)

# Dummy contour and scatter plots
ct  = pl.contourf(x, y, b)
sc  = pl.scatter(a, b, c=c)

# Get current ax and its position:
ax = pl.gca()
axp = ax.get_position()

# Set the colorbar axes relative to figure ax
cax_h = fig.add_axes([axp.x0, axp.y0-0.1, axp.x1-axp.x0, 0.02])
cax_v = fig.add_axes([axp.x1+0.02, axp.y0, 0.02, axp.y1-axp.y0])

pl.colorbar(ct, cax=cax_v, orientation='vertical')
pl.colorbar(sc, cax=cax_h, orientation='horizontal')

rawDescription: why are my colorbars out of the image's range?

description: Why are my colorbars out of the image's range


code: Document.toprettyxml(self, indent='\t', newl='\n', encoding=None)

rawDescription: Changing document's attributes in Python's xml.dom.minidom


code:
class User(UserMixin, Model):
    username = CharField(unique=True)
    email = CharField(unique=True)
    password = CharField(max_length=100)
    joined_at = DateTimeField(default=datetime.datetime.now)
    is_admin = BooleanField(default=False)

    class Meta:
        database = DATABASE
        order_by = ('-joined_at', )

    def get_posts(self):
        return Post.select().where(Post.user == self)

    def get_stream(self):
        return Post.select().where(
            (Post.user << self.following()) |
            (Post.user == self)
        )

    def following(self):
        """ The users we are following """
        return (
            User.select().join(
                Relationship, on=Relationship.to_user
            ).where(
                Relationship.from_user == self
            )
        )

    def followers(self):
        """ get users following """
        return (
            User.select().join(
                Relationship, on =Relationship.from_user
            ).where(
                Relationship.to_user == self
            )
        )

    @classmethod
    def create_user(cls, username, email, password, admin=False):
        try:
            with DATABASE.transaction():
                cls.create(
                    username=username,
                    email=email,
                    password=generate_password_hash(password),
                    is_admin=admin)
        except IntegrityError:
            raise ValueError("user already exists")

rawDescription: Python Flask App building social network


code:
import wx

class UpperTextCtrl(wx.TextCtrl):
    def __init__(self, *args, **kwargs):
        super(UpperTextCtrl, self).__init__(*args, **kwargs)
        self.Bind(wx.EVT_TEXT, self.on_text)
    def on_text(self, event):
        event.Skip()
        selection = self.GetSelection()
        value = self.GetValue().upper()
        self.ChangeValue(value)
        self.SetSelection(*selection)

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None, -1, 'Uppercase Text Control')
        panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        text = UpperTextCtrl(panel, -1, style=wx.TE_MULTILINE)

        # change the font
        font = text.GetFont()
        font.SetPointSize(12)
        text.SetFont(font)

        sizer.Add(text, 1, wx.EXPAND|wx.ALL, 10)
        panel.SetSizer(sizer)

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = Frame()
    frame.Show()
    app.MainLoop()

rawDescription: wxPython TextCtrl transform to UPPERCASE

description: WxPython TextCtrl transform to UPPERCASE


rawDescription: Python - Why is the dictionary shortened when mapping two lists?


code:
Animals = ["phant", "eleph", "tiger", "turtle", "zebra", "ostrich"]
Dict = {"horse":1, "elephant":1, "iger":1, "ostrich":1}

for name in Animals:
    if name in Dict:
        Dict[name]=Dict[name]+1
    else:
        for key, val in Dict.items():
            if len(name) < len(key):
                m = re.search (name, key)
                if m != None:
                    print ("Found match!", name)
                    Dict[key] = Dict[key] + 1
                    break
            elif len(name) > len(key):
                m = re.search (key, name)
                if m != None:
                    print ("Found match!", name)
                    Dict[name] = Dict.pop(key) + 1
                    Dict[name] = Dict[name] + 1
                    break
        else:                 # this line and the one below it are new
            Dict[name] = 1

rawDescription: Conditional merging in Python3

description: Conditional merging in Python3


code:
df
cond = (df.A > .6) & (df.B > .3)
df[cond]
df[~cond]

rawDescription: pyPandas functionality request: reverse/negative df.drop

description: PyPandas functionality request: reverse/negative df.drop


code:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import scrapy
from justeat.items import DmozItem

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["just-eat.co.uk"]
    start_urls = ["http://www.just-eat.co.uk/belfast-takeaway", ]

    def parse(self, response):
        for sel in response.xpath('//*[@id="searchResults"]'):
            names = sel.xpath('//*[@itemprop="name"]/text()').extract()
            names = [name.strip() for name in names]
            addresses = sel.xpath('//*[@class="address"]/text()').extract()
            addresses = [address.strip() for address in addresses]
            result = zip(names, addresses)
            for name, address in result:
                item = DmozItem()
                item['name'] = name
                item['address'] = address
                yield item

rawDescription: Scrapy csv output is on a single line per item


code:
size = 8
[bool(235 & (1 << size - i - 1)) for i in xrange(size)]

rawDescription: Bitmask parsing in python using only standard library


code: score, rid, title, artist = results[0]

rawDescription: Multiple print output, printing only one of them


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self._size = self.ClientSize
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Show()

    def OnSize(self, event):
        if self._size[0] != self.ClientSize[0]:
            self._size = self.ClientSize[0], self.ClientSize[0]
        elif self._size[1] != self.ClientSize[1]:
            self._size = self.ClientSize[1], self.ClientSize[1]

        if self._size != self.ClientSize:
            self.ClientSize = self._size

if __name__ == '__main__':
    app = wx.PySimpleApp()
    win = MainWindow()
    app.MainLoop()

rawDescription: wxPython keeping a wx.Frame square?

description: WxPython keeping a wx.Frame square


code:
if stateid in states:
    print(states[stateid])

rawDescription: Having trouble matching dict key with value


code:
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test.client import Client
from django.test import TestCase

class ProcessAllTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

    def test_login_required(self):
        response = self.client.get(reverse('process_all'))
        self.assertRedirects(response, '/login')

    def test_get_method(self):
        self.client.login(username='john', password='johnpassword')
        response = self.client.get(reverse('process_all'))
        self.assertRedirects(response, '/reports/messages')

        # assert no messages were sent

    def test_post_method(self):
        self.client.login(username='john', password='johnpassword')

        # add pending messages, mock sms sending?

        response = self.client.post(reverse('process_all'))
        self.assertRedirects(response, '/reports/messages')

        # assert that sms messages were sent

rawDescription: Django Nose how to write this test?

description: Django Nose how to write this test


code:
class User(AbstractUser):
    ...
    provider = models.OneToOneField(Provider, null=True)

class Provider(models.Model):
    ...

rawDescription: Django - Creating two user types, where one type can be both


code:
from django.template.defaultfilters import slugify
for obj in MyModel.objects.all():
    obj.slug = slugify(obj.title)
    obj.save()

rawDescription: Generate slug field in existing table

description: Generate slug field in existing table


code:
torfile = lt.create_torrent(h.get_torrent_info())
f = open("torrentfile.torrent", "wb")
f.write(lt.bencode(torfile.generate()))
f.close()

rawDescription: Python libtorrent creates empty torrent with magnet link


code:
def let_user_pick(options):
    print("Please choose:")
    for idx, element in enumerate(options):
        print("{}) {}".format(idx+1,element))
    i = input("Enter number: ")
    try:
        if 0 < int(i) <= len(options):
            return int(i)
    except:
        pass
    return None

rawDescription: Command line: Show list of options and let user choose


code: [sum(t) for t in zip(*dictName.itervalues())]

rawDescription: Python elementwise addition from a dict

description: Python elementwise addition from a dict


code:
from itertools import groupby

groupped = groupby(trs, key=lambda tag: tag.attrib.get('class'))

groups = []
for key, group in groupped:
    groups.append(list(group))

rawDescription: Group list of lxml elements by neighbouring attribute values


code:
#Very simple minded hash
def hashval(str, siz):
    hash = 0
    # Take ordinal number of char in str, and just add
    for x in str: hash += (ord(x))
    return(hash % siz) # Depending on the range, do a modulo operation.

print(hashval('stack', 33))

rawDescription: Hash function that can return a integer range based on string


code:
alist = ['foo','spam', 'bar']
[prefix+elt for elt in alist for prefix in ('','ok.') ]

rawDescription: Prepend prefix to list elements with list comprehension


code:
from itertools import combinations
array = [1, 2, 3, 4]
[i * j for i, j in combinations(array, 2)]

rawDescription: Find all products produced by 2 unique elements of an array (python)


code:
class Fruit:

   def __init__(self, FruitName):
       self.name = FruitName
       self.facts = []

   def addfact(self, FruitName):
       ...

rawDescription: Explicitly creating a new object in Python


code:
import turtle
turtle.Turtle()
turtle.bgcolor('grey')

# decide what your small circle will look like
smallColour = "red"
smallRadius = 5

# draw the small circle
turtle.color(smallColour)
turtle.penup()
turtle.setpos(0, -smallRadius)
turtle.pendown()
turtle.circle(smallRadius)

# decide what your large circle will look like
largeColour = "white"
largeRadius = 100

# draw the large circle
turtle.color(largeColour)
turtle.penup()
print(turtle.pos())
turtle.setpos(0, -largeRadius)
print(turtle.pos())
turtle.pendown()
turtle.circle(largeRadius)

turtle.penup()
turtle.setpos(0, 0)

rawDescription: Creating multiple colored turtles in one window in editor on Python 3.4


code:
f1 = [
     thingies[0][0] + thingies[1][0] + thingies[0][1] + thingies[1][1]
     for thingies in zip(parent_1, parent_2)
] * 4
print(f1)

rawDescription: Quick thought regarding .split()

description: Quick thought regarding .split()


code: preserveAspectRatio = "xMinYMin meet"

rawDescription: Position SVG Rectangle absolutely outside of viewbox using python


code:
g = sns.FacetGrid(teacherValueFinal3, row='Grade Level', col='Course',margin_titles=True)
g.map(sns.violinplot, '2013-2014 Assessment Score', 'Gender', color="RdBu")
g.set_axis_labels('Gender', '2013-2014 Assessment Score')

rawDescription: Change the axes labels after drawing a violinplot on a FacetGrid


code:
df1.Referer = df1.groupby(['Cust'])['Referer'].transform('first')
df1

rawDescription: Use Loop to modify Pandas Dataframe based on condition in data


code:
df2 = df[['A','B','C']].drop_duplicates() #get unique values of ABC
df2 = df2.reset_index(drop = True).reset_index()  #reset index to create a column named index
df2=df2.rename(columns = {'index':'ID'}) #rename index to ID
df = pd.merge(df,df2,on = ['A','B','C'],how = 'left') #append ID column with merge

rawDescription: Pandas DataFrame Groupby to get Unique row condition and identify with increasing value up to Number of Groups


rawDescription: Dealing with string case and diacritics in python


code:
from scapy.all import *

packet = IP(dst="127.0.0.1")/Raw("\xaa\xbb\x00\x02")
send(packet)

rawDescription: Controlling packet injection contents at the byte level with Python and Scapy


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

b = 0.1
d = 0.75
a=1
c=1.5
def dX_dt(X, t=0, a=1, c=1.5):
    """ Return the growth rate of fox and rabbit populations. """
    return np.array([ a*X[0] -   b*X[0]*X[1] ,
                     -c*X[1] + d*b*X[0]*X[1] ])

t = np.linspace(0, 15,  1000)              # time
X0 = np.array([10, 5])          # initials conditions: 10 rabbits and 5 foxes

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)

l1, l2 = plt.plot(t, integrate.odeint(dX_dt, X0, t, (a, c)))

axcolor = 'black'
ax_a = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
ax_c = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)

sa = Slider(ax_a, 'a', 0.1, 10.0, valinit=1)
sc = Slider(ax_c, 'c', 0.1, 10.0, valinit=1.5)

def update(val):
    a = sa.val
    c = sc.val
    x = integrate.odeint(dX_dt, X0, t, (a, c))
    l1.set_ydata(x[:,0])
    l2.set_ydata(x[:,1])
    fig.canvas.draw_idle()

sa.on_changed(update)
sc.on_changed(update)

plt.show()

rawDescription: Interactive countinuous plotting of an ODE model in Python


code:
last_host = None
hosts = []                # the list of hosts
host_responses = []       # the list of responses for each host
responses = []
for output in expandresults:
    if output.val is not None:
        if output.hostname != last_host:    # new host
            if last_host:    # only append host_responses after a new host
                host_responses.append(responses)
            hosts.append(output.hostname)
            responses = [output.val]        # start the new list of responses
            last_host = output.hostname
        else:                               # same host, append the response
            responses.append(output.val)
host_responses.append(responses)

for host, responses in zip(hosts, host_responses):
    self.WriteOut(host, ','.join(responses))

rawDescription: Combing through several large data structures of different classes in Python; How can I combine and store data I need while reducing memory usage?


code:
import netCDF4 as nc
import numpy as np
dout = nc.Dataset('testdset.nc4', mode='w', clobber=True, format="NETCDF4")
dout.createDimension('point', size=None)
dout.createDimension('realization', size=24)
for varname in ['mod_hs','mod_ws']:
    v = dout.createVariable(varname, np.short,
            dimensions=('point', 'realization'), zlib=False,chunksizes=[1000,24])
    v.scale_factor = 0.01
date = 1
end_date = 5000
n = 0
while date < end_date:
    sz=100
    dout.variables['mod_hs'][n:n+sz,:] = np.ones((sz,24))
    dout.variables['mod_ws'][n:n+sz,:] = np.ones((sz,24))
    n += sz
    date += 1
dout.close()

rawDescription: NetCDF file - why is file 1/3 size after fixing record dimension?


code:
import sys

def print_words(file_name):
    input_file = open(file_name, 'r')
    lines = input_file.readlines()
    lines = ' '.join(x for x in lines)
    print(lines)

if __name__ == '__main__':
    print_words(sys.argv[1])

rawDescription: How do I run a python file that takes a text file as input?

description: Run a python file that takes a text file as input


code:
def remove_signature(mail):
    payload = mail.get_payload()
    if isinstance(payload, list):
        for part in payload:
            if part.get_content_type().startswith('application/pkcs7-signature'):
                payload.remove(part)
    return mail

rawDescription: Using the Pythons email.message API, how do you remove a specific part of the message


code:
def partitionIndexes(totalsize, numberofpartitions):
    # Compute the chunk size (integer division; i.e. assuming Python 2.7)
    chunksize = totalsize / numberofpartitions
    # How many chunks need an extra 1 added to the size?
    remainder = totalsize - chunksize * numberofpartitions
    a = 0
    for i in xrange(numberofpartitions):
        b = a + chunksize + (i < remainder)
        # Yield the inclusive-inclusive range
        yield (a, b - 1)
        a = b

rawDescription: Get indices of roughly equal sized chunks


code: any(i.endswith(extension) for i in os.listdir(directory))

rawDescription: How do I tell if a folder contains a file with a specific extension?

description: Tell if a folder contains a file with a specific extension


code: self.canvas.itemconfig(line, dash=())

rawDescription: How to I change TKinter canvas line from dash to solid?


code:
procs = []
for url in urls:
    p = Process(target=get_stats, args=(url, d))
    p.start()
    procs.append(p)

for p in procs:
    p.join()

rawDescription: How do i get multiple processess to update the same dictionary in python multiprocess

description: Get multiple processess to update the same dictionary in python multiprocess


code:
import win32file
import win32api
win32file.MoveFileEx("/path/to/lockedfile.ext", None ,
                 win32file.MOVEFILE_DELAY_UNTIL_REBOOT)

rawDescription: Mark File For Removal from Python?

description: Mark File For Removal from Python


code:
import importlib

def some_topology_thing(topo_type):
    mod = importlib.import_module('topology_{}'.format(topo_type))
    return mod.Topology()

rawDescription: Import all modules in one folder and use them by one of its attributes


code: lm = sns.lmplot(x = "totalX", y = "NormI", hue = "Data Type", data = df, palette="Set1", legend_out=False, scatter_kws={"s": 100})

rawDescription: changing the marker size in python seaborn lmplot

description: Changing the marker size in python seaborn lmplot


code:
a = ET.Element('wp:author')
ET.dump(a)

rawDescription: Writing a custom XML file for the Wordpress Importer using lxml


code:
import os
os.spawnl(os.P_NOWAIT, "./program1.py", "hello")

rawDescription: Launch Multiple copies of a program

description: Launch Multiple copies of a program


code:
from gi.repository import Gtk, Gdk

class QuickSearch(Gtk.Bin):
    def __init__(self, *args, **kwargs):
        super(QuickSearch, self).__init__(*args, **kwargs)
        self.add(Gtk.Entry())

    def do_size_allocate(self, allocation):
        self.set_allocation(allocation)
        child_allocation = Gdk.Rectangle()
        border_width = self.get_border_width()
        child_allocation.x = allocation.x + border_width
        child_allocation.y = allocation.y + border_width
        child_allocation.width = allocation.width - 2 * border_width
        child_allocation.height = allocation.height - 2 * border_width
        self.get_child().size_allocate(child_allocation)

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
search = QuickSearch()
win.add(search)
win.show_all()
Gtk.main()

rawDescription: Extending from GtkBin

description: Extending from GtkBin


code:
def write_words(word1, word2):
    with open("output.txt", "a") as f :
        f.write(word1 + " - " + word2 + '\n')

rawDescription: What did I wrong here [Write to file in new line]?


code:
#constructor from form
def __init__(self, *args, **kwargs):
    user = kwargs.pop('user', None)
    super(ObjectForm, self).__init__(*args, **kwargs)
    if user:
        self.fields['rooms'].queryset = Room.objects.filter(room__venue_creator=user)

rawDescription: Filterig initial data in Django ManyToMany field


code:
class Person(models.Model):
    fist = models.CharField(max_length=20)
    last = models.CharField(max_length=20)

class Shirt(models.Model):
    color = models.CharField(max_length=10)
    quantity = models.PositiveSmallIntegerField(default=1)
    size = models.CharField(max_length=3)
    owner = models.ForeignKey(Person)

rawDescription: Django simle model implementation

description: Django simle model implementation


code:
c = get_config()
c.NotebookManager.save_script = True

rawDescription: Save ipython notebook as script programmatically


code: df.loc[(df.B == df.B.min()), 'A']

rawDescription: conditional selection of data in pandas dataframe

description: Conditional selection of data in pandas dataframe


code:
def get_user(request):
    from django.contrib.auth.models import AnonymousUser
    try:
        user_id = request.session[SESSION_KEY]
        backend_path = request.session[BACKEND_SESSION_KEY]
        backend = load_backend(backend_path)
        user = backend.get_user(user_id) or AnonymousUser()
    except KeyError:
        user = AnonymousUser()
    return user

rawDescription: Where in Django does a user become an AnonymousUser?


code:
x = u'[9:16 PM\xa0Erica: with images, \xa0\xa0and that seemed long to me anyway, 9:17 PM\xa0me: yeah, \xa0Erica: so feel free to make it shorter, \xa0\xa0or rather, please do,  9:18 PM\xa0nobody wants to read about that shit for 2 pages, \xa0me: :), \xa0Erica: while  browsing their site, \xa0me: srsly, \xa0Erica: unless of course your writing is magic,  \xa0me: My writing saves drowning puppies, \xa0\xa0Just plucks him right out and gives  them a scratch behind the ears and some kibble, \xa0Erica: Maine is weird, \xa0me: haha]'
x.encode('ascii', 'ignore')

rawDescription: Getting clean text from text/html documents using BeautifulSoup


code:
from argparse import RawTextHelpFormatter
parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)

rawDescription: Python argparse: Preformatted help text?

description: Python argparse: Preformatted help text


code:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import seaborn
seaborn.set() #make the plots look pretty

df = pd.DataFrame({'value': value, 'type': type})
df['dummy'] = 1
ag = df.groupby(['value','type']).sum().unstack()
ag.columns = ag.columns.droplevel()

ag.plot(kind = 'bar', colormap = cm.Accent, width = 1)
plt.show()

rawDescription: How to plot a histogram by different groups in matplotlib

description: Plot a histogram by different groups in matplotlib


code:
def __format__(self, fmt):
    if not isinstance(fmt, str):
        raise TypeError("must be str, not %s" % type(fmt).__name__)
    if len(fmt) != 0:
        return self.strftime(fmt)
    return str(self)

rawDescription: How does formatting a Python date object work?


code:
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt

labels, values = zip(*Counter(['A','B','A','C','A','A']).items())

indexes = np.arange(len(labels))
width = 1

plt.bar(indexes, values, width)
plt.xticks(indexes + width * 0.5, labels)
plt.show()

rawDescription: Using Counter() in Python to build histogram?


code: re.sub(r"[()\s]", lambda m: '-' if m.group().isspace() else '', a)

rawDescription: how to replace more than 1 pattern in re

description: Replace more than 1 pattern in re


code:
class MyClass(object):
   ...
   def model_fun(self,x,par): ...

obj = MyClass(...)
curve_fit(obj.model_fun, ...)

rawDescription: class method as a model function for scipy.optimize.curve_fit

description: Class method as a model function for scipy.optimize.curve_fit


code:
seq
{e: [e]+[i for i in seq if i != e] for e in seq}

rawDescription: Get a dict from a python list

description: Get a dict from a python list


code:
from multiprocessing.pool import ThreadPool
from multiprocessing import cpu_count

pool = ThreadPool(processes=cpu_count()*2)
pool.map(worker, users)

rawDescription: threading or multiprocessing for load test script

description: Threading or multiprocessing for load test script


code:
from win32com import client

excel=client.Dispatch("Excel.Application")
excel.Visible=True
book=excel.Workbooks.Open("c:/desktop/test.xlsx", False, True)
sheet=book.Worksheets(1)
chart=book.Charts.Add()
chart.SetSourceData(sheet.Range("$A:$B"))

chart.Move(Before=book.Worksheets("Sheet2"))
chart.Move(book.Worksheets("Sheet2"))#equivalent to previous line
chart.Move(book.Worksheets("Sheet2"), None)#also equivalent

chart.Move(After=book.Worksheets("Sheet2"))
chart.Move(None,book.Worksheets("Sheet2"))#equivalent to previous line

rawDescription: Excel win32com programming with Python. Passing Parameters to function


code:
class DeleteQueueItem(db.Model):
    """Model to keep track of items that will be deleted via task queue."""

    # URL path to the blog post is handled as key_name
    delete_when = db.DateTimeProperty()

    @classmethod
    def new(cls, key_name):
        delay = 120  # Seconds
        t = datetime.timedelta(seconds=delay)
        deadline = datetime.datetime.now() - t

        return cls(key_name=key_name, delete_when=deadline)

    def put(self, **kwargs):
      def _tx():
        taskqueue.add(url='/admin/task/delete_page',
                      countdown=delay,
                      params={'path': key_name},
                      transactional=True)
        return super(DeleteQueueItem, self).put(**kwargs)
      if not self.is_saved():
        return db.run_in_transaction(_tx)
      else:
        return super(DeleteQueueItem, self).put(**kwargs)

rawDescription: How to use a custom __init__ of an app engine Python model class properly?

description: Use a custom __init__ of an app engine Python model class properly


code:
# Code for thinning a binary image using Zhang-Suen algorithm
from scipy import weave
import numpy as np
import cv2
import sys

def _thinningIteration(im, iter):
    I, M = im, np.zeros(im.shape, np.uint8)
    expr = """
    for (int i = 1; i < NI[0]-1; i++) {
        for (int j = 1; j < NI[1]-1; j++) {
            int p2 = I2(i-1, j);
            int p3 = I2(i-1, j+1);
            int p4 = I2(i, j+1);
            int p5 = I2(i+1, j+1);
            int p6 = I2(i+1, j);
            int p7 = I2(i+1, j-1);
            int p8 = I2(i, j-1);
            int p9 = I2(i-1, j-1);

            int A  = (p2 == 0 && p3 == 1) + (p3 == 0 && p4 == 1) +
                     (p4 == 0 && p5 == 1) + (p5 == 0 && p6 == 1) +
                     (p6 == 0 && p7 == 1) + (p7 == 0 && p8 == 1) +
                     (p8 == 0 && p9 == 1) + (p9 == 0 && p2 == 1);
            int B  = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
            int m1 = iter == 0 ? (p2 * p4 * p6) : (p2 * p4 * p8);
            int m2 = iter == 0 ? (p4 * p6 * p8) : (p2 * p6 * p8);

            if (A == 1 && B >= 2 && B <= 6 && m1 == 0 && m2 == 0) {
                M2(i,j) = 1;
            }
        }
    }
    """
    weave.inline(expr, ["I", "iter", "M"])
    return (I & ~M)

def thinning(src):
    dst = src.copy() / 255
    prev = np.zeros(src.shape[:2], np.uint8)
    diff = None

    while True:
        dst = _thinningIteration(dst, 0)
        dst = _thinningIteration(dst, 1)
        diff = np.absolute(dst - prev)
        prev = dst.copy()
        if np.sum(diff) == 0:
            break

    return dst * 255

if __name__ == "__main__":
    src = cv2.imread("image.png")
    if src == None:
        sys.exit()
    bw = cv2.cvtColor(src, cv2.cv.CV_BGR2GRAY)
    _, bw2 = cv2.threshold(bw, 10, 255, cv2.THRESH_BINARY)
    bw2 = thinning(bw2)
    cv2.imshow("src", bw)
    cv2.imshow("thinning", bw2)
    cv2.waitKey()

rawDescription: How to effectively scan 2d numpy array?

description: Effectively scan 2d numpy array


code:
def rev(h):
    counter=len(h) - 1 # indexes of h go from 0 to len(h) - 1
    reverse=""
    while counter>=0: # changed to >=0
        reverse+=h[counter]
        counter -= 1
    return reverse

h=input('word\n\n');
revers = rev(h) # put rev(h) after the definition of rev!
print(revers) # actually print the result
# deleted your last line

rawDescription: Writing word backwards

description: Writing word backwards


code:
for i in range(1,len(nList)):
    for distance in nList[i]:
        outputLlist.append('{} metres, {} metres, {} seconds'.format(*distance))

rawDescription: How to use a 'for' loop to iterate nested-list index items in Python 2.7?

description: Use a 'for' loop to iterate nested-list index items in Python 2.7


code:
from django.db import models

class CommonInfo(models.Model):
    source = models.CharField(max_length=100, blank=True, null=True)
    total_size = models.FloatField(blank=True, null=True)
    number_of_files = models.FloatField(blank=True, null=True)
    number_of_files_transferred = models.FloatField(blank=True, null=True)

    def as_dict(self):
      return {
          "source": self.source,
          "total_size": self.total_size,
          "number_of_files": self.number_of_files,
          "number_of_files_transferred": self.number_of_files_transferred
      }

    class Meta:
        abstract = True

class Archive(CommonInfo):

    class Meta:
        db_table = 'archive'

class FullNightlyMetrics(CommonInfo):

    class Meta:
        db_table = 'full_nightly_metrics'

rawDescription: Django repetitive function in models

description: Django repetitive function in models


code:
def syncdb(path):
  print(green("Database Synchronization ..."))
  with cd(path):
    sudo('python manage.py syncdb', user='www-data')

def colstat(path):
  print(green("Collecting Static Files..."))
  with cd(path):
    sudo('python manage.py collectstatic --noinput', user='www-data')

def httpdrst():
  print(green("Restarting Apache..."))
  sudo('apachectl restart')

def srefresh():
  path = '/var/www/project'
  colstat(path)
  syncdb(path)
  httpdrst()

rawDescription: Fabric - Project path environment

description: Fabric - Project path environment


code:
# views.py

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse

@login_required
def index(request):
    return HttpResponse('Only registers will see this page')

# now you can add the stuff that you would want only the registered users to view,
# so basically if a new visitors tries to visit your site say at www.abc.com, he will first be redirected to the www.abc.com/login/ where he needs to create an account, once authenticated, he will then be redirected to the index page

rawDescription: how to set django root url as login url?

description: Set django root url as login url


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

x = np.array([[1,0],[0,1]])
plt.matshow(x, cmap='Blues')
plt.show()

rawDescription: Numpy Array to Graph

description: Numpy Array to Graph


code: del list1[:319]

rawDescription: remove the first several elements from a list python

description: Remove the first several elements from a list python


code:
class ajoutSource(CreateView):
    model = Source
    template_name = "pmd/ajouterSource.html"
    form_class = AjouterSourceForm
    success_url = reverse_lazy(ListerSources)

    def get_context_data(self, **kwargs):
        context = super(ajoutSource, self).get_context_data(**kwargs)
        context["ajoutersource"]=context["form"]
        return context

rawDescription: Django Class Based Views : Override form name


rawDescription: How to convert a datetime with time zone to the UTC time in python

description: Convert a datetime with time zone to the UTC time in python


code:
def innermost(lst):
    if not lst or not isinstance(lst[0], list):
        return lst
    return innermost(lst[0])
lst = [[[3,4,5,6]]]
innermost(lst)

rawDescription: I have a [ [ [3,4,5,6] ] ] , how to transform it to [3,4,5,6] in python?


code:
class MyUser(AbstractUser):
    def get_absolute_url(self):
        return ...

rawDescription: Set `get_absolute_url` in Django auth

description: Set `get_absolute_url` in Django auth


code:
def firstcheck():
    url = 'http://www.hacker.org/challenge/misc/minuteman.php'
    hogniergay = urlopen(url)
    data = hogniergay.read()
    hogniergay.close()
    global html
    html = data

rawDescription: One Minute Man, python 3

description: One Minute Man, python 3


code:
with open("users.txt", "a") as f:
    f.write(username + "\n")

rawDescription: Python: Open and write to a .txt file

description: Python: Open and write to a .txt file


code:
for i in range(len(paths)):
    pathlist = paths[i]
    for n in range(0, len(pathlist)):
        if pathlist[n] == 2:
            plist = list(pathlist)
            plist[n] = 4
            paths[i] = tuple(plist)
            print(paths[i])

rawDescription: Python: Replace Item in Tuple Converted to List


code:
qry = session.query(Option.optionsymbol).filter(and_
            (Option.underlying == stock,
                Option.quotedate == entry_date,
                Option.expiration == exp_date,
                Option.option_type== "put",
                Option.exchange == "*")
            ).order_by('abs(strike - %d)' % desired_strike)

rawDescription: SQLAlchemy order_by formula result

description: SQLAlchemy order_by formula result


code:
Text.position = rectangle.position + rectangle.size / 2
Text.position.X = Text.position.X - text.width / 2

rawDescription: Text in Rect - Pygame

description: Text in Rect - Pygame


code:
def my_lstrip(p, s):
     """Remove leading occurences of p from s
     Keyword arguments:
     p - pattern to remove
     s - input string

     >>> my_lstrip('f', 'foo')
     'oo'
     >>> my_lstrip('foo', 'foobar')
     'bar'
     >>> my_lstrip('foo', 'foofoofoobar')
     'bar'
     >>> my_lstrip('o', 'ooooofoo')
     'foo'
     >>> my_lstrip('fooo', 'foo')
     'foo'
     >>> my_lstrip('bar', 'foo')
     'foo'
     """
     return  my_lstrip(p, s[len(p):]) if s.startswith(p) else s

rawDescription: Need to make a function like .lstrip

description: Need to make a function like .lstrip


code:
words_starting_in_M = []
with open(filepath) as wordsfile:
    for line in wordsfile:
        if line.startswith("M"):
            words_starting_in_M.append(line.rstrip())

rawDescription: read only certain contents from a file

description: Read only certain contents from a file


code:
@event.listens_for(Client.name, 'set')
def update_mcodes(target, value, oldvalue, initiator):
    target.recalculate_mcodes(value)

rawDescription: How to update a relationship when another field is modified in SQLAlchemy

description: Update a relationship when another field is modified in SQLAlchemy


code:
l = [['a', 4], ['b', 2], ['c', 4], ['b', 8]]
l.sort(key=lambda a: (a[1],a[0])) #use only a[1] if you only care about the numbers
print(l)

rawDescription: sorting two-dimensional lists by a certain value

description: Sorting two-dimensional lists by a certain value


code:
import itertools

def has_monochromatic_rectangles(grid):
  # use range instead of xrange here (xrange is not in Python 3)
  points = list(itertools.product(range(len(grid)), range(len(grid[0]))))
  # check if for any rectangle, all 4 colors are equal
  # (this is more brute-force than necessary, but you placed simplicity
  # above efficiency. Also, for 17x17, it doesn't matter at all ;)
  return any(grid[x1][y1] == grid[x1][y2] == grid[x2][y1] == grid[x2][y2]
             for (x1,y1), (x2,y2) in itertools.product(points, points)
             if x1 != x2 and y1 != y2)

def has_max_colors(grid, most):
  # collect all grid values and uniquify them by creating a set
  return len(set(sum(grid, []))) <= most

if __name__ == '__main__':
  # read from STDIN (could easily be adapted to read from file, URL, ...)
  import sys
  grid = [map(int, line.split(',')) for line in sys.stdin]

  assert has_max_colors(grid, 4)
  assert not has_monochromatic_rectangles(grid)

rawDescription: Python: How to make my 4-coloring checker more readable


code:
#!/usr/bin/env python
import re

def lreplace(s, old, new):
    """Return a copy of string `s` with leading occurrences of
    substring `old` replaced by `new`.

    >>> lreplace('abcabcdefabc', 'abc', 'X')
    'XXdefabc'
    >>> lreplace('_abc', 'abc', 'X')
    '_abc'
    """
    return re.sub(r'^(?:%s)+' % re.escape(old),
                  lambda m: new * (m.end() / len(old)),
                  s)

rawDescription: Replacing leading text in Python

description: Replacing leading text in Python


code:
from django.db.models.signals import post_save, pre_save

@receiver(pre_save, sender=Face)
def check_beard(sender, instance=None, created=False, **kwargs):
    if not instance.id and not instance.male: # Check instance id if it saving for first time, and set default
        instance.beard = False

rawDescription: Django Models: default callback: missing "self"


code:
from random import Random

r = Random()
r.seed(some_user_id)
books = Books.objects.filter(name=variable)
jumbled = sorted(books, key=lambda L: r.random())

rawDescription: Randomize queryset deterministically

description: Randomize queryset deterministically


code:
from evaluate import actual_things
def run():
    ...
    actual_things()
    ...

if __name__ == '__main__':
    init()
    load_from_config()
    run()

rawDescription: Python: suggestions how to organize a Python project. Some questions


code:
ds1Cursor.execute(selectSql)
result = ds1Cursor.fetchall()

ds2Cursor.executemany('INSERT INTO [TableName] (Col1, Col2, Col3) VALUES (?, ?, ?)', result)
ds2Cursor.commit()

rawDescription: basic pyodbc bulk insert

description: Basic pyodbc bulk insert


code:
import subprocess
p = subprocess.Popen(['/your/cpp/program'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write('1\n')
p.stdout.readline()
p.stdin.write('10\n')
p.stdout.readline()
p.stdin.write('0\n')
p.stdout.readline()
p.wait()

rawDescription: Process in python - fetch stdout of non-terminating process


code: dict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix'))

rawDescription: Fastest way of deleting certain keys from dict in Python


code: Result = Z[:,None,:,None,None] + Y[:,:,None,:,None] + X[:,:,:,None,:]

rawDescription: Vectorize numpy assignment

description: Vectorize numpy assignment


rawDescription: Extract text from Microsoft Word with final version track changes using Python?


code: newImage = numpy.where(np.logical_and(image1, image2), (image1 + image2) / 2, 0)

rawDescription: Why is this numpy array operation so slow?


code:
np.vstack((A, A[-1]))
np.hstack((A, np.atleast_2d(A[:,-1]).T))

rawDescription: Numpy repeating a row or column

description: Numpy repeating a row or column


code:
def read():
    with open('C:\\Users\\chef\\Python\\fn.csv', 'r') as f:
        usersReader = csv.reader(f)
        for row in usersReader:
            if row == []:
                pass
            else:
                users[row[0]] = row[1]
        f.close();

rawDescription: Dictionary empties after running program


code:
from itertools import groupby

with open('input.txt') as f_input, open('output.txt', 'w') as f_output:
    for k, g in groupby(f_input, lambda x: x != 'ITEM: TIMESTEP\n'):
        if k:
            entries = [line.strip() for line in g]
            block_header = ['ITEM: TIMESTEP'] + entries[:3]
            entries = sorted([line.split() for line in entries[3:]], key=lambda x: int(x[0]))
            f_output.write('\n'.join(block_header) + '\n')

            for row in entries:
                f_output.write(' '.join(row) + '\n')

rawDescription: Sorting a file with python

description: Sorting a file with python


code:
import scipy
import scipy.signal as sig
rr = [1.0, 1.0, 0.5, 1.5, 1.0, 1.0] # rr time in seconds
fs = 8000.0 # sampling rate
pqrst = sig.wavelets.daub(10) # just to simulate a signal, whatever
ecg = scipy.concatenate([sig.resample(pqrst, int(r*fs)) for r in rr])
t = scipy.arange(len(ecg))/fs
pylab.plot(t, ecg)
pylab.show()

rawDescription: simulator of realistic ECG signal from rr data for matlab or python

description: Simulator of realistic ECG signal from rr data for matlab or python


code:
def gather_path(self):
    path_object = PathsOfDomain.objects.filter(FKtoTld=3)

rawDescription: Passing an attribute from method to another method python


code:
a = last_epoch #last epoch recorded
b = time.time() #current epoch time
c = b - a #returns seconds
days = c // 86400
hours = c // 3600 % 24
minutes = c // 60 % 60
seconds = c % 60

rawDescription: Python - Convert seconds from epoch time into human readable time


code:
img_stream = self.form.image.data
mimetype = img_stream.content_type
img_str = img_stream.read().encode('base64').replace('\n', '')

data_uri = 'data:%s;%s,%s' % (mimetype, 'base64', img_str)

rawDescription: How do I get a string representation of an image before uploading?

description: Get a string representation of an image before uploading


code:
import imp
path = '/path/to/file'
with open(path, 'U') as f:
    mod = imp.load_module('temporary', f, path, ('.py', 'U', imp.PY_SOURCE))

builtins = vars(__builtins__)
cls = next(value for name, value in vars(mod).items() if name not in builtins)
const_dict = {name: value for name, value in vars(mod.Constants).items()
                          if not name.startswith('_')}
print(const_dict)

# => {'OS': 'os', 'VERSION': 'version', 'PROGRAM': 'program'}

rawDescription: How to get property names from .py file which contains class definition

description: Get property names from .py file which contains class definition


rawDescription: Finding Index of All Patterns Within Pandas Dataframe


code:
from itertools import groupby
l = ['x', 'x', 'y', 'y', 'x']
list(groupby(l))
[(x, len(list(g))) for x, g in groupby(l)]

rawDescription: Finding ContiguousCount of items in list?


code:
def get_timezones_with_gmt_diff(timezone_string_list = None):
    """
    Converts a datetime object into string.
    """
    if timezone_string_list:
        timezone_list = timezone_string_list
    else:
        timezone_list = pytz.common_timezones

    datetime1 = datetime.strptime("10-07-%s 00:00:00" % datetime.utcnow().year, "%d-%m-%Y %H:%M:%S")
    datetime2 = datetime.strptime("10-12-%s 00:00:00" % datetime.utcnow().year, "%d-%m-%Y %H:%M:%S")

    result_dict = {}
    for time_zone in timezone_list:
        result_dict[time_zone] = [Date.timedelta_in_seconds(pytz.timezone(time_zone).localize(datetime1).tzinfo._utcoffset)/3600,
                                  Date.timedelta_in_seconds(pytz.timezone(time_zone).localize(datetime2).tzinfo._utcoffset)/3600,
                                  time_zone.replace("/", " - ").replace("_", " "),
                                  Date.timedelta_in_seconds(pytz.timezone(time_zone).localize(datetime1).tzinfo._utcoffset)/3600 !=
                                  Date.timedelta_in_seconds(pytz.timezone(time_zone).localize(datetime2).tzinfo._utcoffset)/3600]

    sorted_result_dict = OrderedDict(sorted(result_dict.items(), key=lambda t: t[1][2]))
    return sorted_result_dict

def get_timezones_for_listbox(time_zones_dict):
    list = []
    for time_zone_tuple in time_zones_dict:
        # Has different DST/Summer times:
        if time_zones_dict[time_zone_tuple][3]:
            new_item = "%s      UCT %s/%s" % (str(time_zones_dict[time_zone_tuple][2]), str(time_zones_dict[time_zone_tuple][0]), str(time_zones_dict[time_zone_tuple][1]))
        # Does not change datetime:
        else:
            new_item = "%s      UCT %s" % (str(time_zones_dict[time_zone_tuple][2]), str(time_zones_dict[time_zone_tuple][0]))
        list.append(new_item)
    return list

def timedelta_in_seconds(duration):
    days, seconds = duration.days, duration.seconds
    return days * 24 * 60 * 60 + seconds

rawDescription: Python/Django: Need a ListBox/Dropdown with pytz common_timezones name each difference for UTC (offsets)


code:
data_to_parse = BeautifulSoup(html_payload)
for line in data_to_parse.get_text().split("\n"):
    pass  # ... do something

rawDescription: More elegant way to create a list of lines from BeautifulSoup.findAll


code:
chainpos.append((chainid,x, y, z))
chainpos
import itertools
for id, coor in itertools.groupby(chainpos,lambda x:x[0]):
    print(id, [c[1:] for c in coor])

rawDescription: Separating a list of (X,Y)

description: Separating a list of (X,Y)


rawDescription: List of integers into string (byte array) - python


code:
for d, field in zip(dat, new_fields):
    feature.SetField(field, d)
    layer.CreateFeature(feature)

rawDescription: How to loop through a nested loop and enumerate

description: Loop through a nested loop and enumerate


code:
sql = '''
    SELECT DISTINCT
        f.dm,
        f1.price AS first,
        f.maxp AS max,
        f.minp AS min,
        f2.price AS last
    FROM (
        SELECT datetime, strftime("%Y-%m-%d %H:%M",datetime) dm,
               MIN(datetime) mindate, MAX(datetime) maxdate,
               MIN(price) minp, MAX(price) maxp
        FROM {c}
        WHERE datetime >= ? AND datetime < ?
        GROUP BY dm
        ) f
    INNER JOIN {c} f1
    ON f1.datetime = f.mindate
    INNER JOIN {c} f2
    ON f2.datetime = f.maxdate
    '''.format(c = currency)

rawDescription: Python SQL function, query to group dates by minutes


code:
import types

class MyClass(object):
    def __init__(self):
        self.my_method = types.MethodType(my_method, self)

rawDescription: do I understand the difference between instance attributes and class attributes in Python?

description: Do I understand the difference between instance attributes and class attributes in Python


code:
import http.client

conn = http.client.HTTPSConnection("webapi.teamviewer.com")

headers = {
    'authorization': "Bearer xxxxxxx-xxxxxxxxxxx",
    'cache-control': "no-cache",
    'postman-token': "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxx",
    'content-type': "application/x-www-form-urlencoded"
    }

ids = [35123241, 234234234, 1232312, 5644352, 234243234]
pws = ["47gj6", "fgdg6as", "saa23d", "a24asd", "gre42as"]

for i in range(len(ids)):
    payload = "remotecontrol_id=r%s&groupid=g18932019&alias=%s&password=%s" % (ids[i], ids[i], pws[i])

    conn.request("POST", "/api/v1/devices", payload, headers)

    res = conn.getresponse()
    data = res.read()

    print(data.decode("utf-8"))

rawDescription: TeamViewer API and PostMan

description: TeamViewer API and PostMan


code:
import pandas as pd

di = pd.date_range("2016/01/01", "2016/04/10").to_series()
di.dt.to_period("W-SAT").dt.start_time

rawDescription: Most efficient way to convert datetime64[ns] to a given day of that week?


rawDescription: Selenium: check textarea is cleared on click


code:
import os

url='http://www.test.com/test.zip'
z = zipfile.ZipFile(BytesIO(urllib.urlopen(url).read()))
info = z.infolist()
data = []
for obj in info:
    name = os.path.splitext(obj.filename)
    data.append(name[0], name[1], obj.file_size)

rawDescription: MetaData of downloaded zipped file

description: MetaData of downloaded zipped file


code:
class esm_class:
    BITMASK_FEATURE = 0b11000000
    BITMASK_MODE    = 0b00111100
    BITMASK_TYPE    = 0b00000011

    class Features:
        FEATURE_1 = 0b00
        FEATURE_2 = 0b01
        FEATURE_3 = 0b10
        FEATURE_4 = 0b11

    class Modes:
        MODE_1 = 0b0000
        # …

    class Types:
        TYPE_1 = 0b00
        TYPE_2 = 0b01
        # …

    def __init__(self, type_, mode, feature):
        self.type = type_
        self.mode = mode
        self.feature = feature

    def __bytes__(self):
        '''
        Use this to write an instance of esm_class to a file-like
        object or stream, e.g..:
        mysocket.send(bytes(my_esm_class_obj))
        '''
        return ((self.feature << 6) | (self.mode << 2) |
                self.type).to_bytes(1, byteorder='big')

    @classmethod
    def parse(cls, filelike):
        '''
        Use this to parse incoming data from a file-like object
        and create an instance of esm_class accordingly, e.g:
        my_esm_class_obj = esm_class.parse(stream)
        '''
        instance = cls()
        data = filelike.read(1)
        instance.feature = int.from_bytes((data & cls.BITMASK_FEATURE) >> 6)
        instance.mode = int.from_bytes((data & cls.BITMASK_MODE) >> 2)
        instance.mode = int.from_bytes((data & cls.BITMASK_TYPE) >> 2)

rawDescription: Best way to handle lots of constants with more than one semantics

description: Handle lots of constants with more than one semantics


code:
def is_duplicate(a,b):
  if a['name'] == b['name'] and a['cost'] == b['cost'] and abs(int(a['cost']-b['cost'])) < 2:
    return True
  return False

newlist = []
for a in oldlist:
  isdupe = False
  for b in newlist:
    if is_duplicate(a,b):
      isdupe = True
      break
  if not isdupe:
    newlist.append(a)

rawDescription: Deleting dicts with near-duplicate values from a list of dicts - Python


code:
var = "module"
module = __import__("modules.{0}".format(var), globals(), locals(), [], -1)

rawDescription: Import module dynamic from a folder python


code:
lower_name = course_name.lower()
matches = [x for x in user_courses if x.split('.')[0].lower() == lower_name]
if matches:
    match = matches[0]
    # match is the matched name

rawDescription: Get Matched Value From Iterator With "if value in list" in Python


code:
command=input('''
  What would you like to do? You can say:

  get all
  get unique

  ''')

rawDescription: Multiline input prompt indentation interfering with output indentation


code:
def getImportantObject():
    global __IMPORTANT_OBJECT__
    if __IMPORTANT_OBJECT__ is None:
        __IMPORTANT_OBJECT__ = my_other_module.ImportantObject()
    return __IMPORTANT_OBJECT__

rawDescription: Python - how do I write a "getter" function that will return a variable stored in my module (initiating it first if needed)?


code:
# ev is for everything, let's start with an empty dict
ev = {}

# we identify and label all our stuff
for row in data:

    # unpack a row of the data matrix
    idx1, x, y, idx2 = row

    # the new value for key=idx1 is {} (empty dict) if first time we see
    # idx1, otherwise we keep the old value
    ev[idx1] = ev.get(idx1,{})

    # the new value for key=idx2 of the dictionary that is the value
    # for key=idx1 is the old/default value (a list/the null list)
    # plus a tuple (x,y)
    ev[idx1][idx2] =  ev[idx1].get(idx2,[]).append((x,y))

# we output our carefully labeled collection of x,y data
for idx1 in keys(ev):
    for idx2, xys in ev[idx1]:

        # the choice of the filename is subjective, isn;t it?
        f = open("file%d_%d.out" % (idx1,idx2), "w")

        for x, y in xys:
            f.write("%d %g %g" % (idx1, x, y))

        f.close()

rawDescription: Extracting data from numpy array

description: Extracting data from numpy array


code:
import subprocess
# if you're on windows call this
subprocess.call("notepad", shell=True)
# If on Linux call this
subprocess.call("ls", shell=True)

rawDescription: Running C Program on Windows 8.1 using Python (or not Python)


code: from mercurial.i18n import _

rawDescription: Mercurial/Python - What Does The Underscore Function Do?


code:
import re
import itertools
# All of the strings
z = ['a privacy policy', 'there are many standard challenges that face every business']
junk_terms = ['privacy policy', 'cookie policy', 'copyright']

# Build the regex, making sure we don't capture parts.
regex = re.compile("|".join(r"\b{}\b".format(term) for term in junk_terms))

# Filter out anything that we found junk in.
result = list(itertools.filterfalse(regex.search, z))

rawDescription: How do I check if words in a list are contained in sentences in another list?

description: Check if words in a list are contained in sentences in another list


code:
self.root.grid_columnconfigure(0, weight=1)
self.root.grid_rowconfigure(0, weight=1)
self.contentFrame.grid_columnconfigure(0, weight=1)
self.contentFrame.grid_rowconfigure(0, weight=1)
self.topBar.grid_columnconfigure(0, weight=1)
self.topBar.grid_rowconfigure(0, weight=1)

rawDescription: How to center a tkinter widget in a sticky frame

description: Center a tkinter widget in a sticky frame


code:
for container in axes.containers:
        for i, child in enumerate(container.get_children()):
            child.set_x(df.index[i] - sizes[i]/2)
            plt.setp(child, width=sizes[i])

rawDescription: Modifying bar-width and bar-position in matplotlib bar-plot (looping over containers)


rawDescription: Deleting the last octets of an IP address


code:
import errno
from celery.exceptions import Reject

@app.task(bind=True, acks_late=True)
def render_scene(self, path):
    file = get_file(path)
    try:
        renderer.render_scene(file)

    # if the file is too big to fit in memory
    # we reject it so that it's redelivered to the dead letter exchange
    # and we can manually inspect the situation.
    except MemoryError as exc:
        raise Reject(exc, requeue=False)
    except OSError as exc:
        if exc.errno == errno.ENOMEM:
            raise Reject(exc, requeue=False)

    # For any other error we retry after 10 seconds.
    except Exception as exc:
        raise self.retry(exc, countdown=10)

rawDescription: Canceling a celery task from inside itself?


code:
class SwitchCreator1(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.newSim = Simulator()
        self.s1 = self.newSim.addNewSwitch()

    def getSwitch1(self):
        return self.s1

class SwitchCreator2(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.newSim = Simulator()
        self.s2 = self.newSim.addNewSwitch()

    def getSwitch2(self):
        return self.s2

def main():

    threadList = []

    sc1 = SwitchCreator1()
    threadList.append(sc1)
    sc1.start()
    s1 = sc1.getSwitch1()

    sc2 = SwitchCreator2()
    threadList.append(sc2)
    sc2.start()
    s2 = sc2.getSwitch2()

    s1.connectTo(s2)

    s1.echo("Say hello to my little friend!!! BoooM!!!", s2)

    for t in threadList:
        t.join()

if __name__ == '__main__':
    main()

rawDescription: Modeling a network in Python: instantiating objects in different threads and passing objects between threads in python


code:
books = {}
line = "Calculus | James Stewart"
parts = line.split('|') # can also do title, author = line.split('|')
books[parts[0].strip()] = parts[1].strip()
print(books)

rawDescription: How can I produce a file?

description: Produce a file


code:
@login_required
def delete_post(request, id):
    post_to_delete = get_object_or_404(Post, pk=id)

    if post_to_delete.owner_user != request.user:
        return HttpResponseForbidden()

    if request.method == 'POST':
        post_to_delete.delete()
        return render(request,'delete_post.html', {'deleted':True})

    return render(request,'delete_post.html', {'deleted':False})

rawDescription: Django .delete() does not work

description: Django .delete() does not work


code:
import Tkinter as tk
import tkFont

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        ## Toolbar
        self.toolbar = tk.Frame()
        self.bold = tk.Button(name="toolbar", text="bold",
                              borderwidth=1, command=self.OnBold,)
        self.bold.pack(in_=self.toolbar, side="left")

        ## Main part of the GUI
        # I'll use a frame to contain the widget and
        # scrollbar; it looks a little nicer that way...
        text_frame = tk.Frame(borderwidth=1, relief="sunken")
        self.text = tk.Text(wrap="word", background="white",
                            borderwidth=0, highlightthickness=0)
        self.vsb = tk.Scrollbar(orient="vertical", borderwidth=1,
                                command=self.text.yview)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(in_=text_frame,side="right", fill="y", expand=False)
        self.text.pack(in_=text_frame, side="left", fill="both", expand=True)
        self.toolbar.pack(side="top", fill="x")
        text_frame.pack(side="bottom", fill="both", expand=True)

        # clone the text widget font and use it as a basis for some
        # tags
        bold_font = tkFont.Font(self.text, self.text.cget("font"))
        bold_font.configure(weight="bold")
        self.text.tag_configure("bold", font=bold_font)
        self.text.tag_configure("misspelled", foreground="red", underline=True)

        # set up a binding to do simple spell check. This merely
        # checks the previous word when you type a space. For production
        # use you'll need to be a bit more intelligent about when
        # to do it.
        self.text.bind("<space>", self.Spellcheck)

        # initialize the spell checking dictionary. YMMV.
        self._words=open("/usr/share/dict/words").read().split("\n")

    def Spellcheck(self, event):
        '''Spellcheck the word preceeding the insertion point'''
        index = self.text.search(r'\s', "insert", backwards=True, regexp=True)
        if index == "":
            index ="1.0"
        else:
            index = self.text.index("%s+1c" % index)
        word = self.text.get(index, "insert")
        if word in self._words:
            self.text.tag_remove("misspelled", index, "%s+%dc" % (index, len(word)))
        else:
            self.text.tag_add("misspelled", index, "%s+%dc" % (index, len(word)))

    def OnBold(self):
        '''Toggle the bold state of the selected text'''

        # toggle the bold state based on the first character
        # in the selected range. If bold, unbold it. If not
        # bold, bold it.
        current_tags = self.text.tag_names("sel.first")
        if "bold" in current_tags:
            # first char is bold, so unbold the range
            self.text.tag_remove("bold", "sel.first", "sel.last")
        else:
            # first char is normal, so bold the whole selection
            self.text.tag_add("bold", "sel.first", "sel.last")

if __name__ == "__main__":
    app=App()
    app.mainloop()

rawDescription: Add advanced features to a tkinter Text widget


code:
x = 0;
if abs(stableAcceleration[0]) > abs(stableAcceleration[1]) :
    x += 2
if stableAcceleration[0] > 0:
    x +=1

list = ["normal", "invert", "left", "right"]

print(list[x])

rawDescription: Is it possible in Python to write a sort of truth table to simplify the writing of if statements?


code:
import Tkinter as tk
import random

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.canvas = tk.Canvas(self, width=500, height=500, borderwidth=0, highlightthickness=0)
        self.canvas.pack(side="top", fill="both", expand="true")
        self.rows = 100
        self.columns = 100
        self.cellwidth = 25
        self.cellheight = 25

        self.rect = {}
        self.oval = {}
        for column in range(20):
            for row in range(20):
                x1 = column*self.cellwidth
                y1 = row * self.cellheight
                x2 = x1 + self.cellwidth
                y2 = y1 + self.cellheight
                self.rect[row,column] = self.canvas.create_rectangle(x1,y1,x2,y2, fill="blue", tags="rect")
                self.oval[row,column] = self.canvas.create_oval(x1+2,y1+2,x2-2,y2-2, fill="blue", tags="oval")

        self.redraw(1000)

    def redraw(self, delay):
        self.canvas.itemconfig("rect", fill="blue")
        self.canvas.itemconfig("oval", fill="blue")
        for i in range(10):
            row = random.randint(0,19)
            col = random.randint(0,19)
            item_id = self.oval[row,col]
            self.canvas.itemconfig(item_id, fill="green")
        self.after(delay, lambda: self.redraw(delay))

if __name__ == "__main__":
    app = App()
    app.mainloop()

rawDescription: tkinter: displaying a square grid

description: Tkinter: displaying a square grid


code:
from xml.sax import saxutils as su

unqoutedHtml = su.unescape(content)
newElement = html.document_fromstring(unqoutedHtml)

rawDescription: Python - Can't access some tags using LXML.HTML


code:
import logging
import paramiko

logging.getLogger("paramiko").setLevel(logging.WARNING) # for example

rawDescription: How to use paramiko logging?

description: Use paramiko logging


code:
import threading

class MyApp(ttk.Frame):
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        fname = 'test.txt'
        self.build_ui()
        self.process_file(fname)

    def process_file(self, fname):
        self.show_progress(True)

        # Start thread to process file.
        self.thread = threading.Thread(target=self.process_file_worker, args=(fname,))
        self.thread.daemon = True # Allow the program to terminate without waiting for the thread to finish.
        self.thread.start()

        # Start checking the thread.
        self.process_file_check()

    def process_file_check(self):
        if self.thread.is_alive():
            # Thread is still running, check thread again in 10 milliseconds.
            self.after(10, self.process_file_check)

        else:
            # Thread finished, handle processed results.
            # Do something with `self.fdata`.
            self.show_progress(False)

    def process_file_worker(self, fname):
        # This is run inside the thread.
        fdata = self.read_file(fname)
        fdata = self.spellcheck(fdata)
        self.fdata = fdata

    def show_progress(self, start):
        if start:
            self.prog_win = tk.Toplevel()
            self.prog_win.title('Working...')
            self.prog_win.resizable(0, 0)
            self.progress_bar = ttk.Progressbar(self.prog_win,
                                                orient=tk.HORIZONTAL,
                                                mode='indeterminate',
                                                takefocus=True)
            self.progress_bar.grid()
            self.progress_bar.start()
        else:
            self.progress_bar.stop()
            self.prog_win.destroy()

root = tk.Tk()
root.update()
gui = MyApp(root)
gui.mainloop()

rawDescription: How to implement indeterminate Progressbar in Tkinter?

description: Implement indeterminate Progressbar in Tkinter


code:
from django.utils import timezone
from types import MethodType

def _add_get_in_last_delta(self,
                           time_series_object_name,
                           time_series_field_name):
    # Generate a function name.
    fn = 'get_{}_in_last_delta'.format(time_series_object_name)

    def dynamic_method(self, delta, obj=time_series_object_name, field=time_series_field_name):
        return getattr(self, time_series_object_name).filter(
            **{'{}__gte'.format(time_series_field_name): timezone.now()-delta})

    # Bind the method to the instance.
    setattr(self, fn, MethodType(dynamic_method, self))

rawDescription: How to generate and add an instance method to a class in runtime but compiling a method only once?

description: Generate and add an instance method to a class in runtime but compiling a method only once


code:
from Foundation import NSDictionary, NSString, NSPropertyListSerialization
from Foundation import NSUTF8StringEncoding, NSPropertyListXMLFormat_v1_0

d = {'a': 1, 'b': 2, 'c': 3}
nsd = NSDictionary(d)

# serialize the dictionary as XML into an NSData object
xml_plist_data, error = NSPropertyListSerialization.dataWithPropertyList_format_options_error_(nsd, NSPropertyListXMLFormat_v1_0, 0, None)

if xml_plist_data:
    # convert that data to a string
    xml_plist = NSString.alloc().initWithData_encoding_(xml_plist_data, NSUTF8StringEncoding)
else:
    # look at the error
    pass

rawDescription: Turning NSDictionary into a plist string, not writing it to a file, in PyObjC


code:
from codecs import iterdecode

for line in iterdecode(filename, 'utf16'): yield line

rawDescription: Python/Django: How to convert utf-16 str bytes to unicode?


code:
# implementation detail: this property is implemented as non-data
# descriptor.  non-data descriptors are only invoked if there is
# no entry with the same name in the instance's __dict__.
# this allows us to completely get rid of the access function call
# overhead.  If one choses to invoke __get__ by hand the property
# will still work as expected because the lookup logic is replicated
# in __get__ for manual invocation.

rawDescription: Python - What is a lazy property?

description: Python - What is a lazy property


rawDescription: Python regex stop at ampersand

description: Python regex stop at ampersand


code:
import io
import base64
from IPython.display import HTML

video = io.open('test.mp4', 'r+b').read()
encoded = base64.b64encode(video)
HTML(data='''<video alt="test" controls>
                <source src="data:video/mp4;base64,{0}" type="video/mp4" />
             </video>'''.format(encoded.decode('ascii')))

rawDescription: How can I play a local video in my IPython notebook?

description: Play a local video in my IPython notebook


code:
import os
import filecmp
import shutil

if not os.path.exists(dst) or not filecmp.cmp(src, dst):
    shutil.copyfile(src, dst)

rawDescription: How to shutil.copyfile only if file differ?

description: Shutil.copyfile only if file differ


code:
runFind(L)
def runFind(L):
  i = 1
  start = 0
  answer = []
  while i < len(L):
    if L[i] != L[i-1]+1:
      answer.append((i-start, start))
      start = i
    i += 1
  answer.append((i-start, start))

  return answer

L = [1,2,3,6,4]
runFind(L)
L = [0, 0, 0, 4, 5, 6]
runFind(L)
L = [4, 5, 5, 1, 8, 3, 1, 6, 2, 7]
runFind(L)
L = [1, 1, 1, 2, 3, 5, 1, 1]
runFind(L)
L = [1, 1, 1, 1]
runFind(L)
L = [1, 2, 5, 6, 7]
runFind(L)
L = [1, 0, -1, -2, -1, 0, 0]
runFind(L)

rawDescription: Finding a Run in a List Without using any pre-defined Python Funcitions


code:
import urllib
import base64
import wave
import numpy as np

# Open the network wave stream
request = urllib.request.Request("http://url")
request.add_header('Authorization',
                   b'Basic ' + base64.b64encode(b'user:password'))
in_file = urllib.request.urlopen(request)
in_wave = wave.open(in_file, 'rb')

# Get parameters such as number of channels, framerate etc.
params = in_wave.getparams()

# Open and initialize an output file
out_wave = wave.open('/home/czikus/out.wav', 'wb')
out_wave.setparams(params)

while True:
    # Get N frames as byte array
    frame = in_wave.readframes(10000)
    # Convert the bytes to numpy array
    arr = np.fromstring(frame, 'Int16')
    # Write a numpy array into a wave file
    out_wave.writeframes(arr.tostring())

rawDescription: Raw numpy array from real-time network audio stream in Python


code:
def parseAndEvaluate(exp):
        if gdb.VERSION.startswith("6.8.50.2009"):
            return gdb.parse_and_eval(exp)
        # Work around non-existing gdb.parse_and_eval as in released 7.0
        gdb.execute("set logging redirect on")
        gdb.execute("set logging on")
        gdb.execute("print %s" % exp)
        gdb.execute("set logging off")
        return gdb.history(0)

rawDescription: gdb python scripting: where has `parse_and_eval` gone?

description: Gdb python scripting: where has `parse_and_eval` gone


code:
import matplotlib.pyplot as plt
import random

nconfigs, njobs, nservers = 3, 4, 4

width = .9/(nconfigs*njobs)
job_colors = [(0,0,1), (0,1,0), (1,0,0), (1,0,1)]

def dim(color, fraction=.5):
    return tuple([fraction*channel for channel in color])

plt.figure()
x = 0
for iserver in range(nservers):
    for ijob in range(njobs):
        for iconfig in range(nconfigs):
            color = dim(job_colors[ijob], (iconfig+2.)/(nconfigs+1))
            plt.bar(x, 1.+random.random(), width, color=color)
            x += width
    x += .1

plt.show()

rawDescription: Generating a graph with multiple (sets of multiple sets of multiple) X-axis data sets


code:
import datetime
from django.utils import dateformat
dateformat.format(datetime.datetime.now(), 'F j, Y, P')

rawDescription: Is there a way to get Django's default string for date and time from Python's datetime?


code:
application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/sign', Guestbook)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

rawDescription: Python Google App Engine: Call specific method from yaml file?


code:
from compiler.ast import flatten
list1=[[1,4],5,4]
list2=[5,4,[1,4]]
set(flatten(list1))==set(flatten(list2))

rawDescription: Compare two lists in python where the elements are in different order


code:
fig,ax=plt.subplots(2,1,sharex=True)
ax1 = plt.subplot(2, 1, 1)
a=ax1.bar(index, rating0,width=0.15,alpha=opacity,
                 color='c'
                  )
index=map(lambda x:x+0.15, index)
b=ax1.bar(index,rating1,width=0.15,alpha=opacity,
                 color='r')
index=map(lambda x:x+0.15, index)
c=ax1.bar(index,rating2,width=0.15,alpha=opacity,
                 color='y')
index=map(lambda x:x+0.15, index)
d=ax1.bar(index,rating3,width=0.15,alpha=opacity,
                 color='m')

index=map(lambda x:x-0.45, index)
ax2 = plt.subplot(2, 1, 2, sharex=ax1)
ax2.bar(index, rating0paris,width=0.15,alpha=opacity,
                 color='c')
index=map(lambda x:x+0.15, index)
ax2.bar(index,rating1paris,width=0.15,alpha=opacity,
                 color='r')
index=map(lambda x:x+0.15, index)
ax2.bar(index,rating2paris,width=0.15,alpha=opacity,
                 color='y')
index=map(lambda x:x+0.15, index)
ax2.bar(index,rating3paris,width=0.15,alpha=opacity,
                 color='m')

for axes in ax:
    format_axes(axes)

rawDescription: matplotlib: share x-axis for two barcharts, each with 4 groups

description: Matplotlib: share x-axis for two barcharts, each with 4 groups


code:
s = pd.DataFrame(pd.date_range('2012-1-1', periods=20, freq='D'), columns=["date"])

n = 5

s["date"] = np.int64(s)  #This step may not be needed in future pandas releases
s["bin"] = np.floor((n-0.001)*(s["date"] - s["date"].min( )) /((s["date"].max( ) - s["date"].min( ))))

rawDescription: Split dataframe into n equal time intervals, to groupby, where time interval is (time.max() - time.min())/ n


code:
import math
import numpy as np
import scipy
math.pi == np.pi == scipy.pi

rawDescription: Should I use `scipy.pi`, `numpy.pi`, or `math.pi`?


code:
t = []
for l in line:
    if 'tickme' in l:
        # Start a new bactch after saving the previous batch
        if t: batches.apend(t)
        t = [l.strip()]
    else:
        if len(l.strip()) > 1: t.append(l.strip())

rawDescription: Python parsing selected area/range of text file


code:
class A(object):
    __doc__ = class_docstr.format(name="A")

    # whatever else

rawDescription: Set __doc__ for class in python 2

description: Set __doc__ for class in python 2


rawDescription: Geohashing returns the same position for different hashes


code: converts_time = time.strftime("%I").lstrip('0') + str(":") + str(stop_time.split(":")[0]) + time.strftime("%p")

rawDescription: Split the strings in two parts

description: Split the strings in two parts


code:
scr.pack(side="right", fill="y", expand=False)
text.pack(side="left", fill="both", expand=True)

rawDescription: Scrollbar not stretching to fit the Text widget


code:
from tkinter import *  # python 3

class Other(Toplevel):

    """Note that the constructor of this class
    receives a parent called 'master' and a reference to another Toplevel
    called 'other'"""

    def __init__(self, master, other):

        Toplevel.__init__(self, master)
        self.other = other # other Toplevel

        self.lab = Label(self, text="Insert your name: ")
        self.lab.grid(row=0, column=0)

        self.entry = Entry(self)
        self.entry.grid(row=0, column=1)

        # When you click the button you call 'self.add'
        self.adder = Button(self, text='Add to Listbox', command=self.add)
        self.adder.grid(row=1, column=1)

    def add(self):
        """Using a reference to the other window 'other',
        I can access its attribute 'listbox' and insert a new item!"""
        self.other.listbox.insert("end", self.entry.get())

class Main(Toplevel):

    """Window with a Listbox"""

    def __init__(self, master):
        Toplevel.__init__(self, master)
        self.people = Label(self, text='People')
        self.people.grid(row=0)
        self.listbox = Listbox(self)
        self.listbox.grid(row=1)

if __name__ == "__main__":
    root = Tk()
    root.withdraw()  # hides Tk window

    main = Main(root)
    Other(root, main)  # passing a reference of 'main'

    root.mainloop()

rawDescription: Adding items to a Listbox using Entries from another class in Python tKinter


code:
for i in range(10):
  callbacks.append(lambda x = i : x)

rawDescription: Closures and Loops in Python

description: Closures and Loops in Python


code:
b[:,1]=numpy.nan
c = numpy.r_[a, b]
c.sort(0)
c = c[numpy.unique(c[:,0], True)[1]]

rawDescription: Splice arrays in NumPy?

description: Splice arrays in NumPy


code:
str = 'a,,b,c,'
re.findall(r'[^,;\s]+', str)

rawDescription: split a comma, space, or semicolon separated string using regex

description: Split a comma, space, or semicolon separated string using regex


code:
from PIL import Image

# Open the image and convert it to RGBA.
orig = Image.open("fresh.png").convert("RGBA")

# Paste it onto a white background.
im = Image.new("RGB", orig.size, "#ffffff")
im.paste(orig, None, orig)

# Now a quality downsize.
w, h = im.size
im.thumbnail((w / 2, h / 2), Image.ANTIALIAS)
im.show()

rawDescription: PNG Image Quality in PIL

description: PNG Image Quality in PIL


code:
import imghdr
import os
import os.path
import requests
import shutil

ses = requests.Session()
r = ses.get("http://url", stream=True)
localDest = os.path.join("local/file/path")

if r.status_code == 200:
    ctype = r.headers.get('content-type', '')
    if ctype.partition('/')[0].lower() != 'image':
        raise ValueError('Not served an image')

    clength = r.headers.get('content-length')
    clength = clength and int(clength)

    with open(localDest, 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)

    if clength and os.path.getsize(localDest) != clength:
        os.remove(localDest)
        raise ValueError('Served incomplete response')

    image_type = imghdr.test(localDest)
    if image_type is None:
        os.remove(localDest)
        raise ValueError('Not served an image')

rawDescription: How to verify POST file transfer with python requests library?

description: Verify POST file transfer with python requests library


code:
def exposed_getmodule(self, name):
    """imports an arbitrary module"""
    return __import__(name, None, None, "*")

rawDescription: rpyc: difference between root.getmodule("module_name") and manually returning a module reference?

description: Rpyc: difference between root.getmodule("module_name") and manually returning a module reference


code:
# This is to determine which products belong to the same line
# We can't just use product.id as you can have customised products
# which should be treated as separate lines.  Set as a
# SlugField as it is included in the path for certain views.
line_reference = models.SlugField(_("Line Reference"), max_length=128,
                                  db_index=True)

product = models.ForeignKey(
    'catalogue.Product', related_name='basket_lines',
    verbose_name=_("Product"))
quantity = models.PositiveIntegerField(_('Quantity'), default=1)

# We store the unit price incl tax of the product when it is first added to
# the basket.  This allows us to tell if a product has changed price since
# a person first added it to their basket.
price_excl_tax = models.DecimalField(
    _('Price excl. Tax'), decimal_places=2, max_digits=12,
    null=True)
price_incl_tax = models.DecimalField(
    _('Price incl. Tax'), decimal_places=2, max_digits=12, null=True)
# Track date of first addition
date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)

rawDescription: In Oscar, what is a line?

description: In Oscar, what is a line


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

rawDescription: check how many elements are equal in two numpy arrays python

description: Check how many elements are equal in two numpy arrays python


code:
import requests
import cookielib

URL = '...whatever...'
jar = cookielib.CookieJar()
r = requests.get(URL, cookies=jar)
r = requests.get(URL, cookies=jar)

rawDescription: Putting a `Cookie` in a `CookieJar`

description: Putting a `Cookie` in a `CookieJar`


code:
def parseCsvFile(self, paramsfile) :
    import csv
    csvDict = {}
    category = 'Unknown Category'
    params = []
    with open(paramsfile, 'rb') as csvfile :
        paramsReader = csv.reader(csvfile)
        for row in paramsReader :
            if row[0].startswith('Category') :
                category = row[0]
                csvDict[category] = {}
                params = [p.strip() for p in row[1:] if p]
            else :
                csvDict[category][row[0]] = dict(zip(params, [int(p) for p in row[1:] if p]))
    return csvDict

rawDescription: Python CSV files processing with sub categories


code:
import inspect
import os
os2 = object()
inspect.ismodule(os)
inspect.ismodule(os2)

rawDescription: How to test if a Python object is a module?

description: Test if a Python object is a module


code:
import Tkinter as tk

board = [ [None]*10 for _ in range(10) ]

counter = 0

root = tk.Tk()

def on_click(i,j,event):
    global counter
    color = "red" if counter%2 else "black"
    event.widget.config(bg=color)
    board[i][j] = color
    counter += 1

for i,row in enumerate(board):
    for j,column in enumerate(row):
        L = tk.Label(root,text='    ',bg='grey')
        L.grid(row=i,column=j)
        L.bind('<Button-1>',lambda e,i=i,j=j: on_click(i,j,e))

root.mainloop()

rawDescription: Creating a game board with Python and Tkinter


code:
import inspect
def lfmt(s):
    caller = inspect.currentframe().f_back
    return s.format(**caller.f_locals)

a = 3
b = 'foo'
c = dict(mykey='myval')

print(lfmt('a is {a}, b is {b}, mykey is {c[mykey]}'))
# a is 3, b is foo, mykey is myval

rawDescription: Capturing **vars() pattern in string formatting


code:
@api_view(['POST'])
def store_feedback_view(request, store_id):
    serializer = FeedbackSerializer(data=request.DATA)
    if serializer.is_valid():
        # this line added:
        serializer.object.content_object = get_object_or_404(Store, id=store_id)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

rawDescription: DJANGO - Save data with genericforeignkey on POST method using rest framework


rawDescription: Numpy Array summing with weights

description: Numpy Array summing with weights


code:
def openFile():
    settings = QSettings("Company name", "Application name")
    last_path = settings.value("LAST_PATH", ".")
    path, _ = QFileDialog.getOpenFileName(self, "Open text file", dir=last_path)
    self.settings.setValue("LAST_PATH", os.path.dirname(path))

rawDescription: Remember path over session in QFileDialog


code:
import stripe
stripe.api_key = "sk_test_asdfkljasblahblah123"

token = stripe.Token.create(
    card={
        "number": '4242424242424242',
        "exp_month": 12,
        "exp_year": 2016,
        "cvc": '123'
    },
)

rawDescription: How to generate a valid sample token with stripe?

description: Generate a valid sample token with stripe


code:
from django.utils import translation
user_language = 'en'
translation.activate(user_language)
request.session['django_language'] = user_language

rawDescription: Django, change language while redirecting


code: "powerpoint.exe /s <filename>.ppt"

rawDescription: How do I make powerpoint play presentations/load up ppts automatically?

description: Make powerpoint play presentations/load up ppts automatically


code:
import pymongo
import uuid
c = pymongo.Connection()
uu = uuid.uuid4()
uu
c.test.uuidtest.insert({'_id': uu})
c.test.uuidtest.find_one()

rawDescription: How to create a worldwide unique GUID/UUID system for Mongo with Python?

description: Create a worldwide unique GUID/UUID system for Mongo with Python