code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import csv

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QWidget):
    def __init__(self, fileName, parent=None):
        super(MyWindow, self).__init__(parent)
        self.fileName = fileName

        self.model = QtGui.QStandardItemModel(self)

        self.tableView = QtGui.QTableView(self)
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setStretchLastSection(True)

        self.pushButtonLoad = QtGui.QPushButton(self)
        self.pushButtonLoad.setText("Load Csv File!")
        self.pushButtonLoad.clicked.connect(self.on_pushButtonLoad_clicked)

        self.pushButtonWrite = QtGui.QPushButton(self)
        self.pushButtonWrite.setText("Write Csv File!")
        self.pushButtonWrite.clicked.connect(self.on_pushButtonWrite_clicked)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.tableView)
        self.layoutVertical.addWidget(self.pushButtonLoad)
        self.layoutVertical.addWidget(self.pushButtonWrite)

    def loadCsv(self, fileName):
        with open(fileName, "rb") as fileInput:
            for row in csv.reader(fileInput):
                items = [
                    QtGui.QStandardItem(field)
                    for field in row
                ]
                self.model.appendRow(items)

    def writeCsv(self, fileName):
        with open(fileName, "wb") as fileOutput:
            writer = csv.writer(fileOutput)
            for rowNumber in range(self.model.rowCount()):
                fields = [
                    self.model.data(
                        self.model.index(rowNumber, columnNumber),
                        QtCore.Qt.DisplayRole
                    )
                    for columnNumber in range(self.model.columnCount())
                ]
                writer.writerow(fields)

    @QtCore.pyqtSlot()
    def on_pushButtonWrite_clicked(self):
        self.writeCsv(self.fileName)

    @QtCore.pyqtSlot()
    def on_pushButtonLoad_clicked(self):
        self.loadCsv(self.fileName)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow("/path/to/MyFile.csv")
    main.show()

    sys.exit(app.exec_())

rawDescription: pyqt - populating QTableWidget with csv data

description: Pyqt - populating QTableWidget with csv data


code:
from argparse import RawTextHelpFormatter
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def create_parser(self, *args, **kwargs):
        parser = super(Command, self).create_parser(*args, **kwargs)
        parser.formatter_class = RawTextHelpFormatter
        return parser

rawDescription: Django command: How to insert newline in the help text?


code:
class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = ('bar',)
        read_only_fields = ('bar',) # Not required, because
                                    # SerializerMethodField is read-only already

    bar = serializers.SerializerMethodField('get_bar_dict')

    def get_bar_dict(self, obj):
        return json.loads(obj.bar)  # This gets the dict and returns it
                                    # to the SerializerMethodField above

    # Below is the rest of your code that I didn't touch
    def create(self, data):
        return Foo.objects.create(**data)

rawDescription: Django Serializer Display Model Field as Dictionary


code:
self.l.configure(text=message, font=('Arial', 30))
self.l.update_idletasks()

rawDescription: why isn't the natural height of a Frame updated immediately?

description: Why isn't the natural height of a Frame updated immediately


rawDescription: Sum of products of pairs in a list

description: Sum of products of pairs in a list


code:
for i in xrange(10):
    globals()["x%d" % i] = i

x0
x1
x2
x10

rawDescription: How to use the for statement to create thousands of variables in python

description: Use the for statement to create thousands of variables in python


code:
def foo(): pass
foo.__name__
bar = foo
bar.__name__

rawDescription: referring to the name of the decorated function inside decorator

description: Referring to the name of the decorated function inside decorator


rawDescription: Scroll to text in Tkinter

description: Scroll to text in Tkinter


code:
import datetime
from flask import Flask, render_template

app = Flask(__name__)
wsgi_app = app.wsgi_app

userInput = '07/22/2015'
targetdate = datetime.datetime.strptime(userInput, '%m/%d/%Y').date()

@app.route('/', methods=['GET','POST'])
def index():
    currentDate = datetime.date.today()
    calc = targetdate - currentDate
    msg=str(calc.days)
    return render_template('index.html', message=msg)

rawDescription: Automatically reload Python-Flask application hosted on PythonAnywhere.com


code:
right_fin = image.load('C:\\Users\\Ben\\Pictures\\right.png').convert()
right_fin = image.load('C:/Users/Ben/Pictures/right.png').convert()
right_fin = image.load(r'C:\Users\Ben\Pictures\right.png').convert()

rawDescription: File location is changed?

description: File location is changed


code:
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)

rawDescription: Can Flask post internally in python?

description: Can Flask post internally in python


code:
away = ["away1", "away2", "away3"]
home = ["home1", "home2", "home3"]
list(zip(away, home))

rawDescription: Append csv by row from two lists in Python?


code:
from subprocess import Popen, PIPE
sp = Popen(my_cmd.split(), stdin=PIPE)
sp.stdin.write('\n')
sp.wait()

rawDescription: Synchronous way to enter return key after run command in python?


code:
for index, token in enumerate(tokens):
    process_token(index, token)
...
...
def process_token(index, t):
    ...
    if t == "def":
        handle_def (index - 2, index - 1)
    ...

rawDescription: multiple occurrence of the same thing in python list

description: Multiple occurrence of the same thing in python list


code: images = [Image.open(os.path.join(path, 'my_image_%d.png' % x)) for x in range(1, 6)]

rawDescription: How to create an array of image objects to use in a FOR loop?

description: Create an array of image objects to use in a FOR loop


code: df1.merge(df2, on='n', how='outer')

rawDescription: Combining multiple DataFrames and removing identical names


code:
from bisect import bisect_left

def binary_search(a, x, lo=0, hi=None):   # can't use a to specify default for hi
    hi = hi if hi is not None else len(a) # hi defaults to len(a)
    pos = bisect_left(a,x,lo,hi)          # find insertion position
    return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end

rawDescription: Binary search (bisection) in Python

description: Binary search (bisection) in Python


code:
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it:  "export PYTHONSTARTUP=~/.pystartup" in bash.

import atexit
import os
import readline
import rlcompleter

historyPath = os.path.expanduser("~/.pyhistory")

def save_history(historyPath=historyPath):
    import readline
    readline.write_history_file(historyPath)

if os.path.exists(historyPath):
    readline.read_history_file(historyPath)

atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath

rawDescription: Give the Python Terminal a Persistent History


code:
if language == "hun":
    LOGIN_LABEL_USERNAME_STR                    = u'Felhasználó'
    LOGIN_LABEL_PASSWORD_STR                    = u'Jelszó'

rawDescription: utf-8 coding in python gui

description: Utf-8 coding in python gui


code:
import wx

app=wx.PySimpleApp()
frame=wx.Frame(None)
text=wx.StaticText(frame, label="Colored text")
text.SetForegroundColour((255,0,0)) # set text color
text.SetBackgroundColour((0,0,255)) # set text back color
frame.Show(True)
app.MainLoop()

rawDescription: Change the colour of a StaticText, wxPython


code: f = open('file.txt','rU')

rawDescription: Convert \r text to \n so readlines() works as intended


code:
class CaseFolder(models.Model):
    name = models.CharField()
    parent = models.ForeignKey('self', blank=True, related_name='subfolders')

class Document(models.Model):
    file = models.FileField(upload_to=set_upload_path)
    belongs_to = models.ForeignKey(CaseFolder)

rawDescription: Having a django model which can belong to either of two other models (foreign key relation)


code:
class MediumHandler(object):
    def __init__(self):
        self.hydro = False

    def main(self):
        self.medium = input("soil or hydro")

    def second(self):
        if self.medium == "hydro":
            self.hydro = True

handler = MediumHandler()
handler.main()
handler.second()

rawDescription: how to grab unser inputed data from one function and use in another python

description: Grab unser inputed data from one function and use in another python


code:
from itertools import permutations

original = str(input('What word would you like to unscramble?: '))

with open('dic.txt') as input_file:
    compare = input_file.readlines()

for permutation in permutations(original):
    if permuation in compare:
        print(permutation)

rawDescription: Why is my list comprehension causing the code to return my entire text document rather than only matches of words from permutations of a word?


code: canvas.roundRect(15, 625, 250, 125, 4, stroke=1, fill=0)

rawDescription: Reportlab Rounded Rect

description: Reportlab Rounded Rect


code:
from pydub import AudioSegment
sound = AudioSegment.from_file("/path/to/sound.mp3", format="mp3")

# pan 10% left
panned1 = sound.pan(-0.1)

# left channel lowered 6 dB, right channel unchanged
panned2 = sound.apply_stereo_gain(-6.0, 0.0)

rawDescription: How to specify the output channel (left,right) with pydub?

description: Specify the output channel (left,right) with pydub


code:
for x in l:
    x.func()

rawDescription: How to alter objects using map?

description: Alter objects using map


code:
import re

txt = 'me (I) you (You) him (He) her (She)'
words = re.findall('\((.+?)\)', txt)

# words returns: ['I', 'You', 'He', 'She']
with open('filename.txt', 'w') as out:
    out.write('\n'.join(words))

# file 'filename.txt' contains now:

I
You
He
She

rawDescription: Grab elements inside parentheses

description: Grab elements inside parentheses


code:
import numpy as np
np.genfromtxt("file.dat", skip_header=1, delimiter='\t')

rawDescription: Python NAN NAN NAN NAN NAN when I read a .dat file


code:
target = 'Owl'
animal = Definition.objects.get(name=target)
previous_animal = Definition.objects.order_by('name').filter(name__lt=target)[0]
next_animal = Definition.objects.order_by('name').filter(name__gt=target)[0]

rawDescription: Creating a django query that will retrieve the previous and next object based on alphabetical order


code:
#!/usr/bin/env python

# example basictreeview.py

import pygtk
pygtk.require('2.0')
import gtk

class BasicTreeViewExample:

    def set_status(self, column, cell, model, iter):
        if 'inconsistent' in model.get_value(iter, 0):
            cell.set_property('inconsistent',True)
        else:
            cell.set_property('inconsistent',False)
        return

    def delete_event(self, widget, event, data=None):
        gtk.main_quit()
        return False

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)

        self.window.set_title("Basic TreeView Example")

        self.window.set_size_request(200, 200)

        self.window.connect("delete_event", self.delete_event)

        self.treestore = gtk.TreeStore(str)

        for parent in range(4):
            piter = self.treestore.append(None, ['parent %i' % parent])
            for child in range(3):
                if child == 1:
                    self.treestore.append(piter, ['consistent'])
                else:
                    self.treestore.append(piter, ['inconsistent'])

        self.treeview = gtk.TreeView(self.treestore)

        self.tvcolumn0 = gtk.TreeViewColumn('Column 0')
        self.tvcolumn1 = gtk.TreeViewColumn('Column 1')

        self.treeview.append_column(self.tvcolumn0)
        self.treeview.append_column(self.tvcolumn1)

        self.text = gtk.CellRendererText()
        self.toggle = gtk.CellRendererToggle()

        self.tvcolumn0.pack_start(self.text, True)
        self.tvcolumn1.pack_start(self.toggle, True)

        self.tvcolumn0.add_attribute(self.text, 'text', 0)
        self.tvcolumn1.set_cell_data_func(self.toggle, self.set_status)

        self.window.add(self.treeview)

        self.window.show_all()

def main():
    gtk.main()

if __name__ == "__main__":
    tvexample = BasicTreeViewExample()
    main()

rawDescription: Setting a single row of a CellRendererToggle to inconsistent


code:
import csv

