code:
from PIL import Image, ImageTk
import Tkinter as tk
import os

def callback(event):
    idx, = listbox.curselection()
    path = os.path.join('images', listbox.get(idx))
    label.master_image=ImageTk.PhotoImage(Image.open(path))
    label.configure(image=label.master_image)

def apply():
    canvas.copy_image = label.master_image
    canvas.create_image(10,10, image=canvas.copy_image)

root=tk.Tk()

frame=tk.Frame(master=root)
canvas=tk.Canvas(master=frame)

listbox=tk.Listbox(master=frame)
listbox.insert(tk.END, *os.listdir('images'))
listbox.bind('<ButtonRelease-1>', callback)

label=tk.Label(master=frame)

button=tk.Button(master=frame, text='Apply', command=apply)

canvas.pack()
frame.pack()
listbox.pack()
label.pack()
button.pack()

root.mainloop()

rawDescription: tkinter images on canvas disappears

description: Tkinter images on canvas disappears


code:
for table in root.xpath('//table[@*]'):
    table.attrib.clear()

rawDescription: How to remove all attributes from element

description: Remove all attributes from element


code:
# pseudo-code !

class DataView(ListAPIView):
    """Returns a queryset as a serialized and paginated list.
    Set queryset, permissions, etc. here."""

    def get_queryset(self):
        # add complex lookup here
        queryset = self.queryset
        return queryset

class SummaryView(DataView):
    """Overwrite the get method to serve different
    content, e.g. statistical summary."""

    def summarize(self, request, *args, **kwargs):
        """This can be moved to a Mixin class."""
        # make sure the filters of the parent class get applied
        queryset = self.filter_queryset(self.get_queryset())
        # do statistics here, e.g.
        stats = {'count': queryset.count()}
        # not using a serializer here since it is already a
        # form of serialization
        return Response(stats)

    def get(self, request, *args, **kwargs):
        return self.summarize(request, *args, **kwargs)

rawDescription: Django Restframework: What view to use for statistical summary of queryset?


code:
#!/usr/bin/env python
import gtk
class EntryDialog(gtk.MessageDialog):
    def __init__(self, *args, **kwargs):
        '''
        Creates a new EntryDialog. Takes all the arguments of the usual
        MessageDialog constructor plus one optional named argument
        "default_value" to specify the initial contents of the entry.
        '''
        if 'default_value' in kwargs:
            default_value = kwargs['default_value']
            del kwargs['default_value']
        else:
            default_value = ''
        super(EntryDialog, self).__init__(*args, **kwargs)
        entry = gtk.Entry()
        entry.set_text(str(default_value))
        entry.connect("activate",
                      lambda ent, dlg, resp: dlg.response(resp),
                      self, gtk.RESPONSE_OK)
        self.vbox.pack_end(entry, True, True, 0)
        self.vbox.show_all()
        self.entry = entry
    def set_value(self, text):
        self.entry.set_text(text)
    def run(self):
        result = super(EntryDialog, self).run()
        if result == gtk.RESPONSE_OK:
            text = self.entry.get_text()
        else:
            text = None
        return text

rawDescription: Simple, versatile and re-usable entry dialog (sometimes referred to as input dialog) in PyGTK


code:
a = c
c = getMod(a, c)

rawDescription: Python Order When Setting Multiple Variables


code:
from reverend.thomas import Bayes
guesser = Bayes()
guesser.train('french', 'le la les du un une je il elle de en')
guesser.train('german', 'der die das ein eine')
guesser.train('spanish', 'el uno una las de la en')
guesser.train('english', 'the it she he they them are were to')
guesser.guess('they went to el cantina')
guesser.guess('they were flying planes')
guesser.train('english', 'the rain in spain falls mainly on the plain')
guesser.save('my_guesser.bay')

rawDescription: Best way to return the language of a given string

description: Return the language of a given string


code:
def making_graph(researchers):
    g = ig.Graph()
    for each in researchers:
        for i in range(len(each)):
            g.add_vertex(each[i])
            g.vs[i]['group_id'] = each[i].get_group_id()
            g.vs[i]['researcher_id'] = each[i].get_researcher_id()
            g.vs[i]['name'] = each[i].get_name()
            g.vs[i]['sex'] = each[i].get_sex()
    for v in g.vs:
        for w in g.vs:
            if v['group_id'] == w['group_id'] and v != w and g.are_connected(v, w) is False:
                g.add_edge(v, w)
    return g

rawDescription: How to add edges that are conditional to object attribute using igraph and python

description: Add edges that are conditional to object attribute using igraph and python


code:
data = [
    {
        word
        for sentence in sentences
            if special_word in sentence
                for word in sentence
    }
    for special_word in special_words
]

rawDescription: Python list comprehension on two list

description: Python list comprehension on two list


code:
import time

while True:
    time.sleep(1200) #1200 sec = 20 min
    #your code

rawDescription: Sikuli in Loop Mode

description: Sikuli in Loop Mode


code:
from scrapy.http import FormRequest
import json

class DmozSpider(scrapy.Spider):
    name = "google"
    allowed_domains = ["google.co.in"]
    start_urls = [
        "https://www.google.co.in/trends/hotvideos#hvsm=0"
    ]

    def parse(self, response):
        url = 'https://www.google.co.in/trends/hotvideos/hotItems'
        formdata = {'hvd':'','geo': 'IN','mob': '0','hvsm': '0'}
        yield FormRequest(url=url, formdata=formdata, callback=self.parse_data)

    def parse_data(self, response):
        json_response = json.loads(response.body)
        videos = json_response.get('videoList')
        for video in videos:
            item = CraigslistItem()
            item['title'] = video.get('title')
            item['link'] = video.get('url')
            yield item

rawDescription: scraping url and title from nested anchor tag

description: Scraping url and title from nested anchor tag


rawDescription: Pyside: setting the background of a row in a QVBoxLayout widget


code:
def make_tiny(url):
    connection = httplib.HTTPSConnection('api.shorte.st', 443)
    connection.connect()
    connection.request('PUT', '/v1/data/url', json.dumps({
           "urlToShorten": url,
         }), {
           "public-api-token": "049cd75ad7axxx26ef7364fa38c8792",
           "Content-Type": "application/json"
         })
    results = json.loads(connection.getresponse().read())
    return results.get("shortenedUrl", "none").decode('utf-8')

rawDescription: Regular JSON Curl to pyCurl

description: Regular JSON Curl to pyCurl


code:
import textwrap
import webapp2

class MainHandler(webapp2.RequestHandler):
  def get(self):
    #web page sections
    form_head=textwrap.dedent('''
      <!DOCTYPE html>

          <meta charset="utf-8" />
            <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
            <link href="css/style.css" rel="stylesheet" type="text/css" />
        <title>Gamers R' Us Subscribing</title>

        ''')

    form_body=textwrap.dedent('''

Welcome to Gamers R' Us!

Filler atm.

Subscribe Today!

                <form method="GET">
                Full Name: <input type="text" name="name" placeholder=" John Doe"/>

                Email: <input type="text" name="email" placeholder=" me@domain.com"/>

                <select name="system" class="selectbox">
                  <option value="ps4">Playstation 4</option>
                  <option value="xbone">Xbox One</option>
                  <option value="wiiu">Wii U</option>
                  <option value="pc">PC Gaming</option>
                </select>

                <input type="radio" name="genre" value="FPS">First Person Shooter.

                <input type="radio" name="genre" value="MOBA">Multiplayer Online Battle Arena.

                <input type="radio" name="genre" value="RPG">Role-Playing Game.

                <input type="radio" name="genre" value="RTS">Real Time Strategy.

                <input type="radio" name="genre" value="Other">Other Genre.

                <input type="checkbox" name="subscribe" value="yes" checked>Subscribe for gaming updates and more!

                <input type="submit" class="subbtn" value="Done" />
                </form>

''')

    form_foot=textwrap.dedent('''

      ''')

    #if GET is requested it should display on next screen.
    #else should load page.
    if self.request.GET:
      name=self.request.GET['name']
      email=self.request.GET['email']
      system=self.request.GET['system']
      genre=self.request.GET['genre']
      subscribe=self.request.GET['subscribe']

      #displays form information submitted by user.
      self.response.write(form_head +
                          textwrap.dedent('''

Thanks for Subbing!

                                Name: {name}

                                Email: {email}

                                Preferred System: {system}

                                Preferred Genre: {genre}

''').format(**locals()) +
                          form_foot)

    #Will display error. ** PLACE HOLDER **
    else:
      self.response.write("Help! Error!")

# Do not touch this.
app = webapp2.WSGIApplication([('/', MainHandler)], debug=True)

rawDescription: Unresolved reference for 'self'

description: Unresolved reference for 'self'


rawDescription: How can I extract a javascript value in scrapy

description: Extract a javascript value in scrapy


code:
def list_subdirs(in_path):
    subdirs = []
    for x in os.walk(in_path):
        subdirs.append(x[0])
    return subdirs

rawDescription: python: List all subdirectories recursively?

description: Python: List all subdirectories recursively


code:
class MyStreamListener(tweepy.StreamListener):
    def __init__(self, time_limit=60):
        self.start_time = time.time()
        self.limit = time_limit
        self.saveFile = open('abcd.json', 'a')
        super(MyStreamListener, self).__init__()

    def on_data(self, data):
        if (time.time() - self.start_time) < self.limit:
            self.saveFile.write(data)
            self.saveFile.write('\n')
            return True
        else:
            self.saveFile.close()
            return False

myStream = tweepy.Stream(auth=api.auth, listener=MyStreamListener(time_limit=20))
myStream.filter(track=['test'])

rawDescription: Unable to stop Streaming in tweepy after one minute


code:
sum_percentage = 0.0
new_list = []
for i in old_list:
    new_list.append(i[:2])
    sum_percentage += i[2]
    if sum_percentage >= 0.9:
        break

rawDescription: python conditional access to list of lists

description: Python conditional access to list of lists


code:
for items in d:
    if items in {'a', 'e', 'i', 'o', 'u'}:
        d[d.index(items)] = ['vowel', items]   # Get the index of the element, then replace
print(d)

rawDescription: Python - iterate and change elements of a list


code:
from collections import MutableSequence

class IntList(MutableSequence):
    def __init__(self):
        super(IntList, self).__init__()
        self._list = []

    def __len__(self):
        return len(self._list)

    def __getitem__(self, index):
        return self._list[index]

    def __setitem__(self, index, value):
        if not isinstance(value, int):
            raise TypeError('only integers accepted')
        self._list[index] = value

    def __delitem__(self, index):
        del self._list[index]

    def insert(self, index, value):
        if not isinstance(value, int):
            raise TypeError('only integers accepted')
        self._list.insert(index, value)

rawDescription: constraint list to take only integers

description: Constraint list to take only integers


code:
from pylab import *

x = [[5,2],[10,5],[3,2],[5,99],[10,22],[3,15],[4,30]]
a,b = zip(*x) #Unzip x into a & b as per your example

#Make a dictionary where the key is the item from a and the value
#is the sum of all the corresponding entries in b
sums = {}
for i in range(0,len(a)):
    sums[a[i]] = b[i] if not a[i] in sums else sums[a[i]] + b[i]

#Plot it
ylabel('Bins')
xlabel('Total Times')
barh(sums.keys(),sums.values(),align='center')
show()

rawDescription: Python cumulative histogram of 2D array

description: Python cumulative histogram of 2D array


code:
def enter_quantity():
    for q in menu:
        while True:
            inp = input("How many orders of {} ?: ".format(q))
            try:
               inp = int(inp) # try cast to int
               break
            except ValueError:
                # if we get here user entered invalid input so print message and ask again
                print("{} is not a number".format(inp))
                continue
        # out of while so inp is good, update dict
        quantities[q] = inp

rawDescription: How to check user input (Python)

