code:
import hashlib

#Initialize an empty dictionary.  We'll add entries to this as we read the
#dictionary file in
hash_table = {}

print('Generating hashes...')

#Using with on the file object means that it will be closed automatically
#when the block is finished
with open('dictionary.txt', 'r') as inp_file:

    for word in inp_file.readlines():

        #strip off the trailing whitespace ('\n' or '\n\r' depending on the platform)
        word = word.strip()

        #The requirement is for a salt to be prepended to the cleartext
        #dictionary word.  For each possible salt value...
        for salt in range(0,256):
            #convert the salt from an int to a string here so we don't have to
            #continually do it below
            salt = str(salt)

            #Store the hash/cleartext pair in the dictionary.  The key of the
            #dictionary is the hash and the value is the salted cleartext
            hash_table[hashlib.md5(salt+word).hexdigest()] = salt+word

rawDescription: MD5 hashing and comparison in python

description: MD5 hashing and comparison in python


code:
import pandas as pd
pd.DataFrame(my_data).values

rawDescription: Convert structured array with various numeric data types to regular array


rawDescription: python appending elements to a list from a list

description: Python appending elements to a list from a list


code:
strings = ["one two", "three four", "five six"]
[value for s in strings for value in s.split()]

rawDescription: Python list appending while incrementing


code:
__author__ = ''

import sys
from glob import glob # glob will help us search for files based on their extension or filename.
from distutils.core import setup # distutils sends the data py2exe uses to know which file compile
import py2exe

data_files = []
setup(
    name='WorkgroupDashboard',
    console=['DashboardBack.py'], # 'windows' means it's a GUI, 'console' It's a console program, 'service' a Windows' service, 'com_server' is for a COM server
    # You can add more and py2exe will compile them separately.
    options={ # This is the list of options each module has, for example py2exe, but for example, PyQt or django could also contain specific options
        'py2exe': {
            'packages':['jinja2'],
            'dist_dir': 'dist/test', # The output folder
            'compressed': True, # If you want the program to be compressed to be as small as possible
            'includes':['os', 'logging', 'yaml', 'flask', 'sqlalchemy'], # All the modules you need to be included,  because py2exe guesses which modules are being used by the file we want to compile, but not the imports
        }
    },

    data_files=data_files # Finally, pass the
)

rawDescription: Python Flask - Building the Server as Executable (Py2exe)


code:
import Image
FNAME = '/tmp/test.png'
top = Image.open(FNAME).convert('RGBA')
new_w = new_h = max(top.size)
background = Image.new('RGBA', size = (new_w,new_h), color = (0, 0, 0, 0))
background.paste(top, (0, 0))
background.save('/tmp/result.png')

rawDescription: Padding an image for use in wxpython

description: Padding an image for use in wxpython


code:
s = "Received Ticks are: 380 and nodeID is: 1"
s.split()
words = s.split()
words[3]
words[7]

rawDescription: Parsing serial data read in from USB using Python


rawDescription: How do you get the text from an HTML 'datacell' using BeautifulSoup

description: Get the text from an HTML 'datacell' using BeautifulSoup


code:
import datetime
...
date=time.strptime(argv[1], "%y-%m-%d");
newdate=date + datetime.timedelta(days=1)

rawDescription: Python TimeDelta Add Day to Supplied Argument


code:
# -*- coding: utf-8 -*-

# Objectif : découvrir le fonctionnement d'opencv-python
# http://opencv-python-tutroals.readthedocs.org/en/latest/index.html

import numpy as np
import cv2

# Load an color image in grayscale
img = cv2.imread('Lena.tiff',0)
WINDOW_NAME = 'Image de Lena'
cv2.namedWindow(WINDOW_NAME, cv2.CV_WINDOW_AUTOSIZE)
cv2.startWindowThread()

# Display an image
cv2.imshow(WINDOW_NAME,img)
cv2.waitKey(0)

cv2.destroyAllWindows()

rawDescription: Opencv python. WaitKey don't respond?

description: Opencv python. WaitKey don't respond


code:
fin = open("foo1.txt")
G={}
for line in fin: # load data, create adj lists
    lst = line.split()
    lst = [int(x) for x in lst]
    G[lst[0] ]=lst[1:]
print(G)

rawDescription: Reading a file in python and creating a list turns out to an empty list


rawDescription: Reindex or reorder group

description: Reindex or reorder group


code:
class CombinedFormSet(BaseInlineFormSet):
    # Validate formset data here
    def clean(self):
        super(CombinedFormSet, self).clean()
        for form in self.forms:
            if not hasattr(form, 'cleaned_data'):
                continue

            data = self.cleaned_data
            valid = False
            for i in data:
                if i != {}:
                    if i['is_correct']:
                        valid = True

            if not valid:
                #TODO: translate admin?
                raise forms.ValidationError("A Question must have an answer.")

            # Always return the cleaned data, whether you have changed it or
            # not.
            return data

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 4
    formset = CombinedFormSet

rawDescription: Only validate admin form if condition is true


code:
from random import randrange
from tkinter import *

def checkAnswer():
    dice = randrange(1,7)
    if int(guess) == dice:
        tkMessageBox.showinfo("Well Done!","Correct!")
    if int(guess) > 6:
        tkMessageBox.showinfo("Error"," Invalid number: try again")
    elif int(guess) <= 0:
        tkMessageBox.showinfo("Error"," Invalid number: try again")
    else:
        tkMessageBox.showinfo("Incorrect","Incorrect: dice rolled {}.".format(diceRoll))

root = Tk()

Label(root,text="Enter your guess").pack() #parent wasn't specified, added root

g = StringVar()
inputGuess = Entry(root, textvariable=g).pack() #changed variable from v to g
guess = g.get() #changed variable from v to g

submit = Button(root, text = "Roll Dice", command = checkAnswer).pack() #added root as parent
root.mainloop()

rawDescription: Simple python tkinter dice roll game

description: Simple python tkinter dice roll game


code:
import numpy as np

# set up values
keys = np.array([
    ['key1'],
    ['key2'],
    ['key3']
])
values = np.array([
    [1.1, 1.2, 1.3, 1.4],
    [2.1, 2.2, 2.3, 2.4],
    [3.1, 3.2, 3.3, 3.4]
])
weights = np.array([10., 20., 30., 40.])

# crunch the numbers
res = np.dot(values, weights)

sortedkeys = keys[res.argsort(axis=0)[::-1]]

rawDescription: Numpy - how to sort an array of value/key pairs in descending order


code:
class uint(int):
    def __new__(cls, value):
        unknown = value == 'unknown'
        obj = super(uint, cls).__new__(cls, 1 if unknown else value)
        obj.unknown = unknown
        return obj

    def __str__(self):
        return 'unknown' if self.unknown else super(uint, self).__str__()

rawDescription: Subclass int to allow "unknown" value

description: Subclass int to allow "unknown" value


code:
# Python 3.2
import csv
delimiter = ','
result = {}
with open("data.csv", 'r') as data_file:
    data = csv.reader(data_file, delimiter=delimiter)
    headers = next(data)[1:] # month names starting from 2nd column in csv
    for row in data:
        temp_dict = {}
        name = row[0]
        values = []
        # converting each value from string to int / float
        # (as suggested by OP's example)
        for x in row[1:]:
            try:
                values.append(int(x))
            except ValueError:
                try:
                    values.append(float(x))
                except ValueError:
                    print("Skipping value '{}' that cannot be converted " +
                          "to a number - see following row: {}"
                          .format(x, delimiter.join(row)))
                    values.append(0)
        for i in range(len(values)):
            if values[i]: # exclude 0 values
                temp_dict[headers[i]] = values[i]
        result[name] = temp_dict
print(result)

rawDescription: Python - CSV to Nested Dictionary

description: Python - CSV to Nested Dictionary


code:
from django.db.models import Count, Sum

num_taken = 5  # modify this if you want more/less than 5
query = Car.objects.values('manufacturer').annotate(num_cars=Count('manufacturer')).order_by('-num_cars')
top_cars = query[:num_taken]
others = query[num_taken:].aggregate(total=Sum('num_cars'))['total']
car_nums = [entry['num_cars'] for entry in top_cars] + [others]
car_manufactureres = [entry['manufacturerer'] for entry in top_cars] + ['Others']

rawDescription: Getting the data for a pie chart

description: Getting the data for a pie chart


code:
class Foo(ndb.Model):
  CACHE_KEY = 'bla_cache'
  bla = ndb.StringProperty()

  @clasmethod
  def build_page(cls):
    result = memcache.get(CACHE_KEY)
    if result is None:
      result = cls.query().fetch(100)
    return result

  def _post_put_hook(self, future):
    memcache.delete(CACHE_KEY)

rawDescription: Best practices for caching front page queries for Google App Engine (GAE)


code:
def lookup(param):
    try:
        return getCfgStr(sectName, param)
    except KeyError:
        return None

ports = lookup('ports')
terminal = lookup('terminals')

rawDescription: Try/Except block declaring multiple values


rawDescription: pandas groupby object index turns into FUBAR

description: Pandas groupby object index turns into FUBAR


code:
import locale
locale.setlocale(locale.LC_NUMERIC, 'hi_IN')
locale.format("%d", 10000000000, grouping=True)

rawDescription: Python: How to convert a number which ll separated by comma as number count increases?


code:
class ContextManager():

    def __init__(self):
        self.functions = []

    def func(self, f):
        self.functions.append(f)
        return f

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        for f in self.functions:
            print(f.__name__)

with ContextManager() as cm:

    @cm.func
    def add(x, y):
        return x + y

    def foo():
        return "foo"

    @cm.func
    def subtract(x, y):
        return x - y

# this code prints "add" and "subtract"

rawDescription: Get the list of functions defined in a contextmanager with statement in python


code:
fin = readFile(db)
categoryDict = defaultdict(dict)     # automatically create a subdict
for line in fin:
    itemDict = {}                    # a new innermost dict for every item
    itemInstance = setItemInstances(line)
    itemDict[itemInstance._product_id] = itemInstance
    categoryDict[itemInstance._category_id] = itemDict

rawDescription: nested dictionary python

description: Nested dictionary python


code:
with open(fname, 'w') as file:
    for match in re.finditer(r'Item A(.+?)Item B', subject, re.I):
        s = match.group(1)
        if len(s) > 50:
            file.write(s)

rawDescription: How do I extract text between two different matches?

description: Extract text between two different matches


code:
""" Move mail messegt to parsed folder after its handle """
def __moveMailToParsedFolder(self,num):
    mail_uid = num

    apply_lbl_msg = self.mailbox.copy(mail_uid, self.mailFolderCopyTo)

    if apply_lbl_msg[0] == 'OK':
        self.mailbox.store(mail_uid, '+FLAGS', '\Deleted')
        self.mailbox.expunge()

rawDescription: Use IMAP4 in python to move mail from a mailbox to another mailbox


code:
class PschamberSpider(scrapy.Spider):
    name = "pschamber"
    # start from this, since your domain is a sub-domain on its own,
    # you need to change to this without http://
    allowed_domains = ["cm.pschamber.com"]
    start_urls = (
        'http://cm.pschamber.com/list/',
    )

    def parse(self, response):
        item = PschamberItem()
        for sel in response.xpath('//div[@id="mn-ql"]//a'):
            # xpath and xpath().extract() will return a list
            # extract()[0] will return the first element in the list
            item['industry'] = sel.xpath('text()').extract()[0]

            # another mistake you made here
            # you're trying to call scrapy.Request(LIST of hrefs) which will fail
            # scrapy.Request only takes a url string, not list
            # another big mistake is you're trying to yield the item,
            # whereas you should yield the Request object
            yield scrapy.Request(
                sel.xpath('@href').extract()[0],
                callback=self.parse_2,
                meta={'item': item}
            )
    # another mistake, your callback function DOESNT take item as argument
    def parse_2(self, response):
        for sel in response.xpath('//div[@class="mn-title"]//a'):
            # you can access your response meta like this
            item = response.meta['item']
            item['company'] = sel.xpath('text()').extract()[0]
            # again, yield the Request object
            yield scrapy.Request(
                sel.xpath('@href').extract()[0],
                callback=self.parse_3,
                meta={'item': item}
            )

    def parse_3(self, response):
        item = response.meta['item']
        item['website'] = response.xpath('//a[@class="mn-print-url"]/text()').extract()
        # OK, finally assume you're done, just return the item object
        return item