dictionary = {}
with open('data.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        dictionary[row['Key']] = row['Value']

rawDescription: Python dictionary from excel

description: Python dictionary from excel


code:
import os, time
path = os.path.expanduser('~/Desktop')
fname = time.ctime().replace(':', '-') + '.txt'
with open(os.path.join(path, fname), 'w') as f:
  pass

rawDescription: How to create a text file with the date and time as the title

description: Create a text file with the date and time as the title


code:
from scipy.stats import multivariate_normal
var = multivariate_normal(mean=[0,0], cov=[[1,0],[0,1]])
var.pdf([1,0])

rawDescription: Multivariate normal density in Python?

description: Multivariate normal density in Python


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

arr = np.zeros((21, 21))
arr[5, 5] = arr[15, 15] = 1

i, j = np.ogrid[:11, :11]
# struct = ((i-5)**2 + (j-5)**2 <= 40)
struct = np.abs(i-5)+ np.abs(j-5) <= 8

result = ndimage.binary_dilation(arr, structure=struct)
plt.imshow(result, interpolation='nearest')
plt.show()

rawDescription: Store indices of neighbouring cells which fall within a certain radius


rawDescription: Numpy time-dependent 2D matrix multiplication


code:
from time import sleep
from threading import Thread
queue = []
done = False
num_consumers = 10

def generate():
    #the generator - fill queue with values and set a flag when done
    global queue, done
    for val in permutations(allc, num):
        if len(queue) > 100:
            sleep(0.5)
            continue
        queue.append(val)
    done = True

def consume():
    #the consumer - get a value from the queue and try to login
    global queue, done
    while queue or not done:
        if len(queue) == 0:
            sleep(0.05)
            continue
        try_login(queue.pop())

#create a generator and multiple consumer threads with the respective fcts
generator = Thread(target=generate)
consumers = [Thread(target=consume) for _ in range(num_consumers)]
#start the consumers and the generator
[c.start() for c in consumers]
generator.start()

rawDescription: How to make this function faster using threads?

description: Make this function faster using threads


code:
import numpy as np
from scipy.integrate import ode
import matplotlib.pyplot as plt

def logistic(t, y, r):
    return r * y * (1.0 - y)

r = .01
t0 = 0
y0 = 1e-5
t1 = 5000.0

backend = 'dopri5'
# backend = 'dop853'
solver = ode(logistic).set_integrator(backend)

sol = []
def solout(t, y):
    sol.append([t, *y])
solver.set_solout(solout)
solver.set_initial_value(y0, t0).set_f_params(r)
solver.integrate(t1)

sol = np.array(sol)

plt.plot(sol[:,0], sol[:,1], 'b.-')
plt.show()

rawDescription: Using adaptive step sizes with scipy.integrate.ode


rawDescription: In python, how to sort list by frequency of elements


code:
a = pd.DataFrame(data=np.random.randint(0,100,(2,5)),columns=list('ABCDE'))
b = pd.DataFrame(data=np.random.randint(0,100,(2,5)),columns=list('ABCDE'))
c = pd.concat([a,b],ignore_index=True)
c

rawDescription: Stack two pandas data frames

description: Stack two pandas data frames


code:
def outer():
    def inner():
        return True
    return inner()

rawDescription: Python: Print nested function return value


code:
from collections import Counter
from random import choice

options = [1,2,3,4,5,6]

Counter(choice(options) for _ in range(1000))

rawDescription: python counter, python random list

description: Python counter, python random list


code:
class exampleForm(forms.Form):
 item_price = forms.IntegerField(label = 'item price')
 item_quantity = forms.IntegerField(label = 'quantity')
 item_total = forms.IntegerField(label = 'total')

 def clean_item_total(self):
   total = self.cleaned_data.get("item_price", 0)+self.cleaned_data.get("item_quantity", 0)
   return total

rawDescription: Django Forms : I need to add a field that is a multiple of other fields?


code:
keyBing = ''        # get Bing key from: https://datamarket.azure.com/account/keys
credentialBing = 'Basic ' + (':%s' % keyBing).encode('base64')[:-1] # the "-1" is to remove the trailing "\n" which encode adds
searchString = '%27Xbox+One%27'
top = 20
offset = 0

url = 'https://api.datamarket.azure.com/Bing/Search/Image?' + \
      'Query=%s&$top=%d&$skip=%d&$format=json' % (searchString, top, offset)

request = urllib2.Request(url)
request.add_header('Authorization', credentialBing)
requestOpener = urllib2.build_opener()
response = requestOpener.open(request)

results = json.load(response)

# process results

rawDescription: Search Bing via Azure API using Python

description: Search Bing via Azure API using Python


rawDescription: How can I mask my float number, preferably without using regex?

description: Mask my float number, preferably without using regex


code:
import datetime
df['time_as_float'] = df.index.apply(datetime.timestamp())

rawDescription: Down sampling in pandas and spline interpolation


code: [(y.upper(), y, "", x) for x, y in enumerate(["Red", "Green", "Blue"])]

rawDescription: Convert a list into a quadruple tuple sequence


code:
from mako.template import Template
Template("We display two significant digits: ${'{0:.2f}'.format(34.567645765)}").render()

rawDescription: How can I use Py3k-style string formatting within Mako templates?

description: Use Py3k-style string formatting within Mako templates


code: cell = next(row)

rawDescription: Using generators outside of a loop

description: Using generators outside of a loop


rawDescription: Include non-column value in sqlalchemy query


code:
def maximum_string(string):
    global length_counter, counter, letter
    counter = 1
    length_counter = 0
    letters_left = len(string)
    while letters_left != 0 and length_counter < len(string):
        letter = string[length_counter]
        if letter == 'C' or letter == 'A' or letter == 'K' or letter == 'E' or letter == "K":
            counter += 1
        elif letter == 'N':
            counter += 0
        else:
            counter -= 1
        length_counter += 1
        letters_left -= 1
    if ('p' in string) or ('q' in string) or ('r' in string) or ('s' in string) or ('t' in string) or ('u' in string):
        return len(string) - abs(counter)
    else:
        return 0

rawDescription: Given a String, What is the Length of the One of the Longest WFF in Polish Notation?


code:
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('email', 'first_name', 'last_name', 'website')
    search_fields = ('user__username', 'user__first_name', 'user__last_name', 'user__email')
    # list_filter = ('some_field_to_filter')
    readonly_fields = ('email', 'first_name', 'last_name')

    def email(self, obj):
        return obj.user.email
    def first_name(self, obj):
        return obj.user.first_name
    def last_name(self, obj):
        return obj.user.last_name

admin.site.register(UserProfile, UserProfileAdmin)

rawDescription: How to view (the same) data (of User) in UserProfile in Django

description: View (the same) data (of User) in UserProfile in Django


code:
for name, obj in inspect.getmembers(sys.modules['resources']):
    if inspect.isclass(obj):  # might want to add a few exclusions
        v1_api.register(obj())

rawDescription: Dynamically create Resources for multiple django models in tastypie


code:
from django.template.defaultfilters import truncatechars  # or truncatewords

class Foo(models.Model):
    description = models.TextField()

    @property
    def short_description(self):
        return truncatechars(self.description, 100)

class FooAdmin(admin.ModelAdmin):
    list_display = ['short_description']

rawDescription: How can i make djnago admin to display not more than 100 characters in tables

description: Make djnago admin to display not more than 100 characters in tables


rawDescription: Python: Splitting a string into elements and adding them in a list


code:
def drive(from_, to):
    pass

rawDescription: Is it possible to escape a reserved word in Python?


code: [x[0] for x in t if x[0] < EPS]

rawDescription: Python list compreehension with restrictions


code:
execl(file, *args)
execle(file, *args, env)
execlp(file, *args)
execlpe(file, *args, env)
execv(path, args)
execve(path, args, env)
execvp(file, args)
execvpe(file, args, env)

rawDescription: Execute another Python instance from different instance


code:
import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("Hello, it works!")

rawDescription: Text to Speech Library for Python using Windows 8.1 (SAPI)


code:
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.protocols.basic import LineReceiver
from twisted.internet.defer import Deferred

class ChatProtocol(LineReceiver):
    def __init__(self, factory):
        self.factory = factory
        self.name = None
        self.state = "REGISTER"

    def connectionMade(self):
        self.factory.node.activeTransports.append(self.transport)
        self.sendLine("What's your name?")

    def connectionLost(self, reason):
        self.factory.node.activeTransports.remove(self.transport)
        if self.name in self.factory.users:
            del self.factory.users[self.name]
            self.broadcastMessage("{} has left the channel.".format(self.name))

    def lineReceived(self, line):
        if self.state == "REGISTER":
            self.handle_REGISTER(line)
        else:
            self.handle_CHAT(line)

    def handle_REGISTER(self, name):
        if name in self.factory.users:
            self.sendLine("Name taken, please choose another!")
            return
        self.sendLine("Welcome, {}".format(name))
        self.broadcastMessage("{} has joined the channel.".format(name))
        self.name = name
        self.factory.users[name] = self
        self.state = "CHAT"

    def handle_CHAT(self, message):
        message = "[%s]>> %s" % (self.name, message)
        self.broadcastMessage(message)

    def broadcastMessage(self, message):
        for name, protocol in self.factory.users.iteritems():
            if protocol != self:
                protocol.sendLine(message)

class ChatFactory(Factory):
    """Handle all the nodes' connection"""
    def __init__(self, node):
        self.users = {}
        self.node = node

    def buildProtocol(self, addr):
        return ChatProtocol(self)

class Node:
    def __init__(self, endpoint, clock, stop=None):
        self.Factory = ChatFactory
        self._endpoint = endpoint
        self._listenStarting = None
        self._listeningPort = None
        self.activeTransports = []
        if stop is not None:
            print("Scheduling stop.", stop)
            clock.callLater(stop, self.stop)

    def listen(self):
        self._listenStarting = self._endpoint.listen(self.Factory(self))
        def setPort(port):
            self._listeningPort = port
        def clear(whatever):
            self._listenStarting = None
            return whatever
        self._listenStarting.addCallback(setPort).addBoth(clear)

    def stop(self):
        if self._listenStarting is not None:
            self._listenStarting.cancel()
        if self._listeningPort is not None:
            self._listeningPort.stopListening()
        for transport in self.activeTransports[:]:
            transport.abortConnection()

class Organization:
    def __init__(self, reactor):
        self.reactor = reactor
        self.nodes = []

    def port(self, number):
        return TCP4ServerEndpoint(self.reactor, number)

    def create_leader(self):
        leader_node = Node(self.port(8000), self.reactor, 5)
        leader_node.listen()
        self.nodes.append(leader_node)

    def create_more_nodes(self):
        node_1 = Node(self.port(8001), self.reactor)
        node_2 = Node(self.port(8002), self.reactor)
        self.nodes.append(node_1)
        self.nodes.append(node_2)

    def activate(self):
        self.nodes[1].listen()
        self.nodes[2].listen()

def main(reactor):
    org = Organization(reactor)
    org.create_leader()
    org.create_more_nodes()
    org.activate()
    return Deferred()

if __name__ == '__main__':
    from twisted.internet.task import react
    react(main)

rawDescription: Stopping a Reactor kills All Reactors Running on Different Ports


rawDescription: Match strings in between without returning start and end


code:
from shutil import copyfile
src = r'\svr\shared\test.zip'
dst = r'C:\test.zip'
copyfile(src, dst)

rawDescription: How to copy file from a network using Python

description: Copy file from a network using Python


code:
print("You find yourself in a dark room, do you... (1) Try to find a way out... or... (2) Sit down and think.")
A1 = input('>>')
if A1 == '1':
    print ("You go into panic, you begin to feel dizzy and lightheaded...")
    print ("Do you (1) Sit down and try to relax... or... (2) Slow down, but keep      searching.")
elif A2 == '2':
    A4 = input('>>')
    etc

rawDescription: How to match up if statements with others

description: Match up if statements with others


code:
# get the raw PKG-INFO data
from pkg_resources import get_distribution
pkgInfo = get_distribution('myapp').get_metadata('PKG-INFO')

# parse it using email.Parser
from email import message_from_string
msg = message_from_string(pkgInfo)
print(msg.items())

# optional: convert it to a MultiDict
from webob.multidict import MultiDict
metadata = MultiDict(msg)
print(metadata.get('Author'))
print(metadata.getall('Classifier'))

rawDescription: How can I get the author name, project description etc from a Distribution object in pkg_resources?

description: Get the author name, project description etc from a Distribution object in pkg_resources


code:
import requests
from bs4 import BeautifulSoup
from urlparse import urljoin
from itertools import chain

url = "http://www.foxrun.com.au/Products/Cylinders_with_Gadgets.aspx"

def validate(soup):
    return {"__VIEWSTATE": soup.select_one("#__VIEWSTATE")["value"],
            "__VIEWSTATEGENERATOR": soup.select_one("#__VIEWSTATEGENERATOR")["value"],
            "__EVENTVALIDATION": soup.select_one("#__EVENTVALIDATION")["value"]}

def parse(base, url):
    data = {"__ASYNCPOST": "true"
            }
    h = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko)  Chrome/24.0.1312.57 Safari/537.17'}
    soup = BeautifulSoup(requests.get(url).text)
    data.update(validate(soup))
    # gets links for < 1,2,3,4,5,6>
    pages = [a["id"] for a in soup.select("a[id^=ctl01_ctl00_pbsc1_pbPagerBottom_btnP]")][2:]
    # get images from initial page
    yield [img["src"] for img in soup.select("img")]
    # add token for post
    data.update(validate(soup))
    for p in pages:
        # we need $ in place of _ for the form data
        data["__EVENTTARGET"] = p.replace("_", "$")
        data["RadScriptManager1"] = "ctl01$ctl00$pbsc1$ctl01$ctl00$pbsc1$ajaxPanel1Panel|{}".format(p.replace("_", "$"))
        r = requests.post(url, data=data, headers=h).text
        soup = BeautifulSoup(r)
        yield [urljoin(base, img["src"]) for img in soup.select("img")]