description: Check user input (Python)


code:
pca = PCA(n_components=20)
train_features = pca.fit_transform(train_data)

rfr = sklearn.RandomForestClassifier(n_estimators = 100, n_jobs = 1,
                                         random_state = 2016, verbose = 1,
                                         class_weight='balanced',oob_score=True)

rfr.fit(train_features)

test_features = pca.transform(test_data)
rfr.predict(test_features)

rawDescription: How to apply model trained with PCA and Random Forest to test data?

description: Apply model trained with PCA and Random Forest to test data


code:
CMS_PLACEHOLDER_CONF = {
    'footer': {
        'name': "Footer",
        'default_plugins':[
            {
                'plugin_type':'FooterPlugin',
                'values':{
                    'body':'
This is the footer
'
                },
            },
        ]
    },
}

rawDescription: DjangoCMS: how to auto-add default plugins in placeholders


code:
import xml.etree.ElementTree as et
import xml.etree.cElementTree as et
import lxml.etree as et
...
tree = et.fromstring(xmltext)
...

rawDescription: Python XML Parsing

description: Python XML Parsing


code:
import os

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

...

#MEDIA_ROOT = PROJECT_PATH + '/media/'

TEMPLATE_DIRS = (
    PROJECT_PATH + '/templates/'
)

rawDescription: change default path of django administration

description: Change default path of django administration


code:
from datetime import datetime

# Start with the initial list
A = [u'Sun Oct 06 18:00:55 +0000 2013', u'Sun Oct 06 17:57:41 +0000 2013', u'Sun Oct 06 17:55:44 +0000 2013', u'Sun Oct 06 17:54:10 +0000 2013', u'Sun Oct 06 17:35:58 +0000 2013', u'Sun Oct 06 17:35:58 +0000 2013', u'Sun Oct 06 17:35:25 +0000 2013', u'Sun Oct 06 17:34:39 +0000 2013', u'Sun Oct 06 17:34:39 +0000 2013', u'Sun Oct 06 17:34:39 +0000 2013', u'Sun Oct 06 17:30:35 +0000 2013', u'Sun Oct 06 17:25:28 +0000 2013', u'Sun Oct 06 17:24:04 +0000 2013', u'Sun Oct 06 17:24:04 +0000 2013', u'Sun Oct 06 17:22:08 +0000 2013', u'Sun Oct 06 17:22:08 +0000 2013', u'Sun Oct 06 17:21:00 +0000 2013', u'Sun Oct 06 17:18:49 +0000 2013', u'Sun Oct 06 17:18:49 +0000 2013', u'Sun Oct 06 17:15:29 +0000 2013', u'Sun Oct 06 17:15:29 +0000 2013', u'Sun Oct 06 17:13:35 +0000 2013', u'Sun Oct 06 17:12:18 +0000 2013', u'Sun Oct 06 17:12:00 +0000 2013', u'Sun Oct 06 17:07:34 +0000 2013', u'Sun Oct 06 17:03:59 +0000 2013']

# This is the format string the date/time stamps are using
# On Python 3.3 on Windows you can use this format
# s_format = "%a %b %d %H:%M:%S %z %Y"
# However, Python 2.7 on Windows doesn't work with that. If all of your date/time stamps use the same timezone you can do:
s_format = "%a %b %d %H:%M:%S +0000 %Y"

# Convert the text list into datetime objects
A = [datetime.strptime(d, s_format) for d in A]

# Get the extremes
oldest = min(A)
newest = max(A)

# If you substract oldest from newest you get a timedelta object, which can give you the total number of seconds between them. You can use this to calculate days, hours, and minutes.
delta = int((newest - oldest).total_seconds())
delta_days, rem = divmod(delta, 86400)
delta_hours, rem = divmod(rem, 3600)
delta_minutes, delta_seconds = divmod(rem, 60)

rawDescription: Format These Dates And Get Time Passed

description: Format These Dates And Get Time Passed


code: dict_ = {i: i/c for i in range(a,b) if i % c == d}

rawDescription: Python code test in interview for junior dev


code:
from pandas.io.data import DataReader
from datetime import datetime
goog = DataReader("GOOG",  "yahoo", datetime(2000,1,1), datetime(2012,1,1))
goog["Adj Close"]

rawDescription: Does Python has a similar library like quantmod in R that can download financial statement data?


code: pow(A, B, M)

rawDescription: How to compute (A^B)%M when A,B,M are big numbers?

description: Compute (A^B)%M when A,B,M are big numbers


code:
f1 = open("file1.txt","r")
f2 = open("file2.txt","r")

lines1 = f1.readlines()
lines2 = f2.readlines()

for i in lines2:
    inboth = False
    for x in lines1:
        if i == x:
            inboth = True
    if inboth != True:
        print("The line: \n",i,"\nis in file 2 but not file 1\n")

rawDescription: Get the differences in two files

description: Get the differences in two files


code:
import wx
event = wx.MouseEvent(mouseType=wx.wxEVT_MOUSEWHEEL)
event.WheelRotation = 22
event.m_wheelRotation = 22
event.WheelRotation
event.m_wheelRotation = 25
event.WheelRotation

rawDescription: How to specify properties of wx.MouseEvent?

description: Specify properties of wx.MouseEvent


code: results = [r for k in keywords for r in re.findall(k, message.lower())]

rawDescription: Search strings using regular expression in Python


code:
from datetime import datetime

recordDate = datetime(year=2010, month=10, day=10)
now = datetime.now()
age = now - recordDate
age  # age is the timedelta object
"%d days" % age.days

rawDescription: Remove time from timedelta output in python


code:
from collections import defaultdict

def get_stats(data):
    genres_number = defaultdict(int)
    actors_number = defaultdict(int)

    for movie in data:

        actors = movie.get('actors')
        if actors:
            for actor in actors:
                actors_number[actor] += 1

        genres = movie.get('genres')
        for genre in genres:
            genres_number[actor] += 1

    res = []
    res.append(dict(genres_number))
    res.append(dict(actors_number))
    return res

rawDescription: How can I optimise in term of time this python code

description: Optimise in term of time this python code


code:
import itertools
stuff = [1,2,3]

with open('out.txt','w') as f :
   for i in range(0, len(stuff)+1):
      for subset in itertools.combinations(stuff, L):
        f.write(str(subset))

rawDescription: How to write a list of combinations to a file in python

description: Write a list of combinations to a file in python


code:
ser = serial.Serial()
ser.baudrate = 19200
ser.port = 0
ser.timeout = 2 #By default, this is set to None
ser.open()

rawDescription: Capturing serial data in background process


rawDescription: Is there a better way than double parsing the string?


code:
if request.POST:
    request.SESSION['select_menu_value'] = request.POST.get('select_menu_value')

rawDescription: How to make a variable accessible across all pages in HTML / Template (Django)..?

description: Make a variable accessible across all pages in HTML / Template (Django)..


code:
content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']
updated = []
for string in content:
    print(string)
    updated.append(string.rstrip())

print(updated)

rawDescription: Delete /n at end of a String (Python)

description: Delete /n at end of a String (Python)


code:
def odd_even_router_method_factory(odd, even):
    def route(self, n):
        if n % 2:
            odd.__get__(self)(n)
        else:
            even.__get__(self)(n)
    return route

def attach_default_router(cls):
    route = odd_even_router_method_factory(cls.on_odd, cls.on_even)
    cls.check_number = route
    return cls

rawDescription: Re-use a global function within a class decorator


code:
for k, v in dictionary.iteritems():
    x = [k] * len(v)
    y = v
    pyplot.plot(x, y)

rawDescription: Python: how to make two lists from a dictionary


code: Column('user_id', Integer, key="id")

rawDescription: In SQLAlchemy Core, how can I create a table with a column name that differs from its attribute?


code: MySQLdb.connect(host="localhost", user="root",passwd="*****", use_unicode=True, charset='xxxxx')

rawDescription: Python Mysqldb Returns Question Marks

description: Python Mysqldb Returns Question Marks


code:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

pp = PdfPages('long.pdf')
fig = plt.figure(3, figsize=(4,4))
ax = plt.axes([0.1, 0.1, 0.8, 0.8])
for x in mylist:
    ax.cla()
    labels=x['labels']   # ['Red', 'Blue', 'Green', 'Brown']
    fracs=x['fracs']    # [40, 30, 20, 10]
    p = pie(fracs,labels=labels)
    # slightly difference in these two lines (assigning values this time)
    fig.savefig(pp, format='pdf')   #

rawDescription: Pylab/Matplotlib multilple pie charts into one PDF


code:
file_dialog = QFileDialog(self)
# the name filters must be a list
file_dialog.setNameFilters(["Text files (*.txt)", "Images (*.png *.jpg)"])
file_dialog.selectNameFilter("Images (*.png *.jpg)")
# show the dialog
file_dialog.exec_()

rawDescription: Python PyQt Pyside - setNameFilters in QFileDialog does not work


code:
import numpy as np
q1 = np.linspace(0, 90, 91)
n1 = 1.0
n2 = 1.5
q2 = np.arcsin(n1 * np.sin(q1)/n2)
q2

rawDescription: Variation of an arcsin

description: Variation of an arcsin


code:
def parse(self, response):
    hxs = HtmlXPathSelector(response)

    item = PatioItem()
    item['Name'] = hxs.select("//div[@class='patio-name']/h2/text()").extract()[0]
    node_type = hxs.select("//ul[@class='detail-lister']/li[@class='type-icon']")
    item['Type'] = node_type.select(".//span[@class='detail-desc']/text()").extract()[0]
    node_covered = hxs.select("//ul[@class='detail-lister']/li[@class='covered-icon']")
    item['Covered'] = node_covered.select(".//span[@class='detail-desc']/text()").extract()[0]
    node_heated = hxs.select("//ul[@class='detail-lister']/li[@class='heated-icon']")
    item['Heated'] = node_heated.select(".//span[@class='detail-desc']/text()").extract()[0]
    node_capacity = hxs.select("//ul[@class='detail-lister']/li[@class='capacity-icon last']")
    item['Capacity'] = node_capacity.select(".//span[@class='detail-desc']/text()").extract()[0]

    return [item,]

rawDescription: How can I use Scrapy to parse two different sections of source code and combine the results?

description: Use Scrapy to parse two different sections of source code and combine the results


code:
from gi.repository import Gdk
import cairo

def put_text(pixbuf, text, x, y):
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, pixbuf.get_width(), pixbuf.get_height())
    context = cairo.Context(surface)

    Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, 0)
    context.paint() #paint the pixbuf

    #add the text
    fontsize= 20
    context.move_to(x, y+fontsize)
    context.set_font_size(fontsize)
    context.set_source_rgba(0,0,0,1)
    context.show_text(text)

    #get the resulting pixbuf
    surface= context.get_target()
    pixbuf= Gdk.pixbuf_get_from_surface(surface, 0, 0, surface.get_width(), surface.get_height())

    return pixbuf

rawDescription: How to render text on a GdkPixbuf.Pixbuf

description: Render text on a GdkPixbuf.Pixbuf


rawDescription: python slicing string by pointing special character

description: Python slicing string by pointing special character


code:
@click.command(context_settings=dict(
    ignore_unknown_options=True,
    allow_extra_args=True,
))
@click.pass_context
def runner(ctx, tgt, fun):
    d = dict()
    for item in ctx.args:
        d.update([item.split('=')])
    req = pyaml.p(meh.PostAdapter(tgt, fun, d))
    click.echo(req)

rawDescription: Python click pass unspecified number of kwargs


code:
class BaseModel(models.Model):
    name      = models.CharField(max_length=100)
    location  = models.CharField(max_length=100)

    class Meta:
        abstract = True

class Printer(BaseModel):
    pass

class Publisher(BaseModel):
    pass

rawDescription: Model redundant django tables?

