rawDescription: How to filter rows containing a string pattern from a Pandas dataframe

description: Filter rows containing a string pattern from a Pandas dataframe


code:
import random, pygame, sys, pickle, pygame.mouse, pygame.draw
from pygame.locals import *
pygame.mixer.init()
#             R    G    B
WHITE     = (255, 255, 255)
BLACK     = (  0,   0,   0)
RED       = (255,   0,   0)
GREEN     = (  0, 255,   0)
DARKGREEN = (  0, 155,   0)
DARKGRAY  = ( 40,  40,  40)
BGCOLOR = BLACK

pygame.init()

WINDOWWIDTH = 500
WINDOWHEIGHT = 400
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
rectangle = Rect(0, 0, 130, 170)

while True:
    for event in pygame.event.get():
            if event.type == QUIT:
                    pygame.mixer.music.stop()
                    pygame.quit()
                    sys.exit()
    DISPLAYSURF.fill(BLACK)
    rectangle.center = pygame.mouse.get_pos()
    pygame.draw.rect(DISPLAYSURF, DARKGREEN, rectangle)
    pygame.display.update()

rawDescription: How do I make a rectangle in pygame that automatically moves to my mouse location?

description: Make a rectangle in pygame that automatically moves to my mouse location


code:
from mock import patch
from requests import Response

def test_should_fail_to_request(self):
    mock_response = Response()
    mock_response.status_code = 404
    mock_response.body = json.dumps({"error":{"code":0,"$":"No result"}})

    with patch('requests.get', return_value=mock_response):
        response = my_mod.request_allocine_API("")

    self.assertEqual(response, -1, "There should be an error in the API")

rawDescription: how to test the result of an API without requesting it

description: Test the result of an API without requesting it


code:
text = []
i = 0
while True:
    if i > len(raw_text)-2:
        # No more possible |'s, so wrap things up
        text.append( raw_text[-1] )
        break
    if raw_text[i+1] == '|':
        # Add the items around the |; move past the group
        text.append( [raw_text[i], raw_text[i+2]] )
        i += 3
    else:
        # Add the current element & move on
        text.append( raw_text[i] )
        i += 1

rawDescription: Removing elements before and after a list


code:
X_batch, Y_batch = tf.train.batch([image, label], batch_size=64)

# Alternatively, `X_shape = [None, 32, 32, 3]`
X_shape = tf.TensorShape([None]).concatenate(X_batch.get_shape()[1:])
# Alternatively, `Y_shape = [None, 10]`
Y_shape = tf.TensorShape([None]).concatenate(Y_batch.get_shape()[1:])

# Create tensors that can be fed with a less specific shape
# than `X_batch`, `Y_batch`.
X = tf.placeholder_with_default(X_batch, shape=X_shape)
Y = tf.placeholder_with_default(Y_batch, shape=Y_shape)

rawDescription: How to reshape data to None in tensorflow?

description: Reshape data to None in tensorflow


code: return True

rawDescription: Search function not really searching

description: Search function not really searching


code:
import urllib2
req = urllib2.Request('http://www.python.org/')
#
# Here we request that bytes 18000--19000 be downloaded.
# The range is inclusive, and starts at 0.
#
req.headers['Range'] = 'bytes=%s-%s' % (18000, 19000)
f = urllib2.urlopen(req)
# This shows you the *actual* bytes that have been downloaded.
range=f.headers.get('Content-Range')
print(range)
# bytes 18000-18030/18031
print(repr(f.read()))
# '
\n\n\n\n\n\n\n\n\n'

rawDescription: Download file using urllib in Python with the wget -c feature


code:
#!/usr/bin/env python
import os
import urllib

url = "https://example.com/path" # where to get the file from
dest_dir = os.path.expandvars('%userprofile%/Downloads/ninite') # where to put it

# make the directories (recursively)
try:
    os.makedirs(dest_dir)
except OSError: # ignore errors
    pass

# download the file
urllib.urlretrieve(url, os.path.join(dest_dir, 'ninite.exe'))

rawDescription: Download under user's profile directory

description: Download under user's profile directory


code:
class F(forms.Form):
    meeting_date = forms.DateField(
        widget=forms.DateInput(format='%a %d/%m/%Y',
                               attrs={'id':'select-date'}),
        input_formats=('%a %d/%m/%Y', '%d/%m/%Y',),
        initial=date.today)

rawDescription: How to add weekday to DateInput widget

description: Add weekday to DateInput widget


code:
class NoAttributesClassMeta(type):
    def __setattr__(cls, name, value):
        if name not in cls.__dict__:
            raise AttributeError("Cannot set attributes")
        type.__setattr__(cls, name, value)

rawDescription: How to create class object without __dict__

description: Create class object without __dict__


code:
def get_author(self, obj):
    names = "\n".join([a.author_name for a in obj.author_set.all()])
return names

rawDescription: django model display and search

description: Django model display and search


code:
import pandas as pd
import numpy as np
df=pd.DataFrame({'current':[1,2,2,8,7]})
np.sign(df.current.diff()).map({1:"Greater", 0:"Equal", -1:"Less"})

rawDescription: Getting previous row values from within pandas apply() function


code:
lookup = map(chr, range(32, 127))
import itertools
itertools.permutations(lookup, 10)

rawDescription: I want to nest loop ten times, Is there any better way than this?


code:
for i, t in enumerate(test):
    t.order = i

rawDescription: Pythonic way to set sort order?

description: Pythonic way to set sort order


rawDescription: Python: Replace one list with another list?


code:
import pandas as pd

rdd = sc.parallelize([
    {"x": 1, "y": -1},
    {"x": -3, "y": 0},
    {"x": -0, "y": 4}
])

def combine(iter):
    rows = list(iter)
    return [pd.DataFrame(rows)] if rows else []

rdd.mapPartitions(combine).first()
##    x  y
## 0  1 -1

rawDescription: How to create a DataFrame out of rows while retaining existing schema?

description: Create a DataFrame out of rows while retaining existing schema


code:
connection = pyodbc.connect(...)
connection.begin() # superfluous, but for illustration purposes;
cursor = connection.cursor()
cursor.execute('INSERT ....')
connection.commit() # or rollback

rawDescription: Using BEGIN TRANSACTION / ROLLBACK / COMMIT over various cursors / connections


code:
def total():
    t = 0
    with open("product.txt", "r") as myFile:
        for result in myFile:
            r = result.split()
            t += int(r[1]) + int(r[2])
    return t
print(total()) # 480

rawDescription: Total from text file

description: Total from text file


code:
df["d"]
df["d"].apply(lambda x: str(x))
df["d"].astype(pd.datetime).apply(lambda x: x.date())

rawDescription: Pandas: Timestamp in version 0.18.0 (with time zone)


code:
def transform(s):
    return re.compile(re.escape(s))

rawDescription: Convert string to compiled regex matching the exact string


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

im = np.random.rand(21,21)

fig,(ax1,ax2) = plt.subplots(1,2)

ax1.imshow(im)
ax2.imshow(im)

# Where we want the ticks, in pixel locations
ticks = np.linspace(0,20,5)
# What those pixel locations correspond to in data coordinates.
# Also set the float format here
ticklabels = ["{:6.2f}".format(i) for i in np.exp(ticks/5)]

ax2.set_xticks(ticks)
ax2.set_xticklabels(ticklabels)
ax2.set_yticks(ticks)
ax2.set_yticklabels(ticklabels)

plt.show()

rawDescription: Matplotlib: personalize imshow axis

description: Matplotlib: personalize imshow axis


code:
def merge_Sort(list1, list2, new_list):
    for i in range(len(list1)):
        if list1[0] < list2[0]:
            new_list.append(list1[0])
            list1.remove(list1[0])
            break
        elif list1[0] > list2[0]:
            new_list.append(list2[0])
            list2.remove(list2[0])
            break

    merge_Sort(list1, list2, new_list)

list1 = [8, 15, 16, 50, 75]
list2 = [4, 23, 42, 108]
new_list = []
merge_Sort(list1, list2, new_list)

rawDescription: Recursively calling a Merge Sort algorithm


rawDescription: Matplotlib Figure Editor with QT4 (Solved)


code:
for dicts in d1:
   for key, value in dicts.items():
      new_dict.setdefault(key,[]).extend(value)

rawDescription: Merging different keys inside a list of dictionaries


code: notebook.tab(0, text="New text")

rawDescription: How to change the text of a tab in a Python GUI?

description: Change the text of a tab in a Python GUI


code:
import importlib

import cars

def runmycar(car_name):
    #car_name = 'Tesla'
    module_name = '.' + car_name.lower()

    mod = importlib.import_module(module_name, 'cars')
    cls = getattr(mod, car_name)

    obj = cls()
    obj.run()

rawDescription: How to load module, class and attributes dynamically in python 3.5 package

description: Load module, class and attributes dynamically in python 3.5 package


code:
# Load the words into a dictionary
words = dict((x.strip(), set()) for x in open("/usr/share/dict/words"))

# For each word, remove each letter and see if the remaining word is still
# in the dictionary. If so, add it to the set of shorter words associated with
# that word in the dictionary.
# For example, bear -> {ear, bar, ber}
for w in words:
    for i in range(len(w)):
        shorter = w[:i] + w[i+1:]
        if shorter in words:
            words[w].add(shorter)

# Sort the words by length so we process the shortest ones first
sortedwords = sorted(words, key=len)

# For each word, the maximum chain length is:
#  - the maximum of the chain lengths of each shorter word, if any
#  - or 0 if there are no shorter words for this word
# Note that because sortedwords is sorted by length, we will always
# have maxlength[x] already available for each shorter word x
maxlength = {}
for w in sortedwords:
    if words[w]:
        maxlength[w] = 1 + max(maxlength[x] for x in words[w])
    else:
        maxlength[w] = 0

# Print the words in all chains for each of the top 10 words
toshow = sorted(words, key=lambda x: maxlength[x], reverse=True)[:10]
while toshow:
    w = toshow[0]
    print(w, [(x, maxlength[x]) for x in words[w]])
    toshow = toshow[1:] + list(x for x in words[w] if x not in toshow)

rawDescription: Python- What word can have the most consecutive letters removed and still be a dictionary-valid word?


rawDescription: Sorted a tuple by value use a List when the value is equal


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        layout = QtGui.QVBoxLayout(self)
        self.buttonGroup = QtGui.QButtonGroup(self)
        for text in 'One Two Three'.split():
            button = QtGui.QPushButton(text)
            button.setCheckable(True)
            layout.addWidget(button)
            self.buttonGroup.addButton(button)
        self.buttonGroup.buttonClicked.connect(self.handleButtons)

    def handleButtons(self, button):
        print('Button %s Clicked' % button.text())

if __name__ == '__main__':

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

rawDescription: Can i make a group radiobutton as a group of pressed button, not as a group of circles with one point? (PyQt4)

description: Make a group radiobutton as a group of pressed button, not as a group of circles with one point? (PyQt4)


rawDescription: Intercept Tkinter "Exit" command?

description: Intercept Tkinter "Exit" command


code:
import urllib2

urllib2.urlopen("http://remotehost.com/myscript.php")

rawDescription: Run (remote) php script from (local) python script


code:
def generate_filename(self, instance, filename):
    directory_name = os.path.normpath(force_unicode(datetime.datetime.now().strftime(smart_str(self.app.name))))
    return os.path.join(directory_name, self.get_filename(filename))

class Page(models.Model):
    title = models.CharField(max_length=20)
    app = models.ForeignKey(App)
    file = model.FileField(upload_to=generate_filename)

rawDescription: Django: Saving file to specific location


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import lombscargle

plt.ion()
data = np.loadtxt('hv878_1945.dat')