for url in chain.from_iterable(parse("http://www.foxrun.com.au/", url)):
    print(url)

rawDescription: How to scrap images from a aspx page?

description: Scrap images from a aspx page


code:
Process.Start(
    "dpan.exe",
    string.Format(
        "-np -Lwork_{0}.lib -Owork_{1}.lib \"{2}\" \"{3}.an\"",
        option1, option2, sourceFile, destinationFile
    )
);

rawDescription: Python to C# conversion

description: Python to C# conversion


code:
events = Event.objects.all().annotate(paid_participants=models.Sum(
    models.Case(
        models.When(participant__is_paid=True, then=1),
        default=0, output_field=models.IntegerField()
    )))

rawDescription: How to filter objects for count annotation in Django?

description: Filter objects for count annotation in Django


code:
from matplotlib.dates import YearLocator, DateFormatter

...

# YearLocator defaults to a locator at 1st of January every year
plt.gca().xaxis.set_major_locator(YearLocator())

plt.gca().xaxis.set_major_formatter(DateFormatter('%Y'))

rawDescription: Mofifying X-axis unit on Python graphs

description: Mofifying X-axis unit on Python graphs


code:
def has1dup(lst):
    return len(lst)-1 == len(set(lst))

rawDescription: Efficiently determine if two of three items in a list are the same


code: fname = raw_input("Enter a file name [default: Word_count.txt]:") or "Word_count.txt"

rawDescription: Python if and else , instantiation with in them?


code:
execfile('/usr/local/Modules/default/init/python.py')
module('list')
module('load','foo')
module('list')

rawDescription: Loading environment modules within a python script


code: from __future__ import division

rawDescription: Same equations give different answers : PYTHON


code:
a, b, c = map(the_dict.get,("a","b","c"))
print(a,b,c)

rawDescription: Get mutplie values from a dict at once

description: Get mutplie values from a dict at once


code: unichr(int('fd9b', 16)).encode('utf-8')

rawDescription: Convert unicode codepoint to UTF8 hex in python


rawDescription: Passing python dict to template

description: Passing python dict to template


code:
# Read the image file.
from scipy import misc
data = misc.imread('image.jpg')

# Make a string with the format you want.
text = ''
for row in data:
    for e in row:
        text += '({}, {}, {}) '.format(e[0], e[1], e[2])
    text += '\n'

# Write the string to a file.
with open('image.txt', 'w') as f:
    f.write(text)

rawDescription: Saving RGB matrix as text

description: Saving RGB matrix as text


code:
integer_id = gobject.timeout_add( 180000, callback_func)
#And then somewhere else in your code...
gobject.source_remove(integer_id) #This will stop the timeout_add from occurring!

rawDescription: How to unset a timer set by python gobject.timeout_add ? threads?

description: Unset a timer set by python gobject.timeout_add ? threads


rawDescription: How to change the tab of ttk.Notebook

description: Change the tab of ttk.Notebook


code:
from matplotlib.finance import *

data = parse_yahoo_historical(fetch_historical_yahoo('CKSW', (2013,1,1), (2013, 6, 1)))

ds, opens, closes, highs, lows, volumes = zip(*data)

# Create figure
fig = plt.figure()
ax1 = fig.add_subplot(111)
# Plot the candlestick
candles = candlestick2(ax1, opens, closes, highs, lows,
                       width=1, colorup='g')

# Add a seconds axis for the volume overlay
ax2 = ax1.twinx()

# Plot the volume overlay
bc = volume_overlay(ax2, opens, closes, volumes, colorup='g', alpha=0.5, width=1)
ax2.add_collection(bc)
plt.show()

rawDescription: Adding volume overlay in matplotlib

description: Adding volume overlay in matplotlib


code:
class MediaFileSystemStorage(FileSystemStorage):
    def get_available_name(self, name):
        return name

    def _save(self, name, content):
        if self.exists(name):
            # if the file exists, do not call the superclasses _save method
            return name
        # if the file is new, DO call it
        return super(MediaFileSystemStorage, self)._save(name, content)

def media_file_name(instance, filename):
    h = instance.md5sum
    basename, ext = os.path.splitext(filename)
    return os.path.join('mediafiles', h[0:1], h[1:2], h + ext.lower())

class Media(models.Model):
    # use the custom storage class fo the FileField
    orig_file = models.FileField(
        upload_to=media_file_name, storage=MediaFileSystemStorage())
    md5sum = models.CharField(max_length=36)
    ...

    def save(self, *args, **kwargs):
            if not self.pk:  # file is new
                md5 = hashlib.md5()
                for chunk in self.orig_file.chunks():
                    md5.update(chunk)
                self.md5sum = md5.hexdigest()
            super(Media, self).save(*args, **kwargs)

rawDescription: Django uploads: Discard uploaded duplicates, use existing file (md5 based check)


code:
import functools
def log(func):
    @functools.wraps(func)
    def wrapper(self, infile, outfile):
        retval = func(self, infile, outfile)
        log.info('wrapper1:%s' %outfile)
        return retval
    return wrapper

class Wrapper(object):
    @log
    def wrapper1(self, infile, outfile):
        do_stuff

rawDescription: Python: Log the name and output of each method in a Class automatically


code:
import re
regex = re.compile("^##.*##\n$")
out = open("result.txt","w")
matchfound = True
inmatch =False
for line in open('myfile.txt'):
   if regex.match(line):
       matchfound = True
   else:
        matchfound = False
   if matchfound and not inmatch:
       inmatch = True
       content = []
   elif matchfound and inmatch:
       inmatch = False
       out.write ("".join(content))
   elif inmatch:
       content.append(line)
       out.write(line)
   else:
       out.write(line)
out.close()

rawDescription: How do I copy lines following a tag in a python script?

description: Copy lines following a tag in a python script


code: numpy.concatenate( LIST, axis=0 )

rawDescription: How to convert list of numpy arrays into single numpy array?

description: Convert list of numpy arrays into single numpy array


code: data = csv.reader(csvfile, dialect=csv.excel)

rawDescription: Python CSV library returning 1 item instead of a list of items


code:
def checkio(data):
    for index in range(len(data) - 1, -1, -1):
        if data.count(data[index]) == 1:
            del data[index]
    return data

print(checkio([3, 3, 5, 8, 1, 4, 5, 2, 4, 4, 3, 0]))
[3, 3, 5, 4, 5, 4, 4, 3]
print(checkio([1, 2, 3, 4]))
[]

rawDescription: Delete unique elements from a list

description: Delete unique elements from a list


code:
def on_selection_changed(combo):
    itr = combo.get_active_iter()
    print(slist.get_value(itr, 0), slist.get_value(itr, 1))

combobox.connect('changed', on_selection_changed)

rawDescription: gtk combobox: add items with two fields

description: Gtk combobox: add items with two fields


code:
import subprocess,os
def exe(pyfile,dest="",creator=r"C:\Python34\Scripts\pyinstaller.exe",ico=r"C:\my icons\favicon.ico",noconsole=False):
    insert=""
    if dest: insert+='--distpath ""'.format(dest)
    else: insert+='--distpath "" '.format(os.path.split(pyfile)[0])
    if ico: insert+=' --icon="{}" '.format(ico)
    if noconsole: insert+=' --noconsole '
    runstring='"{creator}" "{pyfile}" {insert} -F'.format(**locals())
    subprocess.check_output(runstring)

rawDescription: How do I compile my Python 3 app to an .exe?

description: Compile my Python 3 app to an .exe


code: d2 = {v:k for k, v in d1.items()}

rawDescription: Two-way mapping between strings and integers


code:
import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt

def func( x, y ):
    return np.sin(x*12.0)*np.sin(y*20.0)

points = np.random.rand(1000, 2)
values = func(points[:,0], points[:,1])

grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]
grid_z = griddata(points, values, (grid_x, grid_y), method='cubic')

plt.imshow(grid_z.T, extent=(0,1,0,1), origin='lower')
plt.scatter(points[:,0], points[:,1], c='k')

plt.show()

rawDescription: Does anyone know how to perform a bicubic spline interpolation in Python?


code:
urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^info', 'app2.views.grid'),
    url(r'^$', 'app2.views.home'),
    url(r'^blog/', 'app1.views.post_list')
)

rawDescription: how to work with two apps in django

description: Work with two apps in django


code:
import sys
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy.settings import Settings
from scrapy import log

sys.path.append('C:/Python27/Scripts/GetAdUrlsFromIndex_project')
from GetAdUrlsFromIndex.spiders.GetAdUrls_spider import getadurls

spider = getadurls(domain='website.com')
crawler = Crawler(Settings())
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start()
reactor.run() # the script will block here

rawDescription: Trying to run a scrapy crawler from another location within script


code:
from itertools import chain
pack(5, 6, *chain(L1, L2))

rawDescription: unpack multiple lists when calling a function

description: Unpack multiple lists when calling a function


code:
todayte = datetime.today()
cmon = todayte.month

for i in range(1, 6):
    t = todayte + relativedelta(weekday=TH(i))
    if t.month != cmon:
        # since t is exceeded we need last one  which we can get by subtracting -2 since it is already a Thursday.
        t = t + relativedelta(weekday=TH(-2))
        break

rawDescription: Get the last thursday of the current month using python