description: Model redundant django tables


code:
import csv, os, sys
y = int(sys.argv[1])

with open("csvinput.csv", 'rb') as input, open('temp.csv', 'wb') as output:
        reader = csv.reader(input, delimiter = ',')
        writer = csv.writer(output, delimiter = ',')

        header = next(reader)
        outdata = []
        outdata.append(header)

        for row in reader:
                kount = int(row[1])
                if y > kount:
                        outdata.append(row)

        writer.writerows(outdata)

rawDescription: How can i access certain columns value in for loop csv python

description: Access certain columns value in for loop csv python


code:
df
df['time'] = df['time'].astype('datetime64[ns]')
df

rawDescription: How do I convert dates in a Pandas data frame to a 'date' data type?

description: Convert dates in a Pandas data frame to a 'date' data type


code:
old = open('temp', 'a')
old.write(delta)

rawDescription: Python difflib take new data and append to old file


rawDescription: Change list formatting in PyYAML output

description: Change list formatting in PyYAML output


code:
OuterFrame = Frame(root, height=500, width=400)
InnerFrame = Frame(OuterFrame, borderwidth=3, relief=RAISED)
InnerFrame.pack(side=TOP, fill=X)

# stuff that goes in the y-resizing InnerFrame

OuterFrame.pack_propogate(False)
OuterFrame.pack()

rawDescription: Tkinter Frame Resize one axis

description: Tkinter Frame Resize one axis


code:
import subprocess
subprocess.call(('someprog.exe', str(i)))

rawDescription: wait a process to finish in Python script

description: Wait a process to finish in Python script


code:
sortedList = sorted(myList, key = lambda y: (y[0].lower(), -y[1]))
sortedList = sorted(myList, key = lambda y: (-y[0].lower(), y[1]))
sortedList = sorted(myList, key = lambda y: (-y[0].lower(), -y[1]))

rawDescription: sort Python list with two keys but only one in reverse order

description: Sort Python list with two keys but only one in reverse order


code:
from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))

rawDescription: Pyspark replace strings in Spark dataframe column


code:
L = [1, 2, 4, 8, 16, 32, 64]
X = 5
i = 0
while i < len(L):
    if 2 ** X == L[i]:
        print('at index',i)
        break;
    i = i+1
    if i==len(L): print(X,'not found')

rawDescription: convert this while loop to a more efficient while loop

description: Convert this while loop to a more efficient while loop


code:
def run_inference_on_image(image):
  """Runs inference on an image.
  Args:
    image: Image file name.
  Returns:
    Nothing
  """
  if not gfile.Exists(image):
    tf.logging.fatal('File does not exist %s', image)
  image_data = gfile.FastGFile(image, 'rb').read()

  # Creates graph from saved GraphDef.
  create_graph()

with tf.Session() as sess:
 # Some useful tensors:
 # 'softmax:0': A tensor containing the normalized prediction across
 #   1000 labels.
 # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
 #   float description of the image.
 # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
 #   encoding of the image.
 # Runs the softmax tensor by feeding the image_data as input to the graph.
 softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
 feature_tensor = sess.graph.get_tensor_by_name('pool_3:0') #ADDED
 predictions = sess.run(softmax_tensor,
                        {'DecodeJpeg/contents:0': image_data})
 predictions = np.squeeze(predictions)
 feature_set = sess.run(feature_tensor,
                        {'DecodeJpeg/contents:0': image_data}) #ADDED
 feature_set = np.squeeze(feature_set) #ADDED
 print(feature_set) #ADDED
 # Creates node ID --> English string lookup.
 node_lookup = NodeLookup()

 top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
 for node_id in top_k:
   human_string = node_lookup.id_to_string(node_id)
   score = predictions[node_id]
   print('%s (score = %.5f)' % (human_string, score))

rawDescription: Tensorflow return similar images

description: Tensorflow return similar images


code:
from collections import OrderedDict

test_string = "line1 \n line2 \n line3 \n line2 \n line2 \n line 4"

"\n".join(list(OrderedDict.fromkeys(test_string.split("\n"))))

rawDescription: Remove duplicate lines from a string in python


code:
import os
import sys
import tempfile
import urllib2

good_urls = set()

with open('urls.txt') as urls:
    for url in urls:
        try:
            r = urllib2.urlopen(url)
        except urllib2.URLError as e:
            r = e
        if r.code in (200, 401):
            sys.stdout.write('[{}]: Up!\n'.format(url))
            good_urls.add(url)
        elif r.code == 404:
            sys.stdout.write('[{}]: Not found!\n'.format(url))
        else:
            sys.stdout.write('[{}]: Unexpected response code {}\n'.format(url, r.code))

tmp = None
try:
    tmp = tempfile.NamedTemporaryFile(mode='w', suffix='.txt', dir='.', delete=False)
    for url in sorted(good_urls):
        tmp.write(url + "\n")
    tmp.close()
    os.rename(tmp.name, 'urls.txt')
    tmp = None
finally:
    if tmp is not None:
        os.unlink(tmp.name)

rawDescription: Delete lines from a txt file after read

description: Delete lines from a txt file after read


code:
svg_size_width = 900
svg_size_height = 4500
dwg = svgwrite.Drawing(name, (svg_size_width, svg_size_height), debug=True)
dwg.add(dwg.rect(insert=(0, 0), size=('100%', '100%'), rx=None, ry=None, fill='rgb(50,50,50)'))
dwg.save()

rawDescription: Python svgwrite module background color

description: Python svgwrite module background color


code:
[(min(t[0] for t in lst),
  min(t[1] for t in lst),
  max(t[0] for t in lst),
  max(t[1] for t in lst))
 for lst in a]

rawDescription: Python: how to get the edge values from this list


code:
def messageWindow():
    win = Toplevel()
    path = r'C:\Users\HP\Desktop\dataset'
    COLUMNS = 10
    image_count = 0
    for infile in glob.glob(os.path.join(path, '*.jpg')):
        image_count += 1
        r, c = divmod(image_count-1, COLUMNS)
        im = Image.open(infile)
        resized = im.resize((100, 100), Image.ANTIALIAS)
        tkimage = ImageTk.PhotoImage(resized)
        myvar = Label(win, image=tkimage)
        myvar.image = tkimage
        myvar.grid(row=r, column=c)
    win.mainloop()  # not sure if you need this, too, or not...

rawDescription: how to display different images using grid function using tkinter?

description: Display different images using grid function using tkinter


code:
import time
import numpy as np
from bokeh.plotting import cursession, figure, show, output_server

output_server("circle_server")

pl = figure(y_range=(-2,2), x_range=(-2,2))

x=1
y=0

pl.circle(x=[x], y=[y], size=25, alpha=0.6, name="circle")
pl.annulus(x=0,y=0, inner_radius = 1, outer_radius = 1, line_alpha=0.6)

show(pl)

renderer = pl.select(dict(name="circle"))

ds = renderer[0].data_source

while True:
    for rad in np.linspace(0,2*np.pi,100):
        #rad = deg*np.pi/180
        ds.data["x"] = [np.cos(rad)]
        ds.data["y"] = [np.sin(rad)]
        cursession().store_objects(ds)
        time.sleep(0.5)

rawDescription: How to animate a circle using bokeh

description: Animate a circle using bokeh


rawDescription: python - getting file path in executable version

description: Python - getting file path in executable version


code: np.arange(10)[:, np.newaxis]

rawDescription: How do you create a numpy vertical arange?

description: Create a numpy vertical arange


code: min(points, key=lambda x: dist(pointToCompare2, x))

rawDescription: Get a unique list/tuple element given a condition in python


code:
d = {1:2}
dis.dis(lambda: d[1])
dis.dis(lambda: d.get(1))
dis.dis(lambda: d.__getitem__(1))

rawDescription: Why are __getitem__(key) and get(key) significantly slower than [key]?


code:
def hepsi(request):

    basliklar = Baslik.objects.filter(active=True).order_by('-updated')

    gunlist = []

    for i in basliklar:

        entryler = i.entry_set.all()
        ent1 = entryler.latest('id')
        ent2 = ent1.updated
        ent3 = str(ent2).split(" ")
        zaman1 = date.today()
        zaman2 = str(zaman1).split(" ")
        zamangun = zaman2[0]
        entgun = ent3[0]

        if entgun == zamangun:
            gunlist.append(i)

    cta = {'basliklar': basliklar, 'entryler': entryler, 'ent1': ent1, 'ent2': ent2, 'entgun': entgun, 'zamangun': zamangun, 'gunlist': gunlist}

    return render(request, "base.html", cta)

rawDescription: Django order_by according to inline's updated time


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

tips = sns.load_dataset("tips")

points = plt.scatter(tips["total_bill"], tips["tip"],
                     c=tips["size"], s=75, cmap="BuGn")
plt.colorbar(points)

sns.regplot("total_bill", "tip", data=tips, scatter=False, color=".1")

rawDescription: Seaborn regplot with colorbar?

description: Seaborn regplot with colorbar


code:
data = [ [5,12,46,4,99,6],[23,66,99,32,77] ]
set_data = [set(s) for s in data]
set_data
myset = set([4,5,6])
[myset.issubset(s) for s in set_data]

rawDescription: Quickly check if a list is a sublist, of one of the elements of a nested list


code: re.compile('name=\w+;size=\d+', re.U)

rawDescription: Regex match for a non-english language in Python


code:
import os
os.system('netsh interface ip set dns "Local Area Connection" static 192.168.0.200')

rawDescription: How to Change DNS Servers Programmaticly in Windows with Python?


code:
import nltk.data, nltk.tag
tagger = nltk.data.load(nltk.tag._POS_TAGGER)

rawDescription: Slow performance of POS tagging. Can I do some kind of pre-warming?


code: df_filtered = df[list(filter(lambda x: "F" not in x, df.columns))]

rawDescription: Dropping Columns in a Dataframe based on if they have a particular letter in the title


code:
import requests
from bs4 import BeautifulSoup, SoupStrainer
import re

########################################Sections##########################
def levelthree(item2_url):
 r = requests.get(item2_url)
 for sectionlinks in BeautifulSoup((r.content),"html.parser",parse_only=SoupStrainer('a')):
  if sectionlinks.has_attr('href'):
   if 'section' in sectionlinks['href']:
         href = "http://law.justia.com" + sectionlinks.get('href')
         href = "\n" + str(href)
         print (href)

########################################Chapters##########################
def leveltwo(item_url):
 r = requests.get(item_url)
 for sublinks in BeautifulSoup((r.content),"html.parser",parse_only=SoupStrainer('a')):
  if sublinks.has_attr('href'):
   if 'chapt' in sublinks['href']:
         chapterlinks = "http://law.justia.com" + sublinks.get('href')
         # chapterlinks = "\n" + str(chapterlinks)

         levelthree(chapterlinks)
         # print (chapterlinks)

######################################Titles###############################
def levelone(url):
 r = requests.get(url)
 for links in BeautifulSoup((r.content),"html.parser",parse_only=SoupStrainer('a')):
    if links.has_attr('href'):
        if 'title' in links['href']:
          titlelinks = "http://law.justia.com" + links.get('href')
          # titlelinks = "\n" + str(titlelinks)
          leveltwo(titlelinks)
          # print (titlelinks)

###########################################################################
base_url = "http://law.justia.com/codes/alabama/2015/"
levelone(base_url)

rawDescription: Python Web Crawler, Can i do function calls from for loops?


code:
class Decorator(object):
    def __init__(self, arg):
        self.arg = arg
    def __call__(self, cls):
        class Wrapped(cls):
            classattr = self.arg
            def new_method(self, value):
                return value * 2
        return Wrapped

@Decorator("decorated class")
class TestClass(object):
    def new_method(self, value):
        return value * 3

rawDescription: python: decorate a class by defining the decorator as a class