ang_freq = np.linspace(.1, 25*6, 10000)
periodogram = lombscargle(data[:,0], data[:,2], ang_freq)
print(ang_freq[np.argmax(periodogram)]/2/np.pi)
plt.plot(ang_freq, periodogram)

rawDescription: Use of scipy.signal.lombscargle

description: Use of scipy.signal.lombscargle


code:
import struct
import random

f = open('myfile','wb')
for i in range(0,9):
    a = random.randint(0,255)
    f.write(struct.pack("=B", a))
f.close()

rawDescription: How to write 8 bit unsigned integer to a file using python?

description: Write 8 bit unsigned integer to a file using python


code:
class SortIterDict(dict):
    def __iter__(self):
        return iter(sorted(super(SortIterDict, self).__iter__()))
    def __reversed__(self):
        return reversed(tuple(iter(self)))
    def get_next(self, n):
        return next((x for x in iter(self) if x > n), None)
    def get_prev(self, n):
        return next((x for x in reversed(self) if x < n), None)

d = SortIterDict({'d':6, 'a':5, 'c':2})
list(d)
list(reversed(d))
d.get_next('b')
d.get_prev('b')

rawDescription: Use iterator protocol to access sorted dictionary


code:
from lxml import etree
import os

titles = set()
for root, dirs, files in os.walk(basedir):
    for filename in files:
        tree = etree.parse(os.path.join(root, filename), parser)
        for title in tree.xpath("//a[@class='ctitle']/@href"):
            titles.add(str(title))

rawDescription: Python/lxml is eating too much memory

description: Python/lxml is eating too much memory


code:
# Then hook it into the Book model explicitly.
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)

    objects = models.Manager() # The default manager.
    dahl_objects = DahlBookManager() # The Dahl-specific manager.

rawDescription: Overwrite method add for ManyToMany related fields


code:
vsb = tk.Scrollbar(master, orient="vertical", command=self.yview)
hsb = tk.Scrollbar(master, orient="horizontal", command=self.xview)
self.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)

self.grid(row=0, column=0, sticky="nsew")
vsb.grid(row=0, column=1, sticky="ns")
hsb.grid(row=1, column=0, sticky="ew")
master.grid_rowconfigure(0, weight=1)
master.grid_columnconfigure(0, weight=1)

rawDescription: adding x and y Scrollbar to a canvas

description: Adding x and y Scrollbar to a canvas


code:
from itertools import groupby
x = [10,10,20,20,20,30]
[list(g) for k, g in groupby(x)]

rawDescription: Python: form a list based on the same values


code:
class sample_token:
    def __init__(self, **response):
        for k,v in response.items():
            if isinstance(v,dict):
                self.__dict__[k] = sample_token(**v)
            else:
                self.__dict__[k] = v
s = sample_token(**response_body)
s.sub
s.sub.cn

rawDescription: Converting a nested dict to Python object


code:
# Echo server program
import socket,os

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
    os.remove("/tmp/socketname")
except OSError:
    pass
s.bind("/tmp/socketname")
s.listen(1)
conn, addr = s.accept()
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()

# Echo client program
import socket

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/tmp/socketname")
s.send(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received ' + repr(data))

rawDescription: how to make a socket server listen on local file

description: Make a socket server listen on local file


rawDescription: How can I delete an element from a multidimensional array in Python?

description: Delete an element from a multidimensional array in Python


code: '&category=%s&v=2' % '%2C+'.join(tag.strip() for tag in tags_list)

rawDescription: Rewrite string formatting without format function


code:
class Shape(object):
    def __new__(cls, desc):
        if cls is Shape:
            if desc == 'big':   return super(Shape, cls).__new__(Rectangle)
            if desc == 'small': return super(Shape, cls).__new__(Triangle)
        else:
            return super(Shape, cls).__new__(cls, desc)

rawDescription: Using a class' __new__ method as a Factory: __init__ gets called twice


code:
def start_requests(self):
    for i in range(1000):
        yield Request("http://www.example.com/bla-bla-bla/" + str(i), self.parse_tv)

rawDescription: Crawling a site recursively using scrapy


code:
@webapp2.cached_property
def jinja2(self):
    # Returns a Jinja2 renderer cached in the app registry, with no autoescaping.
    return jinja2.get_jinja2(lambda app: jinja2.Jinja2(app=app,config={'environment_args':{'autoescape':False}}))

rawDescription: Disable autoescaping in jinja2 on Appengine


code:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')

xyz = []
cur = [0, 0, 0]

for _ in xrange(20):
    axis = random.randrange(0, 3)
    cur[axis] += random.choice([-1, 1])
    xyz.append(cur[:])

x, y, z = zip(*xyz)
ax.plot(x, y, z, label='Random walk')
ax.scatter(x[-1], y[-1], z[-1], c='b', marker='o')   # End point
ax.legend()
plt.show()

rawDescription: Plotting 3D random walk in Python

description: Plotting 3D random walk in Python


code:
import csv

col1 = []
col2 = []

with open('test_dict.csv') as f:
  for row in csv.reader(f):
    col1.append(row[0])
    col2.append(row[1])

rawDescription: How to convert the second column of a csv file to a list of floats?

description: Convert the second column of a csv file to a list of floats


code:
keys = list(dict1.viewkeys() | dict2.viewkeys())
import numpy
numpy.corrcoef(
    [dict1.get(x, 0) for x in keys],
    [dict2.get(x, 0) for x in keys])[0, 1]

rawDescription: calculate the correlation of dictionaries based on their values in python

description: Calculate the correlation of dictionaries based on their values in python


code:
# replace by 'carsStr = input("Cars: ")' if you wish
carsStr = "rad blue blueish redish red blue red"
# str.split() returns a list of strings, never in-place
cars = carsStr.split()
r = cars.count('red')
b = cars.count('blue')
print("red:",r)
print("blue:",b)

rawDescription: Count Single Words in Python

description: Count Single Words in Python


code:
rows = list(reader(response))
query = con.fetchall() # this one you can iterate through, I am just copying what you had
for row in query:
    rs = filter(lambda r: row[1] in r, rows)
    for r in rs:
        if r[4]:
            pass # do some stuff (here)
            break
    else: # this is a for ... else loop
        pass # do some other stuff

rawDescription: Python: if in, then match on field of row found in


code:
import scipy.spatial.distance as ssd
distVec = ssd.squareform(SimMatrix)
linkage = hcluster.linkage(1 - distVec)
dendro  = hcluster.dendrogram(linkage)
show()

rawDescription: Dendrogram through scipy given a similarity matrix


code:
from xlsxwriter.workbook import Workbook

workbook = Workbook('output.xlsx')
for i in range(10):
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, "I'm sheet number %d" % (i + 1))

workbook.close()

rawDescription: export data from sqlite to Excel file in multiple tabs in python

description: Export data from sqlite to Excel file in multiple tabs in python


code:
class HTTPCookieProcessor(BaseHandler):
  def __init__(self, cookiejar=None):
    import cookielib
    if cookiejar is None:
        cookiejar = cookielib.CookieJar()
    self.cookiejar = cookiejar

  def http_request(self, request):
    self.cookiejar.add_cookie_header(request)
    return request

  def http_response(self, request, response):
    self.cookiejar.extract_cookies(response, request)
    return response

  https_request = http_request
  https_response = http_response

rawDescription: Cookiejar use in an opener

description: Cookiejar use in an opener


code:
class MyModel(db.Model):
    """ Base class provides the __repr__ so that each model has short type. """
    __abstract__ = True

    def __unicode__(self):
        # attrs = db.class_mapper(self.__class__).column_attrs
        attrs = db.class_mapper(self.__class__).attrs # show also relationships
        if 'name' in attrs:
            return self.name
        elif 'code' in attrs:
            return self.code
        else:
            return "<%s(%s)>" % (self.__class__.__name__,
                ', '.join('%s=%r' % (k.key, getattr(self, k.key))
                    for k in sorted(attrs)
                    )
                )

rawDescription: Flask-Admin Many-to-Many field display

description: Flask-Admin Many-to-Many field display


rawDescription: Taking complex input from a file in python?


code:
def foo(*args, **kwargs):
    do_something = kwargs.pop("do_something", False)

rawDescription: Python optional, positional and keyword arguments


code:
def blue_upload_to(instance, filename):
    folder = instance.red.some_field
    return folder + os.sep + filename

class MyModel(models.Model):
    red = models.ForeignKey(Anothermodel)
    blue = models.ImageField(upload_to=blue_upload_to)

rawDescription: Dynamic self-referencing "upload_to" folder on ImageField


code:
import feedparser
import memcache
import sys

mc = memcache.Client(["127.0.0.1:11211"])
rss = feedparser.parse('http://example.com/example.rss')

song = []
for i, entry in enumerate(rss.entries):
    title = entry.title.encode('latin-1', 'replace').replace("?" , "-")
    song.append(title)
    mc.set("track%d" % i, title)

rawDescription: Set multiple similar variables in Python


code:
def getFirstPlayer() -> int:
    while True:
        try:
            firstPlayer = str(input())

            if firstPlayer == 'W' or firstPlayer == 'w':
                return 2
            elif firstPlayer == 'B' or firstPlayer == 'b':
                return 1
            else:
                print("Specify which player will move first: B for black, W for white")
                return getFirstPlayer() # changed this line

        except ValueError:
            print("Specify which player will move first: B for black, W for white")
            continue
        else:
            break

rawDescription: Why is my function returning the wrong value on certain conditions?


code:
import Image
import numpy as np

image=Image.open('L_2d.png')
image.load()

image_data = np.asarray(image)
image_data_bw = image_data.max(axis=2)
non_empty_columns = np.where(image_data_bw.max(axis=0)>0)[0]
non_empty_rows = np.where(image_data_bw.max(axis=1)>0)[0]
cropBox = (min(non_empty_rows), max(non_empty_rows), min(non_empty_columns), max(non_empty_columns))

image_data_new = image_data[cropBox[0]:cropBox[1]+1, cropBox[2]:cropBox[3]+1 , :]

new_image = Image.fromarray(image_data_new)
new_image.save('L_2d_cropped.png')

rawDescription: Automatically cropping an image with python/PIL


code:
def prime_func(number):
    number = int(number)
    START = 2
    END = int((number**0.5)) + 1

    if number == 2:
     return 1
    if number == 1:
     return 0

    while True:
        flag = True
        for i in range(START, END):
            if number % i == 0:
                flag = False
                break
        if flag:
            return number
        else:
            number += 1

if __name__ == '__main__':
    num = int(input())
    print(prime_func(num))

rawDescription: Finding Primes Different Approach

description: Finding Primes Different Approach


code:
def searchName(name, score):
    with open(fileName, 'r') as f:
        data = f.read().split('\n')
        with open(newFileName, 'w') as newFile:
            for line in data:
                if name in line:
                    line+=(',') + str(score) + (',')
                newFile.write(line + '\n')

rawDescription: Python Searching for variable in file and appending another value


code: dict(zip(keys,values))

rawDescription: What's the Pythonic way to combine two sequences into a dictionary?


code:
import subprocess

ip = '127.0.0.1'
cycle_time = 42
subprocess.call(['./other_script.py', '--ips={} --cycletime={}'.format(ip, cycle_time)])

rawDescription: python how do i make int's from script 1 shared with script 2 3 ect

description: Python how do i make int's from script 1 shared with script 2 3 ect


code:
class BaseTask(object):
    '''change object to BaseProject whenever you figure out what your `Project`
    class should be, or if you need it at all'''

    def __init__(self, title):
        self.title = title
        self.description=""

class Task(BaseTask):
    def __init__(self, title):
        super(Task, self).__init__(title)
        self.subtasks = []
        self.default_hours = 1

    @property
    def hours(self):
        if len(self.subtasks) < 1:
            return self.default_hours
        return sum(subtask.hours for subtask in self.subtasks)

