code:
import wx

class FadeMixin(object):
    ''' FadeMixin provides one public method: DeleteItem. It is meant to
    be mixed in with a ListCtrl to 'fade out' items before they are
    really deleted. Mixin like this:

    Assumption: the background colour of the control is wx.WHITE

    class MyListCtrl(FadeMixin, wx.ListCtrl):
        ...
    '''
    def __init__(self, *args, **kwargs):
        self.__bgColour = wx.WHITE
        super(FadeMixin, self).__init__(*args, **kwargs)

    def DeleteItem(self, index, fadeStep=10, fadeSpeed=50):
        if self.IsEnabled():
            self.__startDeleteItem(index)
        fgColour, bgColour, transparentColour = self.__getColours(index)
        if fgColour == bgColour == transparentColour:
            self.__finishDeleteItem(index)
        else:
            for colour, setColour in [(fgColour, self.SetItemTextColour),
                                      (bgColour, self.SetItemBackgroundColour)]:
                fadedColour = self.__fadeColour(colour, transparentColour,
                                                fadeStep)
                setColour(index, fadedColour)
            wx.FutureCall(50, self.DeleteItem, index, fadeStep, fadeSpeed)

    def SetBackgroundColour(self, colour):
        self.__bgColour = colour
        super(FadeMixin, self).SetBackgroundColour(colour)

    def GetBackgroundColour(self):
        return self.__bgColour

    def __startDeleteItem(self, index):
        # Prevent user input during deletion. Things could get messy if
        # the user deletes another item when we're still busy fading out the
        # first one:
        self.Disable()
        # Unselect the item that is to be deleted to make the fading visible:
        currentState = self.GetItemState(index, wx.LIST_STATE_SELECTED)
        self.SetItemState(index, ~currentState, wx.LIST_STATE_SELECTED)

    def __finishDeleteItem(self, index):
        super(FadeMixin, self).DeleteItem(index)
        self.Enable()

    def __getColours(self, index):
        fgColour = self.GetItemTextColour(index)
        bgColour = self.GetItemBackgroundColour(index)
        transparentColour = self.GetBackgroundColour()
        if not bgColour:
            bgColour = transparentColour
        return fgColour, bgColour, transparentColour

    def __fadeColour(self, colour, transparentColour, fadeStep):
        newColour = []
        for GetIntensity in wx.Colour.Red, wx.Colour.Green, wx.Colour.Blue:
            currentIntensity = GetIntensity(colour)
            transparentIntensity = GetIntensity(transparentColour)
            if currentIntensity < transparentIntensity:
                newIntensity = min(transparentIntensity,
                                   currentIntensity + fadeStep)
            elif currentIntensity > transparentIntensity:
                newIntensity = max(transparentIntensity,
                                currentIntensity - fadeStep)
            else:
                newIntensity = transparentIntensity
            newColour.append(newIntensity)
        return wx.Colour(*newColour)

class ListCtrl(FadeMixin, wx.ListCtrl):
    pass

class Frame(wx.Frame):
    def __init__(self, *args, **kwargs):
        super(Frame, self).__init__(*args, **kwargs)
        self.list = ListCtrl(self, style=wx.LC_REPORT)
        self.list.InsertColumn(0, 'Column 0')
        self.list.InsertColumn(1, 'Column 1')
        self.fillList()
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelected)
        self.Bind(wx.EVT_LIST_DELETE_ITEM, self.onDeleted)

    def onSelected(self, event):
        self.list.DeleteItem(event.GetIndex())

    def onDeleted(self, event):
        if self.list.GetItemCount() == 1:
            wx.CallAfter(self.fillList, False)

    def fillList(self, firstTime=True):
        for row in range(10):
            self.list.InsertStringItem(row, 'Item %d, Column 0'%row)
            self.list.SetStringItem(row, 1, 'Item %d, Column 1'%row)
        self.list.SetItemBackgroundColour(1, wx.BLUE)
        self.list.SetItemTextColour(2, wx.BLUE)
        self.list.SetItemBackgroundColour(3, wx.GREEN)
        self.list.SetItemTextColour(4, wx.GREEN)
        self.list.SetItemBackgroundColour(5, wx.RED)
        self.list.SetItemTextColour(6, wx.RED)
        self.list.SetItemBackgroundColour(7, wx.BLACK)
        self.list.SetItemTextColour(7, wx.WHITE)
        self.list.SetItemBackgroundColour(8, wx.WHITE)
        self.list.SetItemTextColour(8, wx.BLACK)
        if not firstTime:
            self.list.SetBackgroundColour(wx.BLUE)

app = wx.App(False)
frame = Frame(None, title='Select an item to fade it out')
frame.Show()
app.MainLoop()

rawDescription: Fade in/out the background color of wxpython grid cell


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

data = np.linspace(0, 10, num=256).reshape(16,16)

cf = plt.contourf(data, levels=(0, 2.5, 5, 7.5, 10))
cb = plt.colorbar(cf)

cb.set_ticklabels([r'$<10^{0}$', 1, 2, r'$10^{14}$', r'$10^{14}+12345678$'])
cb.set_label(r'$n_e$ in $m^{-3}$', labelpad=-40, y=0.45)

plt.show()

rawDescription: Matplotlib colorbar background and label placement


code:
import urllib2
direct = urllib2.build_opener()
proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxied = urllib2.build_opener(proxy_handler)

direct.open('http://stackoverflow.com') # opens directly
proxied.open('http://stackoverflow.com') # opens through proxy

rawDescription: Python: urllib2 handle multiple openers

description: Python: urllib2 handle multiple openers


code:
def is_valid_word(hand, word, wordlist):
    hand_cp = dict(hand)
    for letter in word:
        if hand_cp.get(letter):
            # The letter is in our hand, so "use it up".
            hand_cp[letter] = hand_cp[letter] - 1
        else:
            # The letter isn't in our hand, so the word isn't valid.
            return False

    # If we can make the word, now make sure it's a real word:
    # (If wordlist is long, you might want to sort it and do a real search)
    if word not in wordlist:
        return False

    # We haven't found any reason to return False, so this is a valid word.
    return True

rawDescription: Python dictionary values

description: Python dictionary values


code: #! /usr/bin/env python3.1

rawDescription: Is it safe to replace MacOS X default Python interpreter?


code:
from alembic.config import Config
alembic_cfg = Config()
alembic_cfg.set_main_option("script_location", "myapp:migrations")
alembic_cfg.set_main_option("url", "postgresql://foo/bar")
alembic_cfg.set_section_option("mysection", "foo", "bar")

rawDescription: Can I use .py file instead of .ini file on alembic?

description: Use .py file instead of .ini file on alembic


code:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect("xxx.xxx.xxx.xxx",22,username=xxx,password='',timeout=4)

sftp = s.open_sftp()
sftp.put('/home/me/file.ext', '/remote/home/file.ext')

rawDescription: How to transfer a file to ssh server in an ssh-connection made by Python's paramiko?

description: Transfer a file to ssh server in an ssh-connection made by Python's paramiko


code: plt.contourf(lon, lat, Z, transform=ccrs.PlateCarree())

rawDescription: Cartopy map fill entire axis

description: Cartopy map fill entire axis


code:
import itertools
a = [0, 0, [0, 1], [0, 1, 2]]
a2 = [x if isinstance(x, list) else [x] for x in a]
#  = [[0], [0], [0, 1], [0, 1, 2]]
list(itertools.product(*a2))

rawDescription: Get permutations of lists using python

description: Get permutations of lists using python


code:
numcols = 4
growsize = 60*60 #60 samples/min * 60 min/hour
numrows = 3*growsize #3 hours, to start with
private.data = npy.zeros([numrows, numcols]) #alloc one big memory block
rowctr = 0
while (recording):
    private.data[rowctr] = npy.array([new_x, new_y1, new_y2, new_y3])
    rowctr += 1
    if (rowctr == numrows): #full, grow by another hour's worth of data
        private.data = npy.row_stack([private.data, npy.zeros([growsize, numcols])])
        numrows += growsize

rawDescription: Numpy array memory issue

description: Numpy array memory issue


code:
string = 'Hi, This is a test. Are you surprised?'
words = re.split('[,!?.]', string)
print(words)
[u'Hi', u' This is a test', u' Are you surprised', u'']

rawDescription: Split more than one word in python

description: Split more than one word in python


code:
# Generate some data
data = np.random.normal(size=1000)

# Generate the histogram data directly
hist, bin_edges = np.histogram(data, bins=10)

# Get the reversed cumulative sum
hist_neg_cumulative = [np.sum(hist[i:]) for i in range(len(hist))]

# Get the cin centres rather than the edges
bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2.

# Plot
plt.step(bin_centers, hist_neg_cumulative)

plt.show()

rawDescription: how to scale the histogram plot via matplotlib

description: Scale the histogram plot via matplotlib


code:
try:
     while True:
         lst.remove('')   # deletes first empty string
except ValueError:        # no more empty strings
     pass

rawDescription: How does the in operator in python behave when the list it is traversing changes


code:
import urllib
urllib.urlretrieve("http://anysite.co/foo.gz", "foo.gz")

rawDescription: Read file using urllib and write adding extra characters


code:
def new_response(self, link_pattern, link, response, ref_id=""):
    self.db_cursor.execute('''INSERT INTO tb_memory VALUES
    (?, ?, ?, ?)''', (ref_id, link_pattern, link, response))

rawDescription: Inserting Unknowns into SQLite Database

description: Inserting Unknowns into SQLite Database


rawDescription: Generator Expression, access iterator

description: Generator Expression, access iterator


code:
from django.db.models import Min
# First select the min ids
min_id_objects = MyModel.objects.values('A', 'B').annotate(minid=Min('id'))
min_ids = [obj['minid'] for obj in min_id_objects]
# Now delete
MyModel.objects.exclude(id__in=min_ids).delete()

rawDescription: Django: How to delete duplicate rows based on 2 columns?


rawDescription: how to exclude equal column in django model?

description: Exclude equal column in django model


code:
import numpy as np
import codecs

n=10

filecp = codecs.open(myfile, encoding = 'cp1252')
mydata = np.loadtxt(filecp, skiprows = n)

rawDescription: Numpy loadtxt encoding

description: Numpy loadtxt encoding


code:
import StringIO

from django.core.files.uploadedfile import InMemoryUploadedFile

# Create a file-like object to write thumb data (thumb data previously created
# using PIL, and stored in variable 'thumb')
thumb_io = StringIO.StringIO()
thumb.save(thumb_io, format='JPEG')

# Create a new Django file-like object to be used in models as ImageField using
# InMemoryUploadedFile.  If you look at the source in Django, a
# SimpleUploadedFile is essentially instantiated similarly to what is shown here
thumb_file = InMemoryUploadedFile(thumb_io, None, 'foo.jpg', 'image/jpeg',
                                  thumb_io.len, None)

# Once you have a Django file-like object, you may assign it to your ImageField
# and save.
...

rawDescription: How do you convert a PIL `Image` to a Django `File`?

description: Convert a PIL `Image` to a Django `File`


code:
from local_settings.py import environment
if environment == 'dev':
    debug = True
    # anything you'd like

rawDescription: Check if application is running on server or local


code:
class Application(UtilApplication):

    def __init__(self):
        self.configFiles = ['/usr/local/etc/foo/bar.conf']
        UtilApplication.__init__(self)

rawDescription: Alternate configuration file for starpy, asterisk interface library


code:
from twisted.internet.defer import succeed

def verifyHostKey(transport, host, pubKey, fingerprint):
    return succeed(True)

rawDescription: Python Twisted: twisted conch filetransfer verifyHostKey


code:
import urllib
import urllib2
import cookielib

cj = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