description: Python: decorate a class by defining the decorator as a class


code:
import Image, cv2

cap = cv2.VideoCapture(0) # says we capture an image from a webcam
_,cv2_im = cap.read()
cv2_im = cv2.cvtColor(cv2_im,cv2.COLOR_BGR2RGB)
pil_im = Image.fromarray(cv2_im)
pil_im.show()

rawDescription: convert openCV image into PIL Image in Python (for use with Zbar library)

description: Convert openCV image into PIL Image in Python (for use with Zbar library)


code:
subset_a = a > 80
subset_b = (40 < a) & (a <= 80)
subset_c = a <= 40
a[subset_a] += 1
a[subset_b] += 2
a[subset_c] += 3

rawDescription: How can each element of a numpy array be operated upon according to its relative value?


code:
a = a.reset_index()
a
c = pd.merge(a, b, how="left")
c
c = c.set_index(['id1','id2'])
c

rawDescription: How to keep MultiIndex when using pandas merge

description: Keep MultiIndex when using pandas merge


code:
for u in G.nodes():
    for neighbor in G.neighbors(u):
        if G.number_of_edges(u,neighbor)>2:
            print (u,neighbor)

rawDescription: Find edges of multiplicity larger than 2 in a NetworkX MultiGraph


code:
import re
regex = "(?P<chord>[A-G])((?P<accidental>#|b)|(?P<additional>m)){0,2}"
re.match(regex, "Gm").groupdict()
re.match(regex, "G").groupdict()
re.match(regex, "G#m").groupdict()
re.match(regex, "Gm#").groupdict()

rawDescription: Parsing chords with regular expressions

description: Parsing chords with regular expressions


rawDescription: Astropy matplotlib and plot galactic coordinates


rawDescription: Python multiple inheritance constructor not called when using super()


code:
class attributeSetter(object):
    ''' Makes functions appear as attributes. Takes care of autologging.'''
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, owner):
        return self.func.__get__(instance, owner)

    def __set__(self, obj, value):
        return self.func(obj, value)

rawDescription: Python decorator for attribute and method?


code:
# -*- coding: utf-8 -*-
from bidi.algorithm import get_display
import PIL.Image, PIL.ImageFont, PIL.ImageDraw
img= PIL.Image.new("L", (400, 200))
draw = PIL.ImageDraw.Draw(img)
font = PIL.ImageFont.truetype( r"c:\windows\fonts\arial.ttf", 30)
t1 = u'סֶפֶר ספר!'
draw.text( (10,10), 'before BiDi :' + t1, fill=255, font=font)

t2 = get_display(t1)        # <--- here's the magic <---
draw.text( (10,50), 'after BiDi: ' + t2, fill=220, font=font)

img.save( 'bidi-test.png')

rawDescription: Writing text with diacritic ("nikud", vocalization marks) using PIL (Python Imaging Library)


code:
import hashlib

sh = hashlib.sha1()
sh.update('password')
hash_value = sh.hexdigest()
# write hash_value to file/db...

rawDescription: Secure Python Login

description: Secure Python Login


code:
@cache.cache('mycache', type="file", expire=15)
def my_action(self):
  stuff

rawDescription: Location of Beaker's @beaker_cache cache in Pylons


code:
from collections import defaultdict
res = defaultdict(dict)
for (a,b),c in D.items():
    res[a][b] = c

rawDescription: Dictionary Formatting and defaultdict function


rawDescription: Annote and count posts related to a specific class, in Django


code:
my_array = ["abc", "def", "xyz", "abc", "pop", "abc"]
filter (lambda a: a != "abc", my_array)

rawDescription: Remove all specific value from array

description: Remove all specific value from array


code: cellLoc='center'

rawDescription: Centered text in matplotlib tables

description: Centered text in matplotlib tables


code:
import mock
mock_request = mock.Mock()

mock_request.GET.get.return_value = {'sessionid': 'blah'}

x = mock_request.GET.get('sessionid')

assert x == {'sessionid': 'blah'}
mock_request.GET.get.assert_called_once_with('sessionid')

rawDescription: Python mock to create a fake object returns dictionary when any of it's attribute is used


code:
@app.route("/foo", methods=['POST'])
def slack_request():
    """Process a slash-command POST request from Slack"""
    query = QuerySlack(app.config, app.mdb, reporter)
    job = Thread(target=query, args=(response.form['query'],))
    job.start()
    try:
        return "processing {}...".format(' '.join(response.form['query']))
    except (ReportError, QueryError) as err:
        return str(err)

rawDescription: python WSGI with long running process

description: Python WSGI with long running process


code:
while Counter < Amount:
      zf = zipfile.ZipFile(lst[Counter],"w", zipfile.ZIP_DEFLATED,allowZip64=True) # create zip
      zf.write(os.path.join(lst[Counter])) #zip it up
      zf.close() #close the zip
      shutil.move(os.path.join(lst[Counter]),Destination) #move to zip folder
p = subprocess.Popen(SendZipfiles)

rawDescription: Python, wait on a file to zip before sending it


code:
from Tkinter import *
import Tkinter
from tkFileDialog import askopenfile, asksaveasfile
import tkFileDialog

class myproject(Tkinter.Tk):
    def __init__(self):
        Tkinter.Tk.__init__(self)
        self.textbox()
        self.checkbox2()
    def textbox(self):
        self.txt1 = Tkinter.Text(self, borderwidth=3, relief="sunken", height=4,width=55)
        self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)
    def checkbox2(self): #self.checkbox
        checkbox = Tkinter.Checkbutton(self, text = " ")
        checkbox.grid(column=1,row=2)
    def file_save(self):
        f = asksaveasfile(mode='w', defaultextension=".txt")

root = myproject()

menubar = Menu(root)
root.configure(menu=menubar)

filemenu = Menu(menubar,tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Save", command=root.file_save)
root.mainloop()

rawDescription: blank tkinter window when executing

description: Blank tkinter window when executing


code:
#find RGB values
rgb_values = []
for point in line:
   r, g, b = rgb_im.getpixel(point)
   rgb_values += [ (r,g,b)]
#remove similar adjacent values
for i in range(len(rgb_values)-1):
    if rgb_values[i] == rgb_values[i+1]:
        rgb_values.pop(i)
        i -= 1
if len(rgb_values) > 1:
    if rgb_values[-1] == rgb_values[-2]:
         rgb_values.pop(-1)

rawDescription: Colour picking from a curvy line

description: Colour picking from a curvy line


code:
import numpy as np

# fh containts the file handle

# go to position 32 where the image data starts
fh.seek(32)

# read the binary data into unsigned 8-bit array
ba = np.fromfile(fh, dtype='uint8')

# calculate the side length of the square array and reshape ba accordingly
side = int(np.sqrt(len(ba)))
ba = ba.reshape((side,side))

# toss everything else apart from the last bit of each pixel
ba &= 1

# make a 3-deep array with 255,255,255 or 0,0,0
img = np.dstack([255*ba]*3)
# or
img = ba[:,:,None] * np.array([255,255,255], dtype='uint8')

rawDescription: Quickest way to convert 1D byte array to 2D numpy array


code: ode_order(eq, y)

rawDescription: Find the order of a differential equation in Sympy


rawDescription: How to clear the plotted line at every nth x value so looks clearly broken into segments?

description: Clear the plotted line at every nth x value so looks clearly broken into segments


code:
from Bio import SeqIO
out = open("out.txt", "a")
records = list(SeqIO.parse("input.fas","fasta"))
previous = records[-1]
for record in records:
    id = "_".join(str(record.id).rsplit("_")[1:])
    out.write("SEQUENCE_ID=" + previous.id + "e_" + id + "b\n")
    out.write("SEQUENCE_TEMPLATE =%s\n=\n" % previous.seq)
    previous = record
out.close()

rawDescription: In python, how can temporarily extract information from a file, and use that information to manipulate the same file


code:
from sklearn import linear_model
clf = linear_model.LinearRegression()
clf.fit([[getattr(t, 'x%d' % i) for i in range(1, 8)] for t in texts],
        [t.y for t in texts])

rawDescription: Multivariate linear regression in Python


code:
from tkinter import Widget
from os import path

class Ribbon(Widget):
    def __init__(self, master, kw=None):
        self.version = master.tk.call('package','require','tkribbon')
        self.library = master.tk.eval('set ::tkribbon::library')
        Widget.__init__(self, master, 'tkribbon::ribbon', kw=kw)

    def load_resource(self, resource_file, resource_name='APPLICATION_RIBBON'):
        """Load the ribbon definition from resources.

        Ribbon markup is compiled using the uicc compiler and the resource included
        in a dll. Load from the provided file."""
        self.tk.call(self._w, 'load_resources', resource_file)
        self.tk.call(self._w, 'load_ui', resource_file, resource_name)

if __name__ == '__main__':
    import sys
    from tkinter import *
    def main():
        root = Tk()
        r = Ribbon(root)
        name = 'APPLICATION_RIBBON'
        if len(sys.argv) > 1:
            resource = sys.argv[1]
            if len(sys.argv) > 2:
                name = sys.argv[2]
        else:
            resource = path.join(r.library, 'libtkribbon1.0.dll')
        r.load_resource(resource, name)
        t = Text(root)
        r.grid(sticky=(N,E,S,W))
        t.grid(sticky=(N,E,S,W))
        root.grid_columnconfigure(0, weight=1)
        root.grid_rowconfigure(1, weight=1)
        root.mainloop()
    main()

rawDescription: Is there a way to use ribbon toolbars in Tkinter?


code:
from collections import Counter
counted = Counter(tuple(sorted(entry)) for entry in lol)
import pprint
pprint.pprint(dict(counted))

rawDescription: Find duplicate lists where element order is insignificant but repeat list elements are significant


code:
class SomeTrait(Base):
    __tablename__ = 'sometrait'
    id = Column(Integer, primary_key=True)
    detail1 = Column(String)
    detail2 = Column(String)
    __table_args__ = (
        UniqueConstraint('detail1', 'detail2'),
    )

rawDescription: SQLAlchemy many:many relationship, setting uniqueness of a table entry


rawDescription: Extracting a number from a 1-word string


code:
class MyFrame(Frame):
    def __init__(self, master=None):
        ...
        panel1 = CustomPanel(tab1, "hello")
        panel1.pack(fill="both", expand=True)
        tab1.inner_panel = panel1
        ...

    def callCustomMethod(self):
        tab1 = self.noteBook.page(0)
        panel1 = tab1.inner_panel
        ...

rawDescription: {PYTHON + TKINTER} "Type cast" problem: How to retrieve Custom frame objects from a Pmw.NoteBook?


code:
import os
import cPickle as pickle

my_dir = os.path.dirname(__file__)
pickle_file_path = os.path.join(my_dir, 'demo_pickle_file.pkl')

with open(pickle_file_path, 'rb') as pickle_file:
    demo = pickle.load(pickle_file)

rawDescription: How to access file in pythonanywhere?

description: Access file in pythonanywhere


code:
words = ['shoe brand', 'car brand', 'smoothies for everyone']
filters = {'brand'}
[w for w in words if not set(w.split()).intersection(filters)]

rawDescription: Performance: Comparing two lists in python for string matches


code:
import sys
from tkinter import *
import matplotlib
matplotlib.use("TKAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

class GraphPlotter:

    def __init__(self, parent):
        # remember parent
        self.parent = parent

    def graphdis(self):

        f = Figure(figsize=(5,5), dpi=100)
        a = f.add_subplot(111)
        a.plot([1,2,3,4,5,6],[1,2,3,4,5,6])

        # canvas need correct parent - root
        canvas = FigureCanvasTkAgg(f, self.parent)
        canvas.show()
        canvas.get_tk_widget().pack()

class GUIWindow:

    def __init__(self):
        root = Tk()
        root.geometry('1200x650')

        # ****** GUI buttons *********
        radomeButton = Button(root, text="Radome", bd="4")

        wingsButton = Button(root, text="Wings", bd="4")
        engineButton = Button(root, text="Engine", bd="4")
        finsButton = Button(root, text="Fins", bd="4")
        fuelButton = Button(root, text="Fuel", bd="4")

        radomeButton.place(x=25, y=25)

        wingsButton.place(x=175, y=25)
        engineButton.place(x=235, y=25)
        finsButton.place(x=300, y=25)
        fuelButton.place(x=356, y=25)

        # use `root` as parent for canvas
        graphGrab = GraphPlotter(root)

        graphGrab.graphdis()

        root.mainloop()

GUIWindow()

rawDescription: Executing a Function from Another Class in Python


code:
def change(self, event):
    myobject = event.GetEventObject()
    myobject.Disable()

rawDescription: wxPython, Disabling buttons?

description: WxPython, Disabling buttons


code:
for tag in node.xpath('//*[@class]'):
    tag.attrib.pop('class')

rawDescription: Remove class attribute from HTML using Python and lxml


code:
class DynamicForm(forms.Form):
    def __init__(self, *args, **kwargs):
        dynamic_fields = kwargs.pop('dynamic_fields')
        super(DynamicForm, self).__init__(*args, **kwargs)
        for key, value in dynamic_fields:
            self.fields[key.slug] = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=value)

rawDescription: Creating a Django form from a dictionary of objects


code:
response = urllib2.urlopen(url)
CHUNK = 16 * 1024
with open(file, 'wb') as f:
   while True:
      chunk = response.read(CHUNK)
      if not chunk: break
      f.write(chunk)

rawDescription: Stream large binary files with urllib2 to file


code:
from multiprocessing import Process
from somewhere import A, B
if __name__ == '__main__':
    procs = [ Process(target=t) for t in (A,B) ]

    for p in procs:
        p.start()

    for p in procs:
        p.join()

rawDescription: Running methods on different cores on python


rawDescription: Convert Numpy matrix to pandas dataframe


code:
s = True
while s:
    s, i = capture.read()
    if s:
        do_some_stuff(i)

rawDescription: How to use return value of a function as condition of while that returns tuple in python

description: Use return value of a function as condition of while that returns tuple in python


code:
def replacement(match):
    return ''.join(y[0] for y in m.group(0).split())

rawDescription: finding two or more consecutive words starts with upper and replacing with their abbreviation (regex)

description: Finding two or more consecutive words starts with upper and replacing with their abbreviation (regex)


code: set(thingList1) & set(thingList2) & set(thingList3)

rawDescription: intersection of three sets in python?

description: Intersection of three sets in python


code:
soup.findAll('a', attrs={'href': re.compile(".3gp")})
#or
soup.findAll('a', href=re.compile(".3gp"))

rawDescription: Trying to parse HTML using BeautifulSoup, but it not working?


code: coords = the_canvas.coords(item_id)

rawDescription: Get the current coordinates of an item on a Canvas widget given its item handle?


code:
IDs,Xs,Ys,Zs = zip(*filedata)
positions = zip(Xs,Ys,Zs) # list of tuples of (x,y,z)

unique_Xs = []
[unique_Xs.append(val) for val in Xs if val not in unique_Xs]

unique_Ys = []
[unique_Ys.append(val) for val in Ys if val not in unique_Ys]

rawDescription: Make list of X and Y coordinates

description: Make list of X and Y coordinates


code:
x0 = 100
directions = np.cumsum(2 - dragon) % 4
dx = np.take([0, -1, 0, 1], directions)
x = np.cumsum(np.r_[x0, dx])

rawDescription: Fastest way of creating a list through iteration


code:
# Fibonacci Series.
def Fibonacci(num) :
    F_1 = 0
    F_2 = 1
    Fibo = 0
    for i in list(range(num)) :
        Fibo = F_1 + F_2
        F_1 = F_2
        F_2 = Fibo
    return Fibo

print(Fibonacci(7))

rawDescription: can not print the return value from a function

description: Can not print the return value from a function


code:
def default_handler(parsed_url):
    pass

def youtube_handler(parsed_url):
    pass

def hulu_handler(parsed_url):
    pass

handlers = {
    'www.youtube.com': youtube_handler,
    'hulu.com':        hulu_handler,
}

handler = handlers.get(urlParsed.netloc, default_handler)
handler(urlParsed)

rawDescription: Pythonic alternatives to if/else statements


code:
class prediction_history(Callback):
    def __init__(self):
        self.predhis = []
    def on_epoch_end(self, epoch, logs={}):
        self.predhis.append(model.predict(predictor_train))

rawDescription: Python/Keras - Creating a callback with one prediction for each epoch


code:
import os
import sys
from multiprocessing import Pool, Lock

lock = Lock()

def output(msg):
    msg = '%s%s' % (msg, os.linesep)
    with lock:
        sys.stdout.write(msg)

def func(input):
    output(u'pid:%d got input \"%s\"' % (os.getpid(), str(input)))

def executeFunctionInParallel(funcName, inputsList, maxParallelism):
    output(u'Executing function %s on input of size %d with maximum parallelism of %d' % (
      funcName.__name__, len(inputsList), maxParallelism))
    parallelismPool = Pool(processes=maxParallelism)
    executeBooleanResultsList = parallelismPool.map(funcName, inputsList)
    parallelismPool.close()
    output(u'Function %s executed on input of size %d  with maximum parallelism of %d' % (
       funcName.__name__, len(inputsList), maxParallelism))
    # if all parallel executions executed well - the boolean results list should all be True
    return all(executeBooleanResultsList)

if __name__ == "__main__":
    inputsList=[str(i) for i in range(20)]
    executeFunctionInParallel(func, inputsList, 4)

rawDescription: How can I do an atomic write to stdout in python?

description: Do an atomic write to stdout in python


code:
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(0, numdays)]