code:
def transform(s):
    ''' Receives a GeoNode structure as nested lists and returns a Mesh.
    '''
    if isinstance(s, list):
       return merge_meshes([transform(e) for e in s])
    else:
       assert isinstance(s, GeoNode)
       return geonode_to_mesh(s)

rawDescription: Parsing Tree of python classes and applying a grammar


code:
def g(y=10):
    return y**2

def f(x, **kwargs):
    return x * g(**kwargs)

f(5)
f(5, y=0)

rawDescription: How to pass an empty parameter to a python function?

description: Pass an empty parameter to a python function


code:
from hashids import Hashids
hash_id = Hashids(salt='your_secret_here', min_length=8)
hash_id.encrypt(0)   # aDnwJKQZ
hash_id.encrypt(999) # p32jAqVW

# it is reversible
hash_id.decrypt('p32jAqVW')  # (999,)

rawDescription: Generate and Verify Voucher Code Using Python


code: A = re.findall(r'{definition}(.*?)\\end{definition}', raw.read())

rawDescription: How to Parse LaTex file

description: Parse LaTex file


code:
class MozSerializer(serializers.Serializer):

    def __init__(self, *args, **kwargs):
        modelid = kwargs.pop('modelid')
        self.fields['keyword'] = serializers.PrimaryKeyRelatedField(\
                                             queryset=modelid.objects.all())
        super(MozSerializer, self).__init__(*args, **kwargs)

    pda = serializers.FloatField()
    upa = serializers.FloatField()

rawDescription: Django super function does't add variable to class


code:
import types
class MyMethod(TraitType):
    def validate(self, object, name, value):
        if isinstance(value, types.MethodType):
            return value
        if isinstance(value, types.FunctionType):
            return types.MethodType(value, object, object.__class__)
        self.error(object, name, value)

rawDescription: Using function as an instance method with Enthought Traits (Python)


rawDescription: Python regex matching all but last occurance


code:
a=[(0, 'How can I run '), (-1, 'j'), (1, 'J'), (0, 'ava'), (-1, ' '), (0, 'script from a local folder?')]

b='How can I run java script from a local folder?'

result = []

position = 0
for v, txt in a:
    if v == 0:
        result.append((0, (position, position+len(txt))))
    else:
        result.append((v, txt))
    if v<=0:
        position += len(txt)

rawDescription: Efficient way to store tuples of diff info without redundancy


code:
from django.http import HttpResponse

urlpatterns = patterns('',
    url(r'^$', lambda request: HttpResponse("Hello World", content_type="text/plain")),
)

rawDescription: Outputing text from urls.py in Django

description: Outputing text from urls.py in Django


code:
from __future__ import print_function # Python 2/3 compatibility
import boto3

dynamodb = boto3.resource('dynamodb', endpoint_url="http://localhost:8000", region_name="us-west-2")

table = dynamodb.create_table(
    TableName='Posts',
    KeySchema=[
        {
            'AttributeName': 'user_id',
            'KeyType': 'HASH'  #Partition key
        },
        {
            'AttributeName': 'post_id',
            'KeyType': 'RANGE'  #Sort key
        },
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'user_id',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'post_id',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'date',
            'AttributeType': 'N'
        },

    ],
    LocalSecondaryIndexes=[
        {
            'IndexName': 'PostsByDate',
            'KeySchema': [
                {
                    'AttributeName': 'user_id',
                    'KeyType': 'HASH'  #Partition key
                },
                {
                    'AttributeName': 'date',
                    'KeyType': 'RANGE'  #Sort key
                },
            ],
            'Projection': {
                'ProjectionType': 'ALL'
            }
        }
    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10,
        }
)

print("Table status:", table.table_status)

rawDescription: Create table in dynamoDB with LSI using boto


code: starnames = [ n.username+"*" for n in results]

rawDescription: How to process a django queryset?

description: Process a django queryset


code:
import re
re.sub('[a-z]*(\d+)', r'lion\1', 'zebra432')
# You can also refer to more than one capture group
re.sub('([a-z]*)(\d+)', r'\1lion\2', 'zebra432')

rawDescription: Is there a way to use regular expressions in the replacement string in re.sub() in Python?


code:
import csv
import oprator

# read the data from the source file
with open('case_name.csv') as infile:
    data = list(csv.reader(infile, dialect='excel'))

# sort a list of sublists by the item in index 2
data.sort(key=operator.itemgetter(2))

# time to write the results into a file
with open('case_name_sorted.csv', 'w') as outfile:
    writer = csv.writer(outfile, dialect='excel')
    writer.writerows(data)

rawDescription: How to Sort a Column in an Excel sheet

description: Sort a Column in an Excel sheet


code:
x = "hello"
x += " world"
x

rawDescription: Is there a good shortcut for modifying python variables using methods?


code:
date = QtCore.QDate.fromString('20130916', 'yyyyMd')
date.toString('MMMM d, yyyy')
date.toString('MMMM d, yyyy')
unicode(date.toString('MMMM d, yyyy'))

rawDescription: QDate into QString

description: QDate into QString


code:
import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon

class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300,300,300,220)
        self.setWindowTitle('Icon')
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    path = os.path.join(os.path.dirname(sys.modules[__name__].__file__), 'icon_1.png')
    app.setWindowIcon(QIcon(path))
    ex = Example()
    sys.exit(app.exec_())

rawDescription: why using PyQt5 on mac can not add a icon?

description: Why using PyQt5 on mac can not add a icon


code:
from django.core.cache import cache

CHOICES_CACHE_KEY = 'choice_cache_key'

def get_cached_choices():
    choices = cache.get(CHOICES_CACHE_KEY)
    if choices is None:
        choices = ...  # Query the DB here
        cache.set(CHOICES_CACHE_KEY, choices, None)  # None caches forever
    return choices

def construct_forms(choices):
    forms = ...  # build forms with choices
    return forms

@receiver((post_save, post_delete), sender=TheModel, dispatch_uid='change')
def clear_choices_cache(sender, **kwargs):
    cache.delete(CHOICES_CACHE_KEY)

def some_view(request):
    # Do something with the forms
    forms = construct_forms(get_cached_choices())

rawDescription: Setting variables with Django signals without using globals


code:
zip('abc', '12345')
list(itertools.izip_longest('abc', '12345', fillvalue=0))

rawDescription: Trying to write to a CSV but some fields get excluded in scrapy for python


code:
@colander.deferred
def deferred_now(node, kw):
    now = kw['now']
    return now

@colander.deferred
def deferred_now_delta(node, kw):
    return kw['now'] - kw['delta']

class MySchema(MappingSchema):
     to = SchemaNode(Date(), missing=deferred_now)
     frm = SchemaNode(Date(), missing=deferred_now_delta)

def aview(request):
    schema = MySchema().bind(now=now(), delta=somedelta)

rawDescription: Defining 'missing' for colander.SchemaNode dynamically


code:
from functools import partial

d = defaultdict(partial(deque, maxlen=10))

rawDescription: How to make a bounded map of queue in python?

description: Make a bounded map of queue in python


rawDescription: Run bash scripts from python. MAC OS

description: Run bash scripts from python. MAC OS


code:
import win32com.client
app = win32com.client.Dispatch("PowerPoint.Application")

selectedShape = app.ActiveWindow.Selection.ShapeRange(1)

rawDescription: Is there anyway to know what object does the file have in MS powerpoint or word


code:
import numpy as np
import seaborn as sns
import wx

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure

class SamplePanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.toggled = False
        self.figure = Figure()
        self.ax = self.figure.add_subplot(111)

        self.x = np.array(list('XYZV'))
        self.y = np.array([200,400,300,20])

        self.ax.set_ylabel("Sample numbers")

        self.canvas = FigureCanvas(self, -1, self.figure)
        self.button = wx.Button(self, label="Plot data", pos=(100,15))
        self.button.Bind(wx.EVT_BUTTON, self.OnButtonClick)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.sizer.Add(self.button, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

    def OnButtonClick(self, event):
        if not self.toggled:
            sns.barplot(self.x, self.y, palette="BuGn_d", ax=self.ax)
            self.toggled = True
        else:
            self.ax.cla()
            self.toggled = False
        self.Layout()

if __name__ == "__main__":
    app = wx.App(False)
    frame = wx.Frame(None, title='Sample bar plot', size=(800,600))
    panel = SamplePanel(frame)
    frame.Show()
    app.MainLoop()

rawDescription: Seaborn disable plot

description: Seaborn disable plot


code:
class A:
    class B:
        class C:
            def me(self):
                print(self.__module__)
                print(type(self).__name__)
                print(type(self).__qualname__)
                print(repr(self))

rawDescription: get fully qualified name of python class (python 3.3+)

description: Get fully qualified name of python class (python 3.3+)


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.interpolate import interp1d

class AnimatedScatter(object):
    def __init__(self, t, xpositions, ypositions):
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)
        self.sim_data = np.dstack((xpositions, ypositions))
        self.t = t

        nframes = len(t)

        self.ani = animation.FuncAnimation(self.fig, self.update,\
                                           frames=np.arange(nframes),\
                                           init_func=self.setup_plot)

    def setup_plot(self):
        self.scat = self.ax.scatter(self.sim_data[0,:,0], self.sim_data[0,:,1])
        self.fig.suptitle("t = %f" % (self.t[0]))
        return [self.scat]

    def update(self, i):
        self.scat.set_offsets(self.sim_data[i])
        self.fig.suptitle("t = %f" % (self.t[i]))
        return [self.scat]

    def show(self):
        plt.show()

data = np.genfromtxt("data.txt")

tsim = data[:,0]
xsim = data[:,1::2]
ysim = data[:,2::2]

nframes = 100
nparts = xsim.shape[1]

tplot = np.linspace(tsim[0], tsim[-1], nframes)

xplot = np.empty( (nframes, nparts) )
yplot = np.empty( (nframes, nparts) )

for i in xrange( nparts ):
    xspl = interp1d(tsim, xsim[:,i])
    yspl = interp1d(tsim, ysim[:,i])

    xplot[:,i] = xspl(tplot)
    yplot[:,i] = yspl(tplot)

a = AnimatedScatter(tplot, xplot, yplot)
a.show()

rawDescription: making movie from output txt matplotlib

description: Making movie from output txt matplotlib


code:
if not letter.isalpha():
    return 'Failed'

rawDescription: Python - ways of checking True/False without ==?


code:
if not (a or b or c):
    raise MyError

rawDescription: How to force one keyword in python function

description: Force one keyword in python function


code:
x = pd.date_range('20130101',periods=5)
td = pd.Series(x,index=x)-pd.Timestamp('20130101')
td
td.apply(lambda x: x.item().days)

rawDescription: How to convert TimeSeries object in pandas into integer?

description: Convert TimeSeries object in pandas into integer


code:
def make_matrix(num_rows, num_cols, entry_fn):
    ret = [] # you are dealing with an outer list
    # and an outer loop
    for i in range(num_rows):
        cur = [] # and an inner list
        # And an inner loop
        for j in range(num_cols):
            curr.append(entry_fn(i,j)) # you add the result to the inner list
        # and once you're done with the inner loop, and the result to the outer list
        ret.append(cur)
    # finally, complete the outer loop and return the result
    return ret

rawDescription: Python: I don't understand the order of a function calling a function


code:
from django.template.defaultfilters import slugify
slugify("My Product 2.0")   # 'my-product-20'

rawDescription: Convert name of a generic element to URL in Django


