code:
for m in messages:
   if m.SenderEmailAddress == 'some_sender@somewhere.com':
       print(m)

rawDescription: Python Outlook getting all emails from Sender


code:
old_aspect = float(imagex)/float(imagey)
new_aspect = float(width)/float(height)
if old_aspect < new_aspect:
  height = int(width / old_aspect)
else:
  width = int(height * old_aspect)

rawDescription: How do I make PIL take into account the shortest side when creating a thumbnail?

description: Make PIL take into account the shortest side when creating a thumbnail


code:
from collections import OrderedDict

dict=OrderedDict()
dict['first']=1
dict['second']=2
dict['third']=3
dict

rawDescription: How to preserve ordering of items in a python dictionary?

description: Preserve ordering of items in a python dictionary


rawDescription: Join last element in list

description: Join last element in list


code: results.filter('created > ', now - datetime.timedelta(days=2))

rawDescription: how to filter for objects with time

description: Filter for objects with time


code:
import networkx as nx

B = nx.Graph()
B.add_edge('a',1)
B.add_edge('a',2)
B.add_edge('b',1)
B.add_edge('b',2)
B.add_edge('b',3)
B.add_edge('c',3)

nodes = ['a','b','c']
seen = set()
for u in nodes:
#    seen=set([u]) # print both u-v, and v-u
    seen.add(u) # don't print v-u
    unbrs = set(B[u])
    nbrs2 = set((n for nbr in unbrs for n in B[nbr])) - seen
    for v in nbrs2:
        vnbrs = set(B[v])
        common = unbrs & vnbrs
        weight = len(common)
        print("%s, %s, %d"%(u,v,weight))

rawDescription: Bipartite projection and write to CSV with NetworkX -- how to speed up writing to handle large file


code: contents = ''.join([chr(v) for v in stream.ToArray()])

rawDescription: image file from MemoryStream (IronPython web service)

description: Image file from MemoryStream (IronPython web service)


code:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
x = np.random.normal(size=100)
with plt.rc_context(dict(sns.axes_style("whitegrid"),
                         **sns.plotting_context("notebook", font_scale=1.5))):
    sns.kdeplot(x, shade=True)

rawDescription: Using with sns.set in seaborn plots

description: Using with sns.set in seaborn plots


code:
class Checkbook:

    def __init__(self):
        self.transactions = []    # Checkbook is just a wrapper around a list

    def __getitem__(self, index): # implementing [x]
        return self.transactions[index]

    def __setitem__(self, index, transaction): #implementing [x] = i
        self.transactions[index] = transaction

    def append(self, transaction): # implementing .append(x)
        self.transactions.append(transaction)

    def extend(self, transaction_list): # implementing .extend([x,y,z])
        self.transactions.extend(transaction_list)

    # and so on for every method which you want to support

rawDescription: Looking for OOP Pythonic approach for putting objects in a 'list object' as opposed to just using [list]


code:
def setattr_wrapper(cls):
    def watcher_setattr(self, attr, val):
        super(cls, self).__setattr__(attr, val)
        watched = cls.__dict__["_watched_attrs"]
        if attr in watched:
            for method in watched[attr]:
                getattr(self, method)(attr, val)
    return watcher_setattr

class AttrNotifier(type):
    def __new__(metacls, name, bases, dct):
        dct["_watched_attrs"] = {}
        for key, value in dct.items():
            if hasattr(value, "_watched_attrs"):
                for attr in getattr(value, "_watched_attrs"):
                    if not attr in dct["_watched_attrs"]:
                        dct["_watched_attrs"][attr] = set()
                    dct["_watched_attrs"][attr].add(key)
        cls = type.__new__(metacls, name, bases, dct)
        cls.__setattr__ = setattr_wrapper(cls)
        return cls

def on_change(*args):
    def decorator(meth):
        our_args = args
        #ensure that this decorator is stackable
        if hasattr(meth, "_watched_attrs"):
            our_args = getattr(meth, "_watched_attrs") + our_args
        setattr(meth, "_watched_attrs", our_args)
        return meth
    return decorator

# from here on, example of use:
class A(metaclass=AttrNotifier):
    @on_change("bacon")
    def bacon_changed(self, attr, val):
        print ("%s changed in %s to %s" % (attr, self.__class__.__name__, val))

class Spam(A):
    @on_change("bacon", "pepper")
    def changed(self, attr, val):
        print ("%s changed in %s to %s" % (attr, self.__class__.__name__, val))

a = A()
a.bacon = 5

b = Spam()
b.pepper = 10
b.bacon = 20

rawDescription: Detect if super() has a function with decorator?


code:
from distutils.core import setup
import py2exe

# Change the path in the following line for webdriver.xpi
data_files = [('selenium/webdriver/firefox', ['D:/Python27/Lib/site-packages/selenium/webdriver/firefox/webdriver.xpi'])]

setup(
    name='General name of app',
    version='1.0',
    description='General description of app',
    author='author name',
    author_email='author email',
    url='',
    windows=[{'script': 'abc.py'}],   # the main py file
    data_files=data_files,
    options={
        'py2exe':
            {
                'skip_archive': True,
                'optimize': 2,
            }
    }
)

rawDescription: Make exe file from python selenium tests


rawDescription: Floating point operation again

description: Floating point operation again


code:
def get_average(student, typeOfWork):
    return average(student[typeOfWork])

get_average(lloyd,'homework')
get_average(lloyd,'tests')

rawDescription: How do I get a dictionary's information when passed as a variable in a function?

description: Get a dictionary's information when passed as a variable in a function


code:
from collections import OrderedDict

A = OrderedDict({('a','b'): 4, ('b','a'): 5, ('b','c'): 2, ('a','c'): 6})
B = OrderedDict({'b': 2, 'c' : 5})

''' Method 1 quadratic '''
C = {}
for bk, bv in B.items():
    for ak, av in A.items():
        if bk == ak[1]:
            C[ak] = bv * av

print(C)

''' Method 2 linear '''
D = {}
for ak, av in A.items():
    if ak[1] in B:
        D[ak] = av * B[ak[1]]

print(D)

''' Method 3 linear one-liner '''
E = {ak: av * B[ak[1]] for ak, av in A.items() if ak[1] in B}

print(E)

rawDescription: 2 OrderedDictionarys multiplying the two values, multiple keys


code:
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class ExtendedQLabel(QLabel):
    def __init(self, parent):
        super().__init__(parent)

    clicked = pyqtSignal()
    rightClicked = pyqtSignal()

    def mousePressEvent(self, ev):
        if ev.button() == Qt.RightButton:
            self.rightClicked.emit()
        else:
            self.clicked.emit()

if __name__ == '__main__':
    app = QApplication([])
    eql = ExtendedQLabel()
    eql.clicked.connect(lambda: print('clicked'))
    eql.rightClicked.connect(lambda: print('rightClicked'))
    eql.show()
    app.exec_()

rawDescription: How to add signals to a QLabel in PyQt5?

description: Add signals to a QLabel in PyQt5


rawDescription: Assign values to multiple columns in Pandas


code:
from threading import Thread, Lock
some_var = 0
lo = Lock()

def some_func(id):
    global lo
    with lo:
        global some_var
        print("{} here!".format(id))
        for i in range(1000000):
            some_var += 1
        print("{} leaving!".format(id))

rawDescription: Python threading Lock not working in simple example


code:
m = b < 6
b[m] = np.where(b[m]< a,b[m],a)

rawDescription: numpy array filtering twice and replace

description: Numpy array filtering twice and replace


code:
#!/usr/bin/python
import wx

class Tom(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(400, 420))

        panel = wx.Panel(self, -1)
        vbox = wx.BoxSizer(wx.HORIZONTAL)
        self.message=""
        self.write = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE, value=self.message)
        button_send = wx.Button(panel, 1, label='b1')

        vbox.Add(self.write, 1, wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT | wx.BOTTOM, 15)
        vbox.Add(button_send, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 20)
        self.Bind(wx.EVT_BUTTON, self.OnSend, id=1)
        panel.SetSizer(vbox)
        self.Centre()

    def OnSend(self, event):
        b=event.GetEventObject().GetLabel()
        if b.endswith('1'):
            self.message = self.message+"sss"
            self.write.SetValue(self.message)

class MyApp(wx.App):
    def OnInit(self):
        frame = Tom(None, -1, 'Tom')
        frame.ShowModal()
        frame.Destroy()
        return True

app = MyApp()
app.MainLoop()

rawDescription: how to control a function of TextCtrl as dynamic in wxpython?

description: Control a function of TextCtrl as dynamic in wxpython


code: people = [person for person in people if person.name != 'Bob']

rawDescription: Remove a class instance from a list

description: Remove a class instance from a list


code:
import htmlentitydefs
['&'+htmlentitydefs.codepoint2name[ord(x)]+';' for x in u'Íøñ']

rawDescription: How to escape unicode characters to symbol entitiy names in python?

description: Escape unicode characters to symbol entitiy names in python


code: a = Foo()

rawDescription: Python: class methods calling other class methods when initial method is called from within another class


code:
CODECFORTR = UTF-8
SOURCES = source.py
TRANSLATIONS = translation.ts

rawDescription: PyQt4: Non-ASCII character detected in trUtf8 string


code:
class Parse(webapp2.RequestHandler):
    def post(self):
        data = self.request.get("data")

        # Note - order reversed
        funcs = [
            ("func3_option", some.other_other_function),
            ("func2_option", some.other_function),
            ("func1_option", some.function)
        ]
        for opt_name, func in funcs:
            if self.request.get(opt_name) != "disabled":
                data = func(data)

        self.response.write(data)

rawDescription: Ordering multiple functions with enable/disable options


code:
import re
for tag in soup.find_all(re.compile("^value_xxx_c_1_f_8_a_")):
    print(tag.name)

rawDescription: How to use Beautiful Soup to find a tag with changing id?

description: Use Beautiful Soup to find a tag with changing id


code:
import multiprocessing
import queue
import threading
import sys
import socket

MAX_THREAD_COUNT = multiprocessing.cpu_count()

def main(cur):
    cur.execute("""UPDATE ipv6
                      SET port_21 = 0,
                          port_80 = 0,
                          port_443 = 0
                    WHERE address = 'N/A'""")
    q = queue.Queue()
    for _ in range(MAX_THREAD_COUNT):
        CheckPort(q).start()
    cur.execute("""SELECT id_ipv6,
                          address
                     FROM ipv6
                    WHERE address != 'N/A'""")
    for row in cur.fetchall():
        q.put(row)
    q.join()
    for thread in threading.enumerate():
        if isinstance(thread, CheckPort):
            thread.stop()
            thread.join()

class CheckPort(threading.Thread):

    def __init__(self, q):
        super().__init__()
        self.__q = q
        self.__run = True

    def stop(self):
        self.__run = False

    def run(self):
        while self.__run:
            try:
                id, address = self.__q.get(True, 1)
            except queue.Empty:
                continue
            with lock:
                try:
                    cur.execute('''UPDATE ipv6
                                      SET port_21 = ?,
                                          port_80 = ?,
                                          port_443 = ?
                                    WHERE id_ipv6 = ?''',
                                self.check_port(address, 21),
                                self.check_port(address, 80),
                                self.check_port(address, 443),
                                id)
                    db.commit()
                except Exception as error:
                    print('Error:', error, file=sys.stdout)
                self.__q.task_done()

    @staticmethod
    def check_port(address, port):
        sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        sock.settimeout(2)
        try:
            sock.connect((address, port))
        except socket.timeout:
            return 0
        else:
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()
            return 1

if __name__ == '__main__':
    try:
        main(cur)
    except Exception as error:
        print('Error:', error, file=sys.stdout)

rawDescription: Python threads didn't want to close

description: Python threads didn't want to close


code:
import os
import sys

sys.path.append(os.path.realpath(os.getcwd()))

rawDescription: Importing class from another package

description: Importing class from another package


code:
def num_groups(regex):
    return re.compile(regex).groups

rawDescription: Find out number of capture groups in Python regular expressions


code:
import wx

class MyApp(wx.App):
    def OnInit(self):
        frame = wx.Frame(None, -1, "Hello from wxPython")
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

app = MyApp(0)
app.MainLoop()