rawDescription: Creating a range of dates in Python

description: Creating a range of dates in Python


code:
from Tkinter import Tk, Button, RAISED
from functools import partial
root = Tk()
buttons = [['1','2','3'],
          ['4','5','6'],
          ['7','8','9'],
          ['*','0','#']]

def buttonClicked(buttonVal):
    print(buttonVal)

for r in range(4):
    for c in range(3):
        button = Button(root,
                        relief = RAISED,
                        padx = 10,
                        text = buttons[r][c],
                        command = partial(buttonClicked, buttons[r][c]))
        button.grid(row = r, column = c)

root.mainloop()

rawDescription: Creating a Dialpad Using Tkinter

description: Creating a Dialpad Using Tkinter


rawDescription: How to select a submatrix from an adjacency list in Python?

description: Select a submatrix from an adjacency list in Python


code:
# Try three times to make contact
while True:
    try:
        # Connect to API
        connection = urllib2.urlopen(request, timeout=10)
        xmlstring = connection.read()
        break
    except URLError as e:
        tries += 1
        if tries >= 3:
            sys.stderr.write(
                      'own3dStreamsUpdater: Fatal error: Repeated timeouts')
            exit()

rawDescription: Python urllib2.urlopen freezes script infinitely even though timeout is set


code:
class foo:
    def __init__(self, **kwargs):
        vars(self).update(kwargs)

rawDescription: Python: Iterating through constructor's arguments


code:
from urlparse import urljoin
urljoin('http://something.com/random/abc.html', '../../music/MySong.mp3')

rawDescription: python beautifulsoup no link when parsing 'a' tag and href

description: Python beautifulsoup no link when parsing 'a' tag and href


code: "\"" in dfTrain['name'].to_string()

rawDescription: Check for a character in a list of strings


code:
from bisect import bisect
from random import randint
data = []
for x in range(20):
  a,b = randint(1,10),randint(1,100)
  data.insert(bisect(data,(a,1000)),(a,b))
for d in data: print (d)

rawDescription: Most efficient pair-value data structure in Python with support for duplicates and sorting?


code:
import gdata.contacts.data

new_contact = gdata.contacts.data.ContactEntry()

# Set the contact's name.
new_contact.name = gdata.data.Name(
    given_name=gdata.data.GivenName(text='Elizabeth'),
    family_name=gdata.data.FamilyName(text='Bennet'),
    full_name=gdata.data.FullName(text='Elizabeth Bennet')
)

# Set user defined fields
new_contact.user_defined_field.append(
    gdata.contacts.data.UserDefinedField(
        key='Field Name',
        value='Field Value'
    )
)

rawDescription: Specifying custom fields for contacts in Google Contacts API v3


code:
import numpy as np
import sklearn.tree
clf = sklearn.tree.DecisionTreeClassifier()
clf.fit(X,y)
clf.tree_.apply(np.asfortranarray(X.astype(sklearn.tree._tree.DTYPE)))

rawDescription: Using scikit-learn DecisionTreeClassifier to cluster


code:
from PyQt4 import QtCore,QtGui
import sys
import cv2
import numpy as np

class ImageWidget(QtGui.QWidget):
    def __init__(self,parent=None):
        super(ImageWidget,self).__init__(parent)
        self.image=None

    def setImage(self,image):
        self.image=image
        sz=image.size()
        self.setMinimumSize(sz)
        self.update()

    def paintEvent(self,event):
        qp=QtGui.QPainter()
        qp.begin(self)
        if self.image:
            qp.drawImage(QtCore.QPoint(0,0),self.image)
        qp.end()