rawDescription: Scrapy - Visiting nested links and grabbing meta data from each level


code:
p = subprocess.Popen("bc", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate('1+1\n')

rawDescription: How do I send input to and get output from bc using Python?

description: Send input to and get output from bc using Python


rawDescription: Sending file attachments using SMTPLIB.data()


code:
import os, logging
class SupervisorProcessFilter(logging.Filter):
    def filter(self, record):
        record.processName = os.environ['SUPERVISOR_PROCESS_NAME']
        return True

rawDescription: Use process name generated by supervisord in child process logging


code: sorted(L, key=lambda item: (item == "/", item.lower()))

rawDescription: What is a sort key guaranteed to come at the end of a list of unicode strings?


code:
import os
import gtk
from gtk import Socket, Button, Window, VBox, HBox

w = Window()
e = Button("Emacs")
x = Button("XTerm")
s = Socket()
v = VBox()
h = HBox()
w.add(v)
v.add(s)
h.add(e)
h.add(x)
v.pack_start(h, expand=False)

def runemacs(btn):
    x.set_sensitive(False); e.set_sensitive(False)
    os.spawnlp(os.P_NOWAIT, "emacs",
        "emacs", "--parent-id", str(s.get_id()))

def runxterm(btn):
    x.set_sensitive(False); e.set_sensitive(False)
    os.spawnlp(os.P_NOWAIT, "xterm",
        "xterm", "-into", str(s.get_id()))

e.connect('clicked', runemacs)
x.connect('clicked', runxterm)
w.show_all()
gtk.main()

rawDescription: How to embed some application window in my application using any Python GUI framework

description: Embed some application window in my application using any Python GUI framework


code:
import datetime

class MyForm(forms.Form):
    date = forms.DateField(...)

    def clean_date(self):
        date = self.cleaned_data['date']
        if date < datetime.date.today():
            raise forms.ValidationError("The date cannot be in the past!")
        return date

rawDescription: Django: How to set DateField to only accept Today & Future dates


code:
all_keys=np.unique(np.array((array1,array2)).T[0])
dict1=dict(array1)
dict2=dict(array2)
array1=np.array([[i,dict1.get(i,0)] for i in all_keys])
array1
array2=np.array([[i,dict2.get(i,0)] for i in all_keys])
array2

rawDescription: Align numpy arrays based on array keys

description: Align numpy arrays based on array keys


rawDescription: Pyinotify doesn't run with pygtk

description: Pyinotify doesn't run with pygtk


code:
bitmap = wx.EmptyBitmap(w, h)
dc = wx.MemoryDC(bitmap)

rawDescription: How can I draw to a MemoryDC using the GraphicsContext, and then blit that to a PaintDC?

description: Draw to a MemoryDC using the GraphicsContext, and then blit that to a PaintDC


rawDescription: Preventing New Windows from Capturing Focus wxPython


code:
a,b,c  =  [ 1 if i>1 else i for i in [ a, b, c ] ]
a,b,c = map( lambda x: 1 if x>1 else x, [a,b,c] ) #lambda or name of some function

rawDescription: When adding to list why does Python copy values instead of pointers?


code:
import sys

from PyQt4 import QtGui

class TestDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(TestDialog, self).__init__(parent)
        self.initUI()

    def clearLayout(self, layout):
        if layout is None:
            return
        while layout.count():
            child = layout.takeAt(0)
            if child.widget() is not None:
                child.widget().deleteLater()
            elif child.layout() is not None:
                self.clearLayout(child.layout())

        layout.setParent(None)

    def initUI(self):
        search_method = {
            'id': ['id'],
            'detail': ['catagory', 'price', 'enroll_date'],
            'drawer': ['name', 'sex', 'state'],
            'internal': ['transaction_date', 'msg_id'],
        }

        self.layTop = QtGui.QHBoxLayout()
        self.lblBy = QtGui.QLabel("By")
        self.layTop.addWidget(self.lblBy)
        self.radios = {}
        self.layouts = {}
        self.labels = {}
        self.edits = {}

        for option in search_method:
            r = self.radios[option] = QtGui.QRadioButton(option)
            self.layTop.addWidget(r)

        self.vlay = QtGui.QHBoxLayout()
        self.vlay.addLayout(self.layTop)
        self.layInput = QtGui.QVBoxLayout()

        def by_option(option):
            self.clearLayout(self.layInput)
            for input_field in search_method[option]:
                lbl = self.labels[input_field] = QtGui.QLabel(input_field)
                edit = self.edits[input_field] = QtGui.QLineEdit()
                layout = self.layouts[input_field] = QtGui.QHBoxLayout()
                layout.addWidget(lbl)
                layout.addWidget(edit)
                self.layInput.addLayout(layout)
            self.vlay.addLayout(self.layInput)

        for option in search_method:
            self.radios[option].toggled.connect(
                lambda yesno, option=option: by_option(option)
            )

        self.setLayout(self.vlay)

app = QtGui.QApplication(sys.argv)
testDialog = TestDialog()
testDialog.show()
sys.exit(testDialog.exec_())

rawDescription: generate functions to place widgets in pyqt using exec did not recognize self

description: Generate functions to place widgets in pyqt using exec did not recognize self


rawDescription: how to make a single list out of this lists of lists , using list comprehension?

description: Make a single list out of this lists of lists , using list comprehension


code:
filtered = [singleRun.postProcess for singleRun in simObjects if singleRun._ran]
processed = [item() for item in filtered]

rawDescription: Does each item in a list comprehension get resolved as the list is constructed?


code:
def get_user_input(allowed_choices):
    while True:
        s = raw_input("Enter your choice " + "/".join(allowed_choices) + ": ")
        if s in allowed_choices:
            return s

x = get_user_input(['yes', 'no', 'maybe'])

rawDescription: selection from a list python

description: Selection from a list python


code:
class helloworld:
    def world(self):
        print("Hello World!")

m = "world"
hello = helloworld()
getattr(hello, m)()

rawDescription: Using string as variable name

description: Using string as variable name


code:
words = collections.Counter(s.split())
for delim in delims:
    del words[delim]

rawDescription: Perform set operation difference on a list of tuples


code:
import matplotlib.pyplot as plt
def plot_something(x, y, **kwargs):
    title  = kwargs.pop( 'title'  )
    xlabel = kwargs.pop( 'xlabel' )
    ylabel = kwargs.pop( 'ylabel' )
    plt.figure()
    plt.plot(x, y, **kwargs)
    fig = plt.gcf()
    for axis in fig.axes:
        axis.set_title( title )
        axis.xaxis.set_label( xlabel )
        axis.yaxis.set_label( ylabel )
    return axis

plot_conf = {'title': 'Blabla', 'xlabel':'Time (s)', 'ylabel': 'Speed (m/s)'}
x = [1.,2.,3.]
y = [1.,4.,9.]
axis = plot_something(x=x,y=y, **plot_conf)

rawDescription: Add axis label to plot in matplotlib, by passing them as arguments to plot()


code:
import matplotlib, numpy, sys
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

root = Tk.Tk()

f = Figure(figsize=(5,4), dpi=100)
ax = f.add_subplot(111)

data = (20, 35, 30, 35, 27)

ind = numpy.arange(5)  # the x locations for the groups
width = .5

rects1 = ax.bar(ind, data, width)

canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

Tk.mainloop()

rawDescription: Displaying a matplotlib bar chart in Tkinter


code:
import base64
imgdata = base64.b64decode(imgstring)
filename = 'some_image.jpg'  # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
    f.write(imgdata)
# f gets closed when you exit the with statement
# Now save the value of filename to your database

rawDescription: How to convert base64 string to image?

description: Convert base64 string to image


code:
from django.shortcuts import get_object_or_404

@login_required(login_url='/')
def update(request,usuario_id):
    user = get_object_or_404(Usuario, pk=usuario_id)
    form = UsuarioForm(request.POST or None, instance=user)

    if request.method == 'POST' and form.is_valid():
       form.save()
       return redirect('/menu/')
    # you need to pass `usuario` as part of the context to template
    # so you can access usuario.id in template
    return render_to_response('form.html',{ 'form':form, 'usuario': user }, context_instance=RequestContext(request))

rawDescription: How update models modelforms and django

description: How update models modelforms and django


code:
import web.views.home as views_list
urlpatterns = patterns('',
    (r'^$', 'web.views.home.index'),
    *[(r'^home/%s' % i, 'web.views.home.%s' % i) for i in dir(views_list)]
)

rawDescription: Django url.py without method names

description: Django url.py without method names


code:
for i, x in enumerate(a):
    for j in x:
        b[j].append(i)

rawDescription: Reverse indexing a list of lists in Python


code: while not x: time.sleep(0.1)

rawDescription: Python time.sleep indefinitely

description: Python time.sleep indefinitely


code:
word[:2]    # The first two characters
word[2:]    # Everything except the first two characters

rawDescription: Why are slice and range upper-bound exclusive?


code:
for i in range(intNumberOfPlayers):
    if i == intNumberOfPlayers - 1:
        print(i) #print last item

rawDescription: Conditional processing on last item in a range


code:
#Create the array
[Nx, Ny, Nz] = (60, 220, 85)
[I, J, K]    = (np.arange(0,Nx,1),np.arange(0,Ny,1),np.arange(0,Nz,1))

[I, J, K] = np.meshgrid(I, J, K)

#Create the 1-d idexed array
ix = np.ravel_multi_index((I,J,K),(Nx,Ny,Nz),order='F')

print(ix)

rawDescription: multi indexing in python

description: Multi indexing in python


code:
def callback(in_data, frame_count, time_info, flag):
    global b,a,fulldata #global variables for filter coefficients and array
    audio_data = np.fromstring(in_data, dtype=np.float32)
    #do whatever with data, in my case I want to hear my data filtered in realtime
    audio_data = signal.filtfilt(b,a,audio_data,padlen=200).astype(np.float32).tostring()
    fulldata = np.append(fulldata,audio_data) #saves filtered data in an array
    return (audio_data, pyaudio.paContinue)

rawDescription: How to handle in_data in Pyaudio callback mode?

description: Handle in_data in Pyaudio callback mode


code:
predictions = model.predict(parsedTrainData.map(lambda x: x.features))
labelsAndPredictions = parsedTrainData.map(lambda x: x.label).zip(predictions)

rawDescription: How to generate tuples of (original lable, predicted label) on Spark with MLlib?

description: Generate tuples of (original lable, predicted label) on Spark with MLlib


code:
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

rawDescription: Command Line Arguments In Python

description: Command Line Arguments In Python


code:
from Tkinter import Tk, Canvas, mainloop
master = Tk()
points = [10, 10, 50, 10, 50, 50, 10, 50 ]
c = Canvas(master, width=200, height=100)
c.pack()
c.create_line(points + points[0:2], fill = "red")
mainloop()

rawDescription: Pythonic Way To Draw Polygon

description: Pythonic Way To Draw Polygon


code:
eval_link = lambda x: (lambda p: self.go_to_link(x))
for link in list_of_links:
    link_label = Label(self.video_window, text="Frame "+str(video_number), fg="blue", cursor="hand2")
    link_label.pack()
    link_label.place(x=xcod2, y=ycod2)
    link_label.bind("<1>", eval_link(link))

rawDescription: Python Tkinter: Bind function with labels in for loop


code:
with open('input.txt', 'r') as istr:
    new_par = False
    for line in istr:
        line = line.strip()
        if not line:  # blank
            new_par = True
            continue
        if new_par:
            print()  # print a single blank line
        print(' '.join(line.split()))
        new_par = False

rawDescription: How can I format a txt file in python so that extra paragraph lines are removed as well as extra blank spaces?

description: Format a txt file in python so that extra paragraph lines are removed as well as extra blank spaces


code:
# IPv4
client = listening_socket.accept()
(ipv4,port) = client.getsockname()

# IPv6
client = listening_socket.accept()
(address, port, flow_info, scope_id) = client.getsockname()

rawDescription: Capture destination IP in TCP Python SocketServer


code:
combobox = Qt.QComboBox()
combobox.addItems(["test1", "test2", "test3"])
combobox.show()
combobox.view().setDragDropMode(Qt.QAbstractItemView.DragOnly)

model_mime_type = 'application/x-qabstractitemmodeldatalist'

class ComboBox(Qt.QComboBox):
  def __init__(self):
    super(ComboBox, self).__init__()
    self.setAcceptDrops(True)

  def dragEnterEvent(self, e):
    if e.mimeData().hasFormat(model_mime_type) or \
       e.mimeData().hasFormat('text/plain'):
      e.accept()
    else:
      e.ignore()

  def dropEvent(self, e):
    if e.mimeData().hasFormat(model_mime_type):
      encoded = e.mimeData().data(model_mime_type)
      stream = Qt.QDataStream(encoded, Qt.QIODevice.ReadOnly)
      while not stream.atEnd():
        row = stream.readInt()
        column = stream.readInt()
        map = stream.readQVariantMap()
        if len(map.values()) == 1:
          self.addItem(map.values()[0].toString())
      combobox.hidePopup()
    else:
      self.addItem(Qt.QString(e.mimeData().text()))

c2 = ComboBox()
c2.show()

rawDescription: Python / PyQt4: How to make a QComboBox Item draggable


code:
import numpy

def slow( a, b=None ):

    if b is None: b = a
    a = numpy.asmatrix( a )
    b = numpy.asmatrix( b )

    out = 0.0
    for ai in a:
        for bj in b:
            dij = bj - ai
            out += numpy.outer( dij, dij )
    return out

def opsum( a, b=None ):

    if b is None: b = a
    a = numpy.asmatrix( a )
    b = numpy.asmatrix( b )

    RA, CA = a.shape
    RB, CB = b.shape
    if CA != CB: raise ValueError( "input matrices should have the same number of columns" )

    out = -numpy.outer( a.sum( axis=0 ), b.sum( axis=0 ) );
    out += out.T
    out += RB * ( a.T * a )
    out += RA * ( b.T * b )
    return out

def test( a, b=None ):
    print( "ground truth:" )
    print( slow( a, b ) )
    print( "optimized:" )
    print( opsum( a, b ) )
    print( "max abs discrepancy:" )
    print( numpy.abs( opsum( a, b ) - slow( a, b ) ).max() )
    print( "" )

# OP example
test( [[1,2], [3,4]] )

# non-symmetric example
a = [ [ 1, 2, 3 ], [-4, 5, 6 ], [7, -8, 9 ], [ 10, 11, -12 ] ]
a = numpy.matrix( a, dtype=float )
b = a[ ::2, ::-1 ] + 15
test( a, b )

# non-integer example
test( numpy.random.randn( *a.shape ), numpy.random.randn( *b.shape ) )

rawDescription: Fast differences of all row pairs with NumPy


code:
grocery_list = ['apples', 'bananas', 'oranges', 'milk']
for grocery in grocery_list:
  print(grocery, len(grocery))

rawDescription: for statement in python

description: For statement in python


code:
import progressbar, time, sys

def up():
    # My terminal breaks if we don't flush after the escape-code
    sys.stdout.write('\x1b[1A')
    sys.stdout.flush()

def down():
    # I could use '\x1b[1B' here, but newline is faster and easier
    sys.stdout.write('\n')
    sys.stdout.flush()

# Total bar is at the bottom. Move down to draw it
down()
total = progressbar.ProgressBar(maxval=50)
total.start()

for i in range(1,51):
    # Move back up to prepare for sub-bar
    up()

    # I make a new sub-bar for every iteration, thinking it could be things
    # like "File progress", with total being total file progress.
    sub = progressbar.ProgressBar(maxval=50)
    sub.start()
    for y in range(51):
        sub.update(y)
        time.sleep(0.005)
    sub.finish()

    # Update total - The sub-bar printed a newline on finish, so we already
    # have focus on it
    total.update(i)
total.finish()

rawDescription: Double Progress Bar in Python

description: Double Progress Bar in Python


code:
import xml.etree.ElementTree as ET
root = ET.parse('sample.xml').getroot()
l = ET.tostringlist(root.find('text'))
l
''.join(l[2:-2])

rawDescription: python parsing xml with ElementTree doesnt give intrested result

description: Python parsing xml with ElementTree doesnt give intrested result


code:
import xlwt
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('Sheet 1')
sheet.write(0,1,'First text')
workbook.save('test.xls')

rawDescription: Writing to a Google Document With Python


code:
def to_seconds(s):
    hr, min, sec = [float(x) for x in s.split(':')]
    return hr*3600 + min*60 + sec

rawDescription: Fast conversion of time string (Hour:Min:Sec.Millsecs) to float


code:
import pexpect
import sys
game = pexpect.spawn('/usr/games/gnuchess')
# Echo output to stdout
game.logfile = sys.stdout
game.expect('White')
game.sendline('a2a4')
game.expect('White')
game.sendline('b2b3')
game.expect('White')
game.sendline('quit')

rawDescription: Read multiple lines from subprocess.Popen.stdout


code: df = df1.reset_index().merge(df2.reset_index(), on=['index','cols']).set_index('index')

rawDescription: pandas combine multiple dataframes or use as updates

description: Pandas combine multiple dataframes or use as updates


code:
import inspect
from functools import wraps

def positive(name, value):
    if value < 0:
        raise ValueError(name + " must be positive")

def check_params(f):
    signature = inspect.signature(f)
    @wraps(f)
    def wrapper(*args, **kwargs):
        bound_arguments = signature.bind(*args, **kwargs)
        for name, value in bound_arguments.arguments.items():
            annotation = signature.parameters[name].annotation
            if annotation is inspect.Signature.empty:
                continue
            annotation(name, value)
        return f(*args, **kwargs)
    return wrapper

@check_params
def procedural_noise(width: positive, height: positive, seed: positive):
    pass # ...

rawDescription: Check parameters of a function in a Python


code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        '''
        Constructor
        '''
        QMainWindow.__init__(self, parent)
        self.central_widget = QStackedWidget()
        self.setCentralWidget(self.central_widget)
        self.start_screen = Start(self)
        self.second_screen = Second(self)
        self.central_widget.addWidget(self.start_screen)
        self.central_widget.addWidget(self.second_screen)
        self.central_widget.setCurrentWidget(self.start_screen)

        self.start_screen.clicked.connect(lambda: self.central_widget.setCurrentWidget(self.second_screen))
        self.second_screen.clicked.connect(lambda: self.central_widget.setCurrentWidget(self.start_screen))

class Start(QWidget):

    clicked = pyqtSignal()

    def __init__(self, parent=None):
        super(Start, self).__init__(parent)
        layout = QHBoxLayout()
        button = QPushButton(text=QString('Push me!'))
        layout.addWidget(button)
        self.setLayout(layout)
        button.clicked.connect(self.clicked.emit)

class Second(QWidget):

    clicked = pyqtSignal()

    def __init__(self, parent=None):
        super(Second, self).__init__(parent)
        layout = QHBoxLayout()
        button = QPushButton(text=QString('Back to Start!'))
        layout.addWidget(button)
        self.setLayout(layout)
        button.clicked.connect(self.clicked.emit)

app = QApplication(sys.argv)
myWindow = MainWindow(None)
myWindow.show()
app.exec_()

rawDescription: Changing between Widgets in QMainWindows central Widget


code:
from subprocess import Popen
from os import environ

env = dict(os.environ)
env['LD_LIBRARY_PATH'] = '/opt/java/jre/lib/i386/:/opt/java/jre/lib/amd64/'
args = ['/opt/java/jre/bin/java', '-Xincgc', '-Xmx1G', '-jar', 'craftbukkit-0.0.1-SNAPSHOT.jar']
p = Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)