request = urllib2.Request("http://what.cd/index.php", None)
f = urllib2.urlopen(request)
f.close()

data = urllib.urlencode({"username": "your-login", "password" : "your-password"})
request = urllib2.Request("http://what.cd/login.php", data)
f = urllib2.urlopen(request)

html = f.read()
f.close()

rawDescription: Retrieving pages from what.cd

description: Retrieving pages from what.cd


code:
import re
mod='ketobutyric_arp_rm(12);oxidation+%28hw%29(19)'
re.findall(r'\((\d+)\)', mod)

rawDescription: fetching values out of multiple brackets

description: Fetching values out of multiple brackets


rawDescription: How to add multiple value to a dictionary key in Python

description: Add multiple value to a dictionary key in Python


code:
# create array for each column
col1 = [float(35*x) for x in xrange(10)]
col2 = [float(220*x) for x in xrange(10)]

dict = {'col1_name': col1, 'coll2_name': col2}
df = pd.DataFrame(dict)

rawDescription: python pandas dataframe from file

description: Python pandas dataframe from file


code:
fo = open("foo.txt", "r+")

# read first line
line = fo.readline()

# split line only on first ':'
elements = line.split(':', 1)

if len(elements) < 2:
    print("there is no ':' or there is no value after ':' ")
else:
    # remove spaces and "\n"
    result = elements[1].strip()
    print(result)

#
# time for second line
#

# read second line
line = fo.readline()

# split line only on first ':'
elements = line.split(':', 1)

if len(elements) < 2:
    print("there is no ':' or there is no value after ':' ")
else:
    # remove spaces and "\n"
    result = elements[1].strip()
    print(result)

# close
fo.close()

rawDescription: read a specific string from a file in python?

description: Read a specific string from a file in python


code: session.query(...).filter(tuple_(favorite_color, favorite_food).in_([('lavender', 'lentil soup'), ('black', 'carrot juice')]))

rawDescription: Using sqlalchemy to query using multiple column where in clause


code:
n = -42
-n       # if you know n is negative
abs(n)   # for any n

rawDescription: How to convert a negative number to positive?

description: Convert a negative number to positive


code:
"Download many URLs in parallel."

import functools
import urllib.request
import futures

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

def load_url(url, timeout):
    return urllib.request.urlopen(url, timeout=timeout).read()

with futures.ThreadPoolExecutor(50) as executor:
   future_list = executor.run_to_futures(
           [functools.partial(load_url, url, 30) for url in URLS])

rawDescription: Python: Something like `map` that works on threads


code:
def __getitem__(self, item):
    return self.__dict__[item] # you maybe should return a copy
def keys(self):
    return self.__dict__.keys() # you could filter those

rawDescription: Have a class act as a dict?

description: Have a class act as a dict


code:
def isbound(method):
    return method.im_self is not None

def instance(bounded_method):
    return bounded_method.im_self

rawDescription: How do you check whether a python method is bound or not?

description: Check whether a python method is bound or not


code:
import csv

rows = {}
with open('a.csv', 'r', newline='') as acsv:
    areader = csv.DictReader(acsv)
    for row in reader:
        # store the row based on the item1 and item2 columns
        key = (row['item1'], row['item2'])
        rows[key] = row

with open('b.csv', 'r', newline='') as bcsv:
    breader = csv.DictReader(bcsv)
    for row in reader:
        # set the label of matching rows to 1 when present
        key = (row['item1'], row['item2'])
        if key in rows:
            rows[key]['label'] = 1

with open('result.csv', 'w', newline='') as result:
    writer = csv.DictReader(result, fieldnames=areader.fieldnames)
    writer.writerows(rows.values())

rawDescription: Python: how to update a csv file from another csv file


code:
from peewee import JOIN
JOIN['RIGHT_OUTER'] = 'RIGHT OUTER'

rawDescription: MYSQL PeeWee Full Join without RawQuery

description: MYSQL PeeWee Full Join without RawQuery


code:
app = wx.App()
# main frame
frame = interface.MyFrame1(None)
frame.Show()

# plot frame, the correct parenting is important, this is not shown in your example
frame2 = graphs.BarsFrame(parent=frame)
frame2.Show()

app.MainLoop()

rawDescription: How to create and destroy wx.App?

description: Create and destroy wx.App


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

def gaussian(x, x0, y0, variance):
    return y0 * np.exp(-(x - x0) ** 2 / variance)

x = np.linspace(150, 210, 100)
plt.fill_between(x, 0, gaussian(x, 180, 5000, 30), color='red', zorder=0)
plt.fill_between(x, 0, gaussian(x, 181, 4500, 10), color='blue', zorder=1)

plt.show()

rawDescription: superimposed histograms in matplotlib

description: Superimposed histograms in matplotlib


code:
def compat5(L1, L2):
    z = zip(L1, L2)
    return not any(j1<k1 and j2>k2 for j1,j2 in z for k1,k2 in z)

rawDescription: Checking compatible total orders given by a Python list


rawDescription: Python code to detect dark mode in OS X EI Capitan to change the status bar menu icon


code:
def genitiv(name):
    if name[-1]=='s':
       return _(u"%s'" % name)
    else:
       return _(u"%s's" % name)

rawDescription: Python gettext Genitiv 's

description: Python gettext Genitiv 's


code:
def load_dropdown():
    parent = Toplevel()  # <- change to this
    myvalue = StringVar()
    ...

rawDescription: Calling a Tk instance from another Tk instance causes issue setting textvariables


code:
from twisted.internet import reactor
from twisted.web import proxy, server

site = server.Site(proxy.ReverseProxyResource('www.yahoo.com', 80, ''))
reactor.listenTCP(8080, site)
reactor.run()

rawDescription: How to make an HTTP proxy that points to a specific server

description: Make an HTTP proxy that points to a specific server


code:
from collections import deque

path = 'test.txt'

with open(path, 'r') as file:
    lines = deque(file, 4)
    lines.append("\nthis is an additional line.")

with open(path, 'w') as file:
    file.writelines(lines)

rawDescription: Append a text line to a file and remove the first one if there are more than 4 lines in python


code:
token=['aaa','bbb','ccc','ddd',0,'eee',40,'ggg',5]
["{}:{}".format(i,j) for i,j in enumerate(token,1) if isinstance(j,int)]

rawDescription: how to determine an integer in a string list

description: Determine an integer in a string list


code:
import inspect
import yaml
from collections import OrderedDict

class Serializable(yaml.YAMLObject):
    __metaclass__ = yaml.YAMLObjectMetaclass
    @property
    def _dict(self):
        dump_dict = OrderedDict()

        for var in inspect.getargspec(self.__init__).args[1:]:
            if getattr(self, var, None) is not None:
                item = getattr(self, var)
                if isinstance(item, np.ndarray) and item.ndim == 1:
                    item = list(item)
                dump_dict[var] = item

        return dump_dict

    @classmethod
    def to_yaml(cls, dumper, data):
        return ordered_dump(dumper, '!{0}'.format(data.__class__.__name__),
                            data._dict)

    @classmethod
    def from_yaml(cls, loader, node):
        fields = loader.construct_mapping(node, deep=True)
        return cls(**fields)

def ordered_dump(dumper, tag, data):
    value = []
    node = yaml.nodes.MappingNode(tag, value)
    for key, item in data.iteritems():
        node_key = dumper.represent_data(key)
        node_value = dumper.represent_data(item)
        value.append((node_key, node_value))

    return node

rawDescription: Python / YAML: How to initialize additional objects not just from the YAML file, within loadConfig?


code:
logger.handlers[0].stream.close()
logger.removeHandler(logger.handlers[0])

file_handler = logging.FileHandler(filename)
file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(filename)s, %(lineno)d, %(funcName)s: %(message)s")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

rawDescription: Restart logging to a new file (Python)

description: Restart logging to a new file (Python)


code:
with open("redirected_output.txt") as f:
    subprocess.call("/home/bin/cat some_file.txt",stdout=f)

rawDescription: python concatenate files using subprocess

description: Python concatenate files using subprocess


code:
import string

def change(word, pos):
    old = string.ascii_lowercase
    new = old[pos:] + old[:pos]
    return word.translate(string.maketrans(old, new))

rawDescription: python a=b b=c function ETC

description: Python a=b b=c function ETC


code:
import sys
import os
sys.path.append("/path/to/parent") # under which myproject is hosted
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import myproject.myapp.models # or whatever

rawDescription: class browsing in django

description: Class browsing in django


code:
data = {'subject': 'hello',
        'message': 'Hi there',
        'sender': 'foo@example.com',
         'cc_myself': True}
f = ContactForm(data)

rawDescription: Django: How to handle User data validation the right way?


rawDescription: Concatenating Dictionaries

description: Concatenating Dictionaries


code:
class PhotoSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Photo

class VideoSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Video

class GalleryItemModuleSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.GalleryItem

    def to_representation(self, obj):
        """
        Because GalleryItem is Polymorphic
        """
        if isinstance(obj, models.Photo):
            return PhotoSerializer(obj, context=self.context).to_native(obj)
        elif isinstance(obj, models.Video):
           return VideoSerializer(obj, context=self.context).to_native(obj)
        return super(GalleryItemModuleSerializer, self).to_representation(obj)

rawDescription: django-rest-framework + django-polymorphic ModelSerialization

description: Django-rest-framework + django-polymorphic ModelSerialization


code:
import csv

with open('Cars.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['Colour'] == 'blue':
            print(row['ID'] ,row ['Make'],row ['Colour'])

rawDescription: Reading a CSV file using Python 3

description: Reading a CSV file using Python 3


code:
def get_all_f(self, obj, return_key):
    f1,f2,f3 = get_field_values(obj.attribute, obj.another_attribute)
    self.f = {'f1' : f1, 'f2' : f2, 'f3' : f3 }
    return self.f.get(return_key)

def get_field1(self, obj):
    f1 = self.f.get('f1', None)
    if f1 is None :
        f1 = get_all_f('f1')
    return f1

def get_field2(self, obj):
    f2 = self.f.get('f2', None)
    if f2 is None :
        f2 = get_all_f('f2')
    return f2

def get_field3(self, obj):
    f3 = self.f.get('f3', None)
    if f3 is None :
        f3 = get_all_f('f3')
    return f3

rawDescription: Django REST framework: one method to return several fields


code:
with open('scores.txt', newline='') as infile:
    reader = csv.reader(infile)
    for row in reader:
        for i in range(1,5):
            row[i] = int(row[i])
        score_list.append(row[0:5])

rawDescription: Converting certain index values in list to int


code:
from django.core.validators import validate_ipv46_address, RegexValidator

validate_hostname = RegexValidator(regex=r'[a-zA-Z0-9-_]*\.[a-zA-Z]{2,6}')

def clean(self):
    cleaned_data = super(CacheCheck, self).clean()
    record = cleaned_data.get("record")
    hostname = cleaned_data.get(hostname, "")

    if record == "PTR":
        validate_ipv46_address(hostname)
    elif record == "A":
        validate_hostname(hostname)
        # todo: check length of hostname as well

    return cleaned_data

rawDescription: Django Custom Form Validation IP address and Domain name


code:
def window_size(wide,tall):
    tk = Tk()
    canvas = Canvas(tk, width=wide, height=tall)
    canvas.pack()
    return canvas

def random_rect(canvas, width, height):
    x1 = randrange(width)
    y1 = randrange(height)
    x2 = x1 + randrange(width)
    y2 = y1 + randrange(height)
    canvas.create_rectangle(x1, y1, x2, y2) # this is the trouble line

c = window_size(500,500)
random_rect(c, 200, 200)

rawDescription: Implementing a variable shared between functions in Python 3.x


code:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import rcParams
import numpy as np
rcParams['axes.labelsize'] = 18
rcParams['font.family'] = 'serif'
rcParams['font.serif'] = ['Computer Modern Roman']
rcParams['text.usetex'] = True

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

u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)