class MainWindow(QtGui.QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.videoFrame=ImageWidget()
        self.setCentralWidget(self.videoFrame)
        self.timer=QtCore.QTimer(self)
        self.timer.timeout.connect(self.updateImage)
        self.timer.start(30)
        self.capture = cv2.VideoCapture(0)

    def updateImage(self):
        _, img = self.capture.read()
        #img=cv2.cvtColor(img, cv.CV_BGR2RGB)
        height, width, bpc = img.shape
        bpl = bpc * width
        image = QtGui.QImage(img.data, width, height, bpl, QtGui.QImage.Format_RGB888)
        self.videoFrame.setImage(image)

def main():
    app=QtGui.QApplication(sys.argv)
    w=MainWindow()
    w.show()
    app.exec_()

if __name__=='__main__':
    main()

rawDescription: opencv with pyqt4 dialog display

description: Opencv with pyqt4 dialog display


code:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

searches = ['Norway']
data = [['ID', 'MESSAGE']]

driver = webdriver.PhantomJS()
wait = WebDriverWait(driver, 10)
url = 'your URL here'
driver.get(url)

for search in searches:
    # select 1000 results
    select = Select(driver.find_element_by_id("count"))
    select.select_by_visible_text("1000")

    # provide the search query and search
    input = driver.find_element_by_id("q")
    input.clear()
    input.send_keys(search)
    input.submit()

    # wait until loaded
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.top")))

    # parse search results with BeautifulSoup
    pagehtml = driver.page_source
    soup = BeautifulSoup(pagehtml, "html5lib")
    identifiers = [id.get_text(strip=True)
                   for id in soup.find_all('span', {"class": "glyphicon glyphicon-open-file"})]
    messages = [message.get_text(strip=True)
                for message in soup.find_all('td', {"colspan": "3"})]
    data.extend(zip(identifiers, messages))

print(len(data))

rawDescription: Loop through elements beautifulsoup

description: Loop through elements beautifulsoup


code:
from ajaxuploader.backends.base import AbstractUploadBackend
from django.core.files.storage import default_storage

class S3CustomUpload(AbstractUploadBackend):
    NUM_PARALLEL_PROCESSES = 4

    def upload_chunk(self, chunk):
        #save file to s3
        self._fd.write(chunk)
        self._fd.close()

    def setup(self, filename):
        self._fd = default_storage.open('%s/%s' % ('uploads/materials/', str(filename)), 'wb')

    def upload(self, uploaded, filename, raw_data, *args, **kwargs):
        try:
            if raw_data:
                # File was uploaded via ajax, and is streaming in.
                chunk = uploaded.read(self.BUFFER_SIZE)
                while len(chunk) > 0:
                    self.upload_chunk(chunk, *args, **kwargs)
                    chunk = uploaded.read(self.BUFFER_SIZE)
            else:
                # File was uploaded via a POST, and is here.
                for chunk in uploaded.chunks():
                    self.upload_chunk(chunk, *args, **kwargs)
            return True
        except:
            # things went badly.
            return False

    def upload_complete(self, request, filename, *args, **kwargs):
        upload = Upload()
        upload.upload = settings.S3_URL + "uploads/materials/"+ filename
        upload.name = filename
        upload.save()

        return {'pk': upload.pk}

rawDescription: AWS S3 backend for ajax Django upload

description: AWS S3 backend for ajax Django upload


code:
class A(db.Model):
  b = db.ReferenceProperty()

class B(db.Model):
  a = db.ReferenceProperty(A)

rawDescription: How should I deal with a circular import in Google App Engine?


code:
arr = np.random.rand((10,10))
final_string = str(arr.tolist())

rawDescription: How to serialize a numpy array of floats to a string?

description: Serialize a numpy array of floats to a string


code:
import codecs
import os

from bs4 import BeautifulSoup

scripts = []
styles = []
bodies = []
processed = []

def explode(filename):
    # We want to turn the body element into a div so we can use it
    # in one page with all of the other body elements.
    processed.append(filename)
    soup = BeautifulSoup(codecs.open(filename, encoding='utf-8'))
    body = soup.body
    body.name = 'div'
    body['id'] = filename
    body['class'] = 'body'
    bodies.append(body)

    # Ensure that we grab all of the scripts that are required by
    # this page.
    for script in soup.find_all('script'):
        if 'src' in script.attrs:
            content = codecs.open(script['src'], encoding='utf-8').read()
        else:
            content = script.string
        if content not in scripts:
            scripts.append(content)

    # Likewise for the link[stylesheet] elements.
    for link in soup.find_all('link'):
        content = codecs.open(link['href'], encoding='utf-8').read()
        if content not in styles:
            styles.append(content)

    for a in soup.find_all('a'):
        # Make sure all local-links are rewritten to point to a more
        # fully-qualified name (these are line number links).
        if a['href'][0] == '#':
            anchor = u'{}-{}'.format(filename, a['href'][1:])

            a['href'] = u'#{}'.format(anchor)
            a.parent['id'] = anchor
        elif a['href'] in processed:
            # Pages we have already seen, we want to have a local link.
            a['href'] = u'#{}'.format(a['href'])
        else:
            # Otherwise, we want to see if we have a file that matches
            # the href, and embed that. Yay recursion.
            try:
                explode(a['href'])
            except IOError:
                pass
            else:
                a['href'] = u'#{}'.format(a['href'])

TEMPLATE = u'''<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
    <title>Coverage report</title>
    <style>{styles}</style>
    <script>{scripts}</script>
  </head>
  <body>
    {body}
  </body>
</html>
'''

# Fire off the tree walking with htmlcov/index.html
os.chdir('htmlcov')
explode('index.html')

# Override the toggle_lines function to limit it to just our code block.
scripts.append('''
coverage.toggle_lines = function (btn, cls) {
    btn = $(btn);
    var hide = "hide_"+cls;
    if (btn.hasClass(hide)) {
        btn.closest('.body').find("#source ."+cls).removeClass(hide);
        btn.removeClass(hide);
    }
    else {
        $("#source ."+cls).addClass(hide);
        btn.addClass(hide);
    }
};
''')

result = TEMPLATE.format(
    styles=u'\n'.join(styles),
    scripts=u'\n'.join(scripts),
    body=u'\n'.join([unicode(x) for x in bodies])
)

codecs.open('coverage.html', 'w', encoding='utf-8').write(result)
os.chdir('..')

rawDescription: how to get django coverage report in single html file

description: Get django coverage report in single html file


rawDescription: python regex for complex list and integer combinations

description: Python regex for complex list and integer combinations


code:
husbands2wives = bidict({'john': 'jackie'})
husbands2wives['john'] # the forward mapping is just like with dict
husbands2wives[:'jackie'] # use slice for the inverse mapping

rawDescription: build a dictionary for find key by value

description: Build a dictionary for find key by value


code:
def increase_tree_values(node, delta):
    """ Increases/decreases the value of all nodes in the tree by the value 'delta'
    """

    # increase the current node's value
    node.value += delta

    # recursively call function on left child, if it exists
    if node.left_child:
        increase_tree_values(node.left_child, delta)

    # recursively call function on right child, if it exists
    if node.right_child:
        increase_tree_values(node.right_child, delta)

# presuming you have some binary tree called 'tree' already constructed
# increase all nodes in 'tree' by 2
increase_tree_values(tree, 2)

rawDescription: Traverse through binary tree to change the value of each nodes?


rawDescription: Regex Replace [*]

description: Regex Replace [*]


code:
def packetdata(n):
    class PacketData(pt.IsDescription):
        data = pt.UInt8Col(shape=(n,))
    return PacketData

self.tdata = self.hfile.createTable(self.g, 'packetdata', packetdata(128),
                            filters=filters)

rawDescription: Python metaclasses: how do I generalize this helper class?


code: p1 = input('Welcome {0} > Enter your no:'.format(p1))

rawDescription: How to use a raw_input value in a line for taking input in python

description: Use a raw_input value in a line for taking input in python


code: from myapp.appstate import AppState

rawDescription: Python: Choosing between modules and classes


code:
bytes = "abc123"
read_size = struct.calcsize('<H')
with open(file, 'rb') as infile:
    info, = struct.unpack('<H', infile.read(read_size))
    info2 = infile.read(info)
    if info2 == SIGNATURE:
        return

rawDescription: Python Fast Open File Only Need To Compare Bytes


code:
import wx
from wx.lib.mixins.inspection import InspectionMixin

class MyApp(wx.App, InspectionMixin):
    def OnInit(self):
        self.Init()  # initialize the inspection tool
        frame = wx.Frame(None)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        frame.SetSizer(sizer)

        self.__squarePanel = wx.Panel(frame)
        sizer.Add(self.__squarePanel, 0, wx.ALL | wx.EXPAND, 5)

        frame.Bind(wx.EVT_SIZE, self.OnSize)

        frame.Show()
        self.SetTopWindow(frame)
        return True

    def OnSize(self, evt):
        frame = evt.GetEventObject()
        frameW, frameH = frame.GetSize()
        targetSide = min(frameW, frameH)
        self.__squarePanel.SetSize((targetSide, targetSide))

app = MyApp()
app.MainLoop()

rawDescription: Force a panel to be square in wx (python)


code:
import os
dir_name = ...
for filename in os.listdir(dir_name):
    if not filename.endswith(".img"): continue
    full_path = os.path.join(dir_name, filename)
    outASCII = '%s.asc' % (full_path,)
    arcpy.RasterToASCII_conversion(full_path, outASCII)

rawDescription: Raster to ASCII - adding processing multiple files piece of code in Python


code:
class UserAccount(db.Model):

    def __eq__(self, other):
        if isinstance(other, UserAccount):
            return self.user_id == other.user_id
        return NotImplemented

    def __ne__(self, other):
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

rawDescription: How to override equals() in google app engine data model type?

description: Override equals() in google app engine data model type


code:
jobLocation = jobLocationUnclean
for c in "!@#%&*()[]{}/?<>,.":
    jobLocation = jobLocation.replace(c, "")

params.append(jobLocation)
print(jobLocation)

rawDescription: Why does this for loop have no effect? (Python)


code: engine = Python.CreateEngine({'FullFrames': True})

rawDescription: How to pass options to a new IronPython engine?

description: Pass options to a new IronPython engine


rawDescription: Discard headings in res.read() status text


code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.PhantomJS()
driver.get("http://www.regulations.gov/#!documentDetail;D=OCC-2011-0014-0032")

wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.GGAAYMKDGNE")))

rawDescription: Trouble Parsing Text using BeautifulSoup and Python


code:
a = np.arange(5)
perms = np.argsort(np.random.rand(a.shape[0], 3), axis=0) # 3 columns
np.hstack((a[:,np.newaxis], a[perms]))

rawDescription: numpy - fastest way to build 2d array with permuted copies of numpy 1d array

description: Numpy - fastest way to build 2d array with permuted copies of numpy 1d array


rawDescription: Why does pylint object to single character variable names?


code:
# get all rows with distinct (unique) hashes from Remote and create a list of hashes.
remote_hash_list = [item.hash for item in Remote.query.distinct(Remote.hash).all()]

# Now get all Local items that hash is not in remote hashes list
local_items = Local.query.filter(Local.hash.notin_(remote_hash_list)).all()

rawDescription: Comparing two tables using flask-sqlalchemy


code:
class Foo(object):
     @property
     def blah(self):
         return "Cheddar Cheese!"

a = Foo()
print('{a.blah}'.format(a=a))

rawDescription: Python properties and string formatting

description: Python properties and string formatting


code:
import re
regex  = re.compile(r'(?s)name:\s*\((\w+)\).*?year:\s*\((\w+)\)')
mydict = dict(re.findall(regex, data))

rawDescription: python regex find line1 and value after line 1, find line2 and value after line2...etc

description: Python regex find line1 and value after line 1, find line2 and value after line2...etc


code:
class A: foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
class A:
 def __init__(self): self.foo = []
a, b = A(), A()
a.foo.append(5)
b.foo

rawDescription: Python: Difference between class and instance attributes


code:
class ClientSession:

    def __init__(self, *, connector=None, loop=None, request_class=None,
                 response_class=None, cookies=None, headers=None, auth=None):
        if loop is None:
            loop = asyncio.get_event_loop()
        self._loop = loop
        self.cookies = http.cookies.SimpleCookie()
        if connector is None:
            connector = aiohttp.TCPConnector(force_close=True, loop=loop)

rawDescription: aiohtttp connection pooling with ProxyConnector

description: Aiohtttp connection pooling with ProxyConnector


code:
import re
x = 'This is a private post. Cc: @me, @you.and @others,too. I @hope>this is okay'
[re.search(r'(@\w+)', z).groups()[0] for z in x.split() if z.startswith('@')]

rawDescription: How to Cut Off String After Some Special Symbol is Encountered


code:
from django.db import models

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

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ('title',)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

    def __unicode__(self):
        return self.headline

    class Meta:
        ordering = ('headline',)

rawDescription: django many-to-many model simple logic

description: Django many-to-many model simple logic


code:
from multiprocessing import Pool

def func(*args):
    obj = Something(*args)
    obj.run()
    return obj.results()

pool = Pool()
results = pool.map(func, ((1,2,3), (4,5,6)))

rawDescription: Multiprocessing Python Class Object

description: Multiprocessing Python Class Object


code:
proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')

rawDescription: Execute python script using urllib2 from PHP behind Proxy


code:
class IMessageFactory(Interface):
     def __call__():
         """Produce an IMessage provider"""

     def parse(msg):
         """Parses `msg` into a IMessage provider"""

class IMessage(Interface):
     """A message interface"""

     # Optional, show the class method here too
     def parse(msg):
         """Parses `msg` into a IFoo provider"""

rawDescription: Declaring class methods in Zope interfaces


code:
import itertools
list(itertools.combinations(['foo', 'bar', 'la'], 2))

rawDescription: Get all permutations without replacement?


code: img_one[..., ALPHA] - img_two[..., ALPHA] > 0.5

rawDescription: Image Comparison using c++ or python

description: Image Comparison using c++ or python


code:
lineNo = []
css = open("/path/to/stylesheet.css")
for i,line in enumerate(css.readlines(), start=1):
        if "width" in line:
            print (i, line)
            lineNo.append(i)

print (lineNo)

rawDescription: How to run this code in list

description: Run this code in list


code:
def f(a):
     return a[0] + a[1] + a[2]
mm = numpy.random.randn(5, 3)
numpy.apply_along_axis(f, 1, mm)

rawDescription: Numpy: How to map f: (shape (3) ndarray) --> (float) over an ndarray of shape (...,3) to get ndarray of shape (...)?


code: res = 'yes' if 2 > 1 else 'no'

rawDescription: If operator '?' in Python?

description: If operator '?' in Python


code:
import re
s = r'''<html>
 <head>
  <script type="text/javascript">
  function redirecttoauth(sessionid, test) {
   function body ...
  }
  </script>
 </head>
 <body>
 </body>
</html>
'''

start = r'function redirecttoauth\(sessionid'
end = r'}'
result = re.search(r'%s(.*)%s' % (start, end), s, re.DOTALL).group(1)
print(result)

rawDescription: How to get function attributes inside a html?

description: Get function attributes inside a html


code:
CountVectorizer().fit_transform(["foo bar baz", "foo bar quux"]).A
TfidfVectorizer(use_idf=False).fit_transform(["foo bar baz", "foo bar quux"]).A

rawDescription: Is a countvectorizer the same as tfidfvectorizer with use_idf=false?


code:
from itertools import chain, combinations

def powerset(iterable):
    "Returns all the possible subsets of the elements in a given iterable"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def partition(iterable):
    "Returns all the possible ways to partition a set into two subsets"
    s = set(iterable)
    for s1 in powerset(s):
        yield s1, s-s1

def split_vertex(graph, v1):
    # Note that you only need one extra vertex, you can use v for the other
    v2 = graph.vcount()
    graph.add_vertices(1)

    # Find the neighbors of v1
    neis = set(graph.neighbors(v1))

    # Delete all the edges incident on v1 - some of them will be re-added
    g.delete_edges(g.incident(v1))

    # Iterate over the powerset of neis to find all possible splits
    for set1, set2 in partition(neis):
        if len(set1) < 2 or len(set2) < 2:
            continue

        # Copy the original graph
        g2 = g.copy()

        # Add edges between v1 and members of set1
        g2.add_edges([(v1, v3) for v3 in set1])

        # Add edges between v2 and members of set2
        g2.add_edges([(v2, v3) for v3 in set2])

        # Return the result
        yield g2

rawDescription: Generating all possible 3-connected graphs


rawDescription: Relative paths in open in Python 2.5 and 2.7


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d

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

for i in ["x","y","z"]:
    circle = Circle((0, 0), 1)
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z=0, zdir=i)