rawDescription: iPython wx support?

description: IPython wx support


code:
with open('file.txt', 'r') as f:
    print(len(f.readlines()))

rawDescription: Printing number of items from a data file


code:
import pprint

pprint.pprint(globals())
pprint.pprint(locals())

rawDescription: What is a Python equivalent of PHP's var_dump()?


code:
stdin, stdout, stderr = client.exec_command(filedelete)  # Non-blocking call
exit_status = stdout.channel.recv_exit_status()          # Blocking call
if exit_status == 0:
    print ("File Deleted")
else:
    print("Error", exit_status)
client.close()

rawDescription: Wait until task is completed on Remote Machine through Python


code:
import collections
counter = collections.Counter()
counter.update((('user1', 'loggedin'),))
counter.update((('user2', 'compiled'),))
counter.update((('user1', 'compiled'),))
counter.update((('user1', 'compiled'),))
counter

rawDescription: How to count co-ocurrences with collections.Counter() in python?

description: Count co-ocurrences with collections.Counter() in python


code:
pivoted = pd.pivot_table(data=df, columns='Courses', index='Name',
                         aggfunc='sum', fill_value=0)

rawDescription: Generate new dataframe with values in old dataframe as new features in python


code:
#import libraries
from glob import iglob
import shutil
import os
#create path variable
PATH = r'C:\music'
#create everything.mp3
destination = open('everything.mp3', 'wb')
for filename in iglob(os.path.join(PATH, '*.mp3')):
    shutil.copyfileobj(open(filename, 'rb'), destination)
#make them all together with for
destination.close()
#close file

rawDescription: Concatenate audio files [Python 2.7]

description: Concatenate audio files [Python 2.7]


code:
def funB(x, a, **kwargs):
    return funA(x, a, **kwargs)

rawDescription: Call another function and optionally keep default arguments


code:
is_prime = True

for x in range (2, number):
    trial = number % x
    if trial != 0:
        print (x, "is NOT a divisor of", number, "...")
    else:
        is_prime = False
        print (x, "is a divisor of", number, "...")

if is_prime:
    print (number, "is a prime number!")
else:
    print (number, "is not a prime number!")

rawDescription: Printing after a break in a for loop

description: Printing after a break in a for loop


code:
from subprocess import Popen
from tempfile import NamedTemporaryFile

tmp = NamedTemporaryFile('w+')
sbp = Popen(['program_1', '-i', 'input.file', '-o', tmp.name])
sbp = Popen(['program_2', '-i', tmp.name, '-o', 'output.file'])
tmp.close()

rawDescription: Handle file input/output of external binary from python


rawDescription: What's the best django way to do a query that spans several tables?


code:
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: not u.is_authenticated())
def my_view(request):
    ...

rawDescription: Allow access to only non-logged in user in django


rawDescription: Numpy concatenating ints to string

description: Numpy concatenating ints to string


code:
topToolBar.Add(toolbar1,1,wx.ALIGN_LEFT,4) # note the 2nd param 'proportion' is 1
#topToolBar.AddStretchSpacer()
topToolBar.Add(toolbar1,0,wx.ALIGN_RIGHT,4)

rawDescription: How to align 2 toolbars on same the row, one aligned left and one aligned right?

description: Align 2 toolbars on same the row, one aligned left and one aligned right


rawDescription: How to transform a python function of multiple parameters to one that accepts a list?

description: Transform a python function of multiple parameters to one that accepts a list


code:
from Tkinter import *

def getpwd():
    password = ''
    root = Tk()
    pwdbox = Entry(root, show = '*')
    def onpwdentry(evt):
         password = pwdbox.get()
         root.destroy()
    def onokclick():
         password = pwdbox.get()
         root.destroy()
    Label(root, text = 'Password').pack(side = 'top')

    pwdbox.pack(side = 'top')
    pwdbox.bind('<Return>', onpwdentry)
    Button(root, command=onokclick, text = 'OK').pack(side = 'top')

    root.mainloop()
    return password

rawDescription: Simplest method of asking user for password using graphical dialog in Python?


rawDescription: Specify which column not to load in numpy.loadtxt()


code:
from tkinter import Tk, StringVar, Entry
root = Tk()
sv = StringVar(root)
entry = Entry(root, textvariable=sv)
sv.get()
entry.insert('insert', 'hello')
sv.get()

rawDescription: Cannot get the updated value from entry python tkinter


code: return_list = [x for x in list_search if x not in list_users]

rawDescription: Python. How to optimize search functions


code:
if event.inaxes is ax:
    ...

rawDescription: Determine axes of calling event in matplotb


code:
newpath = r'C:\Program Files\arbitrary'
if not os.path.exists(newpath):
    os.makedirs(newpath)

rawDescription: How to create new folder?

description: Create new folder


code:
css_files = soup.findAll('link',{'rel':'stylesheet', 'media': lambda L: L != 'print'})
# [<link href="/assets/application-b275a30a2c6726e3fabb10517f7cb812.css" media="all" rel="stylesheet" type="text/css"/>]

rawDescription: exclude findAll result set

description: Exclude findAll result set


rawDescription: Python get generated url to string

description: Python get generated url to string


code:
import cherrypy
class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

# bind to all IPv4 interfaces
cherrypy.config.update({'server.socket_host': '0.0.0.0'})
cherrypy.quickstart(HelloWorld())

rawDescription: Problems with running cherrypy's hello world example


code: jsonld.frame(doc, frame)

rawDescription: Rdflib, Python: Are there any object framing methods to get nested dict/list structure from a graph a-la JSON-LD?


code: combined_array = np.concatenate((X2WINa, X2Winb))

rawDescription: combining two arrays in numpy,

description: Combining two arrays in numpy,


code:
import collections, json

def flatten(container):
    for i in container:
        if isinstance(i, list) or isinstance(i, tuple):
            for j in flatten(i):
                yield j
        else:
            yield i

with open("D:\\1.SnD\Work\PyCharmProjects\project.json", 'rb') as f:
    json_data = json.loads(str(f.read(), 'utf-8'))

print(collections.Counter(
       flatten(json_data['children'][0]['scripts']))['keyPressed:'])

rawDescription: Count the number of times a value exists in arbitrary nested lists


code:
count = 1
while count <= 100:
    print(count)
    count += 1

rawDescription: Python Count up & Down loop

description: Python Count up & Down loop


code: env.forward_agent = True

rawDescription: How to ForwardAgent yes using fabric?

description: ForwardAgent yes using fabric


rawDescription: Python constructor with many optional parameters


code:
import numpy as np
from sympy import Matrix
a = np.array([[5, 4, 2, 1], [0, 1, -1, -1], [-1, -1, 3, 0], [1, 1, -1, 2]])
m = Matrix(a)
m
P, J = m.jordan_form()
J

rawDescription: Compute jordan normal form of matrix in python/numpy


rawDescription: How to sort a multidimensional list to alphabetical order based on its first row letters in python

description: Sort a multidimensional list to alphabetical order based on its first row letters in python


rawDescription: How to make request.GET appear in form field?

description: Make request.GET appear in form field


code:
def num2txt(num, k=3):

    line = str(num)
    padding = len(line)%k
    if padding:
        line = '0'*(k-padding) + line
    line = [line[i:i+k] for i in range(0, len(line), k)]

    return line

rawDescription: How to specify a fill character to string and split it by chunk?

description: Specify a fill character to string and split it by chunk


code:
endprog = "start"

while endprog != "exit":

    para = int(input("Enter a number 1-9 -> "))

    if para == 1:
        print(''' THE ORIGINATOR
1's are originals. Coming up with new ideas and executing them is
natural. Having things their own way is another trait that gets them as
being stubborn and arrogant. 1\'s are extremely honest and do well to
learn some diplomacy skills. They like to take the initiative and are
often leaders or bosses, as they like to be the best. Being
self-employed is definitely helpful for them. Lesson to learn: Others'
ideas might be just as good or better and to stay open minded.
Famous 1's: Tom Hanks, Robert Redford, Hulk Hogan, Carol Burnett, Wynona
Judd, Nancy Reagan, Raque l Welch.''')
    elif para == 2:
        print('''" THE PEACEMAKER
2's are the born diplomats. They are aware of others' needs and moods
and often think of others before themselves. Naturally analytical and
very intuitive they don't like to be alone. Friendship and companionship
is very important and can lead them to be successful in life, but on the
other hand they'd rather be alone than in an uncomfortable relationship.
Being naturally shy they should learn to boost their self-esteem and
express themselves freely and seize the moment and not put things off.
Famous 2's: President Bill Clinton, Madonna, Whoopee Goldberg, Thomas
Edison, Wolfgang Amadeus Mozart."''')

rawDescription: if statement does not return an answer in python

description: If statement does not return an answer in python


code:
with open('[Content_Type].xml', 'r') as fl:
    readout = fl.read()
spl = readout.split('><')
spl.insert(len(spl)-1, """Override ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml" PartName="/ppt/slides/slide%d.xml"/""" %(slides+1))
final = '><'.join(spl)
with open('[Content_Type].xml', 'w') as fl:
    fl.write(final)

rawDescription: Modifie the xml data in python

description: Modifie the xml data in python


code: index.apply(" OR ".join("silver pearl splayer").split())

rawDescription: How can I make Zope TextIndex return similar documents?

description: Make Zope TextIndex return similar documents


code:
import collections
nt = collections.namedtuple('nt',['one','two'])
nt

import dill

dill.copy(nt)

class Foo(object):
  cnt = nt

f = Foo()
f.cnt
f.cnt(1,2)

dill.copy(f)
dill.copy(Foo)

rawDescription: Where should I define namedtuple classes in Python - which namespace?


code:
import numpy as np
from scipy.special import binom as binom
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot
plt = pyplot
from matplotlib import cm
import matplotlib

'''Define A_(pm)  (Gauss-laguerre polinomials) '''

def Ln(p,m,xj):
    Ln=0.
    for i in range(p+1):#el p+1 es por la indexacion
        Ln=Ln+((-1)**i)*binom(p+m,p-i)*(xj**i)/np.math.factorial(i)
    return Ln

def A(p, m, r, phi):#defino G-L

    A0=np.zeros((len(phi),len(r)))
    for j, rn in enumerate(r):
            A0[:,j]=np.exp(-rn**2)*Ln(p,0,2*rn**2)

    A1=np.zeros_like(A0)
    for j, rn in enumerate(r):
         for k, phin in enumerate(phi):
            A1[k,j]=2*((2*rn**2)**(m/2))*np.sqrt(np.math.factorial(p)/np.math.factorial(p+m))*np.exp(-rn**2)*Ln(p,m,2*(rn**2))*np.sin(m*phin)

    A2=np.zeros_like(A0)

    for j, rn in enumerate(r):
        for k, phin in enumerate(phi):
            A2[k,j]=2*(2*rn**2)**(m/2)*np.sqrt(np.math.factorial(p)/np.math.factorial(p+m))*np.exp(-rn**2)*Ln(p,m,2*rn**2)*np.cos(m*phin)

    return A0, A1, A2

pi=np.pi
r=np.linspace(0,6,50)
phi=np.linspace(0,2*pi,40)

A0, A1, A2=A(5,1,r,phi)#

fig = pyplot.figure(figsize=(11,9), dpi=100)
ax = pyplot.subplot(111, projection='3d')
R, P = np.meshgrid(r, phi)
X, Y = R*np.cos(P), R*np.sin(P)
ax.plot_surface(X, Y, A0)

plt.show()

rawDescription: 3d plotting: cylindrical coordinate function


code:
class A(models.Model):
    name = models.CharField(max_length=60)
    def __unicode__(self):
        return self.name

rawDescription: Django Admin.py customize form

description: Django Admin.py customize form


code:
from matplotlib import pyplot as plt
import numpy as np
xx = np.arange(10)
np.random.seed(101)
yy = np.random.random( 10 )
plt.plot(xx, yy, 'o' )
xticks, xticklabels = plt.xticks()
# shift half a step to the left
# x0 - (x1 - x0) / 2 = (3 * x0 - x1) / 2
xmin = (3*xticks[0] - xticks[1])/2.
# shaft half a step to the right
xmax = (3*xticks[-1] - xticks[-2])/2.
plt.xlim(xmin, xmax)
plt.xticks(xticks)
plt.show()