x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z,  rstride=4, cstride=4, color='b')

# Get rid of the panes
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))

# Get rid of the spines
ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))

# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

# Add the labels
ax.set_xlabel('Third dimension' )
ax.set_ylabel('Row(s)')
ax.set_zlabel('Column(s)')
plt.show()

rawDescription: 3D Plot with Matplotlib: Hide axes but keep axis-labels?


rawDescription: Pandas read excel with Chinese filename

description: Pandas read excel with Chinese filename


code:
# make up some sample (a,b): format might be different to yours but you get the point.
import matplotlib.pyplot as plt
points = [ (1.,2.3), (2.,4.), (3.5,6.) ] # (a1,b1), (a2,b2), ...

plt.hold(True)
plt.xlim(0,4)  # set up the plot limits

for pt in points:
    # plot (x,y) pairs.
    # vertical line: 2 x,y pairs: (a,0) and (a,b)
    plt.plot( [pt[0],pt[0]], [0,pt[1]] )

plt.show()

rawDescription: Draw lines from x axis to points

description: Draw lines from x axis to points


code:
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            # you'll need to loop through the uploaded files here.
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})

def handle_uploaded_file(f):
    destination = open('some/file/name.txt', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

rawDescription: Form from Model with File Upload

description: Form from Model with File Upload


code:
strs =  "/forums/support/"
spl =strs.strip('/').split('/')
a,b,c,d,e = spl + [None]*(5-len(spl))
a,b,c,d,e
strs = "/forums/support/windows/"
spl =strs.strip('/').split('/')
a,b,c,d,e = spl + [None]*(5-len(spl))
a,b,c,d,e
strs = "/forums/support/windows/help_i_deleted_sys32/6/"
spl =strs.strip('/').split('/')
a,b,c,d,e = spl + [None]*(5-len(spl))
a,b,c,d,e

rawDescription: Elegantly Assign Variables of Unknown Length


code:
import re
a = 'Lorem ipsum dolor sit amet'
re.search('ipsum', a).span()
re.search('sum.*sit', a).span()

rawDescription: python find the end offset of a matched string or regex

description: Python find the end offset of a matched string or regex


code:
from xen.util.xmlrpcclient import ServerProxy
server = ServerProxy(serverURI)
def xm_vcpu_pin(args):

    def cpu_make_map(cpulist):
        cpus = []
        for c in cpulist.split(','):
            if c == '':
                continue
            if c.find('-') != -1:
                (x, y) = c.split('-')
                for i in range(int(x), int(y) + 1):
                    cpus.append(int(i))
            else:
                # remove this element from the list
                if c[0] == '^':
                    cpus = [x for x in cpus if x != int(c[1:])]
                else:
                    cpus.append(int(c))
        cpus.sort()
        return ",".join(map(str, cpus))

    dom = args[0]
    vcpu = args[1]
    cpumap = cpu_make_map(args[2])

    server.xend.domain.pincpu(dom, vcpu, cpumap)

rawDescription: Libvirt python add vCPU and memory

description: Libvirt python add vCPU and memory


code:
strings = ['a', 'apple', 'b', 'beta', 'c', 'd']

def prefices_only(strlist):
    ordered = sorted(strlist)
    last = ordered[0]
    results = [last]

    for c in ordered:
        if not c.startswith(last):
            last = c
            results.append(c)

    return results

print(prefices_only(strings))

rawDescription: Make a set prefix-free

description: Make a set prefix-free


rawDescription: Reading JSON with Python Dicts

description: Reading JSON with Python Dicts


code:
import copy
class _ListNode:
    def __init__(self, value, next_):
        self._value = copy.deepcopy(value)
        self._next = next_
        return
class List:
    def __init__(self):
        self._front = None
        self._count = 0
        return
    def addToFront(self, value):
        if self._front == None:
            self._front = _ListNode(value, None)
        else:
            buffer = _ListNode(value, self._front)
            self._front = buffer

    def addToEnd(self, value):
        current = self._front
        if current:
            while current._next != None:
                current = current._next
            current._next = _ListNode(value, None)
        else:
            self._front = _ListNode(value, None)

    def __str__(self):
        buffer = self._front
        result = ""
        while buffer._next != None:
            result+= buffer._value + " > "
            buffer = buffer._next
        result+= buffer._value
        return result

    def copy(self):
        result = List()
        buffer = self._front
        while buffer._next != None:
            result.addToEnd(buffer._value)
            buffer= buffer._next
        result.addToEnd(buffer._value)
        return result

##test:
x = List()
x.addToFront("f")
x.addToFront("e")
x.addToFront("d")
x.addToFront("c")
x.addToFront("b")
x.addToFront("a")
print(x)
print(x.copy())

rawDescription: How to copy linked list in Python?

description: Copy linked list in Python


code:
from django.db import models

class User(models.Model):

    name = models.CharField('Name', max_length=50)

    def __str__(self):
        return self.name

class Project(models.Model):

    name = models.CharField('Name', max_length=50)
    users = models.ManyToManyField(User, through='UserProjects', related_name='projects')

    def __str__(self):
        return self.name

class UserProjects(models.Model):

    user = models.ForeignKey(User)
    project = models.ForeignKey(Project)
    is_active = models.BooleanField('Active')

rawDescription: How to make two Django models with cross relationship?

description: Make two Django models with cross relationship


code:
from flask import Flask
from yourmodule import function_that_return_xml
app = Flask(__name__)

@app.route("/")
def hello():
    xml = function_that_return_xml()
    # make fancy operations if you want
    return xml

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

rawDescription: Calling a local python script from javascript


code:
import asyncmongo
import tornado.web

class Handler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    def get(self, id):
        self.id = id
        self.db = asyncmongo.Client(pool_id='mypool', host='localhost',
            port=27107, dbname='mydb')

        self.db.users.find_one({'username': self.current_user},
            callback=self.on_user)

    def on_user(self, response, error):
        if error:
            raise tornado.web.HTTPError(500)
        self.user = response
        self.db.documents.find_one({'id': self.id, 'user': self.user},
            callback=self.on_document)

    def on_document(self, response, error):
        if error:
            raise tornado.web.HTTPError(500)
        self.render('template', first_name=self.user['first_name'],
            document=response)

rawDescription: Multiple Database calls in an asynchronous request with Tornado


code:
# Print instructions to the user
### 'print "xyz"' will output the xyz text.

# Start with the variables high = 1000, low = 1, and tries = 1
### You can set a variable with 'abc = 1'.

# While high is greater than low
### Python has a while statement and you can use something like 'while x > 7:'.
### Conditions like 'x > 7', 'guess == number' can also be used in `ifs` below.

    # Guess the average of high and low
    ### The average of two numbers is (x + y) / 2.

    # Ask the user to respond to the guess
    ### Python (at least 2.7) has a 'raw_input' for this, NOT 'input'.

    # If the guess was right, print a message that tries guesses were required
    # and quit the program
    ### Look at the 'if' statement for this and all the ones below.

    # If the guess was too high, print a message that says “I will guess lower.”
    # If the guess was too low, print a message that says “I will guess higher.”
    # If the user entered an incorrect value, print out the instructions again.

rawDescription: Creating a high and low game in python and need a lot of help!


code:
pytest_plugins = "pytester"

def test_something(testdir):
    """Test some thing."""
    testdir.makepyfile("""
        import pytest

        @pytest.mark.some
        def test_some():
            assert True

        @pytest.mark.some_thing_else
        def test_some_thing_else():
            assert True
    """)
    result = testdir.runpytest('-vv')
    assert result.stdout.lines[-4:-2] == [
        u'test_something.py::test_some PASSED',
        u'test_something.py::test_some_thing_else PASSED'
    ]

rawDescription: Programmatically collecting or creating tests with py.test


code:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
X = [1,2,3,4,5,6,7]
Y = [1,2,3,4,5,6,7]
label = [0,1,4,2,3,1,1]

# Define a colormap with the right number of colors
cmap = plt.cm.get_cmap('jet',max(label)-min(label)+1)

bounds = range(min(label),max(label)+2)
norm = colors.BoundaryNorm(bounds, cmap.N)

plt.scatter(X, Y, c= label, s=50, cmap=cmap, norm=norm)

# Add a colorbar. Move the ticks up by 0.5, so they are centred on the colour.
cb=plt.colorbar(ticks=np.array(label)+0.5)
cb.set_ticklabels(label)

plt.show()

rawDescription: Create legend for scatter plot using the label of the samples in matplotlib


rawDescription: Django templating system: Is there a way to render None as ''?


rawDescription: How can I label the minor tics in a loglog plot in matplotlib?

description: Label the minor tics in a loglog plot in matplotlib


code:
attrs = ('Levels', 'MaxX', 'MaxY', 'BW')
assert len(tup) == len(attrs)
for attr, val in zip(attrs, tup):
    if val is not None: # don't use !=
        setattr(self, attr, val)

rawDescription: Help Cleaning up a bit of Python Code

description: Help Cleaning up a bit of Python Code


code:
def match(pattern, string, flags):
    return re.search(r"\A(?:" + pattern + ")", string, flags)

rawDescription: Why use re.match(), when re.search() can do the same thing?


code:
import pandas as pd
from bokeh.charts import Bar, output_file, show
x = pd.DataFrame({"gender": ["m","f","m","f","m","f"],
                  "enrolments": [500,20,100,342,54,47],
                  "class": ["comp-sci", "comp-sci",
                            "psych", "psych",
                            "history", "history"]})

bar = Bar(x, values='enrolments', label='class', stack='gender',
         title="Number of students enrolled per class",
         legend='top_right',bar_width=1.0)
output_file("myPlot.html")
show(bar)

rawDescription: Stacked bar plot by grouped data with pandas


code:
def shift(char,shift_by):
    val=ord(char) #gives ascii value of charecter
    val+=shift_by
    if(val>122):
        val=97+(val-122-1)
    return(chr(val))

def encrypt_string(str):
    shifter=2 #change to value of shifter here
    encrypted_string=""
    for i in str :
        if( (ord(i)>=97) and (ord(i)<=122) ):
            i=shift(i,shifter)
        encrypted_string+=i
    return(encrypted_string)

rawDescription: Encryption Python - encrypting a string

description: Encryption Python - encrypting a string


rawDescription: wxpython to display gif images one by one

description: Wxpython to display gif images one by one


rawDescription: Python selenium: Firefox auto download everything


rawDescription: how to use a variable in selenium webdriver find element by xpath?

description: Use a variable in selenium webdriver find element by xpath


code: from pysqlite2 import dbapi2 as sqlite

rawDescription: Python sqlite3: run different sqlite3 version


code:
import numpy as np
indices = [1, 3, 7]
mask = np.zeros(10, dtype=np.bool)
mask[indices] = True
print(mask) # [False  True False  True False False False  True False False]

rawDescription: slicing numpy arrays by combining indices and expression masks

description: Slicing numpy arrays by combining indices and expression masks


code: sorted(some_list, key=lambda x: x[2])

rawDescription: When is a lambda function better than defining?


code:
def accuracy(classifier, gold):
    results = classifier.classify_many([fs for (fs,l) in gold])
    correct = [l==r for ((fs,l), r) in zip(gold, results)]
    if correct:
        return float(sum(correct))/len(correct)
    else:
        return 0

rawDescription: aspect based sentiment using NLTK?

description: Aspect based sentiment using NLTK


code:
import csv
import os
import urllib.request, urllib.parse, urllib.error

ASXCode = 'CSL'
local_filename = "Intra_" + ASXCode + ".csv"
url = ('http://chartapi.finance.yahoo.com/instrument/1.0/' + ASXCode +
       '.ax/chartdata;type=quote;range=1d/csv')

temp_filename, headers = urllib.request.urlretrieve(url)

with open(temp_filename, 'r', newline='') as inf, \
     open(local_filename, 'w', newline='') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf)
    for _ in range(17):   # skip first 17 rows
        next(reader)
    writer.writerows(reader)  # copy the rest