ax.set_xlim3d(-2, 2)
ax.set_ylim3d(-2, 2)
ax.set_zlim3d(-2, 2)

plt.show()

rawDescription: How to plot a 3D patch collection in matplotlib?

description: Plot a 3D patch collection in matplotlib


code:
import numpy as np
import pandas as pd

DC = np.random.randn(3, 3)
df = pd.DataFrame(np.random.randn(1000, 10))
df2 = df.copy()
df[[4,5,6]] = np.dot(DC, df[[4,5,6]].values.T).T

def rotate(vector):
        return np.dot(DC, vector)
df2[[4,5,6]] = df2[[4,5,6]].apply(rotate, axis='columns')
df.equals(df2)

rawDescription: Applying matrix product in specific pandas columns


code:
myDict = {}
for (num, strn) in enumerate(dlist):
    for w in strn.split():
        if w not in myDict:
            myDict[w] = {num}
        else:
            myDict[w].add(num)

rawDescription: if-else comprehension with dictionary not working in python3

description: If-else comprehension with dictionary not working in python3


code:
def isAjax(request):
    return request.environ.get('HTTP_X_REQUEST_WITH') == 'XMLHttpRequest'

rawDescription: How to determine if an HTTP request is asynchronous in Python or Pylons

description: Determine if an HTTP request is asynchronous in Python or Pylons


code:
from numpy.random import random
from bokeh.plotting import figure, show, output_notebook
from IPython.html.widgets import interact
from bokeh.models import ColumnDataSource
output_notebook()

## <-- new cell -->

p = figure()

N = 10
x_data = random(N)+2
y_data = random(N)+2
labels = range(N)
source = ColumnDataSource(
    data={
        'x':x_data,
        'y':y_data,
        'desc':labels
    }
)
p.scatter('x', 'y', source=source)
p.text('x', 'y', 'desc', source=source)
output_notebook()

def update_plot(label_flag=True):
    if label_flag:
        source.data['desc'] = range(N)
    else:
        source.data['desc'] =  ['']*N
    show(p)

interact(update_plot, label_flag=True)

rawDescription: Update data point labels in bokeh plot

description: Update data point labels in bokeh plot


code:
for n, (train, test) in enumerate(cv):
    X_train, y_train = _safe_split(self.estimator, X, y, train)
    X_test, y_test = _safe_split(self.estimator, X, y, test, train)

    rfe = RFE(estimator=self.estimator,
              n_features_to_select=n_features_to_select,
              step=self.step, estimator_params=self.estimator_params,
              verbose=self.verbose - 1)

    rfe._fit(X_train, y_train, lambda estimator, features:
             _score(estimator, X_test[:, features], y_test, scorer))
    scores.append(np.array(rfe.scores_[::-1]).reshape(1, -1))
scores = np.sum(np.concatenate(scores, 0), 0)
# The index in 'scores' when 'n_features' features are selected
n_feature_index = np.ceil((n_features - n_features_to_select) /
                          float(self.step))
n_features_to_select = max(n_features_to_select,
                           n_features - ((n_feature_index -
                                         np.argmax(scores)) *
                                         self.step))
# Re-execute an elimination with best_k over the whole set
rfe = RFE(estimator=self.estimator,
          n_features_to_select=n_features_to_select,
          step=self.step, estimator_params=self.estimator_params)
rfe.fit(X, y)

rawDescription: Score of RFECV() in python scikit-learn

description: Score of RFECV() in python scikit-learn


rawDescription: Knowing an item's location in an array

description: Knowing an item's location in an array


code:
import tokenize
import StringIO

def ns_attr_split(s):
  arr = []
  last_delim = -1
  cnt = 0

  # Tokenize the expression, tracking the last namespace
  # delimiter index in last_delim
  str_io = StringIO.StringIO(s)
  for i in tokenize.generate_tokens(str_io.readline):
    arr.append(i[1])
    if i[1] == '.':
      last_delim = cnt
    cnt = cnt + 1

  # Join the namespace parts into a string
  ns = ""
  for i in range(0,last_delim):
    ns = ns + arr[i]

  # Join the attr parts into a string
  attr = ""
  for i in range(last_delim + 1, len(arr)):
    attr = attr + arr[i]

  return (ns, attr)

rawDescription: Given a Python string describing object.attribute, how do I separate the attributes's namespace from the attribute?


code:
def __nonzero__(self):
    warnings.warn(
        "The behavior of this method will change in future versions.  "
        "Use specific 'len(elem)' or 'elem is not None' test instead.",
        FutureWarning, stacklevel=2
        )
    return len(self._children) != 0 # emulate old behaviour, for now

rawDescription: Why does bool(xml.etree.ElementTree.Element) evaluate to False?


code: os.system("gnome-terminal -e 'bash -c \"sudo add-apt-repository ppa:x2go/ppa && sudo apt-get update ; exec bash\"'")

rawDescription: Python syntax to open gnome-terminal and execute multiple commands


code:
def Professor(name,salary,course):
    ProfDict = {"Name":name,"Salary":salary,"Course":course}
    return "Name: {0[Name]}; Salary: {0[Salary]}; Course: {0[Course]}".format(ProfDict)

rawDescription: Python Dictionary Formatting Query

description: Python Dictionary Formatting Query


code:
def pattern(n):
    if n <= 0:
        return ''
    return '*' + str(pattern(n-1)) + '!'

print(pattern(2))

rawDescription: Recursive pattern returning NoneType

description: Recursive pattern returning NoneType


code:
import numpy as np
mymeans = [13,5]
# stdevs = sqrt(5),sqrt(2)
# corr = .3 / (sqrt(5)*sqrt(2) = .134
mycov = [[5,.3], [.3,2]]
np.cov(np.random.multivariate_normal(mymeans,mycov,500000).T)
np.corrcoef(np.random.multivariate_normal(mymeans,mycov,500000).T)

rawDescription: Sampling from bivariate normal in python


code:
g = h.Graph()
g.addvar(...)

h.graphList[0].append(g)

h.run()

rawDescription: NEURON python Graph() is blank

description: NEURON python Graph() is blank


code:
import dbus
sysbus = dbus.SystemBus()
systemd1 = sysbus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
manager = dbus.Interface(systemd1, 'org.freedesktop.systemd1.Manager')
job = manager.RestartUnit('sshd.service', 'fail')

rawDescription: Starting a systemd service via python

description: Starting a systemd service via python


code:
from cStringIO import StringIO

source_code = StringIO()
source_code.write(final_pdf)
exec(source_code)
p = doIt(buffer)

rawDescription: instantiate python class from class available as string , only in memory!

description: Instantiate python class from class available as string , only in memory!


code:
class Foo():
    def __repr__(self):
        return "I'm Foo"

foo = Foo()
foo

rawDescription: How to display a class like a called variable?

description: Display a class like a called variable


code:
import matplotlib.pyplot as plt

x = range(100)
y = range(100,200)
fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.scatter(x[:4], y[:4], s=10, c='b', marker="s", label='first')
ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second')
plt.legend(loc='upper left');
plt.show()

rawDescription: MatPlotLib: Multiple datasets on the same scatter plot


code:
from construct import BitStruct, BitField
sample = "\xff\x01\x01\x01"
c = BitStruct("foo", BitField("status", 8), BitField("i", 24))
c.parse(sample)

rawDescription: Construct parsing for unaligned int field?


code:
from tkinter import *
from tkinter import ttk

root = Tk()

s = ttk.Style()

s.configure('Red.TLabelframe.Label', font=('courier', 15, 'bold'))
s.configure('Red.TLabelframe.Label', foreground ='red')
s.configure('Red.TLabelframe.Label', background='blue')
lf = ttk.LabelFrame(root, text = "Test", style = "Red.TLabelframe")
lf.pack( anchor = "w", ipadx = 10, ipady = 5, padx = 10,
                  pady = 0, side = "top")
Frame(lf, width=100, height=100, bg='black').pack()
print(s.lookup('Red.TLabelframe.Label', 'font'))
root.mainloop()

rawDescription: Set style for Checkbutton or Labelframe in python tkinter


code:
def __unicode__(self):
    return self.name # to display name attribute

rawDescription: Make object attribute displayabe instead of object django


code:
import aenum
from http import HTTPStatus

aenum.extend_enum(HTTPStatus, 'BAD_SPAM', 513, 'Too greasy')
aenum.extend_enum(HTTPStatus, 'BAD_EGGS', 514, 'Too green')

rawDescription: How to add custom codes to HTTPStatus in Python 3.5?

description: Add custom codes to HTTPStatus in Python 3.5


code:
from pylab import *

def genuchten(t,C,k):
    return 1/(1+(C/t)**k)**(1-1/k)

###MAIN#######
t0, Y, X = ogrid[0:10:100j, 1:10:10j, 1:10:10j]
f0 = genuchten(t0, 3, 3)
f = genuchten(t0, X, Y)
Z = sum(abs(f0-f), axis=0)
contourf(X.ravel(), Y.ravel(), Z)
show()

rawDescription: Contour with Z(X,Y)

description: Contour with Z(X,Y)


code: self.label_lang.values = map(str, result2)

rawDescription: Python - Kivy framework - Spinner values list


rawDescription: create specific permutation of a list in python