rawDescription: subprocess and extra args

description: Subprocess and extra args


code:
import time

class myClass():

    def __init__(self):
        self.ranname = "0"

    def AskForName(self):
        self.ranname = "1"
        name = raw_input("Please enter your name: ")
        print("--------------------")
        print("  .:: ", name, " ::.")
        print("--------------------")
        print("     ")
        time.sleep(2)
        self.Start()

    def TryAgainQuestion(self):
        tryagain = raw_input("Do you want to try again? (Y or N): ")
        if (tryagain == "y"):
            self.AskForName()

        else:
            time.sleep(1)
            print("Made By: Daniel Parker")

    def Start(self):
        if self.ranname == "1":
            self.TryAgainQuestion()

        if self.ranname == "0":
            self.AskForName()

def main():

    myclass = myClass()
    myclass.Start()

   #end of main

if __name__ == "__main__":
    main()

rawDescription: Python Script not Working def

description: Python Script not Working def


code:
import json
mark = '"values":'
lists = json.JSONDecoder().raw_decode(text, text.index(mark)+len(mark))[0]

rawDescription: Python: How to extract specific parts of a string into a list


code:
from astropy.table import Table
t = Table([[1.0]], names=['a'])
t['a'].format = '%.16e'
t.write(sys.stdout, format='ascii')

rawDescription: How to write to astropy Table object values with fix number after the decimal mark?

description: Write to astropy Table object values with fix number after the decimal mark


code:
import Tkinter

class Main(Tkinter.Tk):
    def __init__(self, parent):
        Tkinter.Tk.__init__(self, parent)
        self.first = Menu(self)
        self.second = noMenu(self)

    def first_button_response(self):
        self.first.button.pack_forget()

class noMenu(Tkinter.Frame):
    def __init__(self, parent):
        Tkinter.Frame.__init__(self, parent)
        self.button = Tkinter.Button(
            self, text="Bye button 1", command=parent.first_button_response
        )
        self.button.pack()
        self.pack()

class Menu(Tkinter.Frame):
    def __init__(self, parent):
        Tkinter.Frame.__init__(self, parent)
        self.button = Tkinter.Button(self, text="Button 1")
        self.button.pack()
        self.pack()

if __name__ == "__main__":
    app = Main(None)
    app.mainloop()

rawDescription: Python: tkinter delete object from class and make it invisible


code:
import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty

from kivy.lang import Builder
Builder.load_string('''
#Tabbed Control

<MainScreen>:
    tab_panel: tab_panel
    beta_tab: beta_tab
    TabbedPanel:
        id: tab_panel
        do_default_tab: False

        TabbedPanelItem:
            text: 'Alpha'
            GridLayout:
                rows: 2
                Label:
                    text: 'Alpha content area'
                Button:
                    text: 'Switch to Beta'
                    on_press: root.Switch()
        TabbedPanelItem:
            text: 'Beta'
            id: beta_tab
            BoxLayout:
                Label:
                    text: 'Beta content area'
''')