os.remove(temp_filename)  # clean up
print('{} downloaded'.format(local_filename))

rawDescription: Delete specific rows in csv file from Python 3.4.3


code:
df1['C'] = to_add
df1
df1['B'] = to_add
df1

rawDescription: How to replace an entire Pandas DataFrame column index-wise?

description: Replace an entire Pandas DataFrame column index-wise


code:
def model(position, width, height):
    return  height * sqrt(2*pi) * width * scipy.stats.norm.pdf(x, position, width)

rawDescription: Determining the physical height of a gaussian curve (python)


code:
with open('dictionary.txt') as fin:
    words = fin.read().strip().split('\n')

import re
import time
expr = re.compile(r'a[^aeiouy]+e$', re.I)

# Of course, this extends easily to using a dictionary, too
def bench():
    start = -time.time()
    matches = [word for word in words if expr.search(word)]
    return start + time.time()

rawDescription: Is mapping features of strings helping parsing strings faster?


code:
import requests
import re
from bs4 import BeautifulSoup

user="xyzmohsin"
passwd="abcpassword"

s=requests.Session()
headers={"User-Agent":"Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36"}
s.headers.update(headers)

login_url="https://myaccount.amcom.com.au/ClientLogin.aspx"
r=s.get(login_url)
soup=BeautifulSoup(r.content)
RadMasterScriptManager_TSM=soup.find(src=re.compile("RadMasterScriptManager_TSM"))['src'].split("=")[-1]
EVENTTARGET=soup.find(id="__EVENTTARGET")['value']
EVENTARGUMENT=soup.find(id="__EVENTARGUMENT")['value']
VIEWSTATE=soup.find(id="__VIEWSTATE")['value']
VIEWSTATEGENERATOR=soup.find(id="__VIEWSTATEGENERATOR")['value']

data={"RadMasterScriptManager_TSM":RadMasterScriptManager_TSM,
"__EVENTTARGET":EVENTTARGET,
"__EVENTARGUMENT":EVENTARGUMENT,
"__VIEWSTATE":VIEWSTATE,
"__VIEWSTATEGENERATOR":VIEWSTATEGENERATOR,
"ctl00_TopMenu_RadMenu_TopNav_ClientState":"",
"ctl00%24MemberToolsContent%24HiddenField_Redirect":"",
"ctl00%24MemberToolsContent%24txtUsername":user,
"ctl00%24MemberToolsContent%24txtPassword":passwd,
"ctl00%24MemberToolsContent%24btnLogin":"Login"}

headers={"Content-Type":"application/x-www-form-urlencoded",
"Host":"myaccount.amcom.com.au",
"Origin":"https://myaccount.amcom.com.au",
"Referer":"https://myaccount.amcom.com.au/ClientLogin.aspx"}

r=s.post(login_url,data=data,headers=headers)

rawDescription: Access authenticated page using Python Requests


code:
if all([1<=x<=1000 for x in [i,j,k]]):
    print ("Thank you!")
else:
    print ("Please try again")

rawDescription: Python novice: Setting limits for multiple integers taken as input


code:
def combs(a, k):
    if k == 0:
        return [[]]
    r = []
    for i, x in enumerate(a):
        for c in combs(a[i+1:], k - 1):
            r.append([x] + c)
    #print '\t' * k, k, 'of', a, '=', r
    return r

rawDescription: Using recursion to create a list combination


code:
import bitstring, base64

def base64ToGUID(b64str):
  s = bitstring.BitArray(bytes=base64.b64decode(b64str)).hex
  def rev2(s_):
    def chunks(n):
      for i in xrange(0, len(s_), n):
          yield s_[i:i+n]
    return "".join(list(chunks(2))[::-1])
  return "-".join([rev2(s[:8]),rev2(s[8:][:4]),rev2(s[12:][:4]),s[16:][:4],s[20:]])

assert base64ToGUID("bNVDIrkNbEySjZ90ypCLew==") == "2243d56c-0db9-4c6c-928d-9f74ca908b7b"

rawDescription: decoding base64 guid in python

description: Decoding base64 guid in python


code: [foo.bar for foo in foos]

rawDescription: Elegant pythonic solution for a simple loop


code:
r = re.compile('(?:\sat\s|,|and)(.*?) towards (.*?)(?=\.|,|and)')
s = "peak hour traffic at ulsoor lake jn towards nagatheatre jn, okalipuram towards majestic and bamboo bazaar jn to wards cole's park jn."
r.findall(s)

rawDescription: Extract entity using regex in python

description: Extract entity using regex in python


code:
smsInboundServer = internet.TCPServer(8001, webserver.Site(smsInbound),
    interface='10.0.0.78')

rawDescription: Twisted: how-to bind a server to a specified IP address?


code:
def reverse_dictionary(olddict):
    newdict = {}
    for key, value in olddict.items():
        for string in value:
            newdict.setdefault(string.lower(), []).append(key.lower())

    for key, value in newdict.items():
        newdict[key] = sorted(value)
    return newdict

olddict=({'astute': ['Smart', 'clever', 'talented'],
          'Accurate': ['exact', 'precise'],
          'exact': ['precise'],
          'talented': ['smart', 'keen', 'Bright'],
          'smart': ['clever', 'bright', 'talented']})
result=reverse_dictionary(olddict)

print(result)

rawDescription: How to sort values of a dictionary?

description: Sort values of a dictionary


code:
item['date'] = sel.xpath('//*[@class="ratingDate relativeDate"]/@title').extract()
item['date'] += sel.xpath('//div[@class="col2of2"]//span[@class="ratingDate"]/text()').extract()

rawDescription: How to get title from class attribute in XPath(Python/scrapy)

description: Get title from class attribute in XPath(Python/scrapy)


rawDescription: How to improve the efficiency of time.strptime in Python?

description: Improve the efficiency of time.strptime in Python


code:
from django.conf import settings

def myview(request):
    settings.TEMPLATE_STRING_IF_INVALID = '%s' # '%s' will get expanded to the variable name that was not found
    ...
    template = render(request, 'myview.html', {})
    settings.TEMPLATE_STRING_IF_INVALID = ''
    return template

rawDescription: Enable django's TEMPLATE_STRING_IF_INVALID on a single method


code:
with open('file.txt', 'r') as f:
    fp = f.readlines()

t = [l.strip().split(':') for l in fp if l != '\n']
d = {}
for l in t:
    d[l[0]] = d.setdefault(l[0], 0) + int(l[1])

rawDescription: Turning Text file to dictionary

description: Turning Text file to dictionary


code:
from django.db.models import Q

def companies_matching(merchants):
    """
    Return a queryset for companies whose names contain case-insensitive
    matches for any of the `merchants`.
    """
    q = Q()
    for merchant in merchants:
        q |= Q(name__icontains = merchant)
    return Companies.objects.filter(q)

rawDescription: django icontains with __in lookup

description: Django icontains with __in lookup


code:
import sys

sys.modules[__name__].__file__

rawDescription: How do you show the path of the current running python module?

description: Show the path of the current running python module


code:
"{foo} {bar}".format(foo="foo", bar="bar")
"{foo} {bar}".format(**{"foo": "Hello", "bar": "World!"})

rawDescription: Named replaces in strings with Mako

description: Named replaces in strings with Mako


code:
from lxml import  objectify

class Parser(object):
    def __init__(self, tree, counter_start, counter_interval):
        self.tree = tree
        self.root = tree.getroot()
        self.counter_start = counter_start
        self.counter_interval = counter_interval

    def parse(self):
        counter = self.counter_start
        # for loop to iter voltage items
        # using counter += counter_interval to set the value for example
        # save the tree within the parser class or in the handle function

def handle(file):
    f = open(file)
    tree = objectify.parse(f)
    parser = Parser(tree, 1000, 100)
    parser.parse()
    f.close()

handle("/Desktop/bar.XML")

rawDescription: python: change xml node value by a increase number

description: Python: change xml node value by a increase number


code:
def split_string(source, separatorList):
    splited = [source]
    for separator in separatorList:
        # if you want to exchange two variables, then write in one line can make the code more clear
        source, splited = splited, []
        for sequence in source:
            # there's no need to check `sequence` in advance, just split it
            # if sequence not in separatorList and sequence != ' ':
                # splited = splited + sequence.split(separator)

            # code to prevent appearance of `''` is here, do a if check in list comprehension.
            # `+=` is equivalent to `= splited +`
            splited += [i for i in sequence.split(separator) if i]
    return splited

rawDescription: How to prevent an procedure similar to the split () function (but with multiple separators) returns ' ' in its output

description: Prevent an procedure similar to the split () function (but with multiple separators) returns ' ' in its output


code: ftp.retrlines("LIST -a")

rawDescription: Python 3: ftplib - nlst command does not show files starting with a point


code:
import sys
InFileName = sys.argv[1]

rawDescription: open file in Python using "python scriptname.py filename"

description: Open file in Python using "python scriptname.py filename"


code:
@scen2_api.route("/")
def main():
    global spin
    spin=0
    if dutyCycle != 0.0:
        spin=1
    return jsonify(state=str(spin), pwmvalue=str(dutyCycle))

@scen2_api.route("/PWMValue/<action>")
def action( action):
    global dutyCycle
    dutyCycle = float(action)
    p.ChangeDutyCycle(float(dutyCycle))

    return jsonify(state=str(spin), pwmvalue=str(dutyCycle))

rawDescription: Save variable Python blueprints flask

description: Save variable Python blueprints flask


code:
 # load your image
image = QtGui.QPixmap(_fromUtf8(":/icons/BOOM_OUT.png"))

# prepare transform
t = QtGui.QTransform()
t.rotate(45)

# rotate the pixmap
rotated_pixmap = pixmap.transformed(t)

# and let the label show the rotated version
label.setPixmap(rotated_pixmap)

rawDescription: Rotating a Label In Qt with Python

description: Rotating a Label In Qt with Python


code:
secret = u'ककककक.'.encode('utf-8')

message = u'कककककककककककक'.encode('utf-8')

decoded = DecodeAES(obj, encoded).decode('utf-8')

rawDescription: Encryption decryption of natural language model


code:
import os

filename = os.path.basename(__file__)
for f in os.listdir('/home/you/scripts'):
    if f != filename:
        print(f)

rawDescription: Display all but current executing/running file in python 3.3


code:
import logging
import re

KEY = 'PK_SOME_PUBLIC_KEY'
SECRET_KEY = 'SK_SOME_PRIVATE_KEY'

class StrippingLogRecord(logging.LogRecord):

    pattern = re.compile(r'\b[PS]K_\w+\b', re.I)

    def getMessage(self):
        message = super(StrippingLogRecord, self).getMessage()
        message = self.pattern.sub('-- key redacted --', message)
        return message

if hasattr(logging, 'setLogRecordFactory'):
    # 3.x has this
    logging.setLogRecordFactory(StrippingLogRecord)
else:
    # 2.x needs monkey-patching
    logging.LogRecord = StrippingLogRecord

logging.basicConfig(level=logging.DEBUG)
logging.debug('Message with a %s', KEY)
logging.debug('Message with a %s', SECRET_KEY)

rawDescription: Custom Processing on Python logging messages in a generic way