class SubTask(BaseTask):
    def __init__(self, title):
        super(SubTask, self).__init__(title)
        self.hours = 0

rawDescription: Class Inheritance from same Class

description: Class Inheritance from same Class


code:
from django.contrib.auth.models import User, Permission
from django.db.models import Q

perm = Permission.objects.get(codename='consultant_permission')
users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm) ).distinct()
recipients = list(i for i in users.values_list('email', flat=True) if bool(i))

rawDescription: How to send_mail to Users in group in Django?

description: Send_mail to Users in group in Django


code:
from PyQt4 import QtGui
dir(QtGui.QToolBox)

rawDescription: Autocompletion not working with PyQT4 and PyKDE4 in most of the IDEs


code:
b = BitField("foo",0x0,2)
b.default   # 0

rawDescription: Scapy BitField and type() question

description: Scapy BitField and type() question


rawDescription: Most efficient way to test whether each element from one array exists in a another array, using numpy


rawDescription: Model Method from rest_framework modelSerializer


code:
for x in xrange(max_combo_len, 0, -1):
    possible_combos = (" ".join(item) for item in itertools.permutations(bag,x))
    #then check to see if each possible combo is in a specific Dict
    combos =  (c for c in possible_combos if c in specific_dict)

rawDescription: Python - Speed up generation of permutations of a list (and process of checking if permuations in Dict)


code:
widget = QtGui.QTableWidget(parent) # or get the widget some other way
for i, row in enumerate(to_d_col):
  for j, value in enumerate(row):
    ci = QtGui.QTableWidgetItem(value)
    widget.setItem(i, j, ci)

rawDescription: Printing text from 2-D list python

description: Printing text from 2-D list python


code:
ncol = 1
lgwidth_old = 0.
renderer = fig.canvas.get_renderer()
while True:
    lg = ax.legend(loc='upper center', bbox_to_anchor=(0., -0.05, 1., 0.),
                   borderaxespad=0, ncol=ncol)
    fig.canvas.draw()
    lgbbox = lg.get_window_extent(renderer).inverse_transformed(ax.transAxes)

    if lgwidth_old == lgbbox.width:
        # All the entries fit within a single row. Keep the legend
        # as is and break the loop.
        break

    if lgbbox.width < 1:
        # The width of the legend is still smaller than that of the axe.
        # Continue iterating.
        ncol += 1
        lgwidth_old = lgbbox.width
    else:
        # The width of the legend is larger than that of the axe.
        # Backtrack ncol, plot the legend so it span the entire width of
        # the axe, and break the loop.
        ncol -= 1
        lg = ax.legend(loc='upper center', bbox_to_anchor=(0., -0.05, 1., 0.),
                       borderaxespad=0, ncol=ncol, mode='expand')
        break

    if ncol > 100:
        print('Number max of iteration reached. Something is wrong.')
        break

rawDescription: Control Matplotlib legend box width for wrapping


rawDescription: Pandas select discontinuous dataframe date slices?


rawDescription: Im being asked to to initialize a list, l_counts with as many 0 as characters in the English alphabet


code:
a_function_with_status_display = status_display(a_function)
a_function_with_call_counter = call_counter(a_function)

rawDescription: Python decorators to function variables

description: Python decorators to function variables


code:
class SetTimeoutTestCommand(sublime_plugin.WindowCommand):
    def run(self, edit):
        for x in range(1,10):
            sublime.set_timeout(lambda x=x: print(x), x*1000)

rawDescription: Use of set_timeout with Sublime Text 3 API


code:
from paramiko.client import SSHClient

client = SSHClient()
client.load_system_host_keys()
client.connect('linuxip', username='your_user', password='very_secret')
stdin, stdout, stderr = client.exec_command('python /home/your_user/your/path/to/scripty.py')

rawDescription: Start a process on another computer on the network


code:
import boto.ec2
ec2 = boto.ec2.connect_to_region('us-west-2')  # or region of choice
eip = ec2.allocate_address()
print(eip.public_ip)

rawDescription: Boto allocate elastic IP

description: Boto allocate elastic IP


code:
class test_appletrailer(unittest.TestCase):

    all_trailers = None

    def setup(self):
        # Only initialize all_trailers once.
        if self.all_trailers is None:
            self.__class__.all_trailers = Trailers(res = "720", verbose = True)

rawDescription: Caching result of setUp() using Python unittest


code: time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0

rawDescription: Python datetime to microtime

description: Python datetime to microtime


code:
class A(models.Model):
  name = models.CharField(max_length = 128)
  created_date = models.DateTimeField(auto_now_add = True)
  modified_date = models.DateTimeField(auto_now = True)
  B_list = models.ManyToManyField('B')

class B(models.Model):
  name = models.CharField(max_length = 128)
  created_date = models.DateTimeField(auto_now_add = True)
  modified_date = models.DateTimeField(auto_now = True)

rawDescription: Django: Asymmetric ManyToMany Relation

description: Django: Asymmetric ManyToMany Relation


code:
def my_repeated_function(data):
    print ("My function called.")

Clock.schedule_interval(my_repeated_function, 1.0 / 30) # no brackets on function reference
                                                       # call it 30 times per second

rawDescription: Python Kivy: Add Background loop

description: Python Kivy: Add Background loop


rawDescription: Monitoring a variable for change in Python


code:
html =re.sub(re.compile("<!--.*?-->",re.DOTALL),"",html)
soup=BeautifulSoup(html)
soup.find('p', attrs={'class' : 'lead'})

rawDescription: Getting BeautifulSoup to find a specific <p>


code:
def handle_one():
  do_stuff

def handle_two():
  do_stuff

def handle_three():
  do_stuff

{'one': handle_one,
 'two': handle_two,
 'three': handle_three}[option]()

rawDescription: What's an alternative to if/elif statements in Python?


code:
import pandas as pd
from bson import json_util, ObjectId
from pandas.io.json import json_normalize
import json

def mongo_to_dataframe(mongo_data):

        sanitized = json.loads(json_util.dumps(mongo_data))
        normalized = json_normalize(sanitized)
        df = pd.DataFrame(normalized)

        return df

rawDescription: Getting nested data from MongoDB into a Pandas data frame


code:
def getNegativesList(postivesAndNegativeslist):
    if postivesAndNegativeslist is None:
        return None
    elif len(postivesAndNegativeslist) == 0:
        return None
    negativesList = []
    for val in postivesAndNegativeslist:
        if val<0:
            negativesList.append(val)
    return negativesList
print(getNegativesList([2,-3,-5,10,-1]))

rawDescription: My code isn't executing

description: My code isn't executing


code:
import sys
import trace

# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],
    trace=0,
    count=1)

# run the new command using the given tracer
tracer.run('main()')

# make a report, placing output in the current directory
r = tracer.results()
r.write_results(show_missing=True, coverdir=".")

rawDescription: List of functions calls in python tests

description: List of functions calls in python tests


code:
from ctypes import *
from ctypes.wintypes import *

user32 = WinDLL('user32', use_last_error=True)

HC_ACTION = 0
WH_MOUSE_LL = 14

WM_QUIT        = 0x0012
WM_MOUSEMOVE   = 0x0200
WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP   = 0x0202
WM_RBUTTONDOWN = 0x0204
WM_RBUTTONUP   = 0x0205
WM_MBUTTONDOWN = 0x0207
WM_MBUTTONUP   = 0x0208
WM_MOUSEWHEEL  = 0x020A
WM_MOUSEHWHEEL = 0x020E

MSG_TEXT = {WM_MOUSEMOVE:   'WM_MOUSEMOVE',
            WM_LBUTTONDOWN: 'WM_LBUTTONDOWN',
            WM_LBUTTONUP:   'WM_LBUTTONUP',
            WM_RBUTTONDOWN: 'WM_RBUTTONDOWN',
            WM_RBUTTONUP:   'WM_RBUTTONUP',
            WM_MBUTTONDOWN: 'WM_MBUTTONDOWN',
            WM_MBUTTONUP:   'WM_MBUTTONUP',
            WM_MOUSEWHEEL:  'WM_MOUSEWHEEL',
            WM_MOUSEHWHEEL: 'WM_MOUSEHWHEEL'}

ULONG_PTR = WPARAM
LRESULT = LPARAM
LPMSG = POINTER(MSG)

HOOKPROC = WINFUNCTYPE(LRESULT, c_int, WPARAM, LPARAM)
LowLevelMouseProc = HOOKPROC

class MSLLHOOKSTRUCT(Structure):
    _fields_ = (('pt',          POINT),
                ('mouseData',   DWORD),
                ('flags',       DWORD),
                ('time',        DWORD),
                ('dwExtraInfo', ULONG_PTR))

LPMSLLHOOKSTRUCT = POINTER(MSLLHOOKSTRUCT)

def errcheck_bool(result, func, args):
    if not result:
        raise WinError(get_last_error())
    return args

user32.SetWindowsHookExW.errcheck = errcheck_bool
user32.SetWindowsHookExW.restype = HHOOK
user32.SetWindowsHookExW.argtypes = (c_int,     # _In_ idHook
                                     HOOKPROC,  # _In_ lpfn
                                     HINSTANCE, # _In_ hMod
                                     DWORD)     # _In_ dwThreadId

user32.CallNextHookEx.restype = LRESULT
user32.CallNextHookEx.argtypes = (HHOOK,  # _In_opt_ hhk
                                  c_int,  # _In_     nCode
                                  WPARAM, # _In_     wParam
                                  LPARAM) # _In_     lParam

user32.GetMessageW.argtypes = (LPMSG, # _Out_    lpMsg
                               HWND,  # _In_opt_ hWnd
                               UINT,  # _In_     wMsgFilterMin
                               UINT)  # _In_     wMsgFilterMax

user32.TranslateMessage.argtypes = (LPMSG,)
user32.DispatchMessageW.argtypes = (LPMSG,)

@LowLevelMouseProc
def LLMouseProc(nCode, wParam, lParam):
    msg = cast(lParam, LPMSLLHOOKSTRUCT)[0]
    if nCode == HC_ACTION:
        msgid = MSG_TEXT.get(wParam, str(wParam))
        msg = ((msg.pt.x, msg.pt.y),
                msg.mouseData, msg.flags,
                msg.time, msg.dwExtraInfo)
        print('{:15s}: {}'.format(msgid, msg))
    return user32.CallNextHookEx(None, nCode, wParam, lParam)

def mouse_msg_loop():
    hHook = user32.SetWindowsHookExW(WH_MOUSE_LL, LLMouseProc, None, 0)
    msg = MSG()
    while True:
        bRet = user32.GetMessageW(byref(msg), None, 0, 0)
        if not bRet:
            break
        if bRet == -1:
            raise WinError(get_last_error())
        user32.TranslateMessage(byref(msg))
        user32.DispatchMessageW(byref(msg))

if __name__ == '__main__':
    import time
    import threading
    t = threading.Thread(target=mouse_msg_loop)
    t.start()
    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            user32.PostThreadMessageW(t.ident, WM_QUIT, 0, 0)
            break

rawDescription: Setting up a WindowsHook in Python (ctypes, Windows API)


code:
writer = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
for row in cursor:
    writer.writerow(list(row) + ['', '', '', ''])

rawDescription: Append columns to python cursor before writing to CSV?


code:
import getpass
getpass.getuser()

rawDescription: Is there a portable way to get the current username in Python?


code:
from collections import namedtuple

# PageBoundary is a subclass of named tuple with special relational
# operators. __le__ and __ge__ are left undefined because they don't
# make sense for this class.
class PageBoundary(namedtuple('PageBoundary', 'begin end')):
    # to prevent making an instance dict (See namedtuple docs)
    __slots__ = ()

    def __lt__(self, other):
        return self.end < other.begin

    def __eq__(self, other):
        # you can put in an assertion if you are concerned the
        # method might be called with the wrong type object
        assert isinstance(other, PageBoundary), "Wrong type for other"

        return self.begin == other.begin and self.end == other.end

    def __ne__(self, other):
        return not self == other

    def __gt__(self, other):
        return other < self