class MainScreen(BoxLayout):
    tab_panel = ObjectProperty(None)
    beta_pad = ObjectProperty(None)
    def Switch(self):
        self.tab_panel.switch_to(self.beta_tab)

class BasicApp(App):
    def build(self):
      return MainScreen()

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

rawDescription: Best way of programming kivy

description: Best way of programming kivy


rawDescription: Returning all characters before the first underscore


code:
class foo(object):
    def __init__(self, a):
        self.a = a
    def __call__(self, b): # the function formerly known as "bar"
        return self.a + b

rawDescription: Python: pickling nested functions

description: Python: pickling nested functions


code:
def gridsums(grid, x, y, memo):
    if memo[x][y] is not None:
        return memo[x][y]

    if x == 0 and y == 0:
        sums = [0]
    elif x == 0:
        sums = gridsums(grid, x, y-1, memo)
    elif y == 0:
        sums = gridsums(grid, x-1, y, memo)
    else:
        sums = gridsums(grid, x-1, y, memo) + gridsums(grid, x, y-1, memo)

    sums = [grid[x][y] + s for s in sums]
    memo[x][y] = sums
    return sums

def gridsumsfast(grid):
    memo = []
    for row in grid:
        memo.append([])
        for cell in row:
            memo[-1].append(None)

    return gridsums(grid, len(grid[0]) - 1, len(grid) - 1, memo)

rawDescription: Turning Multidimensional List Into Tree Python


code:
import matplotlib.pyplot as plt

objects = [ ('Earth', 6.371e6),
            ('Jupiter', 6.9911e7),
            ('Sun', 6.96e8),
            ('Pollux', 5.568e9),
            ('Arcturus', 1.789e10),
            ('Aldebaran', 3.076e10),
            ('Antares', 6.14568e11)
          ]

fig, ax = plt.subplots()

for i, (name, radius) in enumerate(objects):
    sgn = 2 * (i % 2) - 1
    ax.annotate(name, xy=(radius,0), xytext=(radius,sgn*1), ha='center',
                arrowprops=dict(facecolor='black', shrink=0.05),)

ax.set_xscale('log')
ax.set_xlim(1.e6,1.e12)
ax.set_ylim(-2,2)

ax.axhline(color='k', lw=3)
ax.plot([obj[1] for obj in objects], [0]*len(objects), 'or', markersize=10)
ax.set_yticks([])
ax.set_xlabel('Radius /m')
plt.show()

rawDescription: Drawing a horizontal axis for size comparison


code:
import random
heads = 0 #initialize the count variables
tails = 0

while True:
    coinresult = random.randint(1, 2) #flip coin
    if coinresult == 1: #if result = 1 then increment heads counter
        heads += 1
    elif coinresult == 2: #if result = 2 then increment tails counter
        tails += 1
    if heads == tails: #check if counts are equal and break loop if they are
        break

print("The number of flips was {count}".format(count = heads + tails))

rawDescription: python - infinite coin flip that stops when number of heads = number of tails

description: Python - infinite coin flip that stops when number of heads = number of tails


code:
from django.core.exceptions import ValidationError

def validate_numeric(value):
    if not (9 <= len(re.sub("[^0-9]","",value)) <= 15):
        raise ValidationError('%s is not a valid phone number' % value)

rawDescription: python regex remove all non-numberic characters and ensure valid phone number

description: Python regex remove all non-numberic characters and ensure valid phone number


code:
class MyGraphicsView(QGraphicsView):
    def __init__(self):
        super(MyGraphicsView, self).__init__()
        self.setDragMode(QGraphicsView.RubberBandDrag)
        self._isPanning = False
        self._mousePressed = False

    def mousePressEvent(self,  event):
        if event.button() == Qt.LeftButton:
            self._mousePressed = True
            if self._isPanning:
                self.setCursor(Qt.ClosedHandCursor)
                self._dragPos = event.pos()
                event.accept()
            else:
                super(MyGraphicsView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self._mousePressed and self._isPanning:
            newPos = event.pos()
            diff = newPos - self._dragPos
            self._dragPos = newPos
            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - diff.x())
            self.verticalScrollBar().setValue(self.verticalScrollBar().value() - diff.y())
            event.accept()
        else:
            super(MyGraphicsView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            if event.modifiers() & Qt.ControlModifier:
                self.setCursor(Qt.OpenHandCursor)
            else:
                self._isPanning = False
                self.setCursor(Qt.ArrowCursor)
            self._mousePressed = False
        super(MyGraphicsView, self).mouseReleaseEvent(event)

    def mouseDoubleClickEvent(self, event): pass

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Control and not self._mousePressed:
            self._isPanning = True
            self.setCursor(Qt.OpenHandCursor)
        else:
            super(MyGraphicsView, self).keyPressEvent(event)

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_Control:
            if not self._mousePressed:
                self._isPanning = False
                self.setCursor(Qt.ArrowCursor)
        else:
            super(MyGraphicsView, self).keyPressEvent(event)

    def wheelEvent(self,  event):
        factor = 1.2;
        if event.delta() < 0:
            factor = 1.0 / factor
        self.scale(factor, factor)

rawDescription: QGraphicsView double click events and ScrollHandDrag mode item issue


code:
class EnumChoices(views.APIView):
    class EnumPermission(permissions.BasePermission):
        def has_permission(self, request, view):
            # whatever permission logic you need, e.g.
            return request.user.has_perm("planning.view_enums")
    permission_classes = (permissions.IsAuthenticated, EnumPermission)

    def get(self, request):
        enums = {}
        return Response(enums)

rawDescription: How can I add a non-model/queryset returning view with django-restframework when using DjangoObjectPermissions?

description: Add a non-model/queryset returning view with django-restframework when using DjangoObjectPermissions


code:
def counter(func):
    def wrapper(val, *args, **kwargs):
        if val:
            wrapper.count = wrapper.count + 1
            if wrapper.count % 100000 == 0: # insert 100,000 at a time, should be speedier thanks to `.executemany()`
                to_logfile(str(wrapper.count) + '\n', 'counter2.log')
                return func(wrapper.valarr, *args, **kwargs)
            else:
                if len(wrapper.valarr)==1000000:
                    wrapper.vallarr = []
                wrapper.valarr.append([val])
                return
    wrapper.count = 0
    wrapper.valarr = []

    return wrapper

rawDescription: Decorator storing input in list to call every `n` calls?


code:
class FutureCollection(Future):
    def __init__(self, *args, **kwargs):
        super(FutureCollection, self).__init__(*args, **kwargs)
        self._waiting_for = []

    def _check_all_done_and_resolve(self, future):
        if all(f.done() for f in self._waiting_for):
            # Maybe check for exceptions a. la.
            # http://tornado.readthedocs.org/en/latest/_modules/tornado/concurrent.html#chain_future
            self.set_result(None)  # Not sure what the result should be.

    def add_future(self, future):
        self._waiting_for.append(future)
        future.add_done_callback(self._check_all_done_and_resolve)

    @property
    def futures(self):
        # Read-only access to the futures that have been added.
        return iter(self._waiting_for)

rawDescription: The equivalent of jquery $.when in Python Tornado


code: subprocess.call(['curl', '-i', '-H', '"emptyheader"', '"http://somewhere:5000/somewhere"'])

rawDescription: With the Python httplib "HTTPConnection" object, how do you send a header without a value?


code:
import random
range_list=[]

for n in range(1000000):
    first=random.randint(0,3000000000)
    last=random.randint(first+101,first+149)
    range_list.append([last,first])

rawDescription: Generate random ranges

description: Generate random ranges


code:
def remove(dic, key):
    re = dict(dic)
    del re[key]
    return re

rawDescription: How to delete all strings that match a regular expression in python?

description: Delete all strings that match a regular expression in python


rawDescription: How to parse command line arguments with flags and without

description: Parse command line arguments with flags and without


code:
from scipy import stats

g = sns.JointGrid(x, y, ratio=100)
g.plot_joint(sns.regplot)
g.annotate(stats.pearsonr)
g.ax_marg_x.set_axis_off()
g.ax_marg_y.set_axis_off()

rawDescription: Turn off marginal distribution axes on jointplot using seaborn package


rawDescription: Is there a faster pythonic way of incrementing part of an array?


code:
import unicodedata, re

all_chars = (unichr(i) for i in xrange(0x110000))
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) == 'Cc')
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0,32) + range(127,160)))

control_char_re = re.compile('[%s]' % re.escape(control_chars))

def remove_control_chars(s):
    return control_char_re.sub('', s)

rawDescription: Stripping non printable characters from a string in python


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

pid = 0 #the pid of the process, aquired earlier by hand

address = 0x0000 #where to read from while in the memory

OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle

PROCESS_ALL_ACCESS = 0x1F0FFF

datadummy = b'.'*200
buffer = c_char_p(datadummy)
bufferSize = len(buffer.value)
bytesRead = c_ulong(0)

processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, int(PID))

ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead))

CloseHandle(processHandle)

rawDescription: Is there any good and easy-to-use module built in Python for editing memory?


code: if (last - first) < 2: return s[first] == e or s[last] == e

rawDescription: Python binary search function from OCW

description: Python binary search function from OCW


code:
from datetime import timedelta
obj.starts += timedelta(days=1, hours=2)

rawDescription: Add 2 hours and 1 day onto a timestamp in django


code:
index_max = a.index(max(a))
a[index_max], a[0] = a[0], a[index_max]

rawDescription: swap the first element with the maximum element in the list-Python

description: Swap the first element with the maximum element in the list-Python


code:
l = ['US', 20, 'en', 'UK', 21, 'en', 'Fra', 23, 'fr']
lists = [[l[3*i+j] for i in range(0, int(len(l)/3))] for j in range(0, 3)]
lists

rawDescription: create new lists from list based on position of element

description: Create new lists from list based on position of element


rawDescription: Trouble with making background of image transparent in python using pygame


code:
def shipment(self, orderItemIds):
    url = "https://api.flipkart.net/sellers/orders/shipments"
    params = {'orderItemsIds': ','.join(orderItemIds)}
    return self.session.get(url, params=params)

rawDescription: pass a string in python requests

description: Pass a string in python requests


code:
a='dqdwqfwqfggqwq'
dict((letter,a.count(letter)) for letter in set(a))

rawDescription: how to get the number of occurrences of each character using python

description: Get the number of occurrences of each character using python


code:
from itertools import repeat

# determine the classes that were not present in the training set;
# the ones that were are listed in clf.classes_.
classes_not_trained = set(clf.classes_).symmetric_difference(all_classes)

# the order of classes in predict_proba's output matches that in clf.classes_.
prob = clf.predict_proba(test_samples)
for row in prob:
    prob_per_class = (zip(clf.classes_, prob)
                    + zip(classes_not_trained, repeat(0.)))

rawDescription: Training a sklearn LogisticRegression classifier without all possible labels


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.text = tk.Text(self, wrap="none")
        xsb = tk.Scrollbar(self, orient="horizontal", command=self.text.xview)
        ysb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
        self.text.configure(yscrollcommand=ysb.set, xscrollcommand=xsb.set)
        ysb.grid(row=0, column=1, sticky="ns")
        xsb.grid(row=1, column=0, sticky="ew")
        self.text.grid(row=0, column=0, sticky="nsew")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        self.text.tag_configure("keyword", foreground="#b22222")

        # this probably isn't what you want to do in production,
        # but it's good enough for illustrative purposes
        self.text.bind("<Any-KeyRelease>", self.highlight)
        self.text.bind("<Any-ButtonRelease>", self.highlight)

    def highlight(self, event=None):
        self.text.tag_remove("keyword", "1.0", "end")

        count = tk.IntVar()
        self.text.mark_set("matchStart", "1.0")
        self.text.mark_set("matchEnd", "1.0")

        while True:
            index = self.text.search("print", "matchEnd","end", count=count)
            if index == "": break # no match was found

            self.text.mark_set("matchStart", index)
            self.text.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
            self.text.tag_add("keyword", "matchStart", "matchEnd")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Match Tkinter Text tag to string?