code:
import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.om_variable = tk.StringVar(self)

        b1 = tk.Button(self, text="Colors", width=8, command=self.use_colors)
        b2 = tk.Button(self, text="Sizes", width=8, command=self.use_sizes)

        self.om = tk.OptionMenu(self, self.om_variable, ())
        self.om.configure(width=20)
        self.use_colors()

        b1.pack(side="left")
        b2.pack(side="left")
        self.om.pack(side="left", fill="x", expand=True)

    def _reset_option_menu(self, options, index=None):
        '''reset the values in the option menu

        if index is given, set the value of the menu to
        the option at the given index
        '''
        menu = self.om["menu"]
        menu.delete(0, "end")
        for string in options:
            menu.add_command(label=string,
                             command=lambda value=string:
                                  self.om_variable.set(value))
        if index is not None:
            self.om_variable.set(options[index])

    def use_colors(self):
        '''Switch the option menu to display colors'''
        self._reset_option_menu(["red","orange","green","blue"], 0)

    def use_sizes(self):
        '''Switch the option menu to display sizes'''
        self._reset_option_menu(["x-small", "small", "medium", "large"], 0)

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

rawDescription: How can I dynamic populate an option widget in tkinter depending on a choice from a drop down menu?

description: Dynamic populate an option widget in tkinter depending on a choice from a drop down menu


code:
s = df.groupby("keys").ids.agg(lambda x:len(x.unique()))
pd.value_counts(s).plot(kind="bar")

rawDescription: Plot key count per unique value count in pandas


code:
fname = 'bigfile.log'
fid = open(fname, "rb")
fid.seek(3 * (2 ** 30) , 0) # go to the ~(3*10^9)th Byte, with respect to the start
Buffer = fid.read(2 * (2 ** 30))

rawDescription: Truncate head of file in Python

description: Truncate head of file in Python


code: from threading import Lock

rawDescription: Asynchronous daemon processing / ORM interaction with Django


code:
def testGeodatabase(self):
    return self.outputGeodatabase in self.gp.ListWorkspaces("*","ALL")

rawDescription: How can this behavior be acomplished? Python "short circuting" test


code:
def calculation():
    while 1:
        global s, n
        r = n % base
        if r == 0: return
        s = digits[r] + s
        n = n // base
        if n == 0: return

#                  .          .          .
digits = "X0123456789"
digits = "X23456789AJKQ" #first digit not use, remain for calculation
currpos = 0
currpos = 30941 #22222 base13 13^4+13^3+13^2+13+1
#currpos_end = 371292 #QQQQQ base13 13^5-1
currpos_end = pow((26+10+1),5)
currpos_end = 371292
#currpos_end = 1024
base = len(digits)
print (currpos)
print (base)
print ()

for currpos in range(currpos, currpos_end):
    n = currpos
    s = ""
    calculation()
    if s == "":
        continue
    print (s, " . ", currpos, " . ", n)
    #do something here with s

rawDescription: python performance compared to freebasic

description: Python performance compared to freebasic


code:
note_nodes=re.split(r'\{(.*?)\}',details['text'])
# ['', 'Code', ' - ', 'Text', '']
note_nodes=[n if i%2==0 else XSL('value-of',select=n)
            for i,n in enumerate(note_nodes)]

rawDescription: Pythonic way to replace text with xml nodes


code: '\n'.join(' '.join(x) for x in zip(a, b))

rawDescription: How do I iterate over the tuples of the items of two or more lists in Python?

description: Iterate over the tuples of the items of two or more lists in Python


code:
testset, testcase = re.search('(.*)\.(.*)-.*', a).group(1, 2)
testset += '.py'

rawDescription: Parsing a string pattern - Python

description: Parsing a string pattern - Python


code:
class Rectangle(object):
    def __init__(self, w, h):
        self.w = w
        self.h = h
    @property
    def area(self):
        return self.w * self.h

rawDescription: Python - Should I use read-only @property without init or setter?


code:
companies = {'company1':pandas.DataFrame(columns=['Date', 'Daily Profit',
                                                 'Daily Loss', 'Daily Revenue']),
             'company2':pandas.DataFrame(columns=['Date', 'Daily Profit',
                                                 'Daily Loss', 'Daily Revenue'])}

company=row['Company Name'] # Get your company name as a string from your summary.
company_details = companies[company] # Returns a DataFrame.

rawDescription: How can I use a variable value to call a dataframe?

description: Use a variable value to call a dataframe


code:
from nose.plugins import Plugin
import datetime

class SeparateReports(Plugin):
  "Log the results of each test into a separate file."
  def afterTest(self, test):
    logname = test.id() + '.log'
    success = test.passed
    date = datetime.datetime.now()
    # print logname, datetime.datetime.now(), success
    with open(logname, 'a') as log:
        log.write("%s: %s\n" % (date, success))

rawDescription: how to make nose to log output of cases to separate files?

description: Make nose to log output of cases to separate files


rawDescription: Matrix of differences in Python, result like MATLAB's bsxfun


code:
import bottle

def preprocessing(func):
    def inner_func(*args, **kwargs):
        print("preprocessing {ip}".format(ip=bottle.request.remote_addr))
        return func(*args, **kwargs)
    return inner_func

bottle.install(preprocessing)

def hello():
    return "hello"

def world():
    return "world"

bottle.route('/hello', 'GET', hello)
bottle.route('/world', 'GET', world)
bottle.run()

rawDescription: How to preprocess all calls?

description: Preprocess all calls


code:
import sys
from sys import _getframe as getframe
import atexit

examined_modules = []

def gendeps():
    """Adds the calling module to the initialization queue."""
    # Get the calling module's name, and add it to the intialization queue
    calling_module_name = getframe(1).f_globals['__name__']
    examined_modules.append(calling_module_name)

def init():
    """Initializes all examined modules in the correct order."""

    for module in examined_modules:
        module = sys.modules[module]
        if hasattr(module, 'init'):
            module.init()
        if hasattr(module, 'deinit'):
            # So modules get de-initialized in the correct order,
            # as well
            atexit.register(module.deinit)

rawDescription: Python dependency analyzer library

description: Python dependency analyzer library


code:
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
                     user="root", # your username
                      passwd="mysql", # your password
                      db="sakila") # name of the data base

cursor = db.cursor()
posts = "select * from ques LIMIT 100"
cursor.execute(posts)
db.commit()
a='hello'
counter = 0

for j in cursor.fetchall():
    counter += 1
    if a in j[0]:
      print ("Row " + str(counter) + "= " + j[0] + " => True")
    else:
      print ("Row " + str(counter) + "= " + j[0] + " => False")
    raw_input("please press enter to continue")

rawDescription: python iterate row one by one mysql field

description: Python iterate row one by one mysql field


code:
from ctypes import *

class item_t(Structure):
    _fields_ = [
        ('name', c_char_p),
    ]

class container_t(Structure):
    _fields_ = [
        ('items', POINTER(POINTER(item_t))),
    ]

rawDescription: How to handle a pointer to a pointer with Python and ctypes

description: Handle a pointer to a pointer with Python and ctypes


code:
from subprocess import Popen

resolve = Popen(["p4", "resolve"])
stdout, stderr = resolve.communicate("m")

rawDescription: Feed input of MS-DOS interactive executable with a string value


rawDescription: Python: Count the occurence of a number being smaller than a threshold accross row


rawDescription: Add a restriction to a regex expression

description: Add a restriction to a regex expression


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

def f(a,x):
    return a*x
def g(a,x):
    return 5*a*x

const=[1,2,3]

fig=plt.figure()
ax=fig.add_subplot(1,1,1)
colors=['r','b','g']
labels = ['a1', 'a2', 'a3']
xArray=np.linspace(0,2,20)
for i in const:
    ax.plot(xArray,f(i,xArray), color=colors[i-1],
            label=labels[i-1])
    ax.plot(xArray,g(i,xArray), color=colors[i-1],ls='--')
plt.legend()
plt.show()

rawDescription: add legend for some of the lines

description: Add legend for some of the lines


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

# http://matplotlib.sourceforge.net/examples/api/colorbar_only.html

fig=plt.figure(figsize=(1,5))
ax=fig.add_subplot(111)
ax.axis([0,1,-50,200])
cmap = mpl.cm.jet
norm = mpl.colors.Normalize(vmin=-40, vmax=180)
cb1 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
                                orientation='vertical',
                                norm=norm,
                                ticks=[-40,180]
                                )

plt.subplots_adjust(left=0.4, right=0.8)
plt.show()

rawDescription: Gradient facecolor matplotlib bar plot

description: Gradient facecolor matplotlib bar plot


code:
from django.conf import settings
def my_view(request):
    # view logic
    context = {
            'STATIC_URL': settings.STATIC_URL,
            # other template variables here
    }
    # render the template and produce a response

rawDescription: django - variable declared in base project does not appear in app

description: Django - variable declared in base project does not appear in app


code:
a = [[1,2.3,'3', object()], [None, [2,3], 4j]]
b = [v for row in a for v in row]
a
b
[id(obj) for row in a for obj in row]
[id(obj) for obj in b]

rawDescription: Flattening a Python list without creating copies of any objects?


code:
try:
    from local_settings import *
except ImportError as e:
    pass

rawDescription: How to manage local vs production settings in Django?

description: Manage local vs production settings in Django


code:
for node in soup.find_all(attrs={"class": re.compile(r'my_class(1|2)')}):
    print(node)

rawDescription: BeautifulSoup - check if elements have specific class


code:
x = getattr(a, "website_{0}_revision".format(name))
x.add(a)

rawDescription: How to replace a word in an attribute name, then add to that list

description: Replace a word in an attribute name, then add to that list


code:
import cv2
cv2.namedWindow("output", cv2.WINDOW_NORMAL)        # Create window with freedom of dimensions
im = cv2.imread("earth.jpg")                        # Read image
imS = cv2.resize(im, (960, 540))                    # Resize image
cv2.imshow("output", imS)                            # Show image
cv2.waitKey(0)                                      # Display the image infinitely until any keypress

rawDescription: OpenCV & Python - Image too big to display


code:
def getSummary(s):
    return s[s.find('\nSummary'):]

rawDescription: Python and reading lines

description: Python and reading lines


code:
for root, dirnames, filenames in os.walk(...):
  dirnames[:] = [
    dir for dir in dirnames
    if not os.path.ismount(os.path.join(root, dir))]
  ...

rawDescription: How do I prevent Python's os.walk from walking across mount points?

description: Prevent Python's os.walk from walking across mount points


code:
def reply(x):
    responses = []

    if any(item in x for item in thanks):
        responses.append("It's my pleasure\n")
    if any(item in x for item in greetings):
        responses.append("How are you?\n")

    if not responses:
        randomAnswers = ["I like cheese.", "That's Cool.", "You are a robot.", "I am not a robot.", "I like music.", "I want to visit australia.","Do you like me?","You're cool."]
        responses.append(random.choice(randomAnswers))

    return responses

rawDescription: Once I've returned a reply the function doesn't continue. Is there a way I can return a value and then carry on?


rawDescription: Python: Bitwise-like list operations

description: Python: Bitwise-like list operations


code:
factories = []
module = globals()

for name, obj in models:
    factory_name = name + 'Factory' # e.g. PersonFactory
    attrs = assemble_factory_attrs(obj, factory_name)
    f = type(factory_name, (object,), attrs)
    module[factory_name] = f
    factories.append(f)

rawDescription: Unpack classes from a list into a module


code:
def get_xpath_count(self,xpath):
    """
    Returns the number of nodes that match the specified xpath, eg. "//table" would give
    the number of tables.

    'xpath' is the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you.
    """
    return self.get_number("getXpathCount", [xpath,])

rawDescription: Using Selenium's Python API - How do I get the number of rows in a table?


code:
page_key = ndb.Key(Book, bookId, Chapter, chapterId, Page, pageId)
page = page_key.get()

rawDescription: Working with ancestors in GAE