rawDescription: Markers on plot edges cut off in matplotlib


code:
class ConnectionHandler(object):
    def __init__(self, databases=None):
        """
        databases is an optional dictionary of database definitions (structured
        like settings.DATABASES).
        """
        self._databases = databases
        self._connections = local()

rawDescription: How are Django persistent connections(CONN_MAX_AGE) distributed?


code:
import matplotlib.pyplot as plt
import datetime
import numpy as np
from obspy.imaging.beachball import Beach
from matplotlib.dates import date2num

# x = np.arange(0,100,4)

x = date2num(np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)]))
y = np.random.randint(100, size=x.shape)

fig, ax = plt.subplots(figsize=(10,6))
ax.plot(x,y)

bball = Beach([70, 90, 80], xy=(x[10],y[10]), width=(.1,15), linewidth=1, alpha=0.85)

bball.set_zorder(1)
ax.add_collection(bball)
plt.show()

rawDescription: ObsPy Plot Beachball in Time Series

description: ObsPy Plot Beachball in Time Series


rawDescription: Getting time frequency of number in array in Python?


rawDescription: Specifying variable in Python

description: Specifying variable in Python


code:
x
from scipy.ndimage.measurements import label
labeled_x, num_labels = label(x)
num_labels
labeled_x

rawDescription: How can I efficiently translate "terrain" numpy array into networkx graph?

description: Efficiently translate "terrain" numpy array into networkx graph


code:
class UserForm(ModelForm):
    bio = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 20}))
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'bio')

rawDescription: How to add extra fields using django.forms Textarea

description: Add extra fields using django.forms Textarea


code:
class Docs :
    def __init__ (self, inTitle, inFormats):
        self.title = inTitle
        self.nameFormats = inFormats
        self.title = []
        self.nameFormats = []
        self.fileMatches = []
        self.dirMatches = []

rawDescription: create class instance and append to list

description: Create class instance and append to list


rawDescription: Finding groups with the same name in Pandas?


code:
class EditForm(forms.Form):
    summary = forms.CharField()
    description = forms.CharField(widget=forms.TextArea)