description: Match Tkinter Text tag to string


code:
images = []
for image_name in image_names:
    images.append(pygame.image.load(image_name))

background = pygame.display.get_surface()
for image in images:
    back.blit(image, image_position) # how you compute the image position is your stuff ;)

pygame.display.update()

rawDescription: Building a background image from smaller images in PyGame


code:
s = '/foo/bar/zoo/file.ext'
import ntpath
import os
s.replace(os.sep,ntpath.sep)

rawDescription: change format of path string to a different os

description: Change format of path string to a different os


code:
var1 = var2 = var3 = None
# code that might change the value of three variables mentioned above
myvar = var1 or var2 or var3

rawDescription: Assigning one of multiple values based on what exists


code:
def nearby_grid_points(x, y, r=1):
    res = []
    for dy in xrange(-r, r+1):
        res.append([(x+dx, y+dy) for dx in xrange(-r, r+1)])
    return res

rawDescription: Python / Pygame - Nearest Coordinates on Grid


code:
class Mammal(object):

    def __init__(self):
        self.blood_sample = 42
        self.dna_sequence = None

    def get_dna_sequence(self):
        if self.dna_sequence == None:
            self.generate_dna_sequence(self.blood_sample)
        return self.dna_sequence

    def generate_dna_sequence(self, blood_sample=None):
        self.dna_sequence = stuff_to_generate_sequence(blood_sample)

class Human(Mammal):
    def __init__(self):
          super(Mammal, self).__init__()
          self.blood_sample = 43

rawDescription: How to set up attributes in Python classes

description: Set up attributes in Python classes


rawDescription: Trying to populate DataFrame via a multiindex slice causes NaNs in Python 3.5 (worked in 2.7)


code:
import numpy as np
matrix=np.random.random((10,10,42))
nx,ny,nz=np.shape(matrix)
CXY=np.zeros([ny, nx])
for i in range(ny):
    for j in range(nx):
        CXY[i,j]=np.max(matrix[j,i,:])

#Binary data
np.save('maximums.npy', CXY)

#Human readable data
np.savetxt('maximums.txt', CXY)

rawDescription: Save a numpy matrix

description: Save a numpy matrix


code: LOG_LEVEL = 'INFO'

rawDescription: Scrapy: how to disable or change log?

description: Scrapy: how to disable or change log


code: np.count_nonzero(A != B)

rawDescription: Count of unequal elements across numpy arrays


code:
import pygame

srf = pygame.display.set_mode((640,480))
pixels = pygame.surfarray.pixels2d(srf)
pixels ^= 2 ** 32 - 1
del pixels

pygame.display.flip()

rawDescription: How to invert colors of an image in pygame?

description: Invert colors of an image in pygame


code:
class A(object):
    @property
    def x(self):
        return [1]
class B(A):
    @property
    def x(self):
        return super(B, self).x + [2]
b = B()
b.x

rawDescription: How do inherit list items in Python?

description: How do inherit list items in Python