code:
def pdf(self,x,*args,**kwds):
    loc,scale=map(kwds.get,['loc','scale'])
    args, loc, scale = self._fix_loc_scale(args, loc, scale)
    x,loc,scale = map(asarray,(x,loc,scale))
    args = tuple(map(asarray,args))
    x = asarray((x-loc)*1.0/scale)
    cond0 = self._argcheck(*args) & (scale > 0)
    cond1 = (scale > 0) & (x >= self.a) & (x <= self.b)
    cond = cond0 & cond1
    output = zeros(shape(cond),'d')
    putmask(output,(1-cond0)+np.isnan(x),self.badvalue)
    if any(cond):
        goodargs = argsreduce(cond, *((x,)+args+(scale,)))
        scale, goodargs = goodargs[-1], goodargs[:-1]
        place(output,cond,self._pdf(*goodargs) / scale)
    if output.ndim == 0:
        return output[()]
    return output

rawDescription: Is the build-in probability density functions of `scipy.stat.distributions` slower than a user provided one?


code:
import re
split_numbers = re.compile(r'-?\d+').findall
sum(int(x) for x in split_numbers('1+23-4+56-7'))

rawDescription: Better way to evaluate mathematical expression in python?


code:
import web

class MyApplication(web.application):
    def run(self, port=8080, *middleware):
        func = self.wsgifunc(*middleware)
        return web.httpserver.runsimple(func, ('0.0.0.0', port))

if __name__ == "__main__":
    app = MyApplication(urls, globals())
    app.run(port=8888)

rawDescription: web.py - specify address and port

description: Web.py - specify address and port


code:
import random

posts = []
for tag in soup.find_all('div', class_='post'):
    title = tag.h2.a.string
    imageURL = tag.p.a['href']
    sourceURL = tag.div.a['href'].split('#', 1)[0]

    posts.append((title, imageURL, sourceURL))

title, imageURL, sourceURL = random.choice(posts)

rawDescription: pull specific iteration output from for loop

description: Pull specific iteration output from for loop


code:
import glob
from netCDF4 import Dataset
import numpy as np
from PIL import Image

WIDTH = 800
HEIGHT = 450

root = Dataset('test.nc', 'w')

root.createDimension('x', WIDTH)
root.createDimension('y', HEIGHT)
root.createDimension('channels', 3)
t = root.createDimension('t', None)

img = root.createVariable('image', 'u1', ('t','y','x','channels'))

images = glob.glob('images/*')

for i,fname in enumerate(images):
    im = Image.open(fname)
    im_array  = np.asarray(im)
    img[i] = im_array

median = np.median(img, axis=0)
im = Image.fromarray(np.uint8(median))
im.save('out.png')

rawDescription: Python memory management with a median image stacker


code:
from urlparse import urlparse, parse_qs
# For Python 3:
# from urllib.parse import urlparse, parse_qs

url = ' https://example.com/main'
url += '/?code=32ll48hma6ldfm01bpki&data=57600&data2=aardappels'

parsed = urlparse(url)
code  = parse_qs(parsed.query).get('code')[0]

rawDescription: Python: Get data from URL query string

description: Python: Get data from URL query string


rawDescription: Converting Strings to two lists in Python


code:
import itertools
site_range=[0,1,2]
[x for x in itertools.product(site_range, repeat=len(site_range))]

rawDescription: how do I generate a cartesian product of several variables using python iterators?

description: Generate a cartesian product of several variables using python iterators


code:
class NotesMixin(object):
    @declared_attr
    def notes(cls):
        return sa.Column(sa.String(4000) , nullable=False, default='')

rawDescription: sqlalchemy Move mixin columns to end

description: Sqlalchemy Move mixin columns to end


code:
import string
l = string.ascii_lowercase
t = str.maketrans(l, l[2:] + l[:2])
m = """g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp.
     bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle.
     sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."""
print(m.translate(t))

rawDescription: unable to convert or run python 2.x code using python 3.0

description: Unable to convert or run python 2.x code using python 3.0


code:
memcache_key = 'request-count-' + self.request.remote_addr

count = memcache.get(memcache_key)

if count is not None and count > MAX_REQUESTS:
    logging.warning("Remote user has %d requests; rejecting." % (count))
    self.error(503)
    return

count = memcache.incr(memcache_key)
if count is None:
    # key didn't exist yet
    memcache.add(memcache_key, 1, time=WINDOW_IN_SECONDS)

rawDescription: Limiting the number of request from any given IP address


code:
class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        loadUi('mainwindow.ui', self)

rawDescription: How do you load .ui files onto python classes with PySide?

description: Load .ui files onto python classes with PySide


code:
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
import numpy as np
x = np.linspace(0, 6, 10)
y = np.sin(x)
z = x

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

ax.plot(x, y, z
         , linestyle='-'
         , linewidth=20
         , marker='o'
         , markersize=20
         , solid_capstyle='round'
)
ax.set_xlim3d(-1, 7)
ax.set_ylim3d(-2, 2)
ax.set_zlim3d(-1, 7)
plt.show()

rawDescription: Is there a way to draw 3D lines as a series of circles with matplotlib?


code:
with open("test.txt", "w") as f_out:
    f_out.write(your_string)

rawDescription: Simplest way to create a file and write a string to it in Python


code:
for line in fileinput.input(["file.dat"]):
  if not fileinput.isfirstline():
    data = proces_line(line);
    output(data)

rawDescription: Elegant way to skip first line when using python fileinput module?


code:
frequency = {('work', 'experience'): 16,
             ('work', 'services'): 25,
             ('must', 'services'): 15,
             ('data', 'services'): 10}
keys = np.array(frequency.keys())
vals = np.array(frequency.values())
keys
vals
unq_keys, key_idx = np.unique(keys, return_inverse=True)
key_idx = key_idx.reshape(-1, 2)
unq_keys
key_idx
n = len(unq_keys)
adj = np.zeros((n, n) ,dtype=vals.dtype)
adj
adj += adj.T
adj

rawDescription: Converting a dictionary of tuples into a numpy matrix


code:
lists = (listOne, listTwo, listThree)
[sum(values) for values in zip(*lists)]

rawDescription: Python adding lists of numbers with other lists of numbers


code:
with open('file.txt') as f:
   for line in f:
      a, b, c = map(int, line.split())
      ...

rawDescription: Read tabbed files in python

description: Read tabbed files in python


code:
import os
os.environ['x'] = 'a'
os.system('echo %x%')

rawDescription: Importing variables from python into a batch file


code:
import csv, pyodbc

# set up some constants
MDB = 'c:/path/to/my.mdb'; DRV = '{Microsoft Access Driver (*.mdb)}'; PWD = 'pw'

# connect to db
con = pyodbc.connect('DRIVER={};DBQ={};PWD={}'.format(DRV,MDB,PWD))
cur = con.cursor()

# run a query and get the results
SQL = 'SELECT * FROM mytable;' # your query goes here
rows = cur.execute(SQL).fetchall()
cur.close()
con.close()

# you could change the mode from 'w' to 'a' (append) for any subsequent queries
with open('mytable.csv', 'wb') as fou:
    csv_writer = csv.writer(fou) # default field-delimiter is ","
    csv_writer.writerows(rows)

rawDescription: how to deal with .mdb access files with python

description: Deal with .mdb access files with python


code:
from azure.storage.blob import BlobService

def copy_azure_files(self):

        blob_service = BlobService(account_name='account_name', account_key='account_key')
        blob_name = 'pretty.jpg'
        copy_from_container = 'image-container'
        copy_to_container = 'demo-container'

        blob_url = blob_service.make_blob_url(copy_from_container,copy_from_container)
        # blob_url:https://demostorage.blob.core.windows.net/image-container/pretty.jpg

        blob_service.copy_blob(copy_to_container, blob_name, blob_url)

        #for move the file use this line
        blob_service.delete_blob(copy_from_container, blob_name)

rawDescription: Python: How to move or copy Azure Blob from one container to another


code:
pattern = u'丨フ丨ノ一丨ノ丶フノ一ノ丨フ一一ノフフ丶'
result = [u'\u4e28\u30d5\u4e28\u30ce\u4e00\u4e28\u30ce\u4e36\u30d5\u30ce\u4e00\u30ce\u4e28\u30d5\u4e00\u4e00\u30ce\u30d5\u30d5\u4e36']

if pattern in result[0]:
    print('found')

rawDescription: determine encoding of content scraped from xpath. convert to unicode

description: Determine encoding of content scraped from xpath. convert to unicode


code:
class Replacer:  # On Py2, use class Replacer(object): to explicitly use new style classes
    def __init__(self):
        self.matchcnt = 0
    def __call__(self, matchobj):
        self.matchcnt += 1
        return matchobj.group(0) + str(self.matchcnt)

rawDescription: How can I know the match index in a regular expression subn's repl function

description: Know the match index in a regular expression subn's repl function


code:
from gmpy2 import mpz
pow(mpz(3),7)
pow(mpz(3),7,13)
mpz(3)**7

rawDescription: Does GMPY2 (or GMP) have a pow() function?


code:
t=time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))
'/'.join( map( str, map(int,t.split("/")) ) )

rawDescription: Get rid of leading zeros for date strings in Python?


code:
myString = "08928192"
n = 2

output = [myString[i:i+n] for i in range(0, len(myString), n)]

print(output)

rawDescription: How to split an 8 character string into groups of two in python

description: Split an 8 character string into groups of two in python


code:
with open(filename, 'r') as f:
    for offset in offsets:
        f.seek(offset)
        print(f.readline())

rawDescription: Get line from file at specified byte offset


code:
def l_case(l):
     s = ""
     for c in l:
          s += chr(ord(c)+32)
     print(s)

rawDescription: My program is working well except for one thing :


code:
total = 0
while location != []:
    test = float("inf")
    for loc in location:
        #do distance calc here set = to dist
        if dist < test:
            test = dist
            temp = loc
    total += test
    location.remove(loc)

rawDescription: algorithm for calc distances between a list of cities

description: Algorithm for calc distances between a list of cities


code:
from io import BytesIO
import urllib
import urllib.request
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
url = "http://imgs.xkcd.com/comics/python.png"
with urllib.request.urlopen(url) as u:
    raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.pack()
root.mainloop()

rawDescription: How to display a png file from a webpage on a tk label in Python?

description: Display a png file from a webpage on a tk label in Python


code:
def using_split2(line, _len=len):
    words = line.split()
    index = line.index
    offsets = []
    append = offsets.append
    running_offset = 0
    for word in words:
        word_offset = index(word, running_offset)
        word_len = _len(word)
        running_offset = word_offset + word_len
        append((word, word_offset, running_offset - 1))
    return offsets

rawDescription: How to split a string on whitespace and retain offsets and lengths of words

description: Split a string on whitespace and retain offsets and lengths of words


code:
import json
with open('./gui-config.json','r') as f:
    js=json.load(f)
    js['configs'][0]['password']='123'

with open('./gui-config.json','w') as f:
    js.dumps(js, f)

rawDescription: JSON saving duplicate info

description: JSON saving duplicate info


code:
ip_dict = {}
for ip_subnet in newSet:
    ip,subnet = ip_subnet.split('/')
    subnet = int(subnet)
    if ip not in ip_dict or ip_dict[ip] > subnet:
        ip_dict[ip] = subnet
updated_list = [str(ip)+"/"+str(subnet) for ip,subnet in ip_dict.iteritems()]

ipTotal = 0
for subnet in ip_dict.values():
    y = 32 - int(subnet)
    x = pow(2, y)
    ipTotal = ipTotal + x

rawDescription: Compairing a list and extracting a number


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

x = np.arange(10)
y = np.random.rand(10)

fig = plt.figure(1, figsize=(10,10))