class CreateForm(EditForm):
    name = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(CreateForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder = ['name', 'summary', 'description']

rawDescription: Django forms, inheritance and order of form fields


code:
list = []
f = open('file', 'r')
for line in f:
   for char in line:
       if (char in listOfSpecialChars):
           list.append(char)

rawDescription: how to find all occurrence of special characters in a file and add them to a python list

description: Find all occurrence of special characters in a file and add them to a python list


code:
order  =  [4, 3, 5, 2, 1]
people = "ABCDE"

result = [x[1] for x in sorted(zip(order, people))]

rawDescription: Really easy python standoff

description: Really easy python standoff


code:
all_ids = []
for m in m_array:
    for s in s_array:
        chi = view.apply_async(run_simulation, m=m, s=s)
        async_results.append(chi)
        all_ids.extend(chi.msg_ids)

rc.get_result(all_ids, owner=False).wait_interactive()

rawDescription: Monitoring status of ipyparallel completion


code:
import datetime
date = (datetime.date.today() - datetime.timedelta(1)).strftime("%d-%b-%Y")
result, data = mail.uid('search', None, '(SENTSINCE {date})'.format(date=date))

rawDescription: Searching through IMAP folder for multiple criterion (python)


code:
target_values = training_set['IC50']
training_data = training_set.drop('IC50')

clf = LinearRegression()
clf.fit(training_data, target_values)

test_data = test_set.drop('IC50')

predicted_values = clf.predict(test_data)

rawDescription: can one predict variable using scikit-learn rather binary classification if yes than how

description: Can one predict variable using scikit-learn rather binary classification if yes than how


code:
d={1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}
''.join('%(message)s%(user)s
' % v for k,v in sorted(d.items()))

rawDescription: Parse dict of dicts to string

description: Parse dict of dicts to string


code:
#...
rules =  models.Rule.objects.filter(pk__in=rule_ids)
for rule in rules:
    module.rules.add(rule)
# instead of: module.rules = rules

rawDescription: How to get values from many to many relationships in django

description: Get values from many to many relationships in django


code:
with open(filename, 'r') as fd:
    lines = fd.read().splitlines()

rawDescription: How do I close a file I didn't assign to a variable in Python?

description: Close a file I didn't assign to a variable in Python


code: return JSONResponse(operator.attrgetter('user_permissions', 'username', 'first_name')(request.user))

rawDescription: django - view returning no value?

description: Django - view returning no value


code:
@subscriber(NewRequest)
def new_request_subscriber(event):
  if condition:
    raise pyramid.httpexceptions.HTTPFound(location=somelocation) ## to issue a proper redirect

rawDescription: How to add conditional redirect to each view in Pyramid?

description: Add conditional redirect to each view in Pyramid


code:
result = df.pivot(index='animal', columns='age', values='count')
result
result.columns = ['age{:d}'.format(col) for col in result.columns]
result

rawDescription: Pandas transposition inside dataframe

description: Pandas transposition inside dataframe


code:
df
df.groupby(["A", "B", "C"]).transform('sum')
df["D"] = df.groupby(["A", "B", "C"]).transform('sum')
df

rawDescription: how to expand sum column using pandas dataframe

description: Expand sum column using pandas dataframe


rawDescription: [Optimizing]Appending Numbers from a list with delimeters


code:
from datetime import datetime,timedelta
month = 1 #jan
day = 1
year = datetime.now().year #if you want current year, year's value otherwise
dt = datetime(year,month,day)
if month==12:
    year += 1
    month = 0
dt_end_month = datetime(year,month+1,day) - timedelta(days=1)
dt_end_month

rawDescription: Month starting date and Ending date

description: Month starting date and Ending date


code: all_keys = set().union(*(d.keys() for d in mylist))

rawDescription: Extract all keys from a list of dictionaries


rawDescription: Pandas groupby: percentage above threshold


code:
indices = 0, 2
somelist = [i for j, i in enumerate(somelist) if j not in indices]

rawDescription: Deleting multiple elements from a list

description: Deleting multiple elements from a list


code:
import numpy as np
import shapely.geometry as geom

# Define the arc (presumably ezdxf uses a similar convention)
centerx, centery = 3, 4
radius = 2
start_angle, end_angle = 30, 56 # In degrees
numsegments = 1000

# The coordinates of the arc
theta = np.radians(np.linspace(start_angle, end_angle, numsegments))
x = centerx + radius * np.cos(theta)
y = centery + radius * np.sin(theta)

arc = geom.LineString(np.column_stack([x, y]))

rawDescription: How to create polygons with arcs in shapely (or a better library)

description: Create polygons with arcs in shapely (or a better library)


code:
class Base(object):
    pass

def base_factory():
    return Base()  # in real code, this would probably be something opaque

def Derived(Base):
    def __new__(cls):
        self = base_factory()     # get an instance of Base
        self.__class__ = Derived  # and turn it into an instance of Derived
        return self

rawDescription: Python: is there a use case for changing an instance's class?


code:
def f(x,y):
    '...some code...'
    single_value = array[x,y] # = dependent array (e.g. DEM)
    '...some code...'
    return z

x = np.arange(array.shape[0])
y = np.arange(array.shape[1])
xx, yy = np.meshgrid(x,y, sparse=True)

f_vec = np.vectorize(f) # vectorization of function f

tp_vec = f_vec(xx,yy).T

rawDescription: Updated: Apply (vectorized) function on each cell to interpolate grid


code:
with open('myoutfilename', 'w') as myoutfile:
    subprocess.call(cmd, stdout=myoutfile)

rawDescription: redirect output to a text file using windows shell '>' in python

description: Redirect output to a text file using windows shell '>' in python


code:
from functools import wraps
def user_required(f):
    @wraps(f)
    def decorator(*args, **kwargs):
        if not current_user.is_authenticated():
            return login_manager.unauthorized()
            # or, if you're not using Flask-Login
            # return redirect(url_for('login_page'))
        return f(*args, **kwargs)
    return decorator

rawDescription: Flask pluggable views and login required


code:
df
df.groupby('cc')['total_value'].apply(lambda x: 100*x.rank()/len(x))
df['prank'] = df.groupby('cc')['total_value'].apply(lambda x: 100*x.rank()/len(x))
df

rawDescription: Python Pandas - returning results of groupby function back to parent table


code:
def Convert_toFullStop(text):
    return text.replace('_', '.')

rawDescription: Python - Convert Underscore to Fullstop

description: Python - Convert Underscore to Fullstop


code:
arr = np.arange(100*100*100).reshape(100, 100, 100)
np.random.shuffle(arr)
indices =  np.argpartition(arr.flatten(), -2)[-2:]
np.vstack(np.unravel_index(indices, arr.shape)).T
arr[97][99][98]
arr[97][99][99]

rawDescription: Get the indices of N highest values in an ndarray


code: brands[brands > 0.001] = 1

rawDescription: If x in y does not equal 0 then replace with 1


code:
import pandas as pd
import re

df = pd.read_csv('Crokis.csv', index_col=0, encoding = "ISO-8859-1", low_memory=False)

# 'Genus' column renaming
f = lambda x: re.sub('genus.*','Genus', x, flags = re.IGNORECASE)
df.rename(columns = f, inplace = True)

rawDescription: Python Pandas normalizing large numbers of columns names optomizing code


rawDescription: Delayed start of tasks with Python multiprocessing


rawDescription: Dictionary output on one line

description: Dictionary output on one line


code:
import StringIO
import gzip

compressed_data = f.read()
compressed_stream = StringIO.StringIO(compressed_data)
gzipper = gzip.GzipFile(fileobj=compressed_stream)
data = gzipper.read()

rawDescription: Decompressing gzip packets with python

description: Decompressing gzip packets with python


code:
s3 = boto3.resource('s3')
s3.Object('my_bucket','my_file_new').copy_from(CopySource='my_bucket/my_file_old')
s3.Object('my_bucket','my_file_old').delete()

rawDescription: Boto3 copy_object s3

description: Boto3 copy_object s3


code: categoricalFeaturesInfo = {1:len(feature1), 2:len(feature2), 3:len(feature3), 9:len(labels)}

rawDescription: Create LabeledPoint from rdd data which has both strings and numbers - PySpark


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

x = np.linspace(0,0.5)
y = x*(1.0-x)

def as_si(x, ndp):
    s = '{x:0.{ndp:d}e}'.format(x=x, ndp=ndp)
    m, e = s.split('e')
    return r'{m:s}\times 10^{{{e:d}}}'.format(m=m, e=int(e))

a=1.92e-7

plt.figure()
plt.plot(x, y)

plt.text(0.01, 0.23, r"$a = {0:s}$".format(as_si(a,2)), size=20)
plt.show()

rawDescription: Displaying numbers with "X" instead of "e" scientific notation in matplotlib


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

x = [1,2,3,4]
y_mat = np.array([[1,2,3,4], [5,6,7,8]])

n, _ = y_mat.shape

colors = mpl.cm.rainbow(np.linspace(0, 1, n))
fig, ax = plt.subplots()
for color, y in zip(colors, y_mat):
    ax.scatter(x, y, color=color)
plt.show()

rawDescription: multiple graphs from a loop in one single plot - Python

description: Multiple graphs from a loop in one single plot - Python


code:
code = load(path)
if path.endswith(".py"):
    code = compile(code)
run(code)

rawDescription: Why is the 'running' of .pyc files not faster compared to .py files?


code:
while True:
    try:
        speed_limit = int(input("What is your speed zone? "))
        break
    except ValueError:
        print("That is not a number! ")
        continue

while True:
    print("What speed is the car going?")
    try:
        pass_car_speed = int(input( "Enter speed, or 0 to quit: "))
    except ValueError:
        print("Invalid number! ")
        continue

    if not pass_car_speed: # 0 is False, non-zero True
        break # quit loop (and program)

    if pass_car_speed <= speed_limit:
        print("This car is under the limit. No ticket needed!")
    else:
        fine = (pass_car_speed - speed_limit) * 10
        name = input("What is the car model name? ")
        print("____________________________________________")
        print("   | P O L I C E   T I C K E T |   ")
        print("   | Speed: ",pass_car_speed,"   ")
        print("   | Fine Cost: ",fine,"    ")
        print("   | Car Name: ",name,"  ")
        print("____________________________________________")

print("Goodbye!")

rawDescription: Python - Little beginner code confusion

description: Python - Little beginner code confusion


code:
import glob
files = glob.glob(yourpath + '/*.extension')
resultList = []
for filename in files:
    with open(filename,'r') as f:
        newData = int([x.strip() for x in f.readlines()][0])
    try:
        resultList.append(newData/oldData)
    except:
        pass
    oldData = newData
print(resultList)

rawDescription: Comparing numbers in different rows

description: Comparing numbers in different rows


code:
class MyModel(models.Model):
    my_attribute = models.CharField(max_length=50)

    def my_link(self):
        return 'google'
    my_link.allow_tags = True # <---

rawDescription: Django 1.4: return HTML in function

description: Django 1.4: return HTML in function


code:
words = {"one","two","ne","three"}

[x for x in words if any(word.endswith(x) for word in words - {x})]
Out[69]: ['ne']

rawDescription: Compare each list's element with others in the list


code:
perimeter = polygon.exterior.coords
new_coords = []
first_vertex = nearest_pt  # as found in the question above
two_tours = itertools.chain(perimeter, perimeter)
for v in two_tours:
    if shapely.geometry.Point(v) == first_vertex:
        new_coords.append(v)
        while len(new_coords) < len(perimeter):
            new_coords.append(two_tours.next())
        break
polygon = shapely.geometry.Polygon(new_coords)

rawDescription: Can I set the order of points in a shapely Polygon?

description: Set the order of points in a shapely Polygon


code:
Button_Array=[]
for i in List1:
    New_Button=wx.Button(panel,-1,label=i)
    Button_Array.append(New_Button)

rawDescription: storing button and other wx widgets in array

description: Storing button and other wx widgets in array


code:
def rev(l):
    l[:] = l[::-1]
    print (l)

rawDescription: Trouble with a function that simulates reverse attribute in python


rawDescription: Pandas: preferred idioms for boolean/predicate searches


code:
class TestClass(object):
    def __init__(self, id, departmentId, active):
        values = [
            {'id': 5},
            {'departmentId': 10},
            {'active': True}]
        vdict = {}
        for a in values:
            vdict[list(a.keys())[0]] = eval(list(a.keys())[0])
        print(vdict)

var = TestClass(1,2,False)

rawDescription: Use of eval when building a dict in a for loop. Name is not defined


code:
import shutil
# SKIPPED
def POST(self):
    form = web.input(image={})
    with open('path/to/image.jpg', 'wb') as saved:
        shutil.copyfileobj(form['image'].file, saved)

rawDescription: How to do an image upload in web.py and save it to the disk

description: Do an image upload in web.py and save it to the disk


code:
t = Image.open("IMG_1.jpg").convert('L') #grayscale image
f = array(t) #Convert test image into an array

OD = 0.51*((f-22.08)/(176.09-f))**(1./-1.519) #Empirical Rodbard formula
OD[np.isnan(OD)] = 0

thB = 0.02
ththin = 0.11
ththick = 0.15

GSb = 162
GSthin = 150
GSthick = 145

if np.where(OD < ththin):
    thresholded = threshold(f, GSthin, GSb)
def to_rgb1(thresholded):
    thresholded.resize((thresholded.shape[0], thresholded.shape[1], 1))
    return np.repeat(thresholded.astype(np.uint8), 3, 2)
cmap = plt.get_cmap('jet')
rgba_img1 = cmap(thresholded)
rgb_img1 = np.delete(rgba_img1, 3, 2)
view = rgb_img1[:, :, 2]
view[view < 0.1] += 128
thin = rgb_img1

if np.where(OD > ththick):
    thresholded2 = threshold(f, threshmax = GSthick)
def to_rgb2(thresholded2):
    thresholded2.resize((thresholded2.shape[0], thresholded2.shape[1], 1))
    return np.repeat(thresholded2.astype(np.uint8), 3, 2)
cmap = plt.get_cmap('jet')
rgba_img2 = cmap(thresholded2)
rgb_img2 = np.delete(rgba_img2, 3, 2)
view2 = rgb_img2[:, :, 0]
view2[view2 > 0] += 128
thick = rgb_img2

rawDescription: If statement to cycle through individual elements in array in Python


code:
from Tkinter import *
from tkFileDialog import askopenfilename
import Image, ImageTk

if __name__ == "__main__":
    root = Tk()

    #setting up a tkinter canvas with scrollbars
    frame = Frame(root, bd=2, relief=SUNKEN)
    frame.grid_rowconfigure(0, weight=1)
    frame.grid_columnconfigure(0, weight=1)
    xscroll = Scrollbar(frame, orient=HORIZONTAL)
    xscroll.grid(row=1, column=0, sticky=E+W)
    yscroll = Scrollbar(frame)
    yscroll.grid(row=0, column=1, sticky=N+S)
    canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set)
    canvas.grid(row=0, column=0, sticky=N+S+E+W)
    xscroll.config(command=canvas.xview)
    yscroll.config(command=canvas.yview)
    frame.pack(fill=BOTH,expand=1)

    #adding the image
    File = askopenfilename(parent=root, initialdir="C:/",title='Choose an image.')
    img = ImageTk.PhotoImage(Image.open(File))
    canvas.create_image(0,0,image=img,anchor="nw")
    canvas.config(scrollregion=canvas.bbox(ALL))

    #function to be called when mouse is clicked
    def printcoords(event):
        #outputting x and y coords to console
        print (event.x,event.y)
    #mouseclick event
    canvas.bind("<Button 1>",printcoords)

    root.mainloop()

rawDescription: How to display picture and get mouse click coordinate on it

description: Display picture and get mouse click coordinate on it


code:
if __name__ == '__main__':
    import sys
    argc = len(sys.argv)
    argv = sys.argv

rawDescription: Is there function in Python which serves as main in C


rawDescription: How to pass members of a dict to a function

description: Pass members of a dict to a function


code: all = [x for t in tests for x in t[1]]

rawDescription: Python: complex list comprehensions where one var depends on another (x for x in t[1] for t in tests)


code:
import email
import poplib
import random
from cStringIO import StringIO
from email.generator import Generator

pop = poplib.POP3(server)

mail_count = len(pop.list()[1])

for message_num in xrange(mail_count):
    message = "\r\n".join(pop.retr(message_num)[1])
    message = email.message_from_string(message)

    out_file = StringIO()
    message_gen = Generator(out_file, mangle_from_=False, maxheaderlen=60)
    message_gen.flatten(message)
    message_text = out_file.getvalue()

    filename = "%s.email" % random.randint(1,100)
    email_file = open(filename, "w")
    email_file.write(message_text)
    email_file.close()

rawDescription: Trouble with encoding in emails

description: Trouble with encoding in emails


code:
# untested code

from __future__ import division # confidence high

# astropy
from astropy.io import fits as pyfits
from astropy import wcs

# your code
H, xedges, yedges = np.histogram2d(glat, glon, bins=[ybins, xbins], weights=Av)
count, x, y = np.histogram2d(glat, glon, bins=[ybins, xbins])
H/=count

# characterize your data in terms of a linear translation from XY pixels to
# Galactic longitude, latitude.

# lambda function given min, max, n_pixels, return spacing, middle value.
linwcs = lambda x, y, n: ((x-y)/n, (x+y)/2)

cdeltaX, crvalX = linwcs(np.amin(glon), np.amax(glon), len(glon))
cdeltaY, crvalY = linwcs(np.amin(glat), np.amax(glat), len(glat))

# wcs code ripped from
# http://docs.astropy.org/en/latest/wcs/index.html

w = wcs.WCS(naxis=2)

# what is the center pixel of the XY grid.
w.wcs.crpix = [len(glon)/2, len(glat)/2]

# what is the galactic coordinate of that pixel.
w.wcs.crval = [crvalX, crvalY]

# what is the pixel scale in lon, lat.
w.wcs.cdelt = numpy.array([cdeltX, cdeltY])

# you would have to determine if this is in fact a tangential projection.
w.wcs.ctype = ["GLON-TAN", "GLAT-TAN"]

# write the HDU object WITH THE HEADER
header = w.to_header()
hdu = pyfits.PrimaryHDU(H, header=header)
hdu.writeto(filename)

rawDescription: Assign WCS coordinates to a FITS image

description: Assign WCS coordinates to a FITS image


code: re.findall(r'.+', 'abc\r\ndef\r\n\r\n')

rawDescription: Extract Text from a Binary File (using Python 2.7 on Windows 7)


code:
import re
s = "Hello, I am 5'8\" tall - wow"
re.findall(r'''\w+|[-'"]''', s)

rawDescription: What would be the regex expression if I wanted to tokenize a string by spaces, -, ', and " in Python?


code:
d = data.iloc[:, 5:12]
d[d.all(axis=1)]

rawDescription: Evaluating boolean expression across Pandas DataFrame


code:
def setLineFormat(self, lineNumber, format):
    cursor = QTextCursor(self.textEdit.document().findBlockByNumber(lineNumber))
    cursor.setBlockFormat(format)

# with
format = QTextBlockFormat()
format.setBackground(Qt.yellow)
# or
format.clearBackground()

rawDescription: Highlight specific line of output

description: Highlight specific line of output


code:
userInput = str(input("Enter The Sentense: "))
truncatedInput = userInput[:140]

rawDescription: How to take user input for less then 140 characters?

description: Take user input for less then 140 characters


code: replacedWord = wordDict.get(currentWord, 'rare_word')

rawDescription: replace all words in a big list

description: Replace all words in a big list


code:
def download(url, max_retries=10):
    for i in range(max_retries):
        print('Downloading: ' + url)
        r = requests.get(url)

        print('Status code: ' + str(r.status_code))

        if r.status_code == requests.codes.ok: return r.content
    return None

download('http://us.battle.net/sc2/en/game/unit/')

rawDescription: Python 3.2: Battle.net scraper gives 404 on certain URLs


code:
L = [1, 2, 3, 4, 5, 6]
from itertools import chain
list(chain.from_iterable(zip(L[1::2], L[::2])))

rawDescription: Reorder Python List

description: Reorder Python List


code:
def convert(n):
    n = int(n)
    suffix = ''
    if 4 <= n <= 20:
         suffix = 'th'
    elif n == 1 or (n % 10) == 1:
         suffix = 'st'
    elif n == 2 or (n % 10) == 2:
         suffix = 'nd'
    elif n == 3 or (n % 10) == 3:
        suffix = 'rd'
    elif n < 100:
        suffix = 'th'
    return str(n) + suffix

def main ():
    day = int(input("Enter the day: "))
    month = int(input("Enter the month: "))
    year = int(input("Enter the year: "))

    print("on the %s day of the %s month of the %s, something amazing happened!" %
          (convert(day), convert(month), convert(year)))

main()

rawDescription: Trouble with Python Code. Objective is to code suffix during input


code:
d = {L[0]:list(L[1:]) for L in second}
answer = [[k]+d[k] for k in first]
answer

rawDescription: sort multi demension list by another single list in python

description: Sort multi demension list by another single list in python


code:
tick_location = np.linspace(0.01, 10, num=10, endpoint=True)
ax2.set_xticks(tick_location)
tick_labels = np.around(1/new_tick_loc*1e4,decimals=-2)
tick_labels_str = tick_labels.astype(str)
tick_labels_free=[]
for i in range(0,10):
    tick_labels_free.append(tick_labels_str[i].split('.')[0])
ax2.set_xticklabels(tick_labels_free)

rawDescription: How can I remove digits after decimal in axis ticks in matplotlib?

description: Remove digits after decimal in axis ticks in matplotlib


code:
import Tkinter as tk
coeff = [-5,4,-3,2,1]

root=tk.Tk()
l=tk.Text(root)
l.tag_configure("s", offset=5)

#insert first coefficient manually
l.insert("insert", str(coeff[0]))
l.insert("insert","x","",str(len(coeff)-1),"s")

#use enumerate to track indexes
for idx, item in enumerate(coeff[1:],2):
    #put a plus if number is positive. If not minus sign will come from number itself
    if item >= 0:
        l.insert("insert","+","") #insert sign
    l.insert("insert", str(item)) #insert coefficient
    #insert variable if not last item.
    if item != coeff[-1]:
        l.insert("insert","x","",str(len(coeff)-idx),"s") #insert variable and its power

l.grid(row=0)
root.mainloop()

rawDescription: Using superscript in Tkinter label

description: Using superscript in Tkinter label


code:
import openpyxl

wb = openpyxl.load_workbook('sheet.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

translated = []
for row in sheet.iter_rows('A2:A74'):
    for cell in row:
        translated.append(cell.value)

for row, val in zip(sheet.iter_rows('B2:B74'), translated):
    for cell in row:
        cell.value = val

wb.save("sheet.xlsx")

rawDescription: Python Openpyxl - Copy values from column A to B with same rows range


code:
from docx import Document

document = Document()
r = 2 # Number of rows you want
c = 2 # Number of collumns you want
table = document.add_table(rows=r, cols=c)
table.style = 'LightShading-Accent1' # set your style, look at the help documentation for more help
for y in range(r):
    for x in range(c):
        cell.text = 'text goes here'
document.save('demo.docx') # Save document

rawDescription: how to create docx files with python

description: Create docx files with python


code:
import random
a = ["Stack", "Overflow", "rocks"]
print(random.choice(a))

rawDescription: Picking a Random Word In Python?

description: Picking a Random Word In Python


code:
import sys, os
script_dir = sys.path[0]
img_path = os.path.join(script_dir, '../y/img1.png')

rawDescription: How to Access a image from another directory? python


code:
pbar = None

def show_progress(count, block_size, total_size):
    if pbar is None:
        pbar = ProgressBar(maxval=total_size)

    downloaded += block_size
    pbar.update(block_size)
    if downloaded == total_size:
        pbar.finish()

rawDescription: How to use progressbar module with urlretrieve

description: Use progressbar module with urlretrieve


code:
window = self.get_window()
x,y = window.get_root_coords(0, 0)

rawDescription: How to get window origin (position) in mate applet?

description: Get window origin (position) in mate applet


rawDescription: Django Adding Values to ForeignKey

description: Django Adding Values to ForeignKey


code: z = list(zip(x, y))

rawDescription: Saving iterator from python's zip

description: Saving iterator from python's zip


code:
def find_items_within(l1, l2, dist):
    l1.sort()
    l2.sort()
    b = 0
    e = 0
    ans = []
    for a in l1:
        while b < len(l2) and a - l2[b] > dist:
            b += 1
        while e < len(l2) and l2[e] - a <= dist:
            e += 1
        ans.extend([(a,x) for x in l2[b:e]])
    return ans

rawDescription: Given Two Lists of Integers, Find Each Pair Within a Distance of Each Other < O(N^2)


code:
import signal
import sys

def handler(signum, frame):
    # do the cleaning if necessary

    # log your data here
    with open('log.log', 'a') as fo:
        fo.write('Force quit on %s.\n' % signum)

    # force quit
    sys.exit(1)  # only 0 means "ok"

signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGHUP, handler)
signal.signal(signal.SIGTERM, handler)

rawDescription: Python check if force closed

description: Python check if force closed


code:
from BeautifulSoup import BeautifulSoup
import urllib

content = urllib.urlopen(url).read()
soup = BeautifulSoup(''.join(content))

td_list = soup.findAll('td', {'class':'value chg'} )

mon3 = td_list[2].text.encode('ascii','ignore')
yr1 = td_list[4].text.encode('ascii','ignore')

rawDescription: Extract Multiline Data from a HTML site using Python


code:
import paho.mqtt.client as paho

def on_message(clnt, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

mqttc = paho.Client()
mqttc.on_message = on_message
mqttc.tls_set("mosquitto.org.crt") # http://test.mosquitto.org/ssl/mosquitto.org.crt
mqttc.connect("test.mosquitto.org", 8883)
mqttc.subscribe("bbc/#")
mqttc.loop_forever()

rawDescription: Wrapping MQTT data in SSL certificate while sending it to MQTT broker


code:
class Room(object):
    # stuff...
    def __getitem__(self, key):
        # get room using the key and return the value
        # you should raise a KeyError if the value is not found
        return self.get_room(key)

dungeon.room = Room()
dungeon.room['room_name']  # this will work!

rawDescription: Pythonic API design (C# -like overriding of index operator?)


code:
while game==True:
    #your game code goes here
    charArray,collideArray = [],[]

rawDescription: How do I avoid recursively adding arrays when I need to merge two arrays in a while-loop?

description: Avoid recursively adding arrays when I need to merge two arrays in a while-loop


code:
both = [ random.randint(0, 500) for i in range(100) ]
odd = [ x for x in both if x % 2 == 1 ]
even = [ x for x in both if x % 2 == 0 ]

rawDescription: Generating random values in python

description: Generating random values in python


code:
import numpy as np
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier

iris = load_iris()
tree = DecisionTreeClassifier(max_depth=2).fit(iris.data, iris.target)

leaf = tree.tree_.apply(iris.data[50:51].astype(np.float32))
print(leaf)
# output [3]
print(tree.tree_.value[leaf])
# output [[[  0.  49.   5.]]]
print(tree.predict_proba(iris.data[50:51]))
# output [[ 0.          0.90740741  0.09259259]]

rawDescription: Finding the corresponding sample fraction for a predicted response in classification trees Python 2.7


code:
import string

def validate(password):
    letters = set(string.ascii_letters)
    digits = set(string.digits)
    pwd = set(password)
    return not (pwd.isdisjoint(letters) or pwd.isdisjoint(digits))

print(validate('123123'))    # False
print(validate('asdfsdf'))   # False
print(validate('12312sfdf')) # True

rawDescription: django form field regex validation for alphanumeric characters

description: Django form field regex validation for alphanumeric characters


code: list2= [line for line in file if 'CONTENT_ITEM_ID' in line]

rawDescription: Python filter/remove URLs from a list

description: Python filter/remove URLs from a list


code:
from django.db.models import IntegerField, Case, Value, When

MyModel.objects.all().order_by(
    Case(
        When(some_field=None, then=Value(1)),
        default=Value(0),
        output_field=IntegerField(),
    ).asc(),
    'some_other_field'
)

rawDescription: Django: Order by evaluation of whether or not a date is empty


code:
from twisted.words.xish import domish

class ElementParser(object):
    "callable class to parse XML string into Element"

    def __call__(self, s):
        self.result = None
        def onStart(el):
            self.result = el
        def onEnd():
            pass
        def onElement(el):
            self.result.addChild(el)

        parser = domish.elementStream()
        parser.DocumentStartEvent = onStart
        parser.ElementEvent = onElement
        parser.DocumentEndEvent = onEnd
        tmp = domish.Element(("", "s"))
        tmp.addRawXml(s)
        parser.parse(tmp.toXml())
        return self.result.firstChildElement()

rawDescription: How to create twisted.words.xish.domish.Element entirely from raw XML

description: Create twisted.words.xish.domish.Element entirely from raw XML


code:
arr = np.array(some_sequence)
reversed_arr = arr[::-1]

do_something(arr)
look_at(reversed_arr)
do_something_else(arr)
look_at(reversed_arr)

rawDescription: Most efficient way to reverse a numpy array


code: 'very long string, much longer than 20 characters'[0:20]

rawDescription: Python Cutting a string to multiple variables


code:
def prepare_images():
    global image_prepare_lock
    thread_table = {}

    with image_prepare_lock:
        if root.winfo_width()-10 <= 0 or root.winfo_height()-10 <= 0:
            width = 10
            height = 10
        else:
            width = root.winfo_width()//2
            height = root.winfo_height()//2-10

        dimensions = [ width, height ]

        for position in prep_grid:
            # Open images here so that threads don't fight for disk access
            prep_grid[position]['photo_raw'] = Image.open( directory + prep_grid[position]['name'] )
            thread_table[position] = Thread(target=prepare_single_image, args=[position, dimensions])
            thread_table[position].start()

        # wait for all children threads to finish
        for position in prep_grid:
            thread_table[position].join()
            prep_grid[position]['photo_tkinter'] = ImageTk.PhotoImage( prep_grid[position]['photo_resized'] )

        root.nametowidget(".title").config(text="Compare photos", bg="green", fg="white")

def prepare_single_image(position, dimensions):
    global prep_grid

    prep_grid[position]['hash'] = hashlib.md5(prep_grid[position]['photo_raw'].tostring()).hexdigest()
    prep_grid[position]['photo_resized'] = prep_grid[position]['photo_raw'].copy()
    prep_grid[position]['photo_resized'].thumbnail( dimensions, Image.ANTIALIAS )

def select_image(event):
    Thread(target=cycle_images, args=[event]).start()

def cycle_images(event):
    global current_grid
    global image_prepare_lock

    with image_prepare_lock:
        current_grid = prep_grid.copy()
        show_images()
        grid_init()

        Thread(target=prepare_images, args=[]).start()

rawDescription: Python: Simple lock for responsive UI during IO


code:
Question.objects.filter(module__course__subject__name = 'Mathematics',
                        num_attempts__gt = 20,
                        avg_score__gt = 0).order_by('avg_score')

rawDescription: Django Follow One-To-Many Relationships

description: Django Follow One-To-Many Relationships


code:
import requests

serve_url = "http://hypem.com/serve/source/{}/{}".format(id, key)
# cookies is a simple key/value dictionary
response = requests.get(serve_url, headers={'Content-Type': 'application/json'}, cookies=cookies)
song_data = response.json()
url = song_data[u"url"]

rawDescription: Downloading music from http

description: Downloading music from http


code:
with open('txt2.txt', 'rb') as file2, open('output.txt', 'wb') as outputfile:
    output = []
    do_block = False
    for line in file2:
        line = line.rstrip()
        if not line: continue
        if line[0] == '?':
            key = line.strip().split('|')[0][1:]
            do_block = key in file1_data
        if do_block:
            output.append(line)
    outputfile.write("\n".join(output))

rawDescription: Not getting the full text in output

description: Not getting the full text in output


rawDescription: Abnormal list behaviour

description: Abnormal list behaviour


code:
def write(self, cr, uid, ids, values, context=None):
    _logger.error("*******************OnUpdate***********************")
    obj = self.browse(cr, uid, ids, context=context)
    _logger.error("Before:%s",obj.sujet)
    res = super(reclamation, self).write(cr, uid, ids,values,context=context)
    _logger.error("After:%s",values['sujet'])
    return res

rawDescription: Get the string field modification before it's update


code:
my_dict = {}
for element in b:
    k,v = element.split(":")
    my_dict[k] = v
my_dict

{'12v': ' 12.1968',
 '3.3v': ' 3.312',
 '5v': ' 5.04',
 'CPU Temp': ' 33',
 'Disk1 Mounted': ' 1',
 'Disk1 Used Space': ' 32',
 'Disk2 Mounted': ' 1',
 'Disk2 Used Space ': ' 0',
 'Fan speed': ' 3245',
 'Motherboard Temp': ' 30',
 'VCore': ' 1.352'}

rawDescription: Creating a dictionary from a string of data


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

import os
import xlrd

dir = './schfiles'
files = os.listdir(dir)
f = files[0]

workbook_path = os.path.join(dir, files[0])
book = xlrd.open_workbook(workbook_path)

sh = book.sheet_by_index(0)
t = sh.cell_value(rowx=xlr2i(35),colx=xlc2i('F'))
t.find(u"Усманов")

rawDescription: python searching Russian substrings in excel

description: Python searching Russian substrings in excel


code:
def get_valid_links(pointers, current_frame):
    allowed_frames = []

    for frame in pointers:
        if frame == current_frame:
            continue

        sequence = []
        next_frame = pointers[frame]
        while next_frame:
            sequence.append(next_frame)
            next_frame = pointers[next_frame]

        if current_frame not in sequence:
            allowed_frames.append(frame)

    return allowed_frames

rawDescription: Linked list search to stop loops before they happen


code:
def __init__(self, *args, **kwargs):
    super(TagForm, self).__init__(*args, **kwargs)
    if 'instance' in kwargs:
        self.fields['projects'].initial = self.instance.project_set.all()

def save(self, *args, **kwargs):
    super(TagForm, self).save(*args, **kwargs)
    self.instance.project_set.clear()
    for project in self.cleaned_data['projects']:
        self.instance.project_set.add(project)

rawDescription: Editing both sides of M2M in Admin Page

description: Editing both sides of M2M in Admin Page


code:
modified_trigger = """
CREATE TRIGGER update_{table_name}_modified
BEFORE UPDATE ON {table_name}
FOR EACH ROW EXECUTE PROCEDURE update_modified_columns()
"""

def create_modified_trigger(target, connection, **kwargs):
    """
    This is used to add bookkeeping triggers after a table is created. It hooks
    into the SQLAlchemy event system. It expects the target to be an instance of
    MetaData.
    """
    for key in target.tables:
        table = target.tables[key]
        connection.execute(modified_trigger.format(table_name=table.name))

Base = declarative_base()

event.listen(Base.metadata, 'after_create', create_modified_trigger)

rawDescription: Add trigger to SQLAlchemy Base Class

description: Add trigger to SQLAlchemy Base Class


code:
import numpy as np
import pylab as plt

def rect(x,y,w,h,c):
    ax = plt.gca()
    polygon = plt.Rectangle((x,y),w,h,color=c)
    ax.add_patch(polygon)

def rainbow_fill(X,Y, cmap=plt.get_cmap("jet")):
    plt.plot(X,Y,lw=0)  # Plot so the axes scale correctly

    dx = X[1]-X[0]
    N  = float(X.size)

    for n, (x,y) in enumerate(zip(X,Y)):
        color = cmap(n/N)
        rect(x,0,dx,y,color)

# Test data
X = np.linspace(0,10,100)
Y = .25*X**2 - X
rainbow_fill(X,Y)
plt.show()

rawDescription: How to fill rainbow color under a curve in Python matplotlib

description: Fill rainbow color under a curve in Python matplotlib


code:
widget.setGeometry(QtCore.QRect(x_pos, y_pos, x_size, y_size))
# A button located at (300, 425) of size 500 by 100
self.btn_example.setGeometry(QtCore.QRect(300, 425, 500, 100))

rawDescription: Python PyQt widgets positioning in pixels


code:
import numpy as np

a, b = 1, 1
n = 7
r = 3

y,x = np.ogrid[-a:n-a, -b:n-b]
mask = x*x + y*y <= r*r

array = np.ones((n, n))
array[mask] = 255

rawDescription: How to apply a disc shaped mask to a numpy array?

description: Apply a disc shaped mask to a numpy array


code: [x for (y,x) in sorted(zip(Y,X))]

rawDescription: Sorting list based on values from another list?


code:
import numpy as np

conns = np.array([[ 1,  2],
                  [ 2,  3],
                  [ 3,  4]])
net = np.zeros((conns.max(), conns.max()), dtype=int)

# two possibilities:

# if you need the number of connections:
for conn in conns:
    net[conn[0]-1, conn[1]-1] += 1

# if you just need a 1 for existing connection(s):
net[conns[:,0]-1, conns[:,1]-1] = 1

rawDescription: Create a Numpy array representing connections in a network


code:
from collections import OrderedDict
import random

ra_list = [5, 6.25, 7.5, 7.6]
e_list = [(6, 'A'), (7.4, 'B'), (7.4, 'C'), (7.7, 'E')]

test_dict = OrderedDict()

for key,val in e_list:
    test_dict.setdefault(key,[]).append(val)

key_list = list(test_dict.keys())
min_key = key_list[0]

for i in ra_list:
    max_key = min_key
    for key in key_list:
        if i >= key:
            max_key = key
        else:
            break
    cate = random.choice(test_dict.get(max_key))

    print( i,cate)

rawDescription: Python in range within list

description: Python in range within list


code:
if len(the_entry_widget.get()) == 0:
    do_something()

rawDescription: Tkinter check if entry box is empty

description: Tkinter check if entry box is empty


code:
def __str__(self):
    return unicode(self).encode('utf-8')

rawDescription: Python __str__ versus __unicode__

description: Python __str__ versus __unicode__


code:
if player_a in reward_dict:
    reward_dict[player] += money
else:
    reward_dict[player] = money

rawDescription: Which style of these two is more explicit (pythonic)?


code:
from flexmock import flexmock
from glob import glob
import sys

flexmock(sys.modules[__name__]).should_receive('glob')

rawDescription: Mocking functions with FlexMock in Python?


code:
def list_maker(anchor, reach):
    return [list(range(anchor-r, anchor+x+1)) for r in range(reach+1) for x in range(reach+1)]
list_maker(8, 2)

rawDescription: All combinations of ranges given an 'anchor' and 'reach'


code:
import uuid

batch_insert_id = uuid.uuid4().hex
# Execute your batch insert query, with batch_insert_id
# as value of batch_insert_id for all rows
cursor.execute("SELECT id FROM mytable WHERE batch_insert_id = '%s'", (batch_insert_id,))
primary_keys = [row[0] for row in cursor.fetchall()]

rawDescription: get a list of primary keys after inserting multiple entries

description: Get a list of primary keys after inserting multiple entries


code:
def f_1():
    print("Run !")

def f_2():
    print("Run, run !")

for_Test = [f_1, f_2]

class Test():
    def __new__(cls):
        for f in for_Test:
            # Based on your linked question
            setattr(cls, f.name, f)

rawDescription: How to access to names of functions defined before a class within the class

description: Access to names of functions defined before a class within the class


code:
from django.db.models import Q

@login_required
def friends_search(request):
    search_result = None

    if request.method == 'POST':
        if request.POST.get('fld_name'):
            try:
                fld_name = request.POST.get('fld_name')
                q = Q(nickname__icontains=fld_name) | Q(family__icontains=fld_name)
                search_result = UserProfile.objects.filter(q)
                if not search_result:
                    search_result = 'По вашему запросу ничего не найдено.'
            except Exception as exc:
                search_result = 'В данный момент доступ к базе данных невозможен. Попробуйте повторить ваш запрос позже.'

    t = loader.get_template('friends_search.html')
    c = RequestContext(request, {
    'search_result': search_result,
}, [custom_proc])
    return HttpResponse(t.render(c))

rawDescription: how to make a selection from multiple fields?

description: Make a selection from multiple fields


code:
with open("IP.txt") as ips:
    all_ips = [x.rstrip() for x in ips] # get all ips in a list and strip newline
    for ip in all_ips:
        policymap = pexpect.spawn ('telnet '+ ip) # first loop it will be 1.1.1.1, second loop  it will be 2.2.2.2 etc..

rawDescription: Python - send lines to multiple devices (listed in a text file with IPs)


code:
class Store(object):
    ...
    @property
    def price(self):
        return self.data.price

rawDescription: Modifying a numpy array in-place or how to get a reference to a numpy array to be updated


code:
filename = 'myfilename.txt'
txt = open(filename)

rawDescription: Learn Python the Hard Way, Exercise 15

description: Learn Python the Hard Way, Exercise 15


code:
class InnerStuff ( object ) :
    def __init__(self):
        self.x = 'Original x'
        self.y = 'Original y'
        self.z = 4.4
    def change_object(self): # Option A
        self.inner_stuff.x = 'Changed x'
        self.inner_stuff.y = 'Changed y'
        self.inner_stuff.z = 3.2

class Stuff ( object ) :
    def __init__(self):
        self.inner_stuff = InnerStuff()

    def change_object(self): # Option B
        self.inner_stuff.x = 'Changed x'
        self.inner_stuff.y = 'Changed y'
        self.inner_stuff.z = 3.2

    def change_object(self): # Option C if chose option A
        self.inner_stuff.change_object()

rawDescription: Python guidelines for modifying object with function


code:
import xbmc
xbmc.executebuiltin('Container.SetViewMode(%d)' % view_mode_id)

rawDescription: How to set default view type in XBMC lists?

description: Set default view type in XBMC lists


code:
# Nodes with name='Singapore' that have a 'year' child
root.findall(".//year/..[@name='Singapore']")

rawDescription: Searching attributes of an XML's element tree with xml.etree.ElementTree


rawDescription: List to Dictonary - Python

description: List to Dictonary - Python


code:
def do_x(url):
    """ Does x with the given url. """
    short = url[1:15]
    # do x with short
    # ...

# process all items in g_data
for item in g_data:
    # find all links in the item
    links = item.contents[1].find_all("a", {"class":"a-link-normal s-access-detail-page a-text-normal"})

    if not links:
        # no links in this item -> skip
        print("No urls to work with.")
        continue

    # process all links
    for link in links:
        urls = link["href"]
        # process each url
        for url in urls:
            do_x(url)

rawDescription: How to take data from variable and put it into another

description: Take data from variable and put it into another


code:
from  __builtin__ import any as b_any
lis= ['yellow', 'orange', 'red']
word = "or"
b_any(word in x for x in lis)

rawDescription: Check if substring is in a list of strings in python


code:
import re

elements = self.driver.find_elements_by_xpath('//table[@id="reporting_view_report_dg_main_body"]//tr//td[4]//span')
pattern = re.compile(r"Name\[wi ,\((\d+)\)\]")

for element in elements:
    print(pattern.findall(element.text))

rawDescription: Selenium Python how to use regex to find 2 digits inside a string value


code:
import sys
from PyQt4.QtGui import QComboBox, QApplication, QCompleter, QSortFilterProxyModel, QStandardItemModel, QStandardItem
from PyQt4.QtCore import Qt

class ExtendedCombo( QComboBox ):
    def __init__( self,  parent = None):
        super( ExtendedCombo, self ).__init__( parent )

        self.setFocusPolicy( Qt.StrongFocus )
        self.setEditable( True )
        self.completer = QCompleter( self )

        # always show all completions
        self.completer.setCompletionMode( QCompleter.UnfilteredPopupCompletion )
        self.pFilterModel = QSortFilterProxyModel( self )
        self.pFilterModel.setFilterCaseSensitivity( Qt.CaseInsensitive )

        self.completer.setPopup( self.view() )

        self.setCompleter( self.completer )

        self.lineEdit().textEdited[unicode].connect( self.pFilterModel.setFilterFixedString )
        self.completer.activated.connect(self.setTextIfCompleterIsClicked)

    def setModel( self, model ):
        super(ExtendedCombo, self).setModel( model )
        self.pFilterModel.setSourceModel( model )
        self.completer.setModel(self.pFilterModel)

    def setModelColumn( self, column ):
        self.completer.setCompletionColumn( column )
        self.pFilterModel.setFilterKeyColumn( column )
        super(ExtendedCombo, self).setModelColumn( column )

    def view( self ):
        return self.completer.popup()

    def index( self ):
        return self.currentIndex()

    def setTextIfCompleterIsClicked(self, text):
      if text:
        index = self.findText(text)
        self.setCurrentIndex(index)

if __name__ == "__main__":
    app = QApplication(sys.argv)

    model = QStandardItemModel()

    for i,word in enumerate( ['hola', 'adios', 'hello', 'good bye'] ):
        item = QStandardItem(word)
        model.setItem(i, 0, item)

    combo = ExtendedCombo()
    combo.setModel(model)
    combo.setModelColumn(0)

    combo.show()

    sys.exit(app.exec_())

rawDescription: How do I Filter the PyQt QCombobox Items based on the text input?


code:
import tkinter as tk

def switch():

     if root.counter <= 1:
          if not root.counter:
               a_label['text'] = 'Second Click'
               a_button['text'] = 'Second Button'
          else:
               a_label['text'] = 'Third Click'
               a_button['text'] = 'Third Button'
          root.counter += 1

root = tk.Tk()
root.counter = 0
a_label = tk.Label(root, text='Blah')
a_label.pack()
a_button = tk.Button(root, text='First Click', command=switch)
a_button.pack()
root.mainloop()

rawDescription: Multiple Events From one Button TKINTER

description: Multiple Events From one Button TKINTER


code:
import re
a = "John A, Smith, william tell, jacob oram"
re.sub(r"(?<=\b\w),", ".", a)

rawDescription: replacing a single charater in a string using regexes in a list

description: Replacing a single charater in a string using regexes in a list


code:
import os, os.path
import shutil

for m in musfile:
    tag.link(m)
    mar = str(tag.getArtist())
    mal = str(tag.getAlbum())
    mti = str(tag.getTitle())
    new_name = mar + ' - ' + mti + '.mp3'
    os.rename(m, new_name)
    new_dir = os.path.join(newmusicdir, mar, mal)    #use os.path.join instead of +'/' to be more multi platform, it is a good habit
    try:
        os.makedirs(new_dir)
    except:
        pass
    shutil.copy(new_name, new_dir)

rawDescription: Python: How to loop a process

description: Python: How to loop a process


code:
from string import ascii_letters
def foo(st):
    letters = ascii_letters
    letters_nd_term = letters + "?!"
    return not any([set(st[:-1]).difference(letters),st[-1] not in letters_nd_term])

rawDescription: Find alphabetic words

description: Find alphabetic words


rawDescription: Indexing Row Values Based on Value of Each Column


code:
from nltk import ContextFreeGrammar
from nltk.parse.generate import generate
from ntlk.util import trigrams

# build a simple grammar
cfg = """
S -> NP VP
VP -> VBZ NP
NP -> DT | NN | DT NN | DT JJ NN | JJ NN
"""

# you get these from your csv
words = "this is a simple sentence".split()
tagged = set(pos_tag(words))
# Add the words to the grammar
for word, tag in tagged:
    cfg += "{tag} -> '{word}'\n".format(word=word, tag=tag)
grammar = parse_cfg(cfg)

valid_trigrams = set()

language = generate(grammar)
for valid_sentence in language:
    valid_trigrams.update(list(trigrams(valid_sentence)))

print(valid_trigrams)
# {('simple', 'sentence', 'is'), ('this', 'is', 'this'), ('a', 'sentence', 'is'), ('sentence', 'is', 'a'), ('a', 'is', 'a'), ('this', 'is', 'simple'), ('sentence', 'is', 'this'), ('this', 'is', 'sentence'), ('is', 'a', 'sentence'), ('is', 'a', 'simple'), ('a', 'simple', 'sentence'), ('a', 'is', 'this'), ('this', 'simple', 'sentence'), ('this', 'is', 'a'), ('is', 'simple', 'sentence'), ('a', 'is', 'simple'), ('this', 'sentence', 'is'), ('is', 'this', 'sentence'), ('sentence', 'is', 'sentence'), ('sentence', 'is', 'simple'), ('is', 'this', 'simple'), ('a', 'is', 'sentence')}

rawDescription: Creating Rules for Word Permutations Based on a word's POS Tag


code:
sizes = np.arange(0, 300, 50)
labels = ['size={0}'.format(s) for s in sizes]

points = [ax.scatter([], [], [], s=s, c='gray') for s in sizes]
plt.legend(points, labels, scatterpoints=1)

rawDescription: How can I create a markersize legend for a 3D scatter plot with matplotlib?

description: Create a markersize legend for a 3D scatter plot with matplotlib


code:
# sign extend b low bits in x
# from "Bit Twiddling Hacks"
def SIGNEXT(x, b):
  m = 1 << (b - 1)
  x = x & ((1 << b) - 1)
  return (x ^ m) - m

rawDescription: movsx in python

description: Movsx in python


code:
def A(x, n):
    a = 3 * x
    for i in range(len(x)):
        a[i] += np.sum(x[np.ix_(n[i]-1)], axis=0)
    return a

rawDescription: How to improve this python vectorial function

description: Improve this python vectorial function


code:
_default = object()

def foo(first, second=_default):
    if second is not _default:
        # Overridden!
        pass

rawDescription: Detecting kwarg override in Python

description: Detecting kwarg override in Python


code:
class WebServer(BaseHTTPServer.HTTPServer):
    def __init__(self, *args, **kwargs):
        BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs)
        # Set FD_CLOEXEC flag
        flags = fcntl.fcntl(self.socket.fileno(), fcntl.F_GETFD)
        flags |= fcntl.FD_CLOEXEC
        fcntl.fcntl(self.socket.fileno(), fcntl.F_SETFD, flags)

rawDescription: how to deal with Python BaseHTTPServer killed,but the port is still be occupied?

description: Deal with Python BaseHTTPServer killed,but the port is still be occupied


code:
import sympy
t = sympy.Symbol('t') # set t as a variable/symbol
sympy.solve(sympy.Eq(10*t, 20*(t-1)), t) # which reads: solve the equation 10*t == 20*(t-1) for t.
# returns [2] (list of solutions to the equation)

rawDescription: Is there any module that can handle unidentified variables?


code:
primelist=[2]
for m in range (2,12):
    for k in primelist:
        if m%k == 0 :
            break
    else:
        primelist.append(m)
print (primelist)

rawDescription: Python primefinder doesn't work the way I want it to


code:
import bpy
# create new clouds texture
wtex = bpy.data.textures.new(name="MyTexture", type='IMAGE')
# set World texture
wrld = bpy.context.scene.world
if wrld:
    slot = wrld.texture_slots.add()
    slot.texture = wtex
    slot.use_map_horizon = True

rawDescription: Blender 2.5 Python animated world texture setup


code: list(itertools.islice('foobar', 3))

rawDescription: python list comprehension set max len

description: Python list comprehension set max len


rawDescription: make django urls ignore additional params

description: Make django urls ignore additional params


code: newTitle = self.text_title.get("1.0", 'end-1c')

rawDescription: SQLite and Python are inserting unwanted linebreaks into database


code: some_list = [l + [10, 11] for l in some_list]

rawDescription: How do I extend a list within a list in Python?

description: Extend a list within a list in Python


code:
found = False # <----
for data in repo.pull_request(prs.number).files():
    if data.filename.endswith((".png",".jpeg",".gif")):
        pass
    else:

        for files_content in [repo.blob(data.sha)]:
             binary_coded_content = io.BytesIO((base64.b64decode(files_content.content)))
             tempfile = 'temp'
             with open(tempfile,'wb') as f:
                 f.write(binary_coded_content.read())
             num_lines = sum(1 for line in open(tempfile, encoding='utf8') if line.rstrip())
             if data.changes_count/num_lines > 0.25:
                found = True # <----
                break #<--- break inner loop
        if found:
            break #<--- break outer loop
    if found: # after the loop ended, we check if we found something...
        print("A file has changed by more than 25%")
    else:
        print("No file has changed by more than 25%")

rawDescription: Line count of decoded binary content from json response


code:
d = {'gender' : Series(['M', 'F', 'F', 'F', 'M']),'year' : Series([1900, 1910, 1920, 1920, 1920])}
df = DataFrame(d)

grouped = df.groupby('gender').year
grouped.plot(kind='hist',legend=True)

rawDescription: Show histogram in Python from dataframe

description: Show histogram in Python from dataframe


code:
from BeautifulSoup import BeautifulSoup
import urllib2
import codecs

response = urllib2.urlopen('http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-real-1-izb-byt-sladkovicova-ul-kosice-sever')
html = response.read()
soup = BeautifulSoup(html)

tabulka = soup.find("table", {"class" : "detail-char"})

records = [] # store all of the records in this list
for row in tabulka.findAll('tr'):
    col = row.findAll('td')
    prvy = col[0].string.strip()
    druhy = col[1].string.strip()
    record = '%s;%s' % (prvy, druhy) # store the record with a ';' between prvy and druhy
    records.append(record)

fl = codecs.open('output.txt', 'wb', 'utf8')
line = ';'.join(records)
fl.write(line + u'\r\n')
fl.close()

rawDescription: parsing table with BeautifulSoup and write in text file

description: Parsing table with BeautifulSoup and write in text file


code:
infile = codecs.open(infilename,'r', encoding='utf-16-le')
outfile = codecs.open(outfilename, 'w', encoding='utf-16-le')
for line in infile:
    fixed_line = line.replace(originalText,replacementText)
    # no need to save up all the output lines in a list
    outfile.write(fixed_line)
infile.close()
outfile.close()

rawDescription: Python string replace for UTF-16-LE file


code:
from google.appengine.ext import endpoints
from protorpc import remote

my_api = endpoints.api(name='awsum_app', version='valpha')

@my_api.api_class(resource_name='users')
class UsersService(remote.Service):

    @endpoints.method(UserRegistrationRequest, UserLoginResponse, path='users/register', name='register')
    def user_register(self, request):
        """Registerin' users man"""

    @endpoints.method(UserLoginRequest, UserLoginResponse, path='users/login', name='login')
    def user_login(self, request):
        """Login dat user"""

    @endpoints.method(UserLogoutRequest, UserLogoutResponse, path='users/logout', name='logout')
    def user_logout(self, request):
        """Dude this user is so login out, cya bro"""

@my_api.api_class(resource_name='friends')
class FriendsService(remote.Service):

    @endpoints.method(AddressBookRequest, AddressBookResponse, path='friends/addressbook', name='addressbook')
    def get_address_book(self, request):
        """Retrieveing mah address book to look up bros to hand out with"""

    @endpoints.method(AddFriendRequestRequest, AddFriendRequestResponse, path='friends/friendrequest', name='friendrequest')
    def send_friend_request(self, request):
        """Hey dis bro looks cool let's add him"""

    @endpoints.method(AcceptFriendRequestRequest, AcceptFriendRequestResponse, path='friends/acceptrequest', name='acceptrequest')
    def accept_friend_request(self, request):
        """Ok man you're cool let's be friend"""

    @endpoints.method(DeleteFriendRequest, DeleteFriendResponse, path='friends/deletefriend', name='deletefriend')
    def delete_friend(self, request):
        """Shit dis fucker's a bitch i ain't no friend no more with this bitch"""

APPLICATION = endpoints.api_server([my_api])

rawDescription: Google App Engine: Best practice for routing and segmenting an app backend (Python)


code:
import subprocess
import sys
try:
    retcode = subprocess.call("D:\\dist\\NewProcess.exe " + sys.argv[1] + " " + sys.argv[2], shell=True)
    if retcode < 0:
        print >>sys.stderr, "Child was terminated by signal", -retcode
    else:
        print >>sys.stderr, "Child returned", retcode
except OSError as e:
    print >>sys.stderr, "Execution failed:", e

rawDescription: How to pass data to an application from python code

description: Pass data to an application from python code


code:
TYPE_CHOICES = (
    (1, 'GTO'),
    (2, 'EWR'),
    (3, 'QPR'),
)

class Document(models.Model):
    # ...your other fields here...
    type = models.IntegerField(choices=TYPE_CHOICES)

rawDescription: Seeking help in designing django models

description: Seeking help in designing django models


code:
from datetime import datetime, timedelta
s = '2004/03/30'
date = datetime.strptime(s, "%Y/%m/%d")
modified_date = date + timedelta(days=1)
datetime.strftime(modified_date, "%Y/%m/%d")

rawDescription: Add 1 day to my date in Python

description: Add 1 day to my date in Python


code:
for x in [tmp for tmp in b if tmp in a]:
        a.remove(x)

rawDescription: how do you remove a list from another list?

description: Remove a list from another list


code:
select = Select(driver.find_element_by_id("dropDown"))
options = select.options
for index in range(0, len(options) - 1):
    select.select_by_index(index)
    # do stuff

rawDescription: selenium iterate through options in dropdown select

description: Selenium iterate through options in dropdown select


code:
import gtk

class Source(gtk.Window):

    def __init__(self):
        super(Source, self).__init__()
        label1 = gtk.Label("The first label")
        label2 = gtk.Label("The second label")

        paned = gtk.HPaned()
        paned.add1(label1)
        paned.add2(label2)
        paned.set_position(600)

        self.add(paned)
        self.set_size_request(800, 400)  # needs sufficient width here
        self.connect('delete-event', gtk.main_quit)
        self.show_all()

if __name__ == "__main__":
    test = Source()
    gtk.main()

rawDescription: Why does set_position fail in this code

description: Why does set_position fail in this code


code:
with pm.Model() as model:
    beta1 = pm.Laplace('beta1', mu=0, b=b)
    beta2 = pm.Laplace('beta2', mu=0, b=b)
    beta3 = pm.Laplace('beta3', mu=0, b=b)

    y_hat = beta1 * x1 + beta2 * x2 + beta3 * x3
    y_obs = pm.Normal('y_obs', mu=y_hat, tau=1.0, observed=y)

    trace = pm.psample(draws=20000, step=pm.Slice(), threads=3)

rawDescription: Parallelization of PyMC

description: Parallelization of PyMC


code:
x = tf.placeholder(tf.float32, [None, 3])
r = tf.random_uniform(tf.shape(x)[0:1])

rawDescription: Specify dynamic shape as an input argument


code:
class ModelObject:
    def attack():
        if not self.attacking:
            self.attacking = True
            self.started = pygame.time.get_ticks()
            # Then compute some stuff

    def isattacking():
        return self.attacking

    def update():
        # attack lasts 1000ms
        self.attacking &= pygame.time.get_ticks() - self.started < 1000

rawDescription: Handle animations within an MVC pattern using Pygame


code:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from scipy import stats

#Setup some dummy data
points = np.random.randn(1000,3)
hist, binedges = np.histogramdd(points, normed=False)

#Setup a 3D figure and plot points as well as a series of slices
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
ax1.plot(points[:,0],points[:,1],points[:,2],'k.',alpha=0.3)

#Use one less than bin edges to give rough bin location
X, Y = np.meshgrid(binedges[0][:-1],binedges[1][:-1])

#Loop over range of slice locations (default histogram uses 10 bins)
for ct in [0,2,5,7,9]:
    cs = ax1.contourf(X,Y,hist[:,:,ct],
                      zdir='z',
                      offset=binedges[2][ct],
                      level=100,
                      cmap=plt.cm.RdYlBu_r,
                      alpha=0.5)

ax1.set_xlim(-3, 3)
ax1.set_ylim(-3, 3)
ax1.set_zlim(-3, 3)
plt.colorbar(cs)
plt.show()

rawDescription: bin 3d points into 3d bins in python

description: Bin 3d points into 3d bins in python


code: [[i.encode('ascii', 'ignore').replace('[', '') for i in x] for x in value]

rawDescription: Convert Unicode string to nested list

description: Convert Unicode string to nested list


rawDescription: Insert the contents of one list into another list at a specific index


code:
idx = s.find('hello') + len('hello')
s[:idx] + s[idx:].replace('hello', '')

rawDescription: how to replace specific word in a sentence with python

description: Replace specific word in a sentence with python


code:
for child1 in node1.getChildren():
    for child2_idx, child2 in enumerate(node2.getChildren()):
        if child1.getData() == child2.getData():
            doNodes(child1, child2_idx, child2)
            break
    else:
        doOther()

rawDescription: Capturing match point 'in' list comprehensions


code:
class ImageWithThumbnailField(ImageField):
    def contribute_to_class(self, cls, name):
        super(ImageWithThumbnailField, self).contribute_to_class(cls, name)

        def photo_thumb(self):
            photo = getattr(self, name, None)
            if photo:
               return u'<img src="%s" />' % (settings.MEDIA_URL + '/thumbs/?h=64&w=80&c=50x0&p=' + photo.name)
            else:
               return u'(no photo)'
        photo_thumb.short_description = u'Photo'
        photo_thumb.allow_tags = True
        photo_thumb.admin_order_field = 'photo'

        setattr(cls, 'photo_thumb', photo_thumb);

rawDescription: Resuable model members in django

description: Resuable model members in django


code:
def askdirectory(self):
    self.dirname = tkFileDialog.askdirectory()
    if self.dirname:
      self.directoryEntry.delete(0, tk.END)
      self.directoryEntry.insert(0, self.dirname)

def askfilename(self):
  filename = tkFileDialog.askopenfilename(initialdir=self.dirname)
  if filename:
    self.dataInput.delete(0, tk.END)
    self.dataInput.insert(0, filename)

rawDescription: Pass directory name to askopenfilename

description: Pass directory name to askopenfilename


code:
from tkinter import *
import tkinter.ttk as ttk
from PIL import Image, ImageTk

def on_vertical(event):
    canvas.yview_scroll(-1 * event.delta, 'units')

def on_horizontal(event):
    canvas.xview_scroll(-1 * event.delta, 'units')

root = Tk()
h = Scrollbar(root, orient=HORIZONTAL)
v = Scrollbar(root, orient=VERTICAL)
canvas = Canvas(root, scrollregion=(0, 0, 1000, 1000), yscrollcommand=v.set, xscrollcommand=h.set)
h['command'] = canvas.xview
v['command'] = canvas.yview
theImage = ImageTk.PhotoImage(Image.open('img'))
canvas.create_image(0,0,image=theImage, anchor='nw')
canvas.grid(column=0, row=0, sticky=(N,W,E,S))

canvas.bind_all('<MouseWheel>', on_vertical)
canvas.bind_all('<Shift-MouseWheel>', on_horizontal)

h.grid(column=0, row=1, sticky=(W,E))
v.grid(column=1, row=0, sticky=(N,S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.mainloop()

rawDescription: Why won't the Python Tkinter Canvas Scroll?


code:
average_temps_array = [sum(map(float, hourly_temp[i:i+24])) / 24
                                 for i in range(0, len(hourly_temp), 24)]

rawDescription: Calculate average values from an array

description: Calculate average values from an array


rawDescription: Combine three regular expressions

description: Combine three regular expressions


code:
import cv2
im = cv2.imread('test.jpg', cv2.IMREAD_GRAYSCALE)
imC = cv2.applyColorMap(im, cv2.COLORMAP_JET)

rawDescription: Is there OpenCV colormap in python?

description: Is there OpenCV colormap in python


code:
def selectAll(self, state=QtCore.Qt.Checked):
    """Select All layers loaded inside the listView"""

    model = self.dlg.selectAllCheckBox.model()
    for index in range(model.rowCount()):
        item = model.item(index)
        if item.isCheckable():
            item.setCheckState(state)

rawDescription: Issue with my Check Box in PyQt and Python


code:
imgsize = (int(self.viewport.cget('width')) - 1,int(self.viewport.cget('height')) - 1)
# limit the draggable mouse area to just the image dimensions
if event.x < 4:
    currentx = 4
elif event.x > imgsize[0]:
    currentx = imgsize[0]
else:
    currentx = event.x
if event.y < 4:
    currenty = 4
elif event.y > imgsize[1]:
    currenty = imgsize[1]
else:
    currenty = event.y

rawDescription: Python tkinter: how to restrict mouse cursor within canvas?


code:
my_dict = {"4":"3", "5":"3", "6":"4", "9":"8"}

from collections import Counter

cn = Counter(my_dict.itervalues())
print([k for k,v in my_dict.iteritems() if cn[v] == 1])
['6', '9']

rawDescription: Python dictionary code

description: Python dictionary code


code: sv = map(sum, v)

rawDescription: Taking 3 or more combinations using `combinations`


code:
import sys

def _call_for_all_streams(func_name):
    def wrapper(self, *args, **kwargs):
        result = []
        for stream in self._streams:
            func = getattr(stream, func_name)
            result.append(func(*args, **kwargs))
        return result
    return wrapper

class OStreamWrapper(object):
    def __init__(self, *streams):
        self._streams = streams

for method in filter(lambda x: not x.startswith('_'), dir(file)):
    setattr(OStreamWrapper, method, _call_for_all_streams(method))

if __name__ == '__main__':
    file1 = open("file1.txt", "w")
    file2 = open("file2.txt", "w")
    ostream = OStreamWrapper(file1, file2, sys.stdout)
    ostream.write("ECHO!")
    ostream.close()

rawDescription: Wrapper to write to multiple streams

description: Wrapper to write to multiple streams


code:
i = cv2.imread(imgNameIn, cv2.CV_LOAD_IMAGE_COLOR) # Need to be sure to have a 8-bit input
img = np.array(i, dtype=np.uint16) # This line only change the type, not values
img *= 256 # Now we get the good values in 16 bit format

rawDescription: NumPy convert 8-bit to 16/32-bit image

description: NumPy convert 8-bit to 16/32-bit image


rawDescription: how to add a column to existing array

description: Add a column to existing array


code:
m=sys.maxint
np.random.uniform(-m,m,5)

rawDescription: Full-range random number in Python

description: Full-range random number in Python


rawDescription: Manually decoding a QR code - how to properly extract length and encoding?


code:
#!/usr/bin/python
from Tkinter import *
class resizeTest:
    def __init__( self, master ):
        def normal():
            self.ma.geometry('220x100')
        def enlarge():
            self.ma.geometry('500x360')
        self.ma = master
        self.ma.title('Resize Test')
        self.ma.geometry('220x100')
        self.f = Frame( self.ma )
        self.f.pack(fill=BOTH, expand=YES)
        self.enlarge = Button( self.f, text='Enlarge', height=1, width=10, padx=0, pady=1, command=enlarge)
        self.enlarge.pack(side=LEFT, fill=BOTH,expand=YES)
        self.normal = Button( self.f, text='Normal', height=1, width=10, padx=0, pady=1, command=normal)
        self.normal.pack(side=RIGHT, fill=BOTH,expand=YES)
root = Tk()
app = resizeTest(root)
root.mainloop()

rawDescription: how can i make my buttons resize

description: Make my buttons resize


code:
cell = sh.cell(x,y)
print(cell.value)

rawDescription: Python xlrd : how to convert an extracted value?


code:
value = ['\x7f', '\x15', '\xb7', '\xdb', '5', '\x03', '\xc0', '@']
''.join(value)
from struct import unpack
unpack('d', ''.join(value))

rawDescription: Unpack from hex to double in Python

description: Unpack from hex to double in Python


code:
if int(c.high0) >= 34:
            plt.text(x, y, int(c.high0), fontsize=7, fontweight='bold')

rawDescription: Parsing an html line and pulling out only numbers that meet a certain criteria


code:
from functools import partial

mapfunc = partial(my_function, ip=ip)
map(mapfunc, volume_ids)

rawDescription: Using Python map() function with keyword arguments


rawDescription: Change my current working directory in Python to my external hard drive.


code:
import requests

cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}

r = requests.post('http://wikipedia.org', cookies=cookie)

rawDescription: How to send cookies in a post request with the Python Requests library?

description: Send cookies in a post request with the Python Requests library


rawDescription: python - get item number from list

description: Python - get item number from list


code:
from Tkinter import Label,Tk
from PIL import Image, ImageTk
import tkFileDialog
root = Tk()

path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
im = Image.open(path)
tkimage = ImageTk.PhotoImage(im)
myvar=Label(root,image = tkimage)
myvar.image = tkimage
myvar.pack()

root.mainloop()

rawDescription: displaying the selected image using tkinter

description: Displaying the selected image using tkinter


code:
#generic subnet creation method
def create_subnet(connection, vpc, cidr, name, test_mode=True):
    print("Creating subnet with CIDR block", cidr)
    subnet = connection.create_subnet(vpc.id, cidr_block=cidr, dry_run=test_mode)

    #wait for subnet to become live
    while subnet.state == 'pending':
        subnets = connection.get_all_subnets()
        for item in subnets:
            if item.id == subnet.id:
                subnet.state = item.state
        time.sleep(5)

    #tag the subnet
    subnet.add_tag("Name", name)
    print("Done")
    return subnet

rawDescription: AWS boto: how to refresh subnet.state after creating it? It's stuck in 'pending' forever and there's no update()


rawDescription: Python 2.7 reading csv fields rather than rows


rawDescription: pandas dataframe slice rows based on date indexes

description: Pandas dataframe slice rows based on date indexes


code:
from ast import literal_eval
data = u'{ \'name\':"xyz", \'data\':[{\'age\': 0, \'foo\': 1}, {\'age\': 1, \'foo\': 1}]}'
dic = literal_eval(data)
dic['data']

rawDescription: How to convert unicode original python type

description: Convert unicode original python type


code:
class MyResource(ModelResource):
    def obj_update(self, bundle, request=None, **kwargs):
        for field_name in self.fields:
            field = self.fields[field_name]

            if type(field) is ToOneField and field.null and bundle.data[field_name] is None:
                setattr(bundle.obj, field_name, None)

        return super(MyResource, self).obj_update(bundle, **kwargs)

rawDescription: Using TastyPie to update a ForeignKey field to null