class PhysicalPage(object):
    # class variables: number of digits each attribute gets
    _PAGE_PAD, _LINE_PAD = 10, 12

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

        # single leading underscore is 'private' by convention
        # not enforced by the language
        self._begin = self.page_num * 10**PhysicalPage._LINE_PAD + tmp_line_num
        #self._end = ...however you calculate this...                    ^ not defined yet

        self.begin_line_num = -1
        self.end_line_num = -1

    # this serves the purpose of a `getter`, but looks just like
    # a normal class member access. used like x = page.begin
    @property
    def begin(self):
        return self._begin

    @property
    def end(self):
        return self._end

    def __lt__(self, other):
        assert(isinstance(other, PhysicalPage))
        return self._end < other._begin

    def __eq__(self, other):
        assert(isinstance(other, PhysicalPage))
        return self._begin, self._end == other._begin, other._end

    def __ne__(self, other):
        return not self == other

    def __gt__(self, other):
        return other < self

class VirtualPage(object):
    def __init__(self, physical_pages=None):
        self.physcial_pages = sorted(physcial_pages) if physical_pages else []

    def __lt__(self, other):
        if self.physical_pages and other.physical_pages:
            return self.physical_pages[-1].end < other.physical_pages[0].begin

        else:
            raise ValueError

    def __eq__(self, other):
        if self.physical_pages and other.physical_pages:
            return self.physical_pages == other.physical_pages

        else:
            raise ValueError

    def __gt__(self, other):
        return other < self

rawDescription: How to use python collections for custom classes

description: Use python collections for custom classes


code:
results1_dict = dict((row[0], list(row[1:])) for row in results1)
results2_dict = dict((row[0], list(row[1:])) for row in results2)

for key, value in results2_dict:
    if key in results1_dict:
        results1_dict[key].extend(value)
    else:
        results1_dict[key] = value

rawDescription: Efficient way to combine results of two database queries


code:
from distutils.core import setup, Command
import distutils.command.install as InstallCommand
from subprocess import call

class FinallyDoSomething(Command):
    description = "Do my custom stuff"
    user_options = []
    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        call(["update-rc.d", "kmsd", "defaults", "21"])

class NewInstall(InstallCommand):
    sub_commands = InstallCommand.sub_commands + [
            ('custom_install', None),]

setup(name='PackageName',
      version='0.1',
      #The rest of the setup config
      cmdclass={
          'install': NewInstall,
          'custom_install': FinallyDoSomething,
          },
      )

rawDescription: Is it possible to define command to execute in setup.py


code:
import re
s = "This is a line of text\!, hello\: It\"s"
re.sub(r'\\([!:])', r'\1', s)

rawDescription: Python Remove backslashes before a set of characters


code:
companies_with_more_than_1_user = (
    Company.objects
        .annotate(num_users=Count('userprofile'))
        .filter(num_users__gt=1)
)
users = User.objects.filter(userprofile__company__in=companies_with_more_than_1_user)

rawDescription: Filter by twice-removed ForeignKey objects


code: ''.join(filter(str.isalpha, a))

rawDescription: Find letters in string without using for loop


code:
import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange
import numpy as np

date1 = datetime.datetime( 2000, 3, 2)
date2 = datetime.datetime( 2001, 10, 10)
delta = datetime.timedelta(days=28)
dates = drange(date1, date2, delta)

ys = np.arange( len(dates) )

fig, ax = plt.subplots()

ax.plot_date(dates, ys*ys)

ax.xaxis.set_major_formatter( DateFormatter('%Y-%m') )

plt.show()

rawDescription: How to plot a datetime in Python?

description: Plot a datetime in Python


code: area_dict = dict(zip(lakes.area, lakes.count))

rawDescription: python pandas dataframe columns convert to dict key and value

description: Python pandas dataframe columns convert to dict key and value


code: OUT = [[i.Name for i in user_worksets], [i.Kind for i in user_worksets]]

rawDescription: Append multiple items into list of lists in Python


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

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.arange(10),12*np.arange(10))
ax.text(0.4, 0.7, 'Correct Position', transform=ax.transAxes)

plt.show()

rawDescription: Positioning text by axis fraction

description: Positioning text by axis fraction


code:
class SocialGroup(Document):
    timestamp = DateTimeField(default=datetime.now)
    course_name = StringField()
    group_name = StringField(choices=[('A', 1), ('B', 1), ('C', 1),('D', 1), ('E', 1), ('F', 1), ('None',1)], default="None")
    meta = {
        'indexes': [
            {'fields': ('course_name', 'group_name'), 'unique': True}
        ]
    }

rawDescription: How to make a combined set of fields unique in Mongodb in Python

description: Make a combined set of fields unique in Mongodb in Python


code:
df = pd.DataFrame(dict(x=np.repeat(np.arange(21), 10), y=np.random.randn(210)))
df.loc[df.x == 20, "x"] = ">= 20"

g = sns.factorplot(x="x", y="y", data=df, kind="box")
g.axes[0, 0].set_xticks(range(20) + [20.5])

rawDescription: How can I adjust the spacing between labels in a factorplot in Seaborn

description: Adjust the spacing between labels in a factorplot in Seaborn


rawDescription: How would i increment this PyGame line

description: How would i increment this PyGame line


code:
import csv
import re

def read_general(fname):
    # Read general info to dict with 'PR 123'-like keys

    # Gerexp that will split row into ready-to-use dict
    re_name = re.compile(r'''
        (?P<Name>.+)
        \ --\  # Separator + space
        (?P<Division>.+)
        \  # Space
        \(
            (?P<Division_Abbreviation>.*)
        \)
        \  # Space
        (?P<Id>\d+)
        \  # Space
        \[Age:\  # Space at the end
            (?P<Age>\d+)
        \]
        ''', re.X)

    general = {}

    with open(fname, 'rt') as f:
        for line in f:
            line = line.strip()
            m = re_name.match(line)

            if m:
                # Name line, start new man
                man = m.groupdict()
                key = '%s %s' % (m.group('Division_Abbreviation'), m.group('Id'))
                general[key] = man

            elif line:
                # Non empty lines
                # Add values to dict
                key, value = line.split(': ', 1)
                man[key] = value

    return general

def add_bool_criteria(fname, field, general):
    # Append a field with YES/NO value

    with open(fname, 'rt') as f:
        yes_keys = set()

        # Phase one, gather all keys
        for line in f:
            line = line.strip()
            _, keys = line.split(': ', 1)

            yes_keys.update(keys.split(', '))

        # Fill data
        for key, man in general.items():  # iteritems() will be faster in Python 2.x
            man[field] = 'YES' if key in yes_keys else 'NO'

def save_csv(fname, general):
    with open(fname, 'wt') as f:
        # Gather field names
        all_fields = set()
        for value in general.values():
            all_fields.update(value.keys())

        # Write to csv
        w = csv.DictWriter(f, all_fields)
        w.writeheader()
        w.writerows(general.values())

def main():
    general = read_general('general.txt')
    add_bool_criteria('cars.txt', 'Car?', general)
    add_bool_criteria('house.txt', 'House?', general)
    from pprint import pprint
    pprint(general)
    save_csv('result.csv', general)

if __name__ == '__main__':
    main()

rawDescription: Python: Parsing Multiple .txt Files into a Single .csv File?


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

# you can do this in one line, that's what 'unpack' is for:
timepoints, intensity = np.loadtxt('dataset', usecols=(0,1), unpack=True, delimiter=",")

interd = timepoints[1] - timepoints[0] # if this is 1, it can be ignored
sp = np.fft.fft(intensity)
freq = np.fft.fftfreq(len(intensity), d=interd)

pl.plot(np.fft.fftshift(freq), np.fft.fftshift(np.abs(sp)))
pl.xlabel("frequency(Hz)")
pl.show()

rawDescription: what is the difference between the two datasets for numpy.fft

description: What is the difference between the two datasets for numpy.fft


code:
import numpy as np

# Create array.
size1 = 10
size2 = 60
shape = (size1, size2)
a = np.mod(np.arange(1, size1 * size2 + 1), size2).reshape(shape)
# Reshape array with z = 1.
b = np.reshape(a, (size1, size2, 1))
# Reshape array with z = 2.
c = np.reshape(a, (size1, size2 / 2, 2))
# Reshape array correctly.
d = np.reshape(a, (size1, 2, size2 / 2))
d = np.swapaxes(d, 1, 2)

rawDescription: Generating a 4-D array from 1-D data reshape


code:
import numpy as np
np.isnan(np.nan) # returns True

rawDescription: NaN in python and validity checking

description: NaN in python and validity checking


code: request, = conn.send.call_args

rawDescription: Asserting an object passed into a mocked method in the python mock


code:
fitness_levels = [-20, 23, -55, 11, 10, -18, -48, 16, -60, 20, 22, 16, 21, 66, 10, 46, -42]
a,b = sorted(fitness_levels[:2], key=abs) # setting defaults. a<=b
ia, ib = 0,1 # indices
for i,val in enumerate(fitness_levels[2:]): # use itertools.islice for large lists (for constant space)
  if abs(val) < abs(a):
    b,a = a,val
    ib, ia = ia, i
  elif abs(val) < abs(b):
    b = val
    ib = i

rawDescription: How to find the two indexes from a list whos values are closest to zero

description: Find the two indexes from a list whos values are closest to zero


code:
def foo(extension):
    return '*.' + ''.join('[%s%s]' % (e.lower(), e.upper()) for e in extension)

foo('mov')

rawDescription: Accounting for lower and uppercase in glob


code:
def item_exists(tree, match, root):
    item, cookie = tree.GetFirstChild(root)

    while item.IsOk():
        if tree.GetItemText(item) == match:
            return True
        #if tree.ItemHasChildren(item):
        #    if item_exists(tree, match, item):
        #        return True
        item, cookie = tree.GetNextChild(root, cookie)
    return False

result = item_exists(tree, 'some text', tree.GetRootItem())

rawDescription: Finding certain child in wxTreeCtrl and updating TreeCtrl in wxPython


code:
import re
url = 'http://yahoo.com/home/?site=new'
re.findall(r'^[^?]+', url)[0]

rawDescription: Straightforward way to get url minus querystring


code:
import subprocess
import re

def findCAS(pdf, page=None):
    '''Find all CAS numbers on the numbered page of a file.

    Arguments:
    pdf -- Name of the PDF file to search
    page -- number of the page to search. if None, search all pages.
    '''
    if page == None:
        args = ['pdftotext', '-layout', '-q', pdf, '-']
    else:
        args = ['pdftotext', '-f', str(page), '-l', str(page), '-layout',
                '-q', pdf, '-']
    txt = subprocess.check_output(args)
    candidates =  re.findall('\d{2,6}-\d{2}-\d{1}', txt)
    checked = [x.lstrip('0') for x in candidates if checkCAS(x)]
    return list(set(checked))

def checkCAS(cas):
    '''Check if a string is a valid CAS number.

    Arguments:
    cas -- string to check
    '''
    nums = cas[::-1].replace('-', '') # all digits in reverse order
    checksum = int(nums[0]) # first digit is the checksum
    som = 0
    # Checksum method from: http://nl.wikipedia.org/wiki/CAS-nummer
    for n, d in enumerate(nums[1:]):
        som += (n+1)*int(d)
    return som % 10 == checksum

rawDescription: How to get pypdf to read page content line by line?

description: Get pypdf to read page content line by line


code:
df
df['C'] =  df.groupby('A')['A'].transform(lambda x: pd.Series(range(1, len(x)+1), index=x.index))
df

rawDescription: Create a column which increments based on another column in Python