for i, j in zip(np.arange(4), [10,15,20,30]):
    ax = fig.add_subplot(2,2,i+1)
    ax.plot(x, y,  linestyle='--', marker='o', color='b')
    ax.set_xlabel(r'$\mathrm{\alpha \ (distance \ weighted)}$', fontsize=j)
    ax.set_ylabel('AUC')
plt.show()

rawDescription: How to set fontsize of axis label with LaTex symbol on matplotlib/seaborn?

description: Set fontsize of axis label with LaTex symbol on matplotlib/seaborn


code:
app = webapp2.WSGIApplication([('/', MainPage),
                               ('/profile/<profile_id>', ProfilePage),])

rawDescription: Creating Unique Profile Pages for Users

description: Creating Unique Profile Pages for Users


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

x=[5,6,2,6,9]
y=[2,4,5,1,10]
x_mean = np.mean(x)
y_mean = np.mean(y)
x_dist_mean = x - x_mean
y_dist_mean = y - y_mean

size = np.abs(x_dist_mean * y_dist_mean) * 100
labels=['horse', 'cat' , 'dog', 'fish', 'ape']

plt.scatter(x_dist_mean, y_dist_mean, s=size, alpha=0.5, label=labels)
for label, x, y in zip(labels, x_dist_mean, y_dist_mean):
    plt.annotate(label, xy = (x, y))

rawDescription: Matplotllib plot scatter with circle sizes proportional from distance to mean


code: [v['rate'] for v in evnt.itervalues()]

rawDescription: Getting lists from subdictionaries

description: Getting lists from subdictionaries


rawDescription: How to define several float groups in a regular expression?

description: Define several float groups in a regular expression


code:
#coding: utf-8
import argparse
import json
import logging
import sys
import numpy
import pylab
from sklearn.cluster import KMeans
from common import init_db_connection
from numpy import array
from scipy.cluster import hierarchy

logger = logging.getLogger("build2")

CLUSTERING_TYPE_KMEANS = "KMEANS"
CLUSTERING_TYPE_HIERARCHY = "HIERARCHY"

def get_coord_names(cursor, limit):
    sql = """
        SELECT DISTINCT unnest(user_ids) ivi_id
        FROM (
            SELECT user_ids
            FROM content_watched_by_users cw
                JOIN content c ON c.id = cw.content_id
            ORDER BY array_length(ivi_ids, 1) DESC
            LIMIT %s
        ) as t
        ORDER BY ivi_id;
    """
    logger.info(cursor.mogrify(sql, (limit,)))
    cursor.execute(sql, (limit,))

    coord_names = [x[0] for x in cursor]
    return coord_names

def get_matrix_of_observations_and_objects(cursor, coords_name, limit):
    sql = """
        SELECT c.title, user_ids
        FROM content_watched_by_users cw
            JOIN content c ON c.id = cw.content_id
        ORDER BY array_length(user_ids, 1) DESC LIMIT %s"""
    logger.info(cursor.mogrify(sql, (limit,)))
    cursor.execute(sql, (limit,))

    logger.info(u"Начинаем получать матрицу наблюдений и массив объектов")
    matrix = []
    objects = []

    for content_id, user_ids in cursor:
        logger.info(u"Обрабатывается %s", content_id)
        objects.append((content_id, len(user_ids)))

        row = [0] * len(coords_name)
        for user_id in user_ids:
            try:
                row[coords_name.index(user_id)] = 1
            except ValueError:
                logger.error(u"Что-то не так с user_ids %s", user_ids)

        matrix.append(row)
    logger.info(u"Матрица наблюдений и массив объектов получены")
    return array(matrix), objects

def fcluster_to_d3_dict(fcluster, objects, name_cluster=False):
    d = {"name": "", "children": []}
    for i in range(max(fcluster)):
        d["children"].append({"name": "", "children": []})

    for index, parent_id in enumerate(fcluster):
        parent = d["children"][parent_id - 1]
        parent["children"].append({"name": objects[index][0], "size": objects[index][1]})

        if name_cluster and not parent["name"]:
            parent["name"] = objects[index][0]
    return d

def code_to_d3_dict(code, objects, name_cluster=False):
    d = {"name": "", "children": []}
    for i in range(max(code) + 1):
        d["children"].append({"name": "", "children": []})

    for index, parent_id in enumerate(code):
        parent = d["children"][parent_id]
        parent["children"].append({"name": objects[index][0], "size": objects[index][1]})

        if name_cluster and not parent["name"]:
            parent["name"] = objects[index][0]
    return d

def save_to_json(result_dict, output_file="d3/flare.json"):
    logger.info(u"Перегоняем в JSON")
    f = open(output_file, "w")
    json.dump(result_dict, f)
    f.close()
    logger.info(u"JSON сохранен по адресу: %s", output_file)

def hierarchy_clustering(matrix, objects, threshold, name_cluster):
    Z = hierarchy.linkage(matrix, method='ward')
    fcluster = hierarchy.fcluster(Z, threshold, 'distance')

    hierarchy.dendrogram(Z)
    pylab.savefig("temp.png")

    logger.info(fcluster)
    result_dict = fcluster_to_d3_dict(fcluster, objects, name_cluster)
    return result_dict

def kmeans_clustering(matrix, objects, k, name_cluster=False):
    S = 1 - (matrix / numpy.max(matrix))
    db = KMeans(n_clusters=k).fit(S)
    logger.info(db.labels_)
    result_dict = code_to_d3_dict(db.labels_, objects, name_cluster)
    return result_dict

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=u'Скрипт для получения красивого графа')
    # БД
    parser.add_argument('--db_host', default="localhost", type=str, dest="db_host",
                        help=u'Хост БД, по умолчанию: localhost')
    parser.add_argument('--db_port', default="5432", type=str, dest="db_port",
                        help=u'Порт БД, по умолчанию: 5432')
    parser.add_argument('--db_name', default="da_test", type=str, dest="db_name",
                        help=u'Имя БД, по умолчанию: da')
    parser.add_argument('--db_user', default="da", type=str, dest="db_user",
                        help=u'Пользователь БД, по умолчанию: da')
    # общее
    parser.add_argument("--log-level", default='INFO', type=str, dest="log_level",
                        choices=['DEBUG', 'INFO', 'WARNINGS', 'ERROR'], help=u"Уровень логирования")
    parser.add_argument('-l', '--limit', required=True, type=int, dest="limit",
                        help=u'Количество контента в выборке. '
                              u'Контент осортирован по количеству просмотревших его пользователей')
    parser.add_argument('-o', '--output', required=True, type=str, dest="output_file_path",
                        help=u'Куда сохранять JSON-результат')
    parser.add_argument('-n', '--name_cluster', action="store_true", dest="name_cluster",
                        help=u'Именовать кластеры по первому элементу в кластере')
    parser.add_argument("-c", "--clustering", default=CLUSTERING_TYPE_KMEANS, type=str, dest="clustering_type",
                        choices=[CLUSTERING_TYPE_KMEANS, CLUSTERING_TYPE_HIERARCHY], help=u"Тип кластеризации")
    # kmeans
    parser.add_argument('-k', '--max_k', type=int, dest="max_k",
                        help=u'Максимальное число кластеров. Только для kmeans')
    # иерархическая
    parser.add_argument('-t', '--threshold', type=float, dest="threshold",
                        help=u'Граница разделения на плоские кластеры. Только для иерархической кластеризации')

    args = parser.parse_args()
    logging.basicConfig(stream=sys.stdout, level=getattr(logging, args.log_level), format="%(asctime)s :: %(message)s")

    connection = init_db_connection(args.db_host, args.db_port, args.db_user, args.db_name)
    cursor = connection.cursor()
    coords_name = get_coord_names(cursor, args.limit)
    matrix, objects = get_matrix_of_observations_and_objects(cursor, coords_name, args.limit)
    connection.close()

    if args.clustering_type == CLUSTERING_TYPE_KMEANS:
        result_dict = kmeans_clustering(matrix, objects, args.max_k, args.name_cluster)
    elif args.clustering_type == CLUSTERING_TYPE_HIERARCHY:
        result_dict = hierarchy_clustering(matrix, objects, args.threshold, args.name_cluster)
    else:
        raise Exception(u"Неизвестный тип кластеризации")
    save_to_json(result_dict, args.output_file_path)

rawDescription: Create chart using python

description: Create chart using python


code:
from kivy.clock import Clock

class app(App):
    def build(self):
        self.layout = Layout()
        self.name = Label(text = "john")
        self.layout.add_widget(self.name)
        self.current_i = 0
        Clock.schedule_interval(self.update, 1)
        return self.layout

    def update(self, *args):
        self.name.text = str(self.current_i)
        self.current_i += 1
        if self.current_i >= 50:
            Clock.unschedule(self.update)

rawDescription: Update properties of a kivy widget while running code


code: next(iter(kf))

rawDescription: Getting the first fold in sklearn.cross_validation.KFold without looping


code:
A1 = A.groupby('key1').mean().reset_index()
pd.merge(B, A1, on='key1')

rawDescription: Merging two DataFrames using an aggregate on a column on one of the DataFrames


code:
class SocialAuthSerializer(serializers.HyperlinkedModelSerializer):
    login = serializers.SerializerMethodField()

    def get_login(self, obj):
        return obj.extra_data['login']

rawDescription: How to add and serialise additional fields of an existing model in Django

description: Add and serialise additional fields of an existing model in Django


rawDescription: Pandas: Biggest index smaller then a date


code: self.genx = [ item for item in self.genx if not range_min < item < range_max ]

rawDescription: Python: Removing a range of numbers from array list


code: Dog.bark = types.MethodType(...)

rawDescription: Python 3: Adding function to a already created object


code: client.get('/page/', {'filter': 'one and two'})

rawDescription: Testing request parameters in Django ("+" behaves differently)


code:
import numpy
data = numpy.array([23, 45, 23, 55, 66, 77])
pattern = numpy.array([1, 2, 1, 1, 2, 2])

set1 = data[pattern == 1]
set2 = data[pattern == 2]

rawDescription: Simple python code for writing data to separate files based on condition?


code:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

# The pylab figure manager will be bypassed in this instance.
# This means that `fig` will be garbage collected as you'd expect.
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)

rawDescription: Create a figure that is reference counted


rawDescription: How to change the location the 'r' axis for matplotlib polar plot?

description: Change the location the 'r' axis for matplotlib polar plot


code:
def find_substrs(li):
    return [y for x,y in zip(li,li[1:]) if y in x]

find_substrs(['hopefully','hope','hop','testing','test'])
Out[49]: ['hope', 'hop', 'test']

rawDescription: Function finding substrings in a list

description: Function finding substrings in a list


code:
import os

TEST_FILENAME = os.path.join(os.path.dirname(__file__), 'test.txt')

rawDescription: make an "always relative to current module" file path?

description: Make an "always relative to current module" file path


code:
for _, maker in makes.iterrows():
    contains_maker = models.models.str.contains(maker.makes)
    models.loc[contains_maker,('makes', )] = maker.makes

rawDescription: Comparing each row in 2 arrays to find the same string and modifying another column based on result


code:
def foo():
  return ['potato']

[p] = foo()
p

rawDescription: what does [sock] = func() mean?

description: What does [sock] = func() mean


code:
df["Suffix"] = df["Story"].str.split().str[-1]
df

rawDescription: Find Last Word in a String within a List (Pandas, Python 3)


code: identifier = None if obj is None else obj.id

rawDescription: Python: A more concise syntax for variable assignment when accessing a NoneType object