code:
def search(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        q_school = Lawyer.objects.filter(last__icontains=q).values_list('school', flat=True)
        q_year = Lawyer.objects.filter(last__icontains=q).values_list('year_graduated', flat=True)
        lawyers = Lawyer.objects.filter(school__icontains=q_school[0]).filter(year_graduated__icontains=q_year[0])
        return render_to_response('search_results.html', {'lawyers': lawyers, 'query': q})
    else:
        return HttpResponse('Please submit a search term.')

rawDescription: How to refine an initial query in Django?

description: Refine an initial query in Django


code:
class Foo(object):
    def aninstancemethod(self):
        pass

    @classmethod
    def aclassmethod(cls):
        pass

    @staticmethod
    def astaticmethod():
        pass

rawDescription: Why always add self as first argument to class methods?


code:
import itertools as it
a = [1091, 2053, 4099, 4909, 5023, 9011]
sort_string = lambda x: sorted(str(x))
[[int(x) for x in v] for k,v in it.groupby(sorted(a, key=sort_string), key=sort_string)]
# [[1091, 9011], [2053, 5023], [4099, 4909]]

rawDescription: Group numbers if they are permutations of each other in Python


rawDescription: Matplotlib imshow() stretch to "fit width"


code:
import IPython.nbformat.current as nbf
nb = nbf.read(open('test.py', 'r'), 'py')
nbf.write(nb, open('test.ipynb', 'w'), 'ipynb')

rawDescription: Converting to (not from) ipython Notebook format


code:
def all_triangle_numbers(n):
    for i in range(1, n + 1):
        print("n = {0}, triangle = {1}".format(i, (i ** 2 + i)//2))

all_triangle_numbers(10)

rawDescription: Triangular Numbers Using Loops (Python)

description: Triangular Numbers Using Loops (Python)


code: df.groupby('product').apply(lambda x: np.std(x) / np.mean(x))

rawDescription: Group a dataframe and calculate normalised standard deviation by group?


rawDescription: Pandas Dataframe from NumPy array - incorrect datatypes and can't change


code:
plt.figure(figsize=(29, 9))
hours = 24
mins = 60
xlabels = ['%02d:%02d' % (divmod(i, 60)) for i in range(0, mins * hours, 10)]
plt.xlim(0, hours * mins)
plt.ylim(0,6)
xdata_org = ['04:04', '13:22']
ydata = [5, 1]
def get_min(time):
    l = time.split(':')
    return int(l[0]) * 60 + int(l[1])
xdata = [get_min(i) for i in xdata_org]
plt.bar(xdata, ydata, width=1)
plt.xticks(range(0, hours * mins, 10), xlabels, rotation='vertical', fontsize=9)
plt.subplots_adjust(left=0.05, right=0.95, bottom=0.3)

rawDescription: python matplot of events each minute

description: Python matplot of events each minute


code:
import subprocess
import os

fifo_name = 'my-bash.rc'
os.mkfifo(fifo_name)

try:
    process = subprocess.Popen(['bash', '--rcfile', fifo_name])
    with open(fifo_name, 'w') as f:
        f.write('echo "This is my-bash.rc"')
    process.wait()
finally:
    os.remove(fifo_name)

rawDescription: How to create a Filehandle in memory and pass to an external command in Python

description: Create a Filehandle in memory and pass to an external command in Python


code:
import datetime
dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
dtnow
dtutcnow
delta = dtnow - dtutcnow
delta
hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
hh,mm
"%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)

rawDescription: How to get an isoformat datetime string including the default timezone?

description: Get an isoformat datetime string including the default timezone


code:
from tkinter import *

Round=0

def button(type):
    global Round
    print (str(type))
    x = type
    Round += type

def win():
    window = Tk()
    window.geometry ('500x500')
    window.title('HELLO')
    blackB = Button(text = 'BLACK', command=lambda: button(0), width=7, height=3, bd=5)
    blackB.place(x=1, y=1)
    brownB = Button(text = 'BROWN', command=lambda: button(1), width=7, height=3, bd=5)
    brownB.place(x=86, y=1)
    redB = Button(text = 'RED', command=lambda: button(2), width=7, height=3, bd=5)
    redB.place(x=172, y=1)
    window.mainloop

win()

rawDescription: Tkinter wit while loop (python 3)

description: Tkinter wit while loop (python 3)


code:
import numpy as np
example = np.arange(9).reshape(3,3)/4.0
example
a = 2 # sample exponent
np.where(example < 1, 1, example**a)

rawDescription: How to make a matrix to the power of a number under some conditions without using loops in Python?

description: Make a matrix to the power of a number under some conditions without using loops in Python


code:
x = bananax
y = bananay

#------ fit a spline to the coordinates, x and y axis are interpolated towards t
t = np.arange(x.shape[0], dtype=float) #t is # of values
t /= t[-1] #t is now devided from 0 to 1
nt = np.linspace(0, 1, 100) #nt is array with values from 0 to 1 with 100 intermediate values

x1 = scipy.interpolate.spline(t, x, nt) #The x values where spline should estimate the y values
y1 = scipy.interpolate.spline(t, y, nt)

#------ create a new linear space for nnt in which an extrapolation from the interpolated spline will be made
nnt = np.linspace(-1, 1, 100) #values <0 are extrapolated (interpolation started at the tip(=0)

x1fit = np.polyfit(nt,x1,3) #fits a polynomial function of the nth order with the spline as input, output are the function parameters
y1fit = np.polyfit(nt,y1,3)

xpoly = np.poly1d(x1fit) #genereates the function based on the parameters obtained by polyfit
ypoly = np.poly1d(y1fit)

rawDescription: Extrapolation from curved datapoints

description: Extrapolation from curved datapoints


code:
c_array = numpy.ascontiguousarray(param, dtype=int)
pointer = c_array.ctypes.data_as(ctypes.c_void_p)

rawDescription: Most efficient way to convert a multidimensional numpy array to ctypes array


code:
from django.contrib import admin
from testapp.models import MyModel1, MyModle2

admin.site.register(MyModel1)
admin.site.register(MyModel2)

rawDescription: Django site administration can't manage data models


code:
import numpy as np    # requires NumPy 1.7 (!)

def select_random(object_dict, n):
    keys = object_dict.keys()
    rate = np.array([x.rate for x in keys])
    prob = rate / rate.sum()
    return np.random.choice(keys, size=n, replace=True, p=prob)

rawDescription: Python not quite random sampling from a list of objects


code: soup.findAll('p', limit=3)

rawDescription: Does Python have something like LINQ to XML


code:
padx = 10
pady = 10
Button(...).pack(padx=padx, pady=pady)

rawDescription: How to set padding of all widgets inside a window or frame in Tkinter

description: Set padding of all widgets inside a window or frame in Tkinter


code:
import os
path = os.path.abspath(__file__)

rawDescription: Get absolute path of caller file

description: Get absolute path of caller file


code:
super_list = []
list1 = [1,2,3]
list2 = [4,5,6]
super_list.append(list1)
super_list.append(list2)
super_list

rawDescription: Copy reference and concatenate lists

description: Copy reference and concatenate lists


code:
from datetime import datetime
d = datetime.strptime("10:30", "%H:%M")
d.strftime("%I:%M %p")
d = datetime.strptime("22:30", "%H:%M")
d.strftime("%I:%M %p")

rawDescription: How can I convert 24 hour time to 12 hour time?

description: Convert 24 hour time to 12 hour time


code: vw_dist = dist[v] + edgedata.get(weight,1)

rawDescription: networkx: edge weight as a calculated value

description: Networkx: edge weight as a calculated value


code:
lines = file.readlines()
for index, line in enumerate(lines):
    if 'characters' in line:
        lines[index] = 'edited line'

rawDescription: Python edit line containing specific characters


code: bytes(map(ord, u'\xf4\xfb\xe2'))

rawDescription: Convert faulty unicode string to bytes

description: Convert faulty unicode string to bytes


code:
class EditableListCtrl(wx.ListCtrl, listmix.TextEditMixin):
    def __init__(self, parent, ID=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0):
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        listmix.TextEditMixin.__init__(self)
        self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginLabelEdit)

    def OnBeginLabelEdit(self, event):
        if event.m_col == 1:
            event.Veto()
        else:
            event.Skip()

rawDescription: wx.ListCtrl with TextEditMixin - Disable Editing of Selected Cells

description: Wx.ListCtrl with TextEditMixin - Disable Editing of Selected Cells


code: credit_card[1::2] = [x*2 for x in credit_card[1::2]]

rawDescription: Multiplying every second number in a list


code:
from werkzeug.wrappers import Request
req = Request(environ, shallow=True)

rawDescription: How to access request in Flask MIddleware

description: Access request in Flask MIddleware


code:
def your_has_perm(user, perm, obj):
    has = user.has_perm(perm, obj)

    if not has and hasattr(obj, 'parent'):
        return your_has_perm(user, perm, obj.parent)

    return has

rawDescription: Object level cascading permission in Django


code:
import numpy as np
import bokeh.plotting as bk

p = bk.figure()

# Vertical line
vline = Span(location=0, dimension='height', line_color='red', line_width=3)
# Horizontal line
hline = Span(location=0, dimension='width', line_color='green', line_width=3)

p.renderers.extend([vline, hline])
bk.show(p)

rawDescription: Infinite horizontal line in Bokeh

description: Infinite horizontal line in Bokeh


rawDescription: How to record the activity name via AndroidViewClient/Culebra

description: Record the activity name via AndroidViewClient/Culebra


rawDescription: apply pandas qcut function to subgroups

description: Apply pandas qcut function to subgroups


code:
def square(cell):
    rows = 'ABCDEFGHI'

    cell_row = rows.index(cell[0][0])
    cell_col = int(cell[0][1]) - 1

    return 3 * (cell_row // 3) + cell_col // 3 + 1

rawDescription: Python - Streamlining sudoku solver code


code:
import Gnuplot
g=Gnuplot.Gnuplot()
y1= [12, 15, 17, 19]
y2= [34, 78, 54, 67]
x= [10, 20, 30, 40]
d1=Gnuplot.Data(x,y1,with_="line")
d2=Gnuplot.Data(x,y2,with_="line")
#g.plot(d1,d2)   #uncomment this line if you want to see the gnuplot window
g.hardcopy('filename.png',terminal = 'png')

rawDescription: Gnuplot python with 2 list

description: Gnuplot python with 2 list


code:
# my_spider.py
class MySpider(CrawlSpider):
    name = 'my_spider'
    ...

    def parse(self, response):
        x = HtmlXPathSelector(response)

        headings = x.select('//h2/text()').extract()
        for h in headings:
            item = MyDjangoItem()
            item['name'] = h
            yield item

        url = 'http://example.com/next'  # I have custom rules for constructing (not extracting) next url
        yield Request(url, callback=self.parse)

rawDescription: Scrapy spider yields several items but pipeline is called only for first per request


code:
k = {'finance_pl':{'S':{'2008':45,'2009':34}}}
ui = 'finance_pl.S'
def getter(adict, key):
    return reduce(dict.get, key.split('.'), adict)

getter(k, ui)

rawDescription: Python List to access dict directly

description: Python List to access dict directly


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

lowerBound = 0.25
upperBound = 0.75
myMatrix = np.random.rand(100,100)

myMatrix =np.ma.masked_where((lowerBound < myMatrix) &
                             (myMatrix < upperBound), myMatrix)

fig,axs=plt.subplots(2,1)
#Plot without mask
axs[0].imshow(myMatrix.data)

#Default is to apply mask
axs[1].imshow(myMatrix)

plt.show()

rawDescription: Matplotlib imshow: how to apply a mask on the matrix


code:
user = User.objects.get(username__iexact='username')
return render_to_response('timeline.html', {'tweets': user.tweets})

rawDescription: 'User' object is not iterable

description: 'User' object is not iterable


code:
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials

json_key = json.load(open('credentials.json'))
scope = ['https://spreadsheets.google.com/feeds']

credentials = SignedJwtAssertionCredentials(
    json_key['client_email'], json_key['private_key'], scope)

gc = gspread.authorize(credentials)

wks = gc.open('PracticeOpsBS')

rawDescription: Gspread to access google spreadsheet: HttpAccessTokenRefreshError, invalid JWT


code:
def _amount_insurance(self, cr, uid, ids, val1, context=None):
    val = 0.0
    for insurance in self.browse(cr, uid, ids,context=context):
        if insurance.xx_insurance_type:
            val = (val1 * (insurance.xx_insurance_type.insurance_percentage/100))
    return val

rawDescription: odoo - get value from many2one field

description: Odoo - get value from many2one field


code:
catch = False
mylist = []
with open("myfile.txt", "r") as f:
    content = f.readlines()
for line in content:
    if line.startswith("<Vertex>"):
        catch = True
        continue
    if catch:
        catch = False
        mylist.append(line)

rawDescription: How can I put certain lines of text from a text file into a list with Python?

description: Put certain lines of text from a text file into a list with Python


code:
named = dict()
unnamed = dict()
all = mo.groups()

# Index every named group by its span
for k,v in mo.groupdict().items():
    named[mo.span(k)] = v

# Index every other group by its span, skipping groups with same
# span as a named group
for i,v in enumerate(all):
    sp = mo.span(i + 1)
    if sp not in named:
        unnamed[sp] = v

print(named)   # {(8, 9): '%'}
print(unnamed) # {(4, 8): '2321', (0, 4): 'aaba'}

rawDescription: Get all unnamed groups in a Python match object


code:
def process_item(self, item, spider):
    return sorted(item['body'])

rawDescription: How to use output processor in ItemLoader from Scrapy to sort a list?

description: Use output processor in ItemLoader from Scrapy to sort a list


code:
x = '3'
number_list = []

for i in range(1,10001):
        number_list.append(str(i))

x_numbers = [y for y in number_list if x in y]

print(len(x_numbers))

rawDescription: If number in range(x, y) contains digit, print number(s)


code:
class Foo:
    def __init__(self,blah):
            self.blah=blah

foo = Foo("Something")
foo.blah
setattr(foo,'blah','somethingElse')
foo.blah

rawDescription: Python: __setattr__ for old-style classes?


code:
# Sample code that connects to Google Drive

from apiclient.discovery import build
import httplib2
from oauth2client.client import SignedJwtAssertionCredentials, VerifyJwtTokenError

SERVICE_EMAIL = "you@gmail.com"
PRIVATE_KEY_PATH ="./private_key.p12"

# Load private key
key = open(PRIVATE_KEY_PATH, 'rb').read()

# Build the credentials object
credentials = SignedJwtAssertionCredentials(SERVICE_EMAIL, key, scope='https://www.googleapis.com/auth/drive')

try:
  http = httplib2.Http()
  http = credentials.authorize(http)
except VerifyJwtTokenError as e:
  print(u"Unable to authorize using our private key: VerifyJwtTokenError, {0}".format(e))
  raise

connection = build('drive', 'v2', http=http)

# You can now use connection to call anything you need for freebase - see their API docs for more info.

rawDescription: Authorization headaches for Freebase API (Python)


code:
Databis
Databis
Databis

rawDescription: Apply functon with a condition on the first row


code:
class ShowroomAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "stock_car":
            kwargs["queryset"] = Car.objects.filter(status='ACTIVE')
        return super(ShowroomAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

rawDescription: How to use ManyToManyField with condition

description: Use ManyToManyField with condition


code:
users = [
    {
        'id': 232,
        'name': 'jon',
        'parent': None
    },
    {
        'id': 3522,
        'name': 'dave',
        'parent': 232
    },
    {
        'id': 2277,
        'name': 'alice',
        'parent': 3522
    },
    {
        'id': 119,
        'name': 'gary',
        'parent': 232
    },
    {
        'id': 888,
        'name': 'gunthe',
        'parent': 119
    },
    {
        'id': 750,
        'name': 'beavis',
        'parent': None
    },
    {
        'id': 555,
        'name': 'urte',
        'parent': 750
    }
]

users_map = {}
for user in users:
    users_map[user['id']] = user

users_tree = []
for user in users:
    if user['parent'] is None:
        users_tree.append(user)
    else:
        parent = users_map[user['parent']]
        if 'childs' not in parent:
            parent['childs'] = []
        parent['childs'].append(user)

print(users_tree)

#user as {data: user, childs: []}

users_map = {}
for user in users:
    users_map[user['id']] = {'data': user, 'childs': []}

users_tree = []
for user in users:
    if user['parent'] is None:
        users_tree.append(users_map[user['id']])
    else:
        parent = users_map[user['parent']]
        parent['childs'].append(users_map[user['id']])

print(users_tree)

rawDescription: How to build a recursive dictionary tree from an ordered adjacency list

description: Build a recursive dictionary tree from an ordered adjacency list


code:
import inspect
import sys

def main():
    # sys.modules contains a mapping between module names and module
    # objects, but many more than the one imported in a file. dir()
    # returns a list of names available to the local scope (also variables
    # functions etc.). Combine those two and you get the modules available
    # to the local scope
    modules = [sys.modules[i] for i in dir() if i in sys.modules]
    files = []
    code = []
    for module in modules:
        try:
            # modules may have a __file__ attribute
            files.append(module.__file__)
            # get's you the actual code
            code.append(inspect.getsource(module))
        except:
            pass
    print(files, code)

if __name__ == '__main__':
    main()

rawDescription: Getting paths to code of imported modules


code:
from multiprocessing import Pool
from contextlib import closing

def f(n):
    return n * 2

def g(args):
    id_, n = args
    return id_, -n

if __name__ == "__main__":
    cases = range(5)
    # Pool automatically uses the same number of subprocesses as cpu_count
    with closing(Pool()) as pool:
        arr = pool.map(f, cases)
    print(arr) # prints [0, 2, 4, 6, 8]

    arr = [None] * len(cases)
    with closing(Pool()) as pool:
        for idx, result in pool.imap_unordered(g, enumerate(cases)):
            arr[idx] = result
    print(arr) # prints [0, -1, -2, -3, -4]

rawDescription: Why are arrays not passed by reference when using Multiprocessing in Python?


code:
from scrapy.conf import settings
settings.get('QA', False)

rawDescription: How do I set a custom flag in Scrapy project?

description: Set a custom flag in Scrapy project


code:
#!/usr/bin/python

import sqlite3
import peewee
from peewee import *
from playhouse.proxy import *

database_a_proxy = Proxy()
database_b_proxy = Proxy()

class BaseModelA(Model):
    class Meta:
            database = database_a_proxy

class BaseModelB(Model):
    class Meta:
            database = database_b_proxy

class RelationInSchemaA(BaseModelA):
    textfield = CharField()

class RelationInSchemaB(BaseModelB):
    textfield = CharField()

database_a = SqliteDatabase('schemaA', **{})
database_b = SqliteDatabase('schemaB', **{})

database_a_proxy.initialize(database_a)
database_b_proxy.initialize(database_b)

try:
   RelationInSchemaA.create_table()
   RelationInSchemaB.create_table()
except:
   pass

RelationInSchemaA.create(textfield='Hello')
RelationInSchemaB.create(textfield='PeeWee')

rawDescription: How to query several similar databases using Peewee?

description: Query several similar databases using Peewee


rawDescription: Python Pandas - Mutiple assignment

description: Python Pandas - Mutiple assignment


code:
import ast
s = "['name2', 'name3']"
s
l = ast.literal_eval(s)
l
type(l)

rawDescription: How to handle lists as single values in csv with Python

description: Handle lists as single values in csv with Python


code:
def get_admin_urls(urls):
    def get_urls():
        my_urls =  patterns('',
           url(r'^$', YourCustomView,name='home'),
        )
        return my_urls + urls
    return get_urls

admin.autodiscover()

admin_urls = get_admin_urls(admin.site.get_urls())
admin.site.get_urls = admin_urls

rawDescription: Django - custom admin page not releated to a model


code:
from pylab import *
import matplotlib.colors

figure(figsize=(3,9))
Z = rand(6,10)

subplot(3,1,1)
c = pcolor(Z)
title('default: no edges')

subplot(3,1,2)
c = pcolor(Z, edgecolors='k', linewidths=4)
title('thick edges')
# use Z values greater than 0.5 as an example
Zbool = Z > 0.5

subplot(3,1,3)
cmap = matplotlib.colors.ListedColormap(['red','grey'])
c = pcolor(Zbool, edgecolors='k', linewidths=4, cmap=cmap)
title('thick boolean edges gray')

show()

rawDescription: setting colours in matplotlab pcolor

description: Setting colours in matplotlab pcolor


code:
import urllib2

request = urllib2.Request('http://maps.google.com/maps/feeds/maps/default/full')
request.add_header('Authorization', 'GoogleLogin auth=%s' % authorization_token)
urllib2.urlopen(request).read()

rawDescription: Using GET and POST with Autorization HTTP header in Python


code:
def timezone_window(self):
    tree = etree.parse("timezones.xml")
    root = tree.getroot()

    self.header_label.set_text("Configure your Timezone")

    scrolledwindow = Gtk.ScrolledWindow()
    scrolledwindow.set_vexpand(True)

    liststore_timezone = Gtk.ListStore(str)

    render = Gtk.CellRendererText()
    col_timezones = Gtk.TreeViewColumn("Timezones",render,text=0)

    treeview_timezone = Gtk.TreeView(liststore_timezone)

    treeview_timezone.set_model(liststore_timezone)
    treeview_timezone.append_column(col_timezones)

    for child in root:
        liststore_timezone.append([child.find('timezone_name').text])

    scrolledwindow.add(treeview_timezone)
    self.main_info_box.pack_start(scrolledwindow, False, False, 0)
    treeview_timezone.show()
    scrolledwindow.show()

rawDescription: Show a TreeView inside a Box after destroy what was inside of that Box (GTK+)


code:
main_array = [[1,2,3,4], [4,5,6,7]]
res = [func(l) for l in main_array for func in (min, max)]
print(res)

rawDescription: Finding the minimum and maximum of a list of arrays


code:
from System.Diagnostics import Process
p = Process()
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.FileName = 'uname'
p.StartInfo.Arguments = '-m -r'
p.Start()
p.WaitForExit()
p.StandardOutput.ReadToEnd()
p.ExitCode

rawDescription: How to run OS shell commands in IronPython/Mono?

description: Run OS shell commands in IronPython/Mono


code:
cat_image = "cat.png"
mouse_c = pygame.image.load(mouse_image).convert_alpha()

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

 x,y = pygame.mouse.get_pos()
 x -= mouse_c.get_width()/2
 y -= mouse_c.get_height()/2

 screen.blit(mouse_c,(x,y))

 pygame.display.update()

rawDescription: How do I set the position of my mouse cursor on the center of an object in pygame?

description: Set the position of my mouse cursor on the center of an object in pygame


code: row = ["ID:1100", "AGE:25-34", "Occupation:IT", "Gender:M", "Product_range:50-60", "Product_cat:Gaming", "Product:XPS 6610"]

rawDescription: How to do column wise intersection with itertools

description: Do column wise intersection with itertools


code:
import matplotlib.pyplot as plt
im = plt.imread(image_name)
implot = plt.imshow(im)

# put a blue dot at (10, 20)
plt.scatter([10], [20])

# put a red dot, size 40, at 2 locations:
plt.scatter(x=[30, 40], y=[50, 60], c='r', s=40)

plt.show()

rawDescription: How do you directly overlay a scatter plot on top of a jpg image in matplotlib / Python?

description: Directly overlay a scatter plot on top of a jpg image in matplotlib / Python


code:
h1 = Image.open("image1").histogram()
h2 = Image.open("image2").histogram()

rms = math.sqrt(reduce(operator.add,
    map(lambda a,b: (a-b)**2, h1, h2))/len(h1))

rawDescription: Compare two images the python/linux way

description: Compare two images the python/linux way


code: any_item_is_whatever = any(item.is_whatever() for item in items)

rawDescription: Is this is an efficient and pythonic way to see if any item in an iterable is true for a certain attribute?


code:
def supplier_default_product(region, supplier=None):
    if supplier is None:
        supplier = region.default_supplier.id
    default_product_instance = Product.objects.get(name=default_product, supplier=supplier)

rawDescription: Use a parameter attribute as a default value for another parameter?


rawDescription: How to return values in dictionary?

description: Return values in dictionary


code:
# The script MUST contain a function named azureml_main
# which is the entry point for this module.
#
# The entry point function can contain up to two input arguments:
#   Param<dataframe1>: a pandas.DataFrame
#   Param<dataframe2>: a pandas.DataFrame
import csv
import numpy as np
import pandas as pd

def azureml_main(dataframe1 = None, dataframe2 = None):
    # Execution logic goes here
    #print('Input pandas.DataFrame #1:\r\n\r\n{0}'.format(dataframe1))

    # If a zip file is connected to the third input port is connected,
    # it is unzipped under ".\Script Bundle". This directory is added
    # to sys.path. Therefore, if your zip file contains a Python file
    # mymodule.py you can import it using:
    # import mymodule

    apple = {}
    microsoft = {}
  #Reading from the csv files
    with open('.\Script Bundle\\apple.csv', 'rb') as f:
      reader = csv.reader(f)
      apple = list_to_dict(list(reader)[0])

    with open('.\Script Bundle\\microsoft.csv', 'rb') as f:
      reader = csv.reader(f)
      microsoft = list_to_dict(list(reader)[0])

#    print('hello world'+ ' '.join(apple[0]))
    applecount =0
    microsoftcount = 0

    input ="i want to buy surface which runs on windows";
    splitted_input = input.split(' ');

    for word in splitted_input:
      if word in apple:
        applecount=applecount+1
      if word in microsoft:
        microsoftcount=microsoftcount+1

    print("apple bag of words count - "+str(applecount));
    print("microsoft bag of words count - "+str(microsoftcount));
    mydata=[{'input words': len(splitted_input)},{'applecount':applecount},{'microsoftcount':microsoftcount}]
    # Return value must be of a sequence of pandas.DataFrame
    return pd.DataFrame(mydata),

def list_to_dict(li):
    dct = {}
    for item in li:
        if dct.has_key(item):
            dct[item] = dct[item] + 1
        else:
            dct[item] = 1
    return dct

rawDescription: Not Getting the Expected Output in AzureML


code:
def chopper(array, val):
    edges = (0, len(array))
    while True:
        m = sum(edges)/2
        edges = (edges[0], m) if array[m] >= val else (m+1, edges[1])
        yield edges

def chopSearch(array, val):
    for l, r in chopper(array, val):
        if array[l] == val:
            return l
        if l==r:
            return -1

rawDescription: Binary search implementations

description: Binary search implementations


code:
from django.contrib.auth import login

def monkey_patch_login(request, user):
    """
    Persist a user id and a backend in the request. This way a user doesn't
    have to reauthenticate on every request. Note that data set during
    the anonymous session is retained when the user logs in.
    """
    session_auth_hash = ''
    if user is None:
        user = request.user
    if hasattr(user, 'get_session_auth_hash'):
        session_auth_hash = user.get_session_auth_hash()

    if SESSION_KEY in request.session:
        if _get_user_session_key(request) != user.pk or (
                session_auth_hash and
                request.session.get(HASH_SESSION_KEY) != session_auth_hash):
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
    request.session[BACKEND_SESSION_KEY] = user.backend
    request.session[HASH_SESSION_KEY] = session_auth_hash
    if hasattr(request, 'user'):
        request.user = user
    rotate_token(request)

login = monkey_patch_login

rawDescription: How to disconnect update_last_login?

description: Disconnect update_last_login


code:
import pandas as pd
from StringIO import StringIO
s = """1, 2
3, 4
5, 6"""
pd.read_csv(StringIO(s), skiprows=[1], header=None)
pd.read_csv(StringIO(s), skiprows=1, header=None)

rawDescription: Skip rows during csv import pandas

description: Skip rows during csv import pandas


code:
#!/usr/bin/env python2.7

from __future__ import print_function

from django.template import Template, Context
from django.conf import settings

settings.configure()

c = Context({'null': u'\x00', 'dbresult': u'\x00'})

t = Template(r"""
{% if dbresult == null %}
result is null
{% else %}
result is {{ dbresult }}
{% endif %}
""")

print(t.render(c))

rawDescription: Handling u'\x00' in django template

description: Handling u'\x00' in django template


code:
local_timezone = pytz.timezone('Asia/Kolkata')

def utc_to_ist(value):
    timestamp_utc=value
    timestamp_utc=pytz.utc.localize(timestamp_utc)
    return timestamp_utc.astimezone(local_timezone)

rawDescription: Flask Moment with Mustache

description: Flask Moment with Mustache


code:
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
'preamble': r'''
\usepackage{titlesec}
\titleformat{\section}
{\color{black}\normalfont\Large\bfseries}
{\color{black}\thesection}{1em}{}
\titleformat{\subsection}
{\color{black}\normalfont\Large\bfseries}
{\color{black}\thesubsection}{1em}{}

\usepackage{hyperref}
\hypersetup{colorlinks=true,
linkcolor=black,
citecolor=black,
filecolor=black,
menucolor=black,
urlcolor=black,
bookmarksnumbered=true
}
'''

# Latex figure (float) alignment
#'figure_align': 'htbp',
}

rawDescription: How to generate black and white pdf from sphinx?

description: Generate black and white pdf from sphinx


code:
if __name__ == "__main__":
    from multiprocessing import Process
    procs=[]
    procs.append(Process(target=unittest.main, kwargs={'verbosity':2}))
    procs.append(Process(target=unittest.main, kwargs={'verbosity':2}))
    for proc in procs:
        proc.start()
    for proc in procs:
        proc.join()

rawDescription: Python unit tests multiple threads

description: Python unit tests multiple threads


code:
import itertools
groups = itertools.groupby(reader, key=lambda row: row[3])
d = {group: [row[2] for row in rows] for (group, rows) in groups}

rawDescription: Python remove duplicates from array

description: Python remove duplicates from array


code:
import shutil

createImage(locA, filename)
shutil.move(os.path.join(locA, filename), locB)

rawDescription: Bottle.py serving larger images with a short delay results to zero length response


code: upload_url = blobstore.create_upload_url('/upload_handler', gs_bucket_name='my_bucket')

rawDescription: Upload images/video to google cloud storage using Google App Engine


code:
import glob

print(glob.glob("/dev/tty.usbmodem*"))

rawDescription: Linux and Python: auto-detect Arduino serial port


code:
import random
input("Think of a number from 1 to 10, then press enter.  Don't tell me, I'll guess it.")
low = 1
high = 10
done = False

for guesses in range(7):
    number = random.randint(low, high)
    print("I'm guessing", number)
    happy = False
    while not happy:
        resp = input('Enter H if your number is higher, L if lower or E for equal: ')[0].upper()
        if resp == 'E':
            if guesses:
                plural = 'es'
            else:
                plural = ''
            print('Yay!  I got it in {} guess{}.'.format(guesses+1, plural))
            happy = True
            done = True
            break
        elif resp == 'H':
            happy = True
            low = number + 1
        elif resp == 'L':
            happy = True
            high = number -1
        else:
            print("That wasn't a valid response.")
    if done:
        break

print('end')

rawDescription: learning python--couldn't figure out random.randint

description: Learning python--couldn't figure out random.randint


code:
#bot answers module

greetings = ["hello {0}", "what's up {0}"]
farewells = ["see you soon {0}", "nos vemos {0}"]
...

rawDescription: What is a good way to store strings in Python?


code:
import unittest

from mock import Mock, patch

import utils

class UtilsTestCase(unittest.TestCase):
    def test_some_function(self):
        user = self.user = Mock()
        user.email = 'user@example.com'
        with patch('utils.requests') as mock_requests:
            mock_requests.get.return_value = mock_response = Mock()
            mock_response.status_code = 200
            mock_response.json.return_value = {"UserId":"123456"}
            results = utils.some_function(self.user)
            self.assertEqual(results['UserId'], '123456')

rawDescription: Django unittest and mocking the requests module


code:
import random
def shuffleDeck():
    suits = {'\u2660','\u2661','\u2662','\u2663'}
    ranks = {'2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'}

    deck = []

    for suit in suits:
        for rank in ranks:
            deck.append(rank + ' ' + suit)

    random.shuffle(deck)
    return deck

def total(hand):
    values = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '1':10, 'A':14, 'K':13, 'Q':12, 'J':11}
    result = values[hand[0]]
    return result

def dealCard(deck):
    card = deck.pop(0)
    return card

def compareHands(playerOne, playerTwo):
    playerOneTotal, playerTwoTotal = total(playerOne), total(playerTwo)
    if playerOneTotal > playerTwoTotal:
        result = 1
    elif playerOneTotal < playerTwoTotal:
        result = -1
    else:
        result = 0
    return result

def war(playerOneDeck, playerTwoDeck):
    playerOneWins = 0
    playerTwoWins = 0
    ties = 0
    if len(playerOneDeck) > 0:
        playGame = input('Ready to play a round? ')
        if playGame == 'y':
            playerOneCard = dealCard(playerOneDeck)
            playerTwoCard = dealCard(playerTwoDeck)
            print('Player A: ', playerOneCard[0], '\nPlayer B: ', playerTwoCard[0])
            if compareHands(playerOneCard, playerTwoCard) == 1:
                playerOneWins += 1
                print('Winner: Player A')
            elif compareHands(playerOneCard, playerTwoCard) == -1:
                playerTwoWins += 1
                print('Winner: Player B')

            while compareHands(playerOneCard, playerTwoCard) == 0:
                ties += 1
                print('Tie')
                playerOneCard = dealCard(playerOneDeck)
                playerTwoCard = dealCard(playerTwoDeck)
                print('Player A: ', playerOneCard[0], '\nPlayer B: ', playerTwoCard[0])
                if compareHands(playerOneCard, playerTwoCard) == 1:
                    playerOneWins += 1
                    print('Winner: Player A')
                elif compareHands(playerOneCard, playerTwoCard) == -1:
                    playerTwoWins += 1
                    print('Winner: Player B')

            war(playerOneDeck, playerTwoDeck)

    else:
        print('End of game.  Player A won {} rounds and Player B won {} rounds.'.format(playerOneWins, playerTwoWins))

deck = shuffleDeck()
playerOneDeck = deck[26:]
playerTwoDeck = deck[:26]
war(playerOneDeck, playerTwoDeck)

rawDescription: Program not looping properly when cards are a tie in Python


code:
def function(input):
    data = input.txt
    A = re.search(r'(re)(ge)(x1)',data).group(2)

    gb = re.search(r'(re)(ge)(x2)',data)
    B = gb.group(2) if gb else ""

    gc = re.search(r'(re)(ge)(x3)',data)
    C = gc.group(2) if gc else ""

    return "%stext%s%s" % (A, B, C)

rawDescription: Optionally return variables if a regex fails in Python?


code:
class View(Frame):
        def __init__(self,master = None):
                Frame.__init__(self)
                self.master.title("teste")
                self.create_menu()
        def create_menu(self):#,width = self.width,height = self.height):
                host = "localhost"
                label_menu = Label(self.master,text = 'Login')
                label_menu.pack()

                self.entrada_menu_login = Entry(self.master)# user
                self.entrada_menu_senha = Entry(self.master, show = "*")# passwd

                btn_login = Button(self.master,text="Logar",command = self.buttonListener) #self.show_entry_fields

                entrada_menu_login.pack()
                entrada_menu_senha.pack()
                btn_login.pack()

        def buttonListener(self):
            conn = Conexao(host,self.entrada_menu_login.get(),self.entrada_menu_senha.get(),"dsti")
            #conn = Conexao(host,"root","d04m10","dsti")
            dbcursor = conn.getConnection()
            #Do the rest of the logic you want to do.

rawDescription: Problems with MySQLdb python

description: Problems with MySQLdb python


code:
import re
s = "i got away with it, heeehe"
match = re.search("he*he", s)
match.group(0)

rawDescription: python get the part of the string matched by the regex

description: Python get the part of the string matched by the regex


rawDescription: How to compare two strings with the same letter and different number?

description: Compare two strings with the same letter and different number


code:
tr = doc.xpath("/html/body/div[1]/div[1]/table[1]/tbody/tr")
for row in tr[3:]:
    table += row.findall('td')

rawDescription: lxml length of web parsed content

description: Lxml length of web parsed content


code:
def check_negative(value):
    ivalue = int(value)
    if ivalue < 0:
         raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)
    return ivalue

parser = argparse.ArgumentParser(...)
parser.add_argument('foo', type=check_negative)

rawDescription: Using argparse, allow only positive integers


rawDescription: Pyspark: Calculating sum of two correspoding columns, based on conditions of two columns in two RDDs


code:
def backup_to_csv(request):

    output = StringIO.StringIO() ## temp output file
    writer = csv.writer(output, dialect='excel')

    #code for writing csv file go here...

    response = HttpResponse(mimetype='application/zip')
    response['Content-Disposition'] = 'attachment; filename=backup.csv.zip'

    z = zipfile.ZipFile(response,'w')   ## write zip to response
    z.writestr("filename.csv", output.getvalue())  ## write csv file to zip

    return response

rawDescription: Confused about making a CSV file into a ZIP file in django


code:
import ftplib

# create a new FTP() instance
f = ftplib.FTP()

# connect to our FTP site
f.connect(host,port)

# log into the FTP site
f.login(username, password)

rawDescription: Connecting to FTP with Python Specifying Port and USN/Passwd


code:
if price.string is None:
    price_text = u' '.join(price.stripped_strings).replace('"', '').encode('utf8')
else:
    price_text = unicode(price.string).strip().encode('utf8')

rawDescription: Issue in scraping data from a html page using beautiful soup


code:
scrollArea = QtGui.QScrollArea(MainWindow)
scrollContent = QtGui.QWidget()
scrollArea.setGeometry(0, 0, 700, 600)
scrollContent.setGeometry(0, 0, 680, 25000)
# Here I add all the content. E.g. label = QtGui.QLabel(scrollContent)
scrollArea.setWidget(scrollContent)

rawDescription: Using exact positions for PushButtons and still be able to scroll through them


code:
# -*- encoding: utf-8 -*-
'''
Python >= 2.4
Django >= 1.0

Author: eu@rafaelsdm.com
'''
from django.core.cache import cache

def cache_per_user(ttl=None, prefix=None, cache_post=False):
    '''Decorador que faz cache da view pra cada usuario
    * ttl - Tempo de vida do cache, não enviar esse parametro significa que o
      cache vai durar até que o servidor reinicie ou decida remove-lo
    * prefix - Prefixo a ser usado para armazenar o response no cache. Caso nao
      seja informado sera usado 'view_cache_'+function.__name__
    * cache_post - Informa se eh pra fazer cache de requisicoes POST
    * O cache para usuarios anonimos é compartilhado com todos
    * A chave do cache será uma das possiveis opcoes:
        '%s_%s'%(prefix, user.id)
        '%s_anonymous'%(prefix)
        'view_cache_%s_%s'%(function.__name__, user.id)
        'view_cache_%s_anonymous'%(function.__name__)
    '''
    def decorator(function):
        def apply_cache(request, *args, **kwargs):
            # Gera a parte do usuario que ficara na chave do cache
            if request.user.is_anonymous():
                user = 'anonymous'
            else:
                user = request.user.id

            # Gera a chave do cache
            if prefix:
                CACHE_KEY = '%s_%s'%(prefix, user)
            else:
                CACHE_KEY = 'view_cache_%s_%s'%(function.__name__, user)

            # Verifica se pode fazer o cache do request
            if not cache_post and request.method == 'POST':
                can_cache = False
            else:
                can_cache = True

            if can_cache:
                response = cache.get(CACHE_KEY, None)
            else:
                response = None

            if not response:
                response = function(request, *args, **kwargs)
                if can_cache:
                    cache.set(CACHE_KEY, response, ttl)
            return response
        return apply_cache
    return decorator

rawDescription: Django per user view caching

description: Django per user view caching


code:
from flask import app, safe_join, send_from_directory

@app.route('/<any(css, img, js, sound):folder>/<path:filename>')
def toplevel_static(folder, filename):
    filename = safe_join(folder, filename)
    cache_timeout = app.get_send_file_max_age(filename)
    return send_from_directory(app.static_folder, filename,
                               cache_timeout=cache_timeout)

@app.route('/<path:htmlfile>.html')
def toplevel_static(htmlfile):
    filename = htmlfile + '.html'
    cache_timeout = app.get_send_file_max_age(filename)
    return send_from_directory(app.template_folder, filename,
                               cache_timeout=cache_timeout)

rawDescription: flask html js css img reference 404 error

description: Flask html js css img reference 404 error


code:
soa = np.array([vec1,vec2])
X,Y,U,V = zip(*soa)
ax = plt.gca()

ax.plot(ax, rotdata[:,0], rotdata[:,1], 'o', c='b', zorder=1)
ax.quiver(X,Y,U,V, angles='xy', scale_units='xy',scale=1,
      width=.02, color='r',zorder=2)

rawDescription: Draw arrows over points

description: Draw arrows over points


code:
import numpy as np

l = np.array([[1, 3], [5, 6], [7, 2], [9, 9]])

ind = np.lexsort((l[:,0], l.sum(axis=1)))

sorted_l = l[ind]

rawDescription: Sorting numpy lists

description: Sorting numpy lists


code:
import multiprocessing as mp

def test():
    import matplotlib.pyplot as plt
    frac = [10, 10, 10, 10, 10, 10, 40]
    labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    plt.pie(frac, labels = labels, autopct='%1.1f%%')
    plt.title('test', bbox={'facecolor' : '0.8', 'pad' : 5})
    plt.show()

p1 = mp.Process(target = test)
p1.daemon = True
p1.start()
p1.join()

rawDescription: Cannot plot anything or display pylab frame in new process using python multiprocessing


code:
import re

units = ['in', 'ft']
tests = ['12in desk', '12 in desk', 'abc 20 ft long', ]
expecteds = ['12 desk', '12 desk', 'abc 20 long', ]

regexp = re.compile(r'(\d+)\s*(%s)\b' % '|'.join(units))
for test, expected in zip(tests, expecteds):
    actual = re.sub(regexp, r'\1', test)
    assert actual == expected

rawDescription: using python re to remove unit after a numeric

description: Using python re to remove unit after a numeric


code:
with open('file') as f:
    seen = set()
    for line in f:
        line_lower = line.lower()
        if line_lower in seen:
            print(line)
        else:
            seen.add(line_lower)

rawDescription: How can I find duplicate lines in a text file (excluding case) and print them?

description: Find duplicate lines in a text file (excluding case) and print them


code:
start_letter = s[0].lower()
rest_letters = s[1:].lower()

rawDescription: Unexpected output in python program

description: Unexpected output in python program