description: Working with ancestors in GAE


code:
prev = None
with open("test_parse") as fh_in:
    for line in fh_in:
        line = line.strip().split()
        if prev and prev[0] == line[0]:
            print(' '.join(prev).replace(prev[4], line[4]).split())
        prev = line

rawDescription: how do i get particular fields in python

description: Get particular fields in python


code:
import os

a = os.environ['a']

rawDescription: Can I read an `export`ed variable from a python script?

description: Read an `export`ed variable from a python script


code:
easy_install_pre.exe %1
unzip_eggs.py %1

rawDescription: How to unzip python eggs?

description: Unzip python eggs


code:
from py2neo import Graph
graph = Graph("http://nifty-site:1138/db/data/")
results = graph.cypher.execute("match (PPnode:Node) return PPnode")

for r in results:
    # get the node you return in your query
    ppNode = r[0]
    # get the properties of your node
    props = ppNode.get_properties()
    # Do nifty stuff with properties, not JSON.

rawDescription: How to get the response of a cypher query in neo4j using python Rest api

description: Get the response of a cypher query in neo4j using python Rest api


code:
#test.py
import foo

_old_open = open  # original function
# monkey-patch
def _new_open(*args, **kwargs):
    try:
        raise(Exception('dummy'))
    except Exception as e:
        import sys
        check_call(*sys.exc_info())
    return _old_open(*args, **kwargs)
__builtins__.open = _new_open

def check_call(e_type, e_value, tb):
    import inspect, sys
    # restore patch to avoid infinite recursion
    __builtins__.open = _old_open
    try:
        stack = inspect.getouterframes(tb.tb_frame)
        frame_info = inspect.getframeinfo(stack[1][0])
        if frame_info.code_context[0].strip()\
                     .startswith('with '):
            return
        sys.stderr.write(
           "DEBUG: open call outside with block at "
           "{f.filename}, line {f.lineno}\n"
           .format(f=frame_info)
        )
    finally:
        __builtins__.open = _new_open

if __name__ == '__main__':
    foo.baz('a.txt')
    foo.bar('a.txt')

# foo.py
def bar(fname):
    f = open(fname, 'w')

def baz(fname):
    with open(fname, 'w') as f:
        f.write('dummy!')

# result:
# DEBUG: open call outside with block at
# /path/to/foo.py, line 13

rawDescription: Is there an easy way to find which part of the code not closing the file


code:
example_set = {None, 1, 2}
filtered_set = {item for item in example_set if item}

print(filtered_set) # {1, 2}

rawDescription: remove items from set that pass a certain test python

description: Remove items from set that pass a certain test python


rawDescription: Python csv writer, numpy array to csv

description: Python csv writer, numpy array to csv


code:
import re

string_example = '123|4.3|123.54|sdflk|hfghjkkf.ffg..t.s..4..tg..3...654..2.fd'

string_final = re.sub(r'(\d)\.(\d)', r'\1,\2', string_example)
print(string_final)

rawDescription: How to replace only particular dots in the string?

description: Replace only particular dots in the string


code:
import numpy as np
QS = [np.random.randint(0, 10, (3,3)) for i in range(6)]
QM = QS[0]+QS[1]+QS[2]+QS[3]+QS[4]+QS[5]
QM
QM2 = np.sum(QS,axis=0)
QM2
np.allclose(QM, QM2)

rawDescription: Summing up all elements in a list of 2D arrays


code:
view = self.window.active_view()
line = view.line(view.sel()[0])
linetext = view.substr(line)

rawDescription: how to get whole line text, on which I got cursor

description: Get whole line text, on which I got cursor


code: inlines = ( get_inline_by_model (models.GenderModel1 ) ,  )

rawDescription: django - one inline for multiple models

description: Django - one inline for multiple models


code:
with session.no_autoflush:
    parent = Parent("my parent")
    db_session.add(parent)
    child = Child("my child", parent)

rawDescription: Getting a parents children through a backref attribute via sqlalchemy relationship causes unnecessary flush


rawDescription: python: how to handle timestamps (ISO8601)

description: Python: how to handle timestamps (ISO8601)


code:
names_to_remove = set(h.vs["name"])
vs_to_keep = g.vs.select(name_notin=names_to_remove)
g.induced_subgraph(vs_to_keep)

rawDescription: delete subgraph from graph

description: Delete subgraph from graph


code:
import glob, os, shutil

files = glob.iglob(os.path.join(source_dir, "*.txt"))
for file in files:
    if os.path.isfile(file):
        shutil.copy2(file, dest_dir)

rawDescription: Python 3.4 Find all file types and copy to directory


code:
windowToImageFilter = vtk.vtkWindowToImageFilter()
windowToImageFilter.SetInput(renWin)
windowToImageFilter.SetInputBufferTypeToRGBA()
windowToImageFilter.ReadFrontBufferOff()
windowToImageFilter.Update()

writer = vtk.vtkAVIWriter()
writer.SetInputConnection(windowToImageFilter.GetOutputPort())
writer.SetFileName("test.avi")
...

rawDescription: Python VTK, how to record a video?

description: Python VTK, how to record a video


code:
import wx

class MainFrame(wx.Frame):

    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        panel = wx.Panel(self)
        notebook = wx.Notebook(panel)

        splitter_window = wx.SplitterWindow(notebook)
        notebook.AddPage(splitter_window, 'Splitter')
        panel1 = wx.Panel(splitter_window, style=wx.BORDER_THEME)
        wx.StaticText(panel1, label='Place Grid here')
        panel2 = wx.Panel(splitter_window, style=wx.BORDER_THEME)
        wx.StaticText(panel2, label='Place Chart here')
        splitter_window.SplitHorizontally(panel1, panel2, 50)

        p_sizer = wx.BoxSizer(wx.VERTICAL)
        p_sizer.Add(notebook, 1, wx.EXPAND | wx.ALL, 7)
        panel.SetSizer(p_sizer)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(panel, 1, wx.EXPAND)
        self.SetSizer(sizer)

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

rawDescription: How to split a notebook in wxpython?

description: Split a notebook in wxpython


code:
body =  " Motion Detection Started \n Pixel Threshold (How much)   = " + str(threshold) + \
        "\n Sensitivity (changed Pixels) = " + str(sensitivity) + \
        "\n File Path for Image Save     = " + filepath

rawDescription: Python Print Output to Email

description: Python Print Output to Email


code:
import dis
dis.dis(compile('[line.split()[i] for i in indexes]', '', 'eval'))

rawDescription: Python: Is the split function evaluated multiple times in a list comprehension?


rawDescription: How to open a window from the command line within a Python script?

description: Open a window from the command line within a Python script


code:
surface='EPsurface_21Oct2015Compensated.LEV'
with open(surface,mode='r', encoding='latin_1') as fileobj, open('testing.txt', 'w') as out:
    for line in fileobj:
        try:
            words=line.split()
            dateS = str(parse('{0} {1}'.format(words[0],words[1])))
            tempS = str(float(words[3]))
            print("{0}, {1}".format(dateS, tempS), file=out)
        except (TypeError,IndexError):
            pass

rawDescription: Turn 2 lists into 2-column text file

description: Turn 2 lists into 2-column text file


code:
class A(models.Model):
    title = models.CharField(max_length=30)

class B(models.Model):
    title = models.CharField(max_length=255)
    a = models.ManyToManyField(A)

class C(models.Model):
    title = models.CharField()
    property1 = models.CharField()

class A_B_C(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)
    c = models.ForeignKey(C)

    class Meta:
        unique_together = ('a', 'b', 'c')

rawDescription: Django complex relationship

description: Django complex relationship


code:
g = sve_DOC['sRes'].groupby(pd.TimeGrouper('M'))
g.transform('mean')

sve_DOC['RIMsDOC2'] = sve_DOC['RIMsDOC'] - g.transform('mean')

rawDescription: Using .groupby and .resample to carry out operations on a pandas dataframe


code:
for d in data:
    jsonstring = json.dumps(d)

rawDescription: Python: Parsing JSON String List for Each JSON Object


code: upload_to = lambda instance, filename : create_file(instance, 'whatever')

rawDescription: Refering to self instance from within a model class


code:
import socket

try:
    HOSTNAME = socket.gethostname()
except:
    HOSTNAME = 'localhost'

rawDescription: How to use Django to get the name for the host server?

description: Use Django to get the name for the host server


code:
tweets                          =   []
MAX_ATTEMPTS                    =   10
COUNT_OF_TWEETS_TO_BE_FETCHED   =   500

for i in range(0,MAX_ATTEMPTS):

    if(COUNT_OF_TWEETS_TO_BE_FETCHED < len(tweets)):
        break # we got 500 tweets... !!

    #----------------------------------------------------------------#
    # STEP 1: Query Twitter
    # STEP 2: Save the returned tweets
    # STEP 3: Get the next max_id
    #----------------------------------------------------------------#

    # STEP 1: Query Twitter
    if(0 == i):
        # Query twitter for data.
        results    = api.search(q="foobar",count='100')
    else:
        # After the first call we should have max_id from result of previous call. Pass it in query.
        results    = api.search(q="foobar",include_entities='true',max_id=next_max_id)

    # STEP 2: Save the returned tweets
    for result in results['statuses']:
        tweet_text = result['text']
        tweets.append(tweet_text)

    # STEP 3: Get the next max_id
    try:
        # Parse the data returned to get max_id to be passed in consequent call.
        next_results_url_params    = results['search_metadata']['next_results']
        next_max_id        = next_results_url_params.split('max_id=')[1].split('&')[0]
    except:
        # No more next pages
        break

rawDescription: Twython search API with next_results

description: Twython search API with next_results


rawDescription: regex search is not catching what it should

description: Regex search is not catching what it should


code:
with open(filename, 'w') as f:
    f.write(repr(df))

rawDescription: Saving a full dataframe to disk as IPython shows it


code:
t ='''

  Some text that i want

  some more text
  some more text

'''

soup = BeautifulSoup(t, "html.parser")

text = list(soup.find('td'))[0]

rawDescription: Find text but skip other elements

description: Find text but skip other elements


code:
import os
img_filename = os.path.splitext('data1.txt')[0] + '.jpg'

rawDescription: how to save a certain file name but change the file type in matplotlib.savefig

description: Save a certain file name but change the file type in matplotlib.savefig


code:
from setuptools import setup, find_packages
import sys

stdout = sys.stdout
stderr = sys.stderr

log_file = open('log', 'w')
sys.stdout = log_file
sys.stderr = log_file

setup (
        ...  ,
        ...
      )

# Make sure to close the log file. You could also use with to surround the setup()
# To ensure log file is closed in the event of exception.
log_file.close()

sys.stdout = stdout
sys.stderr = stderr

with open('log', 'r') as log_file:
    sys.stdout.write(log_file.read())

rawDescription: Saving the installation log generated from setup.py


code:
import os
os.getpid()

rawDescription: Get proccess ID with python

description: Get proccess ID with python


code:
from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = (
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
    )
    year_in_school = models.CharField(max_length=2,
                                      choices=YEAR_IN_SCHOOL_CHOICES,
                                      default=FRESHMAN)

    def is_upperclass(self):
        return self.year_in_school in (self.JUNIOR, self.SENIOR)

rawDescription: Adding a custom validation for a character field in Django


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

x = np.linspace(0, 10)
y = np.sin(x)
plt.plot(x, y, dashes=[10, 5, 20, 5], linewidth=2, color='black')

rawDescription: How to draw more type of lines in matplotlib

description: Draw more type of lines in matplotlib