code:
class Item(Base):
    __tablename__ =  "item"

    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False)

    # relationships
    related = relationship('Item',
            secondary = t_links,
            primaryjoin = (id == t_links.c.from_id),
            secondaryjoin = (id == t_links.c.to_id),
    )

_OTHER_SIDE = set()
from sqlalchemy import event
def Item_related_append_listener(target, value, initiator):
    global _OTHER_SIDE
    if not((target, value) in _OTHER_SIDE):
        _OTHER_SIDE.add((value, target))
        if not target in value.related:
            value.related.append(target)
    else:
        _OTHER_SIDE.remove((target, value))

event.listen(Item.related, 'append', Item_related_append_listener)

# ...
a = Item()
b = Item()
a.related.append(b)
assert a in b.related # True

rawDescription: Implement "related items" feature using SQLAlchemy


code:
def boardinit(self):
    board=[['+' for row in range(17)]for col in range(17)]
    # Set border
    for hor in range(17):
        board[0][hor]= board[16][hor]='--'
    for side in range(17):
        board[side][0]=board[side][16] = '|'

    self.board = board

rawDescription: 'list' object has no attribute 'board'(Matrix)


code:
import cPickle

#
# Load if neccesary
#
def loadfile(variable, filename, namespace=None):
    if module is None:
        import __main__ as namespace
    setattr(namespace, variable, cPickle.load(file(filename,'r')))

# From the main script just do:
loadfile('myvar','myfilename')

# To set the variable in module 'mymodule':
import mymodule
...
loadfile('myvar', 'myfilename', mymodule)

rawDescription: Loading files into variables in python

description: Loading files into variables in python


code:
class SomeDerivedClass(SomeClass):
    @contextlib.contextmanager
    def on_connection(self, target_terminal, source_terminal):
        with super().on_connection(target_terminal, source_terminal):
            ...
            yield
            ...

description: Inheritance with contextlib.contextmanager


code:
import tempfile
import subprocess as subp
import os

tempfp = tempfile.NamedTemporaryFile(delete=False)
try:
    proc = subp.Popen(['somecommand'], stdout=tempfp)
    tempfp.close()
    proc.wait()
    some_c_function(tempfp.name)
finally:
    tempfp.close()
    os.remove(tempfp.name)

rawDescription: Issue system call from Python, get filename for output


code:
import sys
from time import sleep
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class Signals(QObject):
    update = pyqtSignal(int)
    enable_button = pyqtSignal(bool)

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        self.button = QPushButton("Run", self)
        self.button.clicked.connect(self.onButton)

        self.progress = QProgressBar(self)
        self.progress.setTextVisible(False)

        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(5, 5, 5, 5)
        self.layout.addWidget(self.button)
        self.layout.addWidget(self.progress)
        self.layout.addStretch()

        self.worker_thread = QThread()
        self.worker_thread.run = self.worker
        self.worker_thread.should_close = False

        self.signals = Signals()
        self.signals.update.connect(self.progress.setValue)
        self.signals.enable_button.connect(self.button.setEnabled)

        self.setLayout(self.layout)
        self.show()
        self.resize(self.size().width(), 0)

    # Override
    def closeEvent(self, e):
        self.worker_thread.should_close = True
        self.worker_thread.wait()

    @pyqtSlot()
    def onButton(self):
        self.button.setDisabled(True)
        self.worker_thread.start()

    # Worker thread, no direct GUI updates!
    def worker(self):
        for i in range(101):
            if self.worker_thread.should_close:
                break
            self.signals.update.emit(i)
            sleep(0.1)
        self.signals.enable_button.emit(True)

app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())

rawDescription: PyQt, QThread, GIL, GUI

description: PyQt, QThread, GIL, GUI


code:
def my_callback(sender, **kwargs):
    instance = kwargs.get('instance')
    # you can now reference instance.user
    # send email code here

rawDescription: Can someone show me an example of how to use threadlocals in Django?


code:
def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

rawDescription: How to efficiently find the ordinal number of an element in a strictly increasing python list?

description: Efficiently find the ordinal number of an element in a strictly increasing python list


code:
import itertools
a = 'one'
b = 'two'
c = [4, 5]
d = (10, 20, 30)
list(itertools.chain((a, b, *c, *d)))
list(itertools.chain((a, *c, b, *d)))
list(itertools.chain((*a, *c, b, *d)))

rawDescription: iterate over mix of single values and iterables in python

description: Iterate over mix of single values and iterables in python


code:
# urls
(r'^airAgency/(?P<name>[a-zA-Z0-9]+)/$', 'airAgency.views.index'),
   # this passes the value there as 'name' to the view for index

#views
def index(request, name):   # it needs to know name will be passed to it
    some_query = Agency.objects.filter( agency_name = name )
    #should also add catching for unknown objects to go to 404s
    ...
    return some_sort_of_http_response

rawDescription: how to add remove url from urls.py in views.py

description: Add remove url from urls.py in views.py


code:
list1 = ['a', 'b', None, 'c', 'd']
list2 = ['q', 'w', 'e', None, 'r', 't']
[x + y for x, y in zip(list1, list2) if not (x is None or y is None)]

rawDescription: When creating a new list (from data in two separate source lists) - having difficulty adding source data correctly. (Python)


code: df['sex'] = df.sex.str.lower()

rawDescription: pandas srt.lower() not working on dataframe column

description: Pandas srt.lower() not working on dataframe column


code:
class App(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Frame", size=(550, 300))
        self.panel = wx.Panel(self, -1)
        mainSizer = self.makeOuterSizer()

        # fit layout
        self.panel.SetSizer(mainSizer)
        mainSizer.Fit(self.panel)

# ...

def makeGrid(self):

    sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, ""), wx.VERTICAL)

    # make fields
    itemMonomer1_label = wx.StaticText(self.panel, -1, "Text 1")
    self.itemMonomer1_value = wx.TextCtrl(self.panel, -1, "", size=(100, -1))
    itemMonomer2_label = wx.StaticText(self.panel, -1, "Text 2")
    self.itemMonomer2_value = wx.TextCtrl(self.panel, -1, "", size=(100, -1))
    itemMonomer3_label = wx.StaticText(self.panel, -1, "Text 3")
    self.itemMonomer3_value = wx.TextCtrl(self.panel, -1, "", size=(100, -1))

rawDescription: wxPython - problem with nested sizers, a panel and SetSizer / Fit

description: WxPython - problem with nested sizers, a panel and SetSizer / Fit


code:
from dateutil import parser
s = "Date: Jul 10, 2014 4:41:28 PM"
parser.parse(s, fuzzy=True)

rawDescription: Pythonic way to get datetime from string without leading zero


code:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')

rawDescription: Generating matplotlib graphs without a running X server


code:
def build_board(coords, size):
    # if any(i < 0 for coord in coords for i in coord):
    #     return
    board = [[False] * size for _ in range(size)]
    for (row, col) in coords:
        if row < 0 or col < 0:
            return
        board[row][col] = True
    return board

print(build_board([(0,0)],1)) #[[True]]
print(build_board([(0,0)],2)) #[[True,   False], [False, False]]
print(build_board([(0,0),(1,1)],2)) #[[True, False], [False, True]]
print(build_board([(0,0),(-1,3)],2)) #None

rawDescription: Producing a value based off a coordinate system


rawDescription: Updating data of an Image Plane Widget

description: Updating data of an Image Plane Widget


code:
import cloudant

account = cloudant.Account(USERNAME, auth=(API_KEY, API_SECRET))

rawDescription: Using the Cloudant-Python Library to connect using API Keys


code:
import math

def utmToLatLng(zone, easting, northing, northernHemisphere=True):
    if not northernHemisphere:
        northing = 10000000 - northing

    a = 6378137
    e = 0.081819191
    e1sq = 0.006739497
    k0 = 0.9996

    arc = northing / k0
    mu = arc / (a * (1 - math.pow(e, 2) / 4.0 - 3 * math.pow(e, 4) / 64.0 - 5 * math.pow(e, 6) / 256.0))

    ei = (1 - math.pow((1 - e * e), (1 / 2.0))) / (1 + math.pow((1 - e * e), (1 / 2.0)))

    ca = 3 * ei / 2 - 27 * math.pow(ei, 3) / 32.0

    cb = 21 * math.pow(ei, 2) / 16 - 55 * math.pow(ei, 4) / 32
    cc = 151 * math.pow(ei, 3) / 96
    cd = 1097 * math.pow(ei, 4) / 512
    phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu)

    n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0))

    r0 = a * (1 - e * e) / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (3 / 2.0))
    fact1 = n0 * math.tan(phi1) / r0

    _a1 = 500000 - easting
    dd0 = _a1 / (n0 * k0)
    fact2 = dd0 * dd0 / 2

    t0 = math.pow(math.tan(phi1), 2)
    Q0 = e1sq * math.pow(math.cos(phi1), 2)
    fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * math.pow(dd0, 4) / 24

    fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * math.pow(dd0, 6) / 720

    lof1 = _a1 / (n0 * k0)
    lof2 = (1 + 2 * t0 + Q0) * math.pow(dd0, 3) / 6.0
    lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * math.pow(Q0, 2) + 8 * e1sq + 24 * math.pow(t0, 2)) * math.pow(dd0, 5) / 120
    _a2 = (lof1 - lof2 + lof3) / math.cos(phi1)
    _a3 = _a2 * 180 / math.pi

    latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / math.pi

    if not northernHemisphere:
        latitude = -latitude

    longitude = ((zone > 0) and (6 * zone - 183.0) or 3.0) - _a3

    return (latitude, longitude)

rawDescription: How to convert from UTM to LatLng in python or Javascript

description: Convert from UTM to LatLng in python or Javascript


code:
from Tkinter import *

def swap():
    temp=variable1.get()
    variable1.set(variable2.get())
    variable2.set(temp)

master = Tk()

variable1 = StringVar(master)
variable1.set("one") # default value

variable2 = StringVar(master)
variable2.set("one") # default value

w = OptionMenu(master, variable1, "one", "two", "three")
w.pack()

w2 = OptionMenu(master, variable2, "one", "two", "three")
w2.pack()

but = Button(master, text="Swap", command=swap)
but.pack()

mainloop()

rawDescription: Python Tkinter Swapping OptionMenu Selections


code: random.sample(set(fd_list1 + fd_list2 + fd_list3), 10)

rawDescription: shorter way to merge, shuffle and take first n elements of a list

description: Shorter way to merge, shuffle and take first n elements of a list


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import textwrap
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class TestHandler(tornado.web.RequestHandler):
    def post(self):
        details = ""
        for f in self.request.arguments.values():
            details += "<hr/>" + ", ".join(f)
        self.write(details)