code:
type(df.loc[[3]])
type(df.loc[[1]])

rawDescription: Pandas selecting by label sometimes return series, sometimes returns dataframe


code:
import imp
pandas13 = imp.load_module("pandas13",
                           *imp.find_module("pandas", ["/path/to/pandas13/parent/"]))
pandas14 = imp.load_module("pandas14",
                           *imp.find_module("pandas", ["/path/to/pandas14/parent/"]))

rawDescription: Run different versions of Pandas in different module of the same programm


code:
with open("list2.csv") as f:
 print(sum(query in line for line in f))  #gives number of lines found

rawDescription: Print number of lines found

description: Print number of lines found


code:
p = re.compile(pat_eq, re.X)
string_c = string
for match_obj in p.finditer(string):
    original = match_obj.group(0)
    fixed = p1.group(1) + p1.group(2) + '==' + p1.group(4) + p1.group(5)
    string_c = string_c.replace(original, fixed)

return string_c

rawDescription: python's regular expression that repeats

description: Python's regular expression that repeats


code: s = s.replace('\r\n', '\n')

rawDescription:
Remove
 from python string

description:
Remove
 from python string


code:
source = im.split()
mask = source[2].point(lambda i: i < 100 and 255)
im = Image.merge(im.mode, source)

rawDescription: Python PIL remove sections of an image based on its colour


code:
import matplotlib.pyplot as plt

x = [1, 4, 7]
ylow = [0, 3, -2]
yhigh = [1, 4, 2]
width = [8, 15, 6]

plt.vlines(x, ylow, yhigh, linewidth=width,
           antialiased=False)
plt.axis([0, 8, -4, 5])
plt.show()

rawDescription: Asnap hlines and vlines to whole pixels in matplotlib


code:
bag = [['Empty'], ['Misc'], ['Vide'], ['Empty'], ['Empty'], ['Empty']]

for ls in bag:
    if ls != ['Vide']:
        print(ls)

rawDescription: Print only no-matching in list in python 3


code:
from datetime import datetime
#       ^               ^
#       |               |
#    module      class inside module

# Now you can use
now = datetime.now()

rawDescription: The correct way to import and use the datetime python library


code:
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db',
        'TIMEOUT': None,
    }
}

rawDescription: Can I cache data permanently using database caching on python Django

description: Cache data permanently using database caching on python Django


code:
with open('/full/path/to/file', 'wb') as f:
    pickle.dump(object, f)

rawDescription: How to 'pickle' an object to a certain directory?


code:
val3 = getattr(getattr(val1, "val2"), "val3")
example = val3(item)

# Or simply:
example = getattr(getattr(val1, "val2"), "val3")(item)

rawDescription: python getattr multiple levels with values being passed as well

description: Python getattr multiple levels with values being passed as well


rawDescription: How to select multiple columns based on their names in python?

description: Select multiple columns based on their names in python


code:
retval = [True]
def cb(widget):
    retval[0] = False
    gtk.main_quit()
...
return retval[0]

rawDescription: Blocking behavior of PyGTK's main loop

description: Blocking behavior of PyGTK's main loop


code:
import BeautifulSoup
html = 'foo'
bs = BeautifulSoup.BeautifulSoup(html)
bs.findAll(text=True)

rawDescription: Remove HTML tags in AppEngine Python Env (equivalent to Ruby's Sanitize)


code:
class foo(object):
    pass

x = foo()
dir(x) == dir(foo)
x.a = 3
dir(x) == dir(foo)

rawDescription: when will dir(class_name) != dir(instance) in python

description: When will dir(class_name) != dir(instance) in python


code:
df = pd.DataFrame([[np.nan, 3.3, 8], [np.nan, np.nan, 5.5]], index=['Item1', 'Item2'], columns=['Estimate1', 'Estimate2', 'Estimate3'])
df
fill_value = pd.DataFrame({col: df.sum(axis=1) for col in df.columns})
fill_value
df.fillna(fill_value)

rawDescription: How to replace NaN with sum of the row in Pandas DatatFrame

description: Replace NaN with sum of the row in Pandas DatatFrame


code:
def __init__(self, *args, **kwargs):
    if len(args) == 1 and not kwargs and isinstance(args[0], type(self)):
        other = args[0]
        # copy whatever is needed from there, e. g.
        self.__dict__ = dict(other.__dict__) # copy it!
    else:
        self.__dict__ = kwargs
        # what do we do with args here?

rawDescription: How to use *args and **kwargs with __init__ in a smart and elegant way in Python?

description: Use *args and **kwargs with __init__ in a smart and elegant way in Python


code:
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
import numpy as np

x = np.arange(6)
y = np.linspace(0, 11, 50)
z = x[:, np.newaxis] + y**2

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection = '3d')
for xval, zrow in zip(x, z):
    ax.plot(xval*np.ones_like(y), y, zrow, color = 'black')
plt.show()

rawDescription: 3D plots using maplot3d from matplotlib-


code:
country, country_is_new = UserReportedCountry.objects.get_or_create(country_name=my_country_name)
city, city_is_new = UserReportedCity.objects.get_or_create(country=country, city_name=my_city_name)

rawDescription: Using get or insert functionality on one to many django models and modelforms


code:
import global_variables

global_variables.name = 'Inigo Montoya'

rawDescription: Global variables in Python across all modules


code:
# Create some sample data
all_data = 20 * np.random.randn(480,640)

all_data[all_data <= -10] = np.nan
variance_data.append(np.nanvar(all_data))

rawDescription: How to read only specific, needed values from a csv file into python with genfromtxt?

description: Read only specific, needed values from a csv file into python with genfromtxt


code:
import dbf

my_table = dbf.Table('/path/and/filename')

with my_table:
    my_table.add_fields('header3 N(3,0)')

    for record in dbf.Process(my_table):
        record.header3 = record.header1 + record.header2

rawDescription: How to reference cells from DBF with python?

description: Reference cells from DBF with python


code:
agroups,hit,config = tdata[n]
tile.agroups = self.string2groups(agroups)

rawDescription: PGU Tiles collision detection

description: PGU Tiles collision detection


code:
foo = "SSYYNNOOPPSSIISS"
import itertools
''.join(ch for ch, _ in itertools.groupby(foo))

rawDescription: Python: Best Way to remove duplicate character from string


code:
# original image
img = Image.open('test.png')
# converted to have an alpha layer
im2 = img.convert('RGBA')
# rotated image
rot = im2.rotate(22.2, expand=1)
# a white image same size as rotated image
fff = Image.new('RGBA', rot.size, (255,)*4)
# create a composite image using the alpha layer of rot as a mask
out = Image.composite(rot, fff, rot)
# save your work (converting back to mode='1' or whatever..)
out.convert(img.mode).save('test2.bmp')

rawDescription: Specify image filling color when rotating in python with PIL and setting expand argument to true


code:
import os

def tara(directory):
    start = os.getcwd()
    files = []
    os.chdir(directory)

    for oge in os.listdir(os.curdir):
        if not os.path.isdir(oge):
            files.append(oge)
        else:
            files.extend(tara(oge))

    os.chdir(start)
    return files

rawDescription: Opening a file in a folder in Python

description: Opening a file in a folder in Python


code:
def __init__(self, root):
    Frame.__init__(self, root)
    self.root = root
    self.butt_released = True

    button3 = Button(self.but_frame, text='Step', width=15, command=lambda :self.step_funct())
    button3.pack(side='right')
    button4 = Button(self.but_frame, text='Run', width=15)
    button4.pack(side='right')
    button4.bind("<Button-1>", self.butt_press)
    button4.bind("<ButtonRelease-1>", self.butt_release)

def butt_press(self, event):
    self.butt_released = False
    self.run_funct()

def run_funct(self):
    if not self.butt_released:
        self.step_funct()
        self.root.after(10, self.run_funct)

def butt_release(self, event):
    self.butt_released = True

rawDescription: Infinite loop for widget button in tkinter


code:
import shutil

response=urllib2.urlopen('http://www.diffbot.com/api/article?token='+token+'&url='+url).read()
with open(file_out,'w') as outfile:
    shutil.copyfileobj(response, outfile)

rawDescription: how to save json content from a web query

description: Save json content from a web query


code:
story = "this is a very long story"
id = stories_col.find_one_and_update({
    'story': story,
}, {
    '$setOnInsert': { 'story': story }
}, upsert=True, return_document=ReturnDocument.AFTER)

rawDescription: In PyMongo, how to get the _id of the document if found, else insert and get the _id of the inserted document


code:
request_number = 82673

# base dir
_dir = "D:\Current Download"

# create dynamic name, like "D:\Current Download\Attachment82673"
_dir = os.path.join(_dir, 'Attachment%s' % request_number)

# create 'dynamic' dir, if it does not exist
if not os.path.exists(_dir):
    os.makedirs(_dir)

rawDescription: Can I create directories with dynamic names on run time using os.mkdir()?

description: Create directories with dynamic names on run time using os.mkdir()


code:
class App(models.Model):

    package = models.FileField(upload_to=settings.APP_PACKAGE_ROOT)
    assets = models.ManyToManyField('AppAsset', blank=True, null=True)
    download_count = models.IntegerField(default=0)

class AppAsset(models.Model):

    def __unicode__(self):
        return self.asset_file.name

    notes = models.CharField(max_length=255, null=True, blank=True)
    type = models.CharField(max_length=255, null=True, blank=True)
    asset_file = models.FileField(upload_to=settings.APP_PACKAGE_ROOT)

rawDescription: Overriding formset in TabularInline Django admin form


code:
from PySide import QtGui
import sys

class W(QtGui.QTableWidget):
    def __init__(self):
        super(W,self).__init__(3, 3)

        self.verticalHeader().sectionClicked.connect(self.onSectionClicked)

    def onSectionClicked(self, logicalIndex):
        print("onSectionClicked:", logicalIndex)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = W()
    w.show()
    sys.exit(app.exec_())

rawDescription: PySide/pyQt What signal is sent when selecting a whole row in QTableWidget by clicking on vertical header


code:
symbols('a0:3')
numEquations = 15
symbols('a0:%d'%numEquations)

rawDescription: SymPy - Arbitrary number of Symbols

description: SymPy - Arbitrary number of Symbols


code: idx_min, val_min = min(enumerate(data), key=lambda i, x: x[0])

rawDescription: Python: Get the smallest item from a list inside a list


code: ax.imshow(data, extent=[0, 1, 0, 1])

rawDescription: Equivalent to matlab's imagesc in matplotlib?


rawDescription: Spliting Variable to count groups of double characters


code:
A = np.array([1, 3, 5, 7])
B = np.array([2, 4, 6, 8])
np.insert(B, np.arange(len(A)), A)

rawDescription: How do I combine two numpy arrays element wise in python?

description: Combine two numpy arrays element wise in python


code:
import gtk

window = gtk.Window()
window.connect('delete-event',lambda widget, event: True)

rawDescription: In GTK, how do I make a window unable to be closed?


rawDescription: Make SQLAlchemy query by list case insensitive


code:
def as_float32(self):
    """
    See: http://en.wikipedia.org/wiki/IEEE_754-2008
    """
    from struct import pack,unpack
    s = self.bitlist
    return unpack("f",pack("I", bits2int(s)))

# Where the bits2int function converts bits to an integer.
def bits2int(bits):
    # You may want to change ::-1 if depending on which bit is assumed
    # to be most significant.
    bits = [int(x) for x in bits[::-1]]

    x = 0
    for i in range(len(bits)):
        x += bits[i]*2**i
    return x

rawDescription: converting binary string into float

description: Converting binary string into float


code:
forms = dict()
forms['form1'] = {a:3, b:4}
forms['form2'] = {a:7, b:8}

form = forms.get(args)
if form:
   runtest(form)