code:
def iter_entities(cursor=None):
    entries = AppList.query()
    res, cur, more = entries.fetch_page(100, start_cursor=cursor)
    put_queue = [ent for ent in res if not hasattr(ent, 'ignore')]
    # put_queue = []
    # for ent in res:
    #    if not hasattr(ent, 'ignore'):
    #        put_queue.append(ent)
    ndb.put_multi(put_queue)
    if more:
        iter_entities(cur) # a taskqueue is better

rawDescription: How to assign default value to all NDB datastore entries?

description: Assign default value to all NDB datastore entries


code:
from operator import itemgetter
import pickle

# pickle
high_scores = [
    ('Liz', 1800),
    ('Desi', 5000),
    ('Mike', 3200),
    ('John', 2000),
    ('Gabi', 3150),
    ('John', 3500),
    ('Gabi', 3100),
    ('John', 3000),
    ('Liz', 2800),
    ('Desi', 2800),
]

high_scores.append(('Dave', 3300))
high_scores = sorted(high_scores, key=itemgetter(1), reverse=True)[:10]

with open('highscores.txt', 'w') as f:
    pickle.dump(high_scores, f)

# unpickle
high_scores = []

with open('highscores.txt', 'r') as f:
    high_scores = pickle.load(f)

rawDescription: Highscores using python / Saving 10 highscores and ordering them


code:
class Foobar():
    def __init__(self, foo, bar, choo):
        self.foo = foo
        self.bar = bar
        self.choo = choo

    def doIt(self):
        return self.foo + self.bar

makeFooLookup = {
    "first":  ("eenie", "meenie", "miney"),
    "second": ("teeny", "toonie", "tiny"),
    "third":  ("biggie", "baggie", "boogie")
}
def makeFoo(label, lookup=makeFooLookup):
    return Foobar(*lookup[label])

rawDescription: Python - Getting access to class instance via module property (by string name)


code:
from difflib import SequenceMatcher
SequenceMatcher(None, "Hello you!", "Hello you").ratio()
0.9473684210526315
SequenceMatcher(None, "Apple", "Orange").ratio()
0.18181818181818182

rawDescription: How do I compare these two strings in python?

description: Compare these two strings in python


code:
import numpy as np
import scipy as sp
import scipy.ndimage

def flood_fill(test_array,h_max=255):
    input_array = np.copy(test_array)
    el = sp.ndimage.generate_binary_structure(2,2).astype(np.int)
    inside_mask = sp.ndimage.binary_erosion(~np.isnan(input_array), structure=el)
    output_array = np.copy(input_array)
    output_array[inside_mask]=h_max
    output_old_array = np.copy(input_array)
    output_old_array.fill(0)
    el = sp.ndimage.generate_binary_structure(2,1).astype(np.int)
    while not np.array_equal(output_old_array, output_array):
        output_old_array = np.copy(output_array)
        output_array = np.maximum(input_array,sp.ndimage.grey_erosion(output_array, size=(3,3), footprint=el))
    return output_array

rawDescription: Python equivalent to Matlab funciton 'imfill' for grayscale?


code:
import dateutil.parser as dparser
date = dparser.parse('5th November 2010')
date

rawDescription: Parse this date in Python: 5th November 2010


code:
from Levenshtein import jaro_winkler  # May not be module name

heard_words = "brain"
possible_words = ["watermelon", "brian"]

word_scores = [jaro-winkler(heard_word, possible) for possible in possible_words]
guessed_word = possible_words[word_scores.index(max(word_scores))]

print('I heard {0} and guessed {1}'.format(heard_word, guessed_word))

rawDescription: Is there an in-built method in nltk to find words/phrases that closely match the given word?


code:
import email.parser
import StringIO
import zipfile

with open('message.eml') as f:
    msg = email.parser.Parser().parse(f)
attachment = msg.get_payload(1)
zipf = StringIO.StringIO(attachment.get_payload())
zip = zipfile.ZipFile(zipf)
filenames = zip.namelist()

rawDescription: How to get a list of files from the archive (rar or zip) attached to the E-mail using Python?

description: Get a list of files from the archive (rar or zip) attached to the E-mail using Python


code:
import pygame

screen = pygame.display.set_mode((500, 500))

pic1 = pygame.image.load("pic1.png")
pic2 = pygame.image.load("pic2.png")
pic3 = pygame.image.load("pic3.png")
pic4 = pygame.image.load("pic4.png")
pic5 = pygame.image.load("pic5.png")
pic6 = pygame.image.load("pic6.png")

counter = 0
pics = [pic1, pic2, pic3, pic4, pic5, pic6]
x = 100
y = [10, 50, 100, 150, 200, 250]

while(1): ## infinite loop

    screen.blit(pics[counter], (x, y[counter])) ## this will change position for the different heights
    counter += 1

    if counter >= 5:
        counter = 0

rawDescription: Pygame bouncing ball

description: Pygame bouncing ball


rawDescription: Python AppEngine Sort By Referenced Property


code:
from twisted.internet import reactor, protocol, task

class MyProtocol(protocol.Protocol):
    def connectionMade(self):
        self.factory.clientConnectionMade(self)
    def connectionLost(self, reason):
        self.factory.clientConnectionLost(self)

class MyFactory(protocol.Factory):
    protocol = MyProtocol
    def __init__(self):
        self.clients = []
        self.lc = task.LoopingCall(self.announce)
        self.lc.start(10)

    def announce(self):
        for client in self.clients:
            client.transport.write("10 seconds has passed\n")

    def clientConnectionMade(self, client):
        self.clients.append(client)

    def clientConnectionLost(self, client):
        self.clients.remove(client)

myfactory = MyFactory()
reactor.listenTCP(9000, myfactory)
reactor.run()

rawDescription: Running a function periodically in twisted protocol


code:
import SocketServer
import BaseHTTPServer

class ThreadingHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
    pass

rawDescription: BasicHTTPServer, SimpleHTTPServer and concurrency


code:
matrix = [ [ 1, 0, 0, 1, ...], [0, 1, ...], ...]
assert all(len(row)==len(matrix) for row in matrix) # check whether both dimensions are the same
if all(matrix[i][i] == 1 for i in range(len(matrix))):
    print("Relation is reflexive")
else:
    print("Relation is not reflexive")

rawDescription: Determining if a relation is reflexive

description: Determining if a relation is reflexive


code:
def encode(pic_data, file_data):
    """encode pic_data with the information stored in file_data"""
    # file data is shorter than pic_data, I test for it in the real code
    # would also need to make sure that the length of pic_data is greater than
    # the length of file_data by the number of 0s and 255s in it, to be safe
    new_pic_data = pic_data.copy()
    offset = 0
    for i in range(len(file_data)):
        # Now, 1 is 1 and 0 is -1, which still allows us to
        # distinguish 0 from nothing
        data_value = 1 if file_data[i] == '1' else -1
        # rgb max value is between 0 and 255
        while pic_data[i + offset] == 0 and data_value == -1:
            offset += 1
        while pic_data[i + offset] == 255 and data_value == 1:
            offset += 1
        new_pic_data[i + offset] += data_value

    return new_pic_data

def decode(pic_data_original, pic_data_modified):
    """
    extract a binary string from the differences between the input
    data sets
    """
    # both data sets have to be the same length
    new_file_data = ['1' if (pic_data_modified[i] - pic_data_original[i] == 1)
                     else '0' if (pic_data_modified[i] - pic_data_original[i] == -1)
                     else ''
                     for i in range(len(pic_data_original))]
    return ''.join(i for i in new_file_data)

binary_string = '01100001'  # the data to be hidden
flat_rgb_data = [18, 15, 255, 0, 151, 0, 254, 199, 21, 180, 105, 205]  # the picture

# [17, 16, 255, 1, 150, 0, 253, 198, 20, 181, 105, 205]
encoded_rgb_data = encode(flat_rgb_data, binary_string)

# getting binary_string back, '01100001'
decoded_data = decode(flat_rgb_data, encoded_rgb_data)

print(decoded_data)

rawDescription: Hiding binary values in a number list

description: Hiding binary values in a number list


code: self.function = lambda *args: module1.f(*args)[0]

rawDescription: Assign function, ignore first value

description: Assign function, ignore first value


code:
import colorsys

def rgb_range(color_num):
    h_rng = [ix / float(color_num) for ix in range(color_num)]
    return [colorsys.hsv_to_rgb(h, 1.0, 1.0) for h in h_rng]

rawDescription: Protovis-style color scale in Python?

description: Protovis-style color scale in Python


code:
import numpy as np
x = [[0,0], [1,0], [2,1], [3,0], [4,0], [5,1]] # Create dummy list
x = np.asarray(x) # Convert list to numpy array
x[x[:, 1] != 0] # Select out items whose second column don't contain zeroes

rawDescription: Delete line from 2D array in Python

description: Delete line from 2D array in Python


code:
sql = """
   select userid
      from usertab
    where name like %s
""" % cursor.connection.literal(search)

rawDescription: Python mysql string substitution not working


code:
frames=[]
for row in self.rowResults:
    frames.append(pandas.DataFrame(row))
self.results = pandas.concat(frames)

rawDescription: how to convert a list of list of dictionaries into a single panda dataframe?

description: Convert a list of list of dictionaries into a single panda dataframe


code:
while True:
    try:
        x = int(raw_input("put in a number"))
        break
    except ValueError:
        continue # or maybe print a message here...

rawDescription: Force a user to put in a intger

description: Force a user to put in a intger


code: ''.join(choice(chars) for _ in range(length))          # in py2k use xrange

rawDescription: Generate password in python

description: Generate password in python


code:
from __future__ import print_function

df1 = pd.read_csv('c:/temp/test_1.csv', usecols=[0,1], header = 0)

while True:
    try:
        number = int(raw_input("Please enter first choice: "))
    except ValueError:
        print('Please enter a valid integer.')
        continue
    try:
        print(df1.ix[:, number])
    except IndexError:
        print('Please enter an index between 0 and {}'.format(len(df) - 1))
        continue
    break

rawDescription: Variable substitution for column position in a read_csv data frame based on raw_input


code:
from elasticsearch import Elasticsearch

self.elastic_con = Elasticsearch([host], verify_certs=True)
mapping = '''
{
  "mappings":{
    "logs_june":{
      "_timestamp":{
        "enabled":"true"
      },
      "properties":{
        "logdate":{
          "type":"date",
          "format":"dd/MM/yyy HH:mm:ss"
        }
      }
    }
  }
}'''
self.elastic_con.indices.create(index='test-index', ignore=400, body=mapping)

rawDescription: python elasticsearch client set mappings during create index

description: Python elasticsearch client set mappings during create index


code:
from numpy import *
from matplotlib.pyplot import *
from scipy.signal import convolve2d
from scipy.ndimage.filters import minimum_filter as mini

a=random.rand(100,100)
neighbours = ones((3,3))
threshold=0.2
u=convolve2d(a<threshold,neighbours,'same')
mins=((u>=6)*(a<threshold))
minis=mini(choose(mins,(1,a)),size=(3,3))==a

subplot(121);imshow(mins,cmap=cm.gray_r,interpolation='none')
subplot(122);imshow(minis,cmap=cm.gray_r,interpolation='none')

rawDescription: How to check if a neighbourhood of at least five elements of an array satisfies a criterion?

description: Check if a neighbourhood of at least five elements of an array satisfies a criterion


code:
from flask import make_response

@app.route('/cart/', methods = ['GET'])
def cart_addition():
    if 'productid' in flask.request.cookies:
        output = 'Pass'
    else:
        output = 'Fail'

    resp = make_response(render_template('output.html', output=output))
    resp.set_cookie('productid', '11')
    return resp

rawDescription: Flask Cookies are not working

description: Flask Cookies are not working


code:
def __getattr__(self, attr):
  def default_method(*args):
    self.apply(attr, *args)
  return default_method

rawDescription: Python __getattribute__ (or __getattr__) to emulate php __call


code:
import calendar
import datetime