description: Create specific permutation of a list in python


code:
class MyDatabase(object):
    def __getitem__(self, x):
        if 10 <= x <= 15:
            return "foo"
        else:
            raise IndexError('key not in database')
db = MyDatabase()
db[12]

rawDescription: Is it possible to create a Python list and fake populating it?


code:
[...]
from reportlab.pdfbase.pdfmetrics import stringWidth
[...]

# student name variable.
student_name = 'Alex'

# Content.
line1 = " is working on college project."
line2 = "Reportlab is very good lib, "
line3 = " liked it"

# drawString location calculation.
x = 0
y = 8.5 * 72

# First string.
can.setFont('Helvetica-Bold', 8)
can.drawString(x, y, student_name)
can.setFont('Helvetica', 8)
textWidth = stringWidth(student_name, 'Helvetica-Bold', 8)
x += textWidth + 1
can.drawString(x, y, line1)

y = y - 72

# Second String.
x = 0
can.setFont('Helvetica', 8)
can.drawString(x, y, line2)
textWidth = stringWidth(line2, 'Helvetica', 8)
x += textWidth + 1
can.setFont('Helvetica-Bold', 8)
can.drawString(x, y, student_name)
textWidth = stringWidth(student_name, 'Helvetica-Bold', 8)
x += textWidth + 1
can.setFont('Helvetica', 8)
can.drawString(x, y, line3)

# Create PDF.
can.save()

rawDescription: How to add bold and normal text in one line using drawString method in reportlab (python)

description: Add bold and normal text in one line using drawString method in reportlab (python)


code:
def bind_arg(arg):
    def my_len(self, arg):
        return arg+1
    return my_len

rawDescription: Python mock.patch.object with functool.partial bound arguments possible?


code:
def basic_gen_primes(n):
    """Return a list of all primes less then or equal to n"""
    if n < 2:
        return []

    # The sieve.  Each entry i represents (2i + 1)
    size = (n + 1) // 2
    sieve = [True] * size

    # 2(0) + 1 == 1 is not prime
    sieve[0] = False

    for i, value in enumerate(sieve):
        if not value:
            continue

        p = 2*i + 1

        # p is prime.  Remove all of its multiples from the sieve
        # p^2 == (2i + 1)(2i + 1) == (4i^2 + 4i + 1) == 2(2i^2 + 2i) + 1
        multiple = 2 * i * i + 2 * i
        if multiple >= size:
            break

        while multiple < size:
            sieve[multiple] = False
            multiple += p

    return [2] + [2*i+1 for i, value in enumerate(sieve) if value]

rawDescription: Optimalization of the primes finding function


rawDescription: update new value to key in dictionary (python)

description: Update new value to key in dictionary (python)


code:
fruits = {"apple", "banana"} #notice the {}, or `set(["apple","banana"])` in Python 2.6 or earlier
[b for b, f in baskets if fruits.issubset(f)]

rawDescription: How can I find the intersection of a list and a nested list?

description: Find the intersection of a list and a nested list


code:
def checkChange(FileName, oldContent):
    fSrc = open(FileName, 'r')
    actualContent = fSrc.read()
    fSrc.close()
    if actualContent != oldContent:
        print(1)
    return actualContent

rawDescription: Python Check txt variable loop

description: Python Check txt variable loop


code:
#!/usr/bin/env python
import pyaudio
import socket
import sys
import time

# Pyaudio Initialization
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 10240

p = pyaudio.PyAudio()

stream = p.open(format = FORMAT,
                channels = CHANNELS,
                rate = RATE,
                input = True,
                frames_per_buffer = chunk)

# Socket Initialization
host = ''
port = 50000
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connected = False
while not connected:
    try:
        s.connect((host,port))
        connected = True
    except Exception as e:
        pass #Do nothing, just try again

# Main Functionality
while 1:
    data = stream.read(chunk)
    s.send(data)
    s.recv(size)

rawDescription: make client socket wait for server socket with Python

description: Make client socket wait for server socket with Python


rawDescription: text file format from array

description: Text file format from array


code:
names = []  # Here we define an empty list.
while True:
    eingabe = input('Please enter a name: ')
    if not eingabe:
        break

    names.append(eingabe)
    print(eingabe)

rawDescription: How can I store the user input in a while - loop? (python)

description: Store the user input in a while - loop? (python)


rawDescription: find nearest value in numpy array

description: Find nearest value in numpy array


rawDescription: Getting a child element with Selenium and Python


code:
import sys
sys.path.insert(0, '/this/path/will/be/considered/first')

rawDescription: How is the python module search path determined on Mac OS X?


code:
def handle(self):
    tot_data = b""

    length = self.request.recv(4)
    size = struct.unpack("!i", length)[0]
    while len(tot_data) < size:
        data = self.request.recv(size - len(tot_data))
        if not data: break
        tot_data += data

    data = bytes(b"ACK")
    # just send back the ack when transfer completed
    self.request.sendall(data)

rawDescription: Socket connection between Java and Python


code:
from tkinter import *
#Window setup(ignore this)
app = Tk()
app.title('Geometry Calculator')
app.geometry('384x192+491+216')
app.iconbitmap('Geo.ico')
app.minsize(width=256, height=96)
app.maxsize(width=384, height=192)
app.configure(bg='WhiteSmoke')
#This is the emtry list...
PointList = []
#Here is where I define the variable that I will be appending to the list (which is the              object of the Entry box below)
StrPoint = StringVar()
def list_add(event):
    print ("hello")
#I don't really know how the bind-checking works and how I would implement it; I want to check if the user hits enter while in the Entry box here
    if event.char == '':
        PointList.append(StrPoint)
e1 = Entry(textvariable=StrPoint)
e1.grid(row=0, column=0)#use grid in next line,else it would return None
e1.bind('<Return>', list_add)# bind Entry

mainloop()

rawDescription: Checking if the user presses 'Return' while selected in an Entry box Tkinter


rawDescription: Compute the product of neighborhood for each cell in a matrix with numpy/scipy


code:
x1, y1 = np.loadtxt('file1.txt').transpose()
x2, y2 = np.loadtxt('file2.txt').transpose()

# interpolate (x2, y2) onto grid x1
from scipy.interpolate import interp1d
func = interp1d(x2, y2, kind='cubic')
y2_interp = func(x1)

rawDescription: How to interpolate a single column of data to match the shape of another column of data?

description: Interpolate a single column of data to match the shape of another column of data


code:
mult_index = [tuple(x.split('.')) for x in df.columns]
df.columns = pd.MultiIndex.from_tuples(mult_index)
df.stack()

rawDescription: Joining pandas DataFrame columns together based on column name


code:
with open(word_file) as words:
    for line in words:
        word = line.strip()
        website = "http://dictionary.goo.ne.jp/srch/jn/"+word+"/m0u/"
        print(website)

rawDescription: Link broken up into two?

description: Link broken up into two


code:
x = [('a_key', 'a value'), ('another_key', 'another value')]
y = dict(x)
y['a_key']
y['another_key']

rawDescription: Access list of tuples

description: Access list of tuples


code:
class Lookahead:
    def __init__(self, iter):
        self.iter = iter
        self.buffer = []

    def __iter__(self):
        return self

    def next(self):
        if self.buffer:
            return self.buffer.pop(0)
        else:
            return self.iter.next()

    def lookahead(self, n):
        """Return an item n entries ahead in the iteration."""
        while n >= len(self.buffer):
            try:
                self.buffer.append(self.iter.next())
            except StopIteration:
                return None
        return self.buffer[n]

rawDescription: Using lookahead with generators

description: Using lookahead with generators


code:
# count the number of friends for each user
# friends are users as well, so need alias
# construct subquery for use in final query

friend = db.aliased(User)

sub = db.session.query(
    User.id,
    db.func.count(friend.id).label('fc')
).join(friend, User.friends
).group_by(User.id).subquery()

# query users, join on subquery to get friend count
# order by friend count, descending

users = db.session.query(User
).join(sub, sub.c.id == User.id
).order_by(sub.c.fc.desc()
).paginate(page, MONKEYS_PER_PAGE, False)

rawDescription: How to sort a table by maximum value of a column using flask/sqlalchemy?

description: Sort a table by maximum value of a column using flask/sqlalchemy


code:
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse.urlparse(login_url or
                                                        settings.LOGIN_URL)[:2]
            current_scheme, current_netloc = urlparse.urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(path, login_url, redirect_field_name)
        return _wrapped_view
    return decorator

rawDescription: How to pass Django request object in user_passes_test decorator callable function

description: Pass Django request object in user_passes_test decorator callable function


code:
# config
from kivy.config import Config
Config.set('kivy', 'keyboard_mode', 'systemandmulti')

rawDescription: Kivy virtual keyboard not showing

description: Kivy virtual keyboard not showing


rawDescription: pymongo/mongodb: query if an element in an array of mongodb object

description: Pymongo/mongodb: query if an element in an array of mongodb object


code:
import time
import tkinter as Tk

def _start():
    for outer in range(5):
        if active_stat.get():
            time.sleep(1) # some code in the real app
        else:
            active_stat.set(True)
            break
        for inner in range(5):
            if active_stat.get():
                #counterstr.set("%02d-%02d" % (outer,inner)) #does not update till the end of loop
                textbox.insert(Tk.END, "%02d-%02d\n" % (outer,inner)) #does not show till the end of loop
                print ("{}-{}".format(outer,inner))
                time.sleep(1) #some code in the real app
            else:
                active_stat.set(True)
                break
            root.update()

def _stop():
    active_stat.set(False)

root = Tk.Tk()

active_stat = Tk.BooleanVar(root)
active_stat.set(True)

#counterstr=Tk.StringVar()
#Tk.Label(root, textvariable=counterstr).pack(side=Tk.TOP)
textbox=Tk.Text(root)
textbox.pack(side=Tk.TOP)
Tk.Button(root, text='Start', command=_start).pack(side=Tk.LEFT)
Tk.Button(root, text='Stop', command=_stop).pack(side=Tk.LEFT)
Tk.Button(root, text='Quit', command=root.quit).pack(side=Tk.LEFT)
root.mainloop()

rawDescription: Break ongoing loop started by a tkinter button


code:
import os
os.system('mysqldump -u root -p%s database > database.sql' % password)

rawDescription: Export MySQL database to sql file with Python os.system


code:
parameters = {'vect__wordvect__ngram_range': [(1, 1), (1, 2)],
              'vect__lettervect__lowercase': [True, False],
              'vect__transformer_weights': [[1,0], [0,1], [1,1]]}

rawDescription: scikit-learn FeatureUnion gridsearch over subsets of features

description: Scikit-learn FeatureUnion gridsearch over subsets of features


code: sns.kdeplot(a, 500)

rawDescription: Restrict xlim on kdeplot while keeping it smooth


code:
from heapq import heappop, heappush

def distance(a, b):
   pq = [(0,0,0)]
   lena = len(a)
   lenb = len(b)
   while True:
      (wgh, i, j) = heappop(pq)
      if i == lena and j == lenb:
         return wgh
      if i < lena:
         # deleted
         heappush(pq, (wgh+1, i+1, j))
      if j < lenb:
         # inserted
         heappush(pq, (wgh+1, i, j+1))
      if i < lena and j < lenb:
         if a[i] == b[i]:
            # unchanged
            heappush(pq, (wgh, i+1, j+1))
         else:
            # changed
            heappush(pq, (wgh+1, i+1, j+1))
      # ... more possibilities for changes, like your "+(i-i1-1)+1+(j-j1-1)"

rawDescription: Cython Damerau-Levenshtein speed-up

description: Cython Damerau-Levenshtein speed-up


code:
with open('/home/kwal0203/Desktop/eggs.csv', 'a') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["Hello my friend"])

rawDescription: Python output to CSV

description: Python output to CSV