else:
   print('Invalid form: {}'.format(args))

rawDescription: Python Easy Way to Match String Input to existing dictionary


code:
import difflib

words = ["Hi", "Hello", "Bye", "His", "Her"]
print(difflib.get_close_matches('Hi', words))
# ['Hi', 'His']

rawDescription: How to get all words that are similar to a word the user types Python

description: Get all words that are similar to a word the user types Python


code:
import re
the_string="http://hello-world.com"
re.findall(r'[\w.]+',the_string)

rawDescription: Python compile all non-words except dot[.]


code:
import csv

newlines = []
with open('csvfilename.csv', 'rb') as csvfile:
  reader = csv.reader(csvfile)
  i=0
  for row in reader:
    newlines.append(row[:i] + [1] + row[i+1:])
    i+=1
with open('newcsvfilename.csv','wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerows(newlines)

rawDescription: python CSV edit elements in the diagonal of a matrix

description: Python CSV edit elements in the diagonal of a matrix


code:
import sys
import imp

class CustomImportFinder(object):

    @staticmethod
    def find_module(fullname, path=None):
        # Do your custom stuff here, look in database, etc.
        code_from_database = "VAR = 1"
        return CustomImportLoader(fullname, path, code_from_database)

class CustomImportLoader(object):

    def __init__(self, fullname, path, code_from_database):
        super(CustomImportLoader, self).__init__()
        self.fullname = fullname
        self.path = path
        self.code_from_database = code_from_database

    def is_package(fullname):
        # is this a package?
        return False

    def load_module(self, fullname):
        code = self.code_from_database
        ispkg = self.is_package(fullname)
        mod = sys.modules.setdefault(fullname, imp.new_module(fullname))
        mod.__file__ = "<%s>" % self.__class__.__name__
        mod.__loader__ = self
        if ispkg:
            mod.__path__ = []
            mod.__package__ = fullname
        else:
            mod.__package__ = fullname.rpartition('.')[0]
        exec(code, mod.__dict__)
        return mod

sys.meta_path.append(CustomImportFinder)

import blah
print(blah)
# <module 'blah' (built-in)>
print(blah.VAR)
# 1

rawDescription: IronPython - Is there a way to load a python script from the database or embedded from a string resource?


code:
from itertools import groupby

result = []
for key, group in groupby(warnstufe2, lambda x: x[0]):
    for element in group:
        a = element[1:4]
        b = element[4:12]
        c = [a,b]
        result.append(c)

print (result)

rawDescription: Join a list of tuples

description: Join a list of tuples


code:
import matplotlib.dates as md
yfmt = md.DateFormatter('%H:%M')
ax.yaxis.set_major_formatter(yfmt)

rawDescription: Formatting time on a plot in Python

description: Formatting time on a plot in Python


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

# number of bars
N = 20

# plot a random bar graph
fig = plt.figure()
ax = fig.add_subplot(111)
bars = ax.bar(np.arange(N), np.random.random(N))

# change the colors according to the color map 'jet'
for i, b in enumerate(bars):
    b.set_color(plt.cm.jet(1. * i / (N - 1)))

rawDescription: barplot with N distinct colors shade in matplotlib

description: Barplot with N distinct colors shade in matplotlib


code:
self=[1,2,3,4,5,6,7,8]

def evens(self):
    evens=[]
    for item in self:
        if item%2==0:
            evens.append(item)
    return 'intlist({})'.format(evens)

evens(self)
print(evens(self))

rawDescription: return something without the single quote

description: Return something without the single quote


code:
with open("test.txt", "r") as f:
    for a_line in f:
        command, quantity, price = a_line.split()
        print(command, quantity, price)
        # do what you want with these values here
        # please note that quantity and price are strings. need to
        # change them to float if you want to do some calculations.

rawDescription: Python Reading Commands from File

description: Python Reading Commands from File


code:
invite_list = data
invite_list.append(adata)

rawDescription: append list with dictionary type in python

description: Append list with dictionary type in python


rawDescription: Taking a fullpage screenshot using Selenium server in python


code:
def dispatch_request(self):
    redirect = redirect_if_unauthorized()
    if redirect:
        return redirect

rawDescription: Flask trying to call function with a redirect


code:
# Textview with inverted colors
import gtk

tv = gtk.TextView()
tv.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse('black'))
tv.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('white'))

rawDescription: pygtk: invert colors of a textview Widget

description: Pygtk: invert colors of a textview Widget


code:
class CustomField(Field):
    def to_native(self, obj):
        return obj.macAddresses.all()

rawDescription: How can one customize Django Rest Framework serializers output?


rawDescription: Unicode into iterable list

description: Unicode into iterable list


code:
from Tkinter import *

def cipher():
    data = text_area.get("1.0",END)

    As,Ts,Cs,Gs, = 0,0,0,0

    for x in data:
        if 'A' == x:
            As+=1
        elif x == 'T':
            Ts+=1
        elif x =='C':
            Cs+=1
        elif x == 'G':
            Gs+=1
    result.set('Num As: '+str(As)+' Num of Ts: '+str(Ts)+' Num Cs: '+str(Cs)+' Num Gs: '+str(Gs))

window = Tk()

frame=Frame(window)
frame.pack()

text_area = Text(frame)
text_area.pack()

result = StringVar()
result.set('Num As: 0 Num of Ts: 0 Num Cs: 0 Num Gs: 0')
label=Label(window,textvariable=result)
label.pack()

button=Button(window,text="Count", command=cipher)
button.pack()

window.mainloop()

rawDescription: How to read text from a Tkinter Text Widget

description: Read text from a Tkinter Text Widget


rawDescription: Convert datetime columns to a different timezone pandas


code:
if 'file' in form.changed_data:
     """
     File is changed
     """
     raise forms.ValidationError("No, don't change the file because blah blah")
else:
     """
     File is not changed
     """

rawDescription: How to check if a FileField has been modified in the Admin of Django?

description: Check if a FileField has been modified in the Admin of Django


code:
import wx

########################################################################
class PanelOne(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        self.countdown = wx.StaticText(self, label="This panel will self-destruct in 10 seconds")

########################################################################
class PanelTwo(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        txt = wx.StaticText(self, label="Panel Two")

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Panel Smacker")
        self.panelOne = PanelOne(self)
        self.time2die = 10

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.update, self.timer)
        self.timer.Start(1000)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.panelOne, 1, wx.EXPAND)
        self.SetSizer(self.sizer)

    #----------------------------------------------------------------------
    def update(self, event):
        """"""
        if self.time2die < 0:
            self.panelOne.Destroy()
            self.panelTwo = PanelTwo(self)
            self.sizer.Add(self.panelTwo, 1, wx.EXPAND)
            self.Layout()
            self.timer.Stop()
        else:
            msg = "This panel will self-destruct in %s seconds" % self.time2die
            self.panelOne.countdown.SetLabel(msg)
        self.time2die -= 1

if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    frame.Show()
    app.MainLoop()

rawDescription: What is the recommended way to redraw wxframe content?


code: [s for s in (square(x) for x in range(12)) if s > 50]

rawDescription: Anaphoric list comprehension in Python

description: Anaphoric list comprehension in Python


code: [reverse(page, args=args) for page, args in ITERABLE]

rawDescription: How do you use map(reverse, ITERABLE) with arguments to reverse?

description: Use map(reverse, ITERABLE) with arguments to reverse


code:
def feed_forward(self, inputs):
    yield inputs
    activation = inputs
    for weight in self.weights:
        activation = activation.dot(weight)
        yield activation

rawDescription: Converting code using list built so far, to a generator


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector

class MySpider(CrawlSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com']

    rules = (
        Rule(SgmlLinkExtractor(allow=('country', )), callback='parse_country'),
        Rule(SgmlLinkExtractor(allow=('city', )), callback='parse_city'),
        Rule(SgmlLinkExtractor(allow=('street', )), callback='parse_street'),
    )

    def parse_country(self, response):
        self.log('Hi, this is a country page! %s' % response.url)

    def parse_city(self, response):
        self.log('Hi, this is a city page! %s' % response.url)

    def parse_street(self, response):
        self.log('Hi, this is a street page! %s' % response.url)

rawDescription: Crawling depth automation

description: Crawling depth automation


code:
df.groupby(['A', 'B'])
df.sort('C', ascending=False)

rawDescription: Group by 2 columns while sorting sorting by a 3rd


code:
IMP_CHOICES = (
    ('1', 'imp 1'),
    ('2', 'imp 2'),
    ('3', 'imp 3'),
    ('4', 'imp 4'),
)

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file  = forms.FileField(widget=forms.FileInput())
    imp = forms.ChoiceField(choices=IMP_CHOICES)

rawDescription: django combobox

description: Django combobox


rawDescription: Use string variable **kwargs as named argument


rawDescription: Is there a "ceil or floor" function?

description: Is there a "ceil or floor" function


code:
regex = r"\b[A-Z][a-zA-Z\.]*[A-Z]\b\.?"
re.findall(regex, "AbIA AoP U.S.A.")

rawDescription: Correct Regex for Acronyms In Python

description: Correct Regex for Acronyms In Python


code:
def get_or_create(session, model, defaults=None, **kwargs):
    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return instance, False
    else:
        params = dict((k, v) for k, v in kwargs.iteritems() if not isinstance(v, ClauseElement))
        params.update(defaults or {})
        instance = model(**params)
        session.add(instance)
        return instance, True

rawDescription: Does SQLAlchemy have an equivalent of Django's get_or_create?


code:
from Tkinter import *

OPTIONS = (
    "egg",
    "go",
    "spam"
)

controlsMap = {}

root = Tk()

def callbackFunc(name, index, mode):
    value = root.getvar(name) #getvar: return the value of Tcl variable NAME
    widget = controlsMap[name]
    if value == 'go':
        widget.config(bg='green',fg='black',
                 activebackground='green',
                 activeforeground='black')
    else:
        widget.config(bg='SystemButtonFace',fg='SystemButtonText',
                 activebackground='SystemButtonFace',
                 activeforeground='SystemButtonText')

var1 = StringVar(root, name='var1') #give it a master and a name
var1.set(OPTIONS[0])
om1 = OptionMenu(root, var1, *OPTIONS)
om1.config(width=5)
om1.grid(row=0, column=0)
controlsMap['var1'] = om1
var1.trace_variable('w', callbackFunc)

var2 = StringVar(root, name='var2') #
var2.set(OPTIONS[0])
om2 = OptionMenu(root, var2, *OPTIONS)
om2.config(width=5)
om2.grid(row=0, column=1)
controlsMap['var2'] = om2
var2.trace_variable('w', callbackFunc)

var3 = StringVar(root, name='var3') #
var3.set(OPTIONS[0])
om3 = OptionMenu(root, var3, *OPTIONS)
om3.config(width=5)
om3.grid(row=0, column=2)
controlsMap['var3'] = om3
var3.trace_variable('w', callbackFunc)

root.mainloop()

rawDescription: Different color for different choices in tkinter option menu


rawDescription: How can I specify an AES key in Python?

description: Specify an AES key in Python


code:
import types
class Scriptable:
    def __init__(self, script = None):
        if script is not None:
            self.script = types.MethodType(script, self)   # replace the method
    def script(self):
        print("greetings from the default script")

rawDescription: Assigning a function to an object attribute


code:
xs = array([1,2,5,6,9,10,11])
ys = xs**2

x = arange(12)
y = zeros(12, dtype=int32)
put(y, xs, ys)

plt.plot(x, y, 'o', clip_on=False)

rawDescription: Connect the points to zero for missing points


code:
with open('whatever.py', 'w') as py_file:
  py_file.write("print('hello world!')")

rawDescription: Python writes itself or another file

description: Python writes itself or another file


rawDescription: Displaying true output, not stored address


code:
import tensorflow as tf

sess = tf.Session()

x = tf.Variable(42.)
y = tf.placeholder(dtype=tf.float32)

assign = x.assign(y)

sess.run(tf.initialize_all_variables())

for i in range(10000):
    sess.run(assign, feed_dict={y: i})
    print(i, sess.run(x))

rawDescription: Avoid cluttering the tensorflow graph with assign operations


code:
from matplotlib.pyplot import axes, pie, show, figure, subplot
import matplotlib.gridspec as gridspec

fig = figure(facecolor = 'k')

ax1 = subplot(111, axisbg='k')
ax1.pie([1,2,3,4])
ax1.set_frame_on(True)
ax1.spines['bottom'].set_color('w')
ax1.spines['left'].set_color('w')
ax1.spines['top'].set_color('w')
ax1.spines['right'].set_color('w')

rawDescription: Python matplotlib - White spines with pie chart?


code:
import json
class Person(object):
    firstName = ""
    lastName = ""
def as_person(d):
    p = Person()
    p.__dict__.update(d)
    return p
s = '{ "firstName" : "John", "lastName" : "Smith" }'
o = json.loads(s, object_hook=as_person)
type(o)
o.firstName
o.lastName

rawDescription: Is there a python json library can convert json to model objects, similar to google-gson?


code:
example
for part in message['payload']['parts']:
      if part['filename']:

        file_data = base64.urlsafe_b64decode(part['body']['data']
                                             .encode('UTF-8'))

        path = ''.join([store_dir, part['filename']])

        f = open(path, 'w')
        f.write(file_data)
        f.close()

rawDescription: base64 decoding using Python with attachment downloaded with REST-based Gmail API

description: Base64 decoding using Python with attachment downloaded with REST-based Gmail API


code:
from openerp.osv import orm, fields
class logs(orm.Model):
    _name = 'logs'
    _columns = {'name': fields.char('Name', ...),
                'message': fields.char('Message', ...),
               }
    # ...

class student(orm.Model):
    _name = 'student'
    _columns = {...}
    def some_method(self, cr, uid, ids, context=None):
        # get the logs model
        logs_obj = self.pool.get('logs')
        # prepare the value dict for new entry
        values = {'name': val_of_the_name_col,
                  'message':  val_of_the_message_col,
                  }
        # call create
        log_id = logs_obj.create(cr, uid, value, context=context)

rawDescription: Is it possible to use the create method from within one class to insert into another class table in OpenERP?


code:
import struct
struct.unpack('<BBBB', struct.pack('<I', 4278298816))
'{}.{}.{}.{}'.format(*_)

rawDescription: convert uint32 into readable values

description: Convert uint32 into readable values


code:
from scrapy.loader import ItemLoader
from scrapy.loader.processors import TakeFirst, MapCompose, Join

class MyItemLoader(ItemLoader):
    default_output_processor = TakeFirst()

    message_in = MapCompose(unicode, unicode.strip)
    message_out = Join()

rawDescription: Removing brackets from Scrapy json output


code:
final_winner = None
while not final_winner:
    winner_index = random.randint(0, participant_count-1)
    winner = player_list[winner_index]
    if (date.today() - timedelta(days= 4*365/12)) > next_check.win_date.date():
        final_winner = winner

rawDescription: python django randomy selecting user and checking condition continuously

description: Python django randomy selecting user and checking condition continuously


code:
import numpy as np
from sklearn.decomposition import TruncatedSVD

model = TruncatedSVD(n_components=10).fit(X)
X_proj = model.transform(X)
explained_variances = np.var(X_proj, axis=0) / np.var(X, axis=0).sum()

rawDescription: TruncatedSVD - Explained Variance

description: TruncatedSVD - Explained Variance


code:
name = "manifest.v3"
name.find("manifest.v3") >= 0
name = "manifest.v3.old.old"
name.find("manifest.v3") >= 0
name == "manifest.v3"
name = "manifest.v3"
name == "manifest.v3"

rawDescription: Match and read file from zip

description: Match and read file from zip


code:
vars = sorted(expression.free_symbols)
evaluated = expression.subs(*zip(vars, your_values))

rawDescription: Evaluating a function at a point in SymPy


code:
def Identify():
    global _portlist1
    _portlist1 = ["a", "b"]

rawDescription: Gloabal variable lost between function calls


code:
import matplotlib.pyplot as plt

fig,ax=plt.subplots(1)

ax.arrow(0.5,0.6,0.55,0.,fc='r',ec='r',clip_on=True)
ax.arrow(0.5,0.4,0.55,0.,fc='b',ec='b',clip_on=False)

plt.show()

rawDescription: Can matplotlib lib annotate / add arrow to a FIGURE not an AXIS?


code:
user_change = int(request.COOKIES.get('voted_or_added', -1))
return render(request, 'xbox_wishlist/wishlist.html', { 'user_change': user_change, })

rawDescription: How can i compare a context variable with a SQL ID in a Django template?

description: Compare a context variable with a SQL ID in a Django template


rawDescription: Is there a way for an entry widget to automatically be selected


code:
from io import StringIO
from lxml import etree

dtd.elements()[0].content.right.left
#>>> <lxml.etree._DTDElementContentDecl object name='c' type='element' occur='once' at 0x7f6999a28250>

rawDescription: Parsing dtd file with lxml library (python)


code:
HOST, PORT = "", 9999

server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

server.serve_forever()

rawDescription: Why can not I access my SockectServer in local area network while I can access in my own computer?


code:
from textwrap import dedent

def function(s):
    """Testing doctests.

    >>> print function('''%@import
    ... blahblah
    ... %@''')
    <BLANKLINE>
    \\begin{shadedquoteBlueBar}
    \\fontsize{9pt}{9pt}
    \\begin{Verbatim}
    blahblah}
    \\end{Verbatim}
    \\end{shadedquoteBlueBar}
    \\noindent

    """
    s = dedent(r"""
               \begin{shadedquoteBlueBar}
               \fontsize{9pt}{9pt}
               \begin{Verbatim}
               blahblah}
               \end{Verbatim}
               \end{shadedquoteBlueBar}
               \noindent""")
    return s

rawDescription: Python/Doctest - doctesting complex strings


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string("""
<MyWidget>:
    Carousel:
        BoxLayout:
            orientation: 'vertical'
            Label:
                text: "Screen 1"
            Label:
                text: "Some text"
        BoxLayout:
            orientation: 'vertical'
            Label:
                text: "Screen 2"
            BoxLayout:
                Button:
                    text: "1"
                Button:
                    text: "2"
                Button:
                    text: "3"
                Button:
                    text: "4"
        BoxLayout:
            orientation: 'vertical'
            Label:
                text: "Screen 3"
            Label:
                text: "Some other text"
""")

class MyWidget(BoxLayout):
    pass

class MyApp(App):
    def build(self):
        return MyWidget()

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

rawDescription: Swapping screens with motion in kivy

description: Swapping screens with motion in kivy


rawDescription: Vectorizing standard deviation calculations for pandas dataseries


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import StringProperty

kv = '''

BoxLayout:
    orientation: 'vertical'
    Label:
        text: app.text
    Button:
        text: 'click me'
        on_press: app.clicked()

'''

class MyApp(App):
    text = StringProperty("hello world")

    def build(self):
        return Builder.load_string(kv)

    def clicked(self):
        self.text = "clicked!"

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

rawDescription: Loading one line of text from file to Kivy label


code:
# 1. only load individual columns - loading simple tuples instead
# of full ORM objects with identity tracking.  these tuples can be
# used directly in a dict comprehension
dimensionMap = dict(
    connection.session.query(Dimension.businessKey, Dimension.primarySyntheticKey)
)

# 2. For bulk inserts, use Table.insert() call with
# multiparams in chunks
buf = []
for row in sheet.allrows():
    dimensionId = dimensionMap[row[0]]
    metric = row[1]

    buf.append({"dimensionId": dimensionId, "metric": metric})

    if len(buf == 20000):
        connection.session.execute(Fact.__table__.insert(), params=buf)
        buf[:] = []

connection.session.execute(Fact.__table__.insert(), params=buf)
sys.stdout.write('All Done')

rawDescription: Very poor weakref performance in Python/SQL Alchemy


code:
[x for x in d if x.startswith('extra')]
# iterate on keys, or you can modify it to iterate on values

rawDescription: Simplify dict to list with if function

description: Simplify dict to list with if function


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('hello_world3.xlsx')
worksheet = workbook.add_worksheet()

myformat = workbook.add_format()
myformat.set_pattern(1)
myformat.set_bg_color('#C00000')

worksheet.conditional_format(0, 4, 0, 4, {'type': 'cell',
                                          'criteria': 'between',
                                          'minimum':  0,
                                          'maximum':  110,
                                          'format':   myformat})

worksheet.write(0, 4, 50)

workbook.close()

rawDescription: XlsxWriter : make a solid filled data bar


code:
shape = [1, 2, 5, 8]
pos = [0, 1, 1, 3]

my_array = np.ones(shape)
my_array[tuple(pos)] # will return 1

rawDescription: Dynamic Access of Multi dimensional Python Array


code:
for device in data['device']:
    if device['id'] == 5:
        print('Device:', device['name'])
        break
else:
    print('No such device')

rawDescription: Python 3 JSON - Select by value rather than index?


code:
def answer(meetings):
    last_end = -1
    ans = 0
    for end,start in sorted( (end,start) for start,end in meetings ):
        if start >= last_end:
            last_end = end
            ans += 1
    return ans, (len(meetings) - ans)

rawDescription: Schedule Optimization in Python for lists of lists [interval scheduling]


code:
if __name__ == '__main__':
    import xmlrunner
    unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))

rawDescription: Unable to see test result for python scripts on jenkins


code:
def plot_psi(n, l, start=(0.001*bohr),stop=None,step=(0.005*bohr)):
    if stop is None:
        stop = ((30*n-10)*bohr)

rawDescription: Setting argument defaults from arguments in python


code:
from collections import Counter

salary = ['55000', '30000', '55000', '30000', '80000']

counter = Counter(salary)

# This returns all unique list elements and their count, sorted by count, descending
mc = counter.most_common()
print(mc)

# This returns the unique list elements and their count, where their count equals
#   the count of the most common list element.
gmc = [(k,c) for (k,c) in mc if c == mc[0][1]]
print(gmc)

# If you just want an arbitrary (list element, count) pair that has the most occurences
amc = counter.most_common()[0]
print(amc)

rawDescription: Finding modes for multiple dictionary keys


code:
Row1 = 1
Column1 = 2
Row2 = 10
Column = 2

Formula = "=sum(r%(first)sc%(second)s:r%(third)sc%(fourth)s)" % {'first':Row1,
                                                                 'second':Column1,
                                                                 'third':Row2,
                                                                 'fourth':Column}
xl.Cells(1,1).FormulaR1C1 = Formula

rawDescription: python win32com : Change Excel formula witout inputing value yourself

description: Python win32com : Change Excel formula witout inputing value yourself


code:
if form_1.is_valid() and form_2.is_valid():
    review = form_1.save()
    photo = form_2.save(commit=False)
    photo.review_comments = review
    photo.save()

rawDescription: Automatically including the foreign key within the second form


code:
from sys import stdout
from time import sleep
for i in range(1,20):
    stdout.write("\r%d" % i)
    stdout.flush()
    sleep(1)
stdout.write("\r  \r\n") # clean up

rawDescription: Printing to the same console line but dynamically


code:
#generic swap puzzle[a][b] with puzzle[c][d]
puzzle[a][b], puzzle[c][d] = puzzle[c][d], puzzle[a][b]

rawDescription: Swap an item in list of list in python?

description: Swap an item in list of list in python


code: fieldA = [obj.get("fieldA", "missing") for obj in json["objects"]]

rawDescription: In python, is there a way to automatically substitute for missing values?