if __name__ == "__main__":
    tornado.options.parse_command_line()

    app = tornado.web.Application(handlers=[(r"/", TestHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Iterating all Values of self.request.arguments


code:
import ast
ast.literal_eval("45.5")
ast.literal_eval("3")
ast.literal_eval("John")

rawDescription: Deduce the type of data in a string

description: Deduce the type of data in a string


code:
# list already contains names
unique_names = set(list_of_all_names)
unique_list = list(unique_names) # lst now contains only unique names

# extract record field from each record and make set
unique_names = set(x.name for x in list_of_all_records)
unique_list = list(unique_names) # lst now contains only unique names

# make dict mapping name to a complete record
d = dict((x.name, x) for x in list_of_records)
# insert complete record into database using name as key
for name in d:
    insert_into_database(d[name])

rawDescription: Which one is more efficient?

description: Which one is more efficient


code:
from docx import Document
import re
import os

path = '/users/tdobbins/downloads/smithtxt'
direct = os.listdir(path)

for i in direct:
    document = Document()
    document.add_heading(i, 0)
    myfile = open('/path/to/read/from/'+i).read()
    myfile = re.sub(r'[^\x00-\x7F]+|\x0c',' ', myfile) # remove all non-XML-compatible characters
    p = document.add_paragraph(myfile)
    document.save('/path/to/write/to/'+i+'.docx')

rawDescription: How to convert txt file or PDF to Word doc using python?

description: Convert txt file or PDF to Word doc using python


code: re.findall('\((\d+)\)', text)

rawDescription: Retrieve matching strings from text file


code:
def script(dicesides, random):
    if dicesides in [4,6,12]:
        dice = int(random.randrange(1, dicesides))
        print(dicesides, " sided dice, score", dice)
    else:
        print("That number is invalid. Please try again.")
        var()

rawDescription: any suggestions on shortening this python code?

description: Any suggestions on shortening this python code


code:
import pandas as pd
df = pd.DataFrame(some_list, columns=["colummn"])
df.to_csv('list.csv', index=False)

rawDescription: How to save a list as a .csv file with python with new lines?

description: Save a list as a .csv file with python with new lines


rawDescription: 3D plot with categorical axis [Python/Matplotlib]


code:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout

class Test(FloatLayout):
    def __init__(self, **kwargs):
        super(Test,self).__init__(**kwargs)
        print(self.parent)
        # None
        print(self.get_parent_window())
        # None
        print(self.get_root_window())
        # None
        print(self.size)
        # [1, 1]
        print(self.size_hint)
        # [1, 1]

class game(App):
    def build(self):
        print(self.root)
        # None
        return Test()

    def on_start(self):
        print(self.root)
        # <__main__.Test object at 0x10a9d8a10>
        print(self.root.parent)
        # <kivy.core.window.window_pygame.WindowPygame object at 0x10a90d6d0>
        print(self.root.get_parent_window())
        # <kivy.core.window.window_pygame.WindowPygame object at 0x10a90d6d0>
        print(self.root.get_root_window())
        # <kivy.core.window.window_pygame.WindowPygame object at 0x10a90d6d0>
        print(self.root.size)
        # [800, 600]

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

rawDescription: Animating in float layout KIVY

description: Animating in float layout KIVY


code:
from multiprocessing.dummy import Pool
from functools import partial
import time

class Test(object):
    def __init__(self):
        self.count = 0
        self.threads = 4

    def get_case(self, x):
        time.sleep(x)

    def callback(self, total, x):
        self.count += 1
        print("Working ({}/{}) cases processed.".format(self.count, total))

    def do_async(self):
        thread_pool = Pool(self.threads)
        input_list = range(5)
        callback = partial(self.callback, len(input_list))
        tasks = [thread_pool.apply_async(self.get_case, (x,),
                                         callback=callback) for x in input_list]
        return [task.get() for task in tasks]

if __name__ == "__main__":
    t = Test()
    t.do_async()

rawDescription: Printing an update line whenever a subprocess finishes in Python 3's multiprocessing Pool


code:
from django.db.models import F
Entry.objects.filter( n_comments__gt=F('n_pingbacks') )

rawDescription: Using database values in django queryset


code:
from django.db import transaction

@transaction.commit_manually
def set_fullname(userprofile, fullname, i=0):
    new_fullname = u"{}{}".format(fullname, str(i) if i else '')
    try:
        userprofile.fullname = new_fullname
        userprofile.save()

        transaction.commit()

        return userprofile
    except IntegrityError:
        transaction.rollback()

        i += 1
        # Just recursively try until we a valid name. This could be problematic if you
        # have a TON of users, but in that case you could just the filter before then to see
        # what number to start from.
        return set_fullname(userprofile, fullname, i)

userprofile = set_fullname(userprofile, fullname)

rawDescription: django - creating users making their fullname unique

description: Django - creating users making their fullname unique


code:
set1 = set([1,2])
set2 = set([2,3])
set1.isdisjoint(set2)

rawDescription: Python: test empty set intersection without creation of new set


code:
import itertools
import numpy as np
N = 10000
H1 = [np.array([0.04,0.03,0.01,0.002])] * N
H2 = [np.array([0.06,0.02,0.02,0.004])] * N

D1 = np.array([0.01,0.02,0.1,0.01]    )
D2 = np.array([0.1,0.3,0.01,0.4] )

Tp = np.sum(D1)
Tn = np.sum(D2)

T = []
append2 = T.append
E = []
append3 = E.append

for h1,h2 in itertools.izip(H1,H2):
    Err = []
    append1 = Err.append
    for v in h1:

        #L1 = [1 if i>=v else 0 for i in h1]
        #L2 = [1 if i>=v else 0 for i in h2]
        L1 = h1 > v
        L2 = h2 > v
        Sp = np.dot(D1,L1)
        Sn = np.dot(D2,L2)

        err = min(Sp+Tn-Sn, Sn+Tp-Sp)
        append1(err)

    b = np.argmin(Err)
    append2(h1[b])
    append3(Err[b])

rawDescription: How to reduce time taken For loop in python?

description: Reduce time taken For loop in python


code:
from selenium.common.exceptions import WebDriverException
try:
    driver = webdriver.Firefox()
except WebDriverException:
    driver = webdriver.Chrome()

rawDescription: py2app selenium without firefox install

description: Py2app selenium without firefox install


code:
import numpy as np

x = np.diag((1,1))
c = np.linalg.solve(x,objective(x))

res = linprog(c, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds),
             options={"disp": True})

rawDescription: Lambda objective function for python linear optimisation


code:
result = [] # final result
for i in range(len(A)):

    row = [] # the new row in new matrix
    for j in range(len(B)):

        product = 0 # the new element in the new row
        for v in range(len(A[i])):
            product += A[i][v] * B[v][j]
        row.append(product) # append sum of product into the new row

    result.append(row) # append the new row into the final result

print(result)

rawDescription: How to multiply matrixes using for loops - Python

description: Multiply matrixes using for loops - Python


code:
import Image

background = Image.open("test1.png")
foreground = Image.open("test2.png")

background.paste(foreground, (0, 0), foreground)
background.show()

rawDescription: How to merge a transparent png image with another image using PIL

description: Merge a transparent png image with another image using PIL


code:
import clr

from System import Array
from System import Byte

clr.AddReference('System.Messaging')
from System.Messaging import MessageQueue
from System.Messaging import Message

ourQueue = '.\\private$\python_in'
ourOutQueue = '.\\private$\python_out'

if not MessageQueue.Exists(ourQueue):
    queue = MessageQueue.Create(ourQueue)
else:
    queue = MessageQueue(ourQueue)

if not MessageQueue.Exists(ourOutQueue):
    out_queue = MessageQueue.Create(ourOutQueue)
else:
    out_queue = MessageQueue(ourOutQueue)

mymessage = Message()
mymessage.Label = 'MyLabel'
mymessage.ResponseQueue = out_queue

mystring = 'hello world'
mybytearray = bytearray(mystring)

# this is very hacky
mymessage.BodyStream.Write(Array[Byte](mybytearray),0,len(mybytearray))

queue.Send(mymessage)

rawDescription: How to create a new MSMQ message in IronPython with label, reply queue and other properties

description: Create a new MSMQ message in IronPython with label, reply queue and other properties


code:
import _winreg as wr

key_location = r'Software\MyCompany\MyProgram'
try:
    key = wr.OpenKey(wr.HKEY_CURRENT_USER, key_location, 0, wr.KEY_ALL_ACCESS)
    value = wr.QueryValueEx(key, 'My String')
    print('Found value:', value)
except:
    print('Creating value.')
    key = wr.CreateKey(wr.HKEY_CURRENT_USER, key_location)
    wr.SetValueEx(key, 'My String', 0, wr.REG_SZ, 'This is what I want to save!')
wr.CloseKey(key)

rawDescription: Saving data in Python without a text file?


code:
def print_menu():
    print('1. Add a student and his/her grade')
    print('2. Quit and Sort')

grades = {}
menu_choice = 0
print_menu()
while menu_choice != 2:
    menu_choice = int(input("Type in a number (1-2): "))
    if menu_choice == 1:
        print("Add Student and His/Her Grade")
        name = input("Student: ")
        phone = input("Grade: ")
        grades[name] = phone #Use the right variables
    elif menu_choice == 2:
        print("Grades:")
        for x in sorted(grades.keys()):  #Sort
            print("Student: ", x, "\tGrade:", grades[x])
            print()
        print_menu()

rawDescription: How do I sort to this code with Python?

description: Sort to this code with Python


code:
plt.table(cellText=dcsummary.values,colWidths = [0.25]*len(dc.columns),
rowLabels=dcsummary.index,
colLabels=dcsummary.columns,
cellLoc = 'center', rowLoc = 'center',
loc='bottom', bbox=[0.25, -0.5, 0.5, 0.3])

rawDescription: Matplotlib table plot, how to add gap between the graph and table


code:
import time
import subprocess

p = subprocess.Popen(["firefox", "http://www.facebook.com"])
time.sleep(600)
p.kill()

rawDescription: Close/terminate web browser using Python 3?


code:
class memoized(object):
   '''Decorator. Caches a function's return value each time it is called.
   If called later with the same arguments, the cached value is returned
   (not reevaluated).
   '''
   def __init__(self, func):
      self.func = func
      self.cache = {}
   def __call__(self, *args):
      if not isinstance(args, collections.Hashable):
         # uncacheable. a list, for instance.
         # better to not cache than blow up.
         return self.func(*args)
      if args in self.cache:
         return self.cache[args]
      else:
         value = self.func(*args)
         self.cache[args] = value
         return value
   def __repr__(self):
      '''Return the function's docstring.'''
      return self.func.__doc__
   def __get__(self, obj, objtype):
      '''Support instance methods.'''
      return functools.partial(self.__call__, obj)

rawDescription: how to define a smart compute function decorator?

description: Define a smart compute function decorator


code:
words = {"the", "set", "of", "words"}
if words <= set_of_words:
   do_stuff()

rawDescription: Testing if multiple objects are in a list using one "in" statement (Python)


code:
import os
os.system("acpi -b > batteryinfo.txt")
#code to parse batteryinfo.txt

rawDescription: laptop's power state on ubuntu

description: Laptop's power state on ubuntu


code:
import glob,csv
files = glob.glob("*.txt")
fo = open("combined.csv","a")
writer = csv.writer(fo,delimiter=' ')

datum = {}

for f in files:
    with open(f) as fi:
        for row in csv.reader(fi,delimiter=' '):
            crow = row[0],row[4]
            if crow in datum:
                if float(datum[crow][-4]) < float(row[3]):
                    datum[crow] = row[0:]
            else:
                datum[crow] = row[0:]

rawDescription: SOLVED: Double conditional filtering of many csv files in python


rawDescription: Python NetworkX Increase circular graph size


code:
r = requests.get(url)

data = r.json() # as its a rest api you can directly access the json object

print(data)

rawDescription: How to read objects from REST API using python?

description: Read objects from REST API using python


code:
EXTRA_MODEL_FIELDS = (
    (
        "cartridge.shop.models.Order.callback_uuid",
        "django.db.models.CharField",
        (),
        {"blank" : False, "max_length" : 36, "default": ""},
    ),
    (
        "cartridge.shop.models.Product.download_file",
        "django.db.models.FileField",
        (),
        { "blank" : True, "default" : "" , "upload_to" : "downloads", },
    ),
)

rawDescription: mezzanine and cartridge schemamigration issues

description: Mezzanine and cartridge schemamigration issues