theDay = datetime.date(YEAR, MONTH, DAY)
beginDayEpochTime = calendar.timegm(theDay.timetuple())

rawDescription: Python: How to get the UTC epoch for 0:00 and 11:59 of a specified date?


code:
import numpy as np
import pylab as plt

# Create some test data
secret_data_X1 = np.linspace(0,1,100)
secret_data_Y1 = secret_data_X1**2
secret_data_X2 = np.linspace(1,2,100)
secret_data_Y2 = secret_data_X2**2

# Show the secret data
plt.subplot(2,1,1)
plt.plot(secret_data_X1,secret_data_Y1,'r')
plt.plot(secret_data_X2,secret_data_Y2,'b')

# Loop through the plots created and find the x,y values
X,Y = [], []
for lines in plt.gca().get_lines():
    for x,y in lines.get_xydata():
        X.append(x)
        Y.append(y)

# If you are doing a line plot, we don't know if the x values are
# sequential, we sort based off the x-values
idx = np.argsort(X)
X = np.array(X)[idx]
Y = np.array(Y)[idx]

plt.subplot(2,1,2)
plt.plot(X,Y,'g')
plt.show()

rawDescription: Merge two existing plots into one plot

description: Merge two existing plots into one plot


code:
from webapp2_extras.appengine.auth.models import User

class Comment(db.model):
  text = db.StringProperty()
  author = db.StringProperty()

  def get_author(self):
    return User.get_by_auth_id(self.author)

rawDescription: Google App Engine (Python) : use UserProperty with Webapp2 User Model


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
ticketCount = soup.find('span', id='ticket_count').get_text(strip=True)
print(ticketCount)

rawDescription: Python Beautifulsoup:how to get rid of '\n' in the texts of html tag


code:
# create data
x = np.array(range(20))
y = np.array(19 * [0] + [1])

(y[np.logical_and(x>=9, x<=13)] >= 0.05).any()  # False
(y[np.logical_and(x>=9, x<=20)] >= 0.05).any()  # True

rawDescription: Subselection using np.logical_and in Numpy


code:
class User(models.Model):
    user_id = models.CharField(primary_key=True, max_length=200)
    name = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=200)
    user_password = models.CharField(max_length=20)
    email = models.CharField(max_length=200)
    category = ( ('A','First AC'), ('B','Second AC'), ('C','Third AC'), ('D','Sleeper') )

    def __str__(self):
        return '{}'.format(self.user_id)

rawDescription: Django admin screen doesn't show entities by name


code:
i=0
for n in range(len(eventBreakL)):
    if n < len(eventBreakL)-1:
        i+=1
        eventL = c_eventConditionL[eventBreakL[n]:eventBreakL[n+1]-1]
        tL,isubL,vgsL,vdsL = [],[],[],[]
        for m in eventL:
            tL.append(m[1])
            isubL.append(m[-1])
            vdsL.append(m[2])
            vgsL.append(m[3])
        c_isub_plot.plot(tL,isubL,label=str(i))
        c_isub_plot.legend()
        vgvd_plot.plot(tL,vgsL,label=str(i))
        vgvd_plot.plot(tL,vdsL,label=str(i))
        vgvd_plot.legend()

rawDescription: Matplotlib Legend in a Loop?

description: Matplotlib Legend in a Loop


code:
def select_choice():
    ...
    return (i, card)

my_i, my_card = select_choice()

rawDescription: How can I return two values from a function in Python?

description: Return two values from a function in Python


code:
import requests

def tide_on(url):
    r = requests.get(url, stream=True, **kwargs)

    for line in r.iter_lines():
        # wish to stop after consuming just one line
        print(line)
        break

    r.close()

rawDescription: python-requests hook similar to pycurl.WRITEFUNCTION?

description: Python-requests hook similar to pycurl.WRITEFUNCTION


rawDescription: changing the value of var1

description: Changing the value of var1


code:
from GoogleScraper import scrape_with_config, GoogleSearchError
def saveLink(self, query):
        # See in the config.cfg file for possible values
        try:
            if query:
                file_name = query.replace(" " , "_")
                self.config = {
                    'SCRAPING': {
                        'use_own_ip': 'True',
                        'keyword': query,
                        'search_engines': 'bing',
                        'num_pages_for_keyword': 1,
                        'scrape_method': 'http'
                    },
                    'SELENIUM': {
                        'sel_browser': 'chrome',
                    },
                    'OUTPUT': {
                        'output_filename': "path/" + file_name + ".json"
                    },
                    'GLOBAL': {
                        'do_caching': 'False'
                    }
                }

                raw_html = ""
                sqlalchemy_session = scrape_with_config(self.config)
        except Exception:
            import traceback
            print(traceback.format_exc())

rawDescription: How to use GoogleScraper package to scrape link from different search engines in Python

description: Use GoogleScraper package to scrape link from different search engines in Python


code:
import time, socket

class ControllableSocket:
    def __init__(self, latency, bandwidth):
        self._latency = latency
        self._bandwidth = bandwidth
        self._bytesSent = 0
        self._timeCreated = time.time()
        self._socket = socket.socket()

    def send(self, bytes):
        now = time.time()
        connectionDuration = now - self._timeCreated
        self._bytesSent += len(bytes)
        # How long should it have taken to send how many bytes we've sent with our
        # given bandwidth limitation?
        requiredDuration = self._bytesSent / self._bandwidth
        time.sleep(max(requiredDuration - connectionDuration, self._latency))
        return self._socket.send(bytes)

rawDescription: Simple way to simulate a slow network in python


code:
import os
for root, dirs, files in os.walk('path/to/local/dir'):
    for fname in files:
        full_fname = os.path.join(root, fname)
        ftp.storbinary('STOR remote/dir' + fname, open(full_fname, 'rb'))

rawDescription: Python ftplib - uploading multiple files?


code:
queryset.annotate(tag_to_show=Case(
                      When(my_tag__iregex=pattern, then=F('my_tag')),
                      output_field=CharField(),
                      default=Value("Not matched")))

rawDescription: Django ORM: Annotate the Value of matching object


code:
def OnSurnameBoxFocusIn(self,event):
    self.SurnameBox.setStyleSheet("QLineEdit {background-color:yellow}");
    QtGui.QLineEdit.focusInEvent(self.SurnameBox,event) # <- put back old behavior

def OnSurnameBoxFocusOut(self,event):
    self.SurnameBox.setStyleSheet("QLineEdit {background-color:white}");
    QtGui.QLineEdit.focusOutEvent(self.SurnameBox,event) # <- put back old behavior

def OnNameBoxFocusIn(self,event):
    self.NameBox.setStyleSheet("QLineEdit {background-color:yellow}");
    QtGui.QLineEdit.focusInEvent(self.NameBox,event) # <- put back old behavior

def OnNameBoxFocusOut(self,event):
    self.NameBox.setStyleSheet("QLineEdit {background-color:white}");
    QtGui.QLineEdit.focusOutEvent(self.NameBox,event) # <- put back old behavior

rawDescription: Python: Qt4 QLineEdit the TextCursor Doesn't disappear


code:
urls = {'google': 'http://www.google.com',
        'yahoo': 'http://www.yahoo.com'}

s = ''.join(['window.open("%s", "%s");' % (url, name)
             for name, url in urls.items()])

self.response.out.write('<script>%s</script>' % s)

rawDescription: GAE python self.redirect(http://google.com') to new browser window


code:
import ast
s = '{{1,2},{2,3},{4,5}}'
polygon_array = ast.literal_eval(s.replace('{', '(').replace('}', ')'))
polygon_array
polygon_array[1][0]

rawDescription: How do I convert this to an array?

description: Convert this to an array


code:
import txt2cfg
import ma2lxo
txt2cfg.main( inFile, outFile )
ma2lxo.main( inFile, outFile )

rawDescription: How to run a Python script from another Python script in the cross-platform way?

description: Run a Python script from another Python script in the cross-platform way


code:
with open('data.csv', 'r') as f1:
    r = csv.reader(f1, delimiter='\t')
    next(r, None) # skip first line
    for row in r:
        thirdc = row[0].split()[2]
        if float(thirdc) > 0.0:
            print(thirdc)

    1.00000000000000E+00
    1.00000000000000E+00
    1.00000000000000E+00

rawDescription: display row values depending on column values in python

description: Display row values depending on column values in python


code:
msgset = set(ar.msg_ids)
completed = msgset.difference(rc.outstanding)
pending = msgset.intersection(rc.outstanding)

rawDescription: How to see the number of finished or remaining map_async jobs?

description: See the number of finished or remaining map_async jobs


code:
def is_linked(friend_a, friend_b, visited = {}): # At worst, will call this N-1 times

    friends = friend_a.get_friends()

    # You can assume this method is O(1)
    if friends.contains(friend_b):
        return True

    visited[friend_a] = 1
    for friend in friends:

        # Prevents infinite recursion
        # Assume O(1)
        if friend in visited:
            next # At worst, this will happen N-2 times

        return is_linked(friend, friend_b, visited)

    del visited[friend_a]
    return False

rawDescription: What is the worst case time complexity of this rudimentary graph search?


code:
def prime_factors(n):
  for i in range(2,n):
    if n % i == 0:
      return [i] + prime_factors(n / i)
  return [n]

rawDescription: How can I make this Python recursive function return a flat list?

description: Make this Python recursive function return a flat list


code: PBFfile = open(r'MyFilePath.osm.pbf', 'rb')

rawDescription: Offset when reading binary file in python


code:
from ctypes import *

your_dll = cdll.LoadLibrary("your_dll.dll")

PFloat = POINTER(c_float)
PInt   = POINTER(c_int)

p_data    = PFloat()
p_classes = PInt()
buff      = create_string_buffer(1024)
n1        = c_int( 0 )
n2        = c_int( 0 )

ret = your_dll.read_data( buff, byref(n1), byref(n2), byref(p_data), byref(p_classes) )

print('Data:    ', p_data.contents)
print('Classes: ', p_classes.contents)

rawDescription: How to use float ** in Python with Swig?

description: Use float ** in Python with Swig


code:
from wand.image import Image as WandImage
from wand.color import Color
import numpy
import cv2

RESOLUTION=72
source_file='rose:'
img_buffer=None

with WandImage(filename=source_file, resolution=(RESOLUTION,RESOLUTION)) as img:
    img.background_color = Color('white')
    img.format        = 'tif'
    img.alpha_channel = False
    # Fill image buffer with numpy array from blob
    img_buffer=numpy.asarray(bytearray(img.make_blob()), dtype=numpy.uint8)

if img_buffer is not None:
    retval = cv2.imdecode(img_buffer, cv2.IMREAD_UNCHANGED)

rawDescription: How to convert wand image object to open cv image (numpy array)

description: Convert wand image object to open cv image (numpy array)


code:
from BeautifulSoup import BeautifulSoup
import re
soup = BeautifulSoup('')
style = soup.find('img')['style']
urls = re.findall('url\((.*?)\)', style)
urls

rawDescription: How to pull out CSS attributes from inline styles with BeautifulSoup

description: Pull out CSS attributes from inline styles with BeautifulSoup


code: self.fileMenu.menuAction().setStatusTip("File Menu is hovered")

rawDescription: QStatusBar message disappears on menu hover


code:
import MySQLdb

db = MySQLdb.connect(...)
cursor = db.cursor()

data = [
    {"name":"Tom", "gender":"male"},
    {"name":"Jack", "gender":"male"},
    {"name":"Lee", "gender":"male"}
]
cursor.executemany("""
    INSERT INTO foo (name, gender)
    VALUES (%(name)s, %(gender)s)""", data)
db.commit()

rawDescription: insert list of dict into MySQL using Python

description: Insert list of dict into MySQL using Python