rawDescription: set / line intersection solution

description: Set / line intersection solution


code:
color_dict = { 'Allan':'red', 'Betty':'blue', 'Chris':'black', 'Diane':'green','Eugene':'purple' }

plt.scatter( data['a'], data['b'], color=[ color_dict[i] for i in data['c'] ] )

rawDescription: Python scatter plot with colors corresponding to strings


code:
max = -1

for c in str(2013):
    i = int(c)
    if i > max:
        max = i

rawDescription: Find the maximum digit of an integer

description: Find the maximum digit of an integer


code:
import math
import time
from timeit import Timer

userInput = "0"

while not userInput.isdigit() or int(userInput) <= 0:

    userInput = input("Calcular la raiz de: ") #Get input from user (userInput)

userInput = int(userInput)

epsilon = 0.000001
x=1
count=0

setup = 'from __main__ import userInput, epsilon, x, count'

operations = '''
x = 1
count = 0
while (abs(x**2 - userInput) > epsilon):

    x = 0.5 * (x + (userInput/x))
    count = count+1
'''

print('The operations took %.4f microseconds.' % Timer(operations, setup).timeit(1))

#run the operations again to get the x and count values
x = 1
count = 0
while (abs(x**2 - userInput) > epsilon):

    x = 0.5 * (x + (userInput/x))
    count = count+1
print("La raíz de", userInput, "es:",x,"implicó",count,"intentos")

rawDescription: Get a more precise timer in python

description: Get a more precise timer in python


code:
import csv

a = csv.reader(open(DATA+'testi1.csv'))
G = Graphics()

# create 2 lists so as to save the desired column fields
x_series=[]
y_series=[]

# iterate the csv file
for x,y,z in a:
  # append the first and third columns to
  # x_series and y_series list respectively
  x_series.append( int(x) )
  y_series.append( int(z) )

# then make the scatter plot
plot = scatter_plot(zip(x_series,y_series))
G += plot

G.set_axes_range(0, 20, 0, 20)

G

rawDescription: Sage importing from csv and plotting numbers larger than 10


code:
grouped = {}
for event in list_of_events:
    key = tuple(event['date'].isocalendar()[:1])
    grouped.setdefault(key, []).append(event)

rawDescription: How to group and count events by week?

description: Group and count events by week


code:
MIDDLEWARE_CLASSES = (
    # Make sure djangosecure.middleware.SecurityMiddleware is listed first
    'djangosecure.middleware.SecurityMiddleware',
) + MIDDLEWARE_CLASSES

rawDescription: Django Cookie Cutter SSL

description: Django Cookie Cutter SSL


code:
def menu_rec(items):
    result = []
    for x in items or []:
        url = URL('shop', 'category', args=pretty_url(x.id, x.slug))
        menu = menu_rec(x.children)  # recursive call
        result.append((x.title, None, url, menu))
    return result

rawDescription: List comprehension break down, deconstruction and/or disassemble


code: numpy.dot(numpy.dot(a, m), a)

rawDescription: Multiplying Rows and Columns of Python Sparse Matrix by elements in an Array


code:
files = [os.path.join(path, filename)
         for path, dirs, files in os.walk(dir)
         for filename in files
         if not filename.endswith(".bak")]
return random.choice(files)

rawDescription: Randomly selecting a file from a tree of directories in a completely fair manner


code:
img1 = np.arange(5, dtype='float32')
img2 = np.arange(5, dtype='float32')
np.column_stack((img1,img2)).ravel()

rawDescription: how to rearrange value order in numpy?

description: Rearrange value order in numpy


code:
cursor.execute('INSERT ...')
new_id = cursor.lastrowid
db.commit()
return new_id

rawDescription: Inserting row into SQLite table

description: Inserting row into SQLite table


code:
class User(object):
    def __init__(self, loginName, password):
        self.loginName = loginName
        self.password = password

    def __call__(self):
        if self.login():
            return self
        return None

    def login(self):
        database = db.connection
        return database.checkPassWord(self.loginName, self.password)

a = User("me", "mypassword")
a = a() # a is now either None or an instance that is aparantly logged in.

rawDescription: __call__ vs. __init__: Who gets the arguments? Who gets called first?


rawDescription: Pandas: Random order of columns when writing DataFrame to csv


code:
import urllib, bs4

pages = bs4.BeautifulSoup(urllib.urlopen(your_url).read())
lists = pages('ul') # your list of unordered list elements

rawDescription: Python extract all unordered list from a web page


code:
import pygame, OpenGL
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *

def main():
    pygame.init()
    pygame.display.set_mode((600,600), DOUBLEBUF|OPENGL)
main()

img = pygame.image.load('myPixelArt.bmp')
textureData = pygame.image.tostring(img, "RGB", 1)
width = img.get_width()
height = img.get_height()

im = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, im)

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, textureData)
glEnable(GL_TEXTURE_2D)

def wall(image):
    glBegin(GL_QUADS)
    glTexCoord2f(0,0)
    glVertex3f(-4,-4,-16)
    glTexCoord2f(0,1)
    glVertex3f(-4,4,-16)
    glTexCoord2f(1,1)
    glVertex3f(4,4,-8)
    glTexCoord2f(1,0)
    glVertex3f(4,-4,-8)
    glEnd()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    glLoadIdentity()
    gluPerspective(45, 1, 0.05, 100)
    glTranslatef(0,0,-5)
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

    wall(im)

    pygame.display.flip()
    pygame.time.wait(50)

rawDescription: OpenGL image display in 3d space

description: OpenGL image display in 3d space


code:
from functools import wraps

def token_required_on_post(f):
    require = token_required(f)

    @wraps(f)
    def wrapped(*args, **kwargs):
        if request.method == 'POST':
            return require(*args, **kwargs)

        return f(*args, **kwargs)

    return wrapped

@token_required_on_post
def articles(request):
    ...

rawDescription: Apply a decorator depending on the request method


rawDescription: Can a dictionary value be assigned as the key?


code:
from math import sqrt

def is_within(point, circle):
    distance = sqrt(((point.x - circle.x) ** 2) +
                    ((point.y - circle.y) ** 2))
    return distance < circle.radius

rawDescription: How to detect whether or not user is clicking inside Circle in python graphics window

description: Detect whether or not user is clicking inside Circle in python graphics window


code:
from django.template import Template, Context
t = Template('''
    {% for first in firstList %}
        {% for second in firstList %}
            {% if first == second %}
                {{ first }}
            {% endif %}
        {% endfor %}
    {% endfor %}
''')
t.render(Context({'firstList': ['foo', 'bar'], 'secondList': ['foo', 'bar']}))
print(t.render(Context({'firstList': ['foo', 'bar'], 'secondList': ['foo', 'bar']})))

rawDescription: Using loops in django templates, the way you use them in python


code:
import re
a = "√22+34-4+√(2+3)/5+√3"
re.sub(r'√(\d+)', r'√(\1)', a)  # \1 is whatever was captured by (\d+)

rawDescription: Perform selective replacement on a python string?


rawDescription: How to extract email body using the google app engine mail api?

description: Extract email body using the google app engine mail api


code:
@classmethod
def create(cls, *args, **kwargs):
    obj = cls(*args, **kwargs)
    obj.set_defaults()
    return obj

rawDescription: Inheritance and factory functions in Python and Django


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

values = [1000000, 1525097, 2050194, 1095638, 1620736, 2145833, 1191277, 1716375, 1286916, 1382555]
strategy = [1,2,3,4,5,6,7,8,9,10]
value = np.array(values)
strategies = np.array(strategy)
plt.bar(strategy, values, .8)
plt.ylabel("Values")
plt.xlabel("Bin Number")
plt.title("Histogram")
plt.axis([1,11,0,2200000])
plt.show()

rawDescription: matplotlib: histogram is not displaying

description: Matplotlib: histogram is not displaying


rawDescription: Decode Hex String in Python 3

description: Decode Hex String in Python 3


code:
LIGHT_MESSAGES = {
    'English': "There are %(number_of_lights)s lights.",
    'Pirate':  "Arr! Thar be %(number_of_lights)s lights."
}

def lights_message(language, number_of_lights):
    """Return a language-appropriate string reporting the light count."""
    return LIGHT_MESSAGES[language] % locals()

def is_pirate(message):
    """Return True if the given message sounds piratical."""
    return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None

rawDescription: Single quotes vs. double quotes in Python


code:
#Class-type
class Weekdays(object):
    ...

    def __unicode__(self): # Request for the matching
        ret = []
        for i,ele in enumerate(Weekdays.CHOICES):
            if (self.raw & ele[0]) >> i == 1:
                ret.append(unicode(ele[0]))
        return ','.join(ret)

    def __iter__(self):
        for i,ele in enumerate(Weekdays.CHOICES):
            if (self.raw & ele[0]) >> i == 1:
                yield Weekdays(ele[0])

#Field to include in the model
class WeekdayField(models.Field):
    ...

    # DB to PY
    def to_python(self, value):
        if isinstance(value, int):
            return [ wd for wd in Weekdays(value) ]
        if isinstance(value, unicode):
            return [ wd for wd in Weekdays(int(value)) ]
        if isinstance(value, Weekdays):
            return value
        if isinstance(value, list): #list of Weekdays
            wd = []
            for val in value:
                wd += self.to_python(val)
            return wd

    #PY to DB
    def get_prep_value(self, value):
        if isinstance(value, Weekdays):
            return value.raw
        if isinstance(value, list):
            sum_raw = 0
            for val in value:
                sum_raw += self.get_prep_value(val)
            return sum_raw

rawDescription: django custom field saves but not visualize

description: Django custom field saves but not visualize


code:
old = 'ABCDEF'
new = 'ABCDGHI'
set(new) - set(old)
set(old) - set(new)

rawDescription: Compare two lists, find old (removed) and new (added) values


code: make.contents[0].replaceWith('Top of the world Ma!')

rawDescription: Changing element value with BeautifulSoup returns empty element


code:
from __future__ import division

import numpy as np
from six.moves import zip
from bokeh.plotting import *

output_file("scatter.html")

figure()

N = 4000

x = np.random.random(size=N) * 100
y = np.random.random(size=N) * 100
radii = np.random.random(size=N) * 1.5
colors = ["#%02x%02x%02x" % (r, g, 150)
          for r, g in zip(np.floor(50+2*x), np.floor(30+2*y))]

circle(x, y, radius=radii,
       fill_color=colors, fill_alpha=0.6,
       line_color=None, Title="Colorful Scatter")

grid().grid_line_color = None
axis().axis_line_color = None
curplot().outline_line_color = None

# Turn off tick labels
axis().major_label_text_font_size = '0pt'
# Turn off tick marks
axis().major_tick_line_color = None  # turn off major ticks
axis()[0].ticker.num_minor_ticks = 0  # turn off minor ticks
axis()[1].ticker.num_minor_ticks = 0

show()  # open a browser

rawDescription: Turning off Tick Marks in Bokeh

description: Turning off Tick Marks in Bokeh


code:
input = open("input.txt")
output = open("output.txt","w")
name=['Julie', 'Stan', 'Nick']

i = 0

for row in input:
   if "[NAME]" in row:
      row=row.replace("[NAME]",name[i])
      i+=1
   output.write(row)

input.close()
output.close()

rawDescription: Replace a string in file in it's original place python


rawDescription: Intersection of a set and list of dictionaries


code:
layout_frame = tk.Frame(master, bg="red")
layout_frame.grid(row=1, column=2, rowspan=9, sticky=tk.N+tk.S+tk.W+tk.E)
inner_frame = tk.Frame(master=layout_frame, bg="red")
inner_frame.grid(row=0, column=0, rowspan=9, sticky=tk.N+tk.S+tk.W+tk.E)

rawDescription: Tkinter Grid Layout Widget not in parent