code: reduce(lambda x,y:7*x+y, numlist)

rawDescription: list of arbitrary-base digits to int

description: List of arbitrary-base digits to int


code: arry = (arry >= 6).astype(int)

rawDescription: Assign 0 and 1 based on values greater than in one line


code: nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels)

rawDescription: How do I customize the display of edge labels in networkx?

description: Customize the display of edge labels in networkx


code:
lis=[1,2,3]
[x*3 for x in lis]
num=123
[int(x)*4 for x in str(num)]  #convert num to a string and iterate over it
''.join(str(int(x)*3) for x in str(num)) #to get something like 4812

rawDescription: How do you multiply each point of a linked list by a number x?

description: Multiply each point of a linked list by a number x


code:
#!/usr/bin/env python3

from gi.repository import Gtk

class Demo:
    def __init__(self):
        self.window = Gtk.Window()
        self.window.set_default_size(640, 480)
        self.window.connect('delete-event', self.on_app_exit)

        scrolledwindow = Gtk.ScrolledWindow()
        self.window.add(scrolledwindow)

        self.liststore = Gtk.ListStore(str, str, int, str)

        # You need to use self.fillStore() instead.
        self.liststore.append(['Debian', 'i386', 0, 'ok'])
        self.liststore.append(['Fedora', 'amd64', 1, 'ok'])
        self.liststore.append(['Ubuntu', 'i386', 2, 'ok'])

        treeview = Gtk.TreeView(model=self.liststore)
        scrolledwindow.add(treeview)

        names = ('Name', 'URL', 'Bitrate', 'Format')
        for i in range(4):
            renderer_text = Gtk.CellRendererText()
            column = Gtk.TreeViewColumn(names[i], renderer_text, text=i)
            treeview.append_column(column)

    def fillStore(self):
        pass

    def run(self):
        self.window.show_all()
        Gtk.main()

    def on_app_exit(self, widget, event=None):
        Gtk.main_quit()

if __name__ == '__main__':
    demo = Demo()
    demo.run()

rawDescription: python gtk fill ListStore in TreeView

description: Python gtk fill ListStore in TreeView


code: cursor = db.tweets.find({"tweet.timestamp":{'$gte':startEpoch, '$lte':endEpoch}})

rawDescription: Pymongo returning incorrectly when using "$gte" and "$lte"


code: numpy.random.normal(size=[1, 2])

rawDescription: Generate two-dimensional normal distribution given a mean and standard deviation


code:
import cv2

def crop(img):
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    sub_face = img

    faces = face_cascade.detectMultiScale(img, 1.1, 5)
    for (x,y,w,h) in faces:
        sub_face = img[y:y+h, x:x+w]

    return sub_face

imageToCrop = cv2.imread('izz.jpg',0)
croppedImage = crop(imageToCrop)

cv2.imshow('img',croppedImage)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: Capture face area by camera

description: Capture face area by camera


code:
class Foo:
    def __getitem__(self, value):
            return value
foo = Foo()
foo["1"]
foo[0]

rawDescription: How to have data structure with both tuple and dictionary characteristic

description: Have data structure with both tuple and dictionary characteristic


code:
def tobits(s):
    result = []
    for c in s:
        bits = bin(ord(c))[2:]
        bits = '00000000'[len(bits):] + bits
        result.extend([int(b) for b in bits])
    return result

def frombits(bits):
    chars = []
    for b in range(len(bits) / 8):
        byte = bits[b*8:(b+1)*8]
        chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
    return ''.join(chars)

rawDescription: Convert string to list of bits and viceversa


code: { str(len(x)) : x for x in py_list if not x.isdigit() and str(len(x)) in py_list }

rawDescription: Pair string lengths to strings from unordered list


code:
#b.py
def runb():
    from __main__ import callback
    callback()

rawDescription: Python global variables and callbacks

description: Python global variables and callbacks


code:
from openpyxl import load_workbook

wb = load_workbook("myfile.xlsx", use_iterators=True)
ws = wb.active

data = []
for row in ws.iter_rows():
    new_row = []
    new_row += [row[1].value]
    new_row += [row[3].value]
    data += new_row

rawDescription: Nonsequential cells with openpyxl

description: Nonsequential cells with openpyxl


code: os.system("echo '/usr/bin/python /(somewhere)/scripts/backup/testbackup.py' | at now")

rawDescription: Execute background process from django that can't be interrupted by the web server


code:
import csv, json

header = ['ID', 'name', 'type', 'area', 'HAC', 'verticalAccuracy', 'course', 'lat', 'lng']

with open('file.DAT') as datfile:
    with open('output.csv', 'wb') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=header)
        writer.writeheader()
        for line in datfile:
            writer.writerow(json.loads(line))

rawDescription: Parsing .DAT file with Python

description: Parsing .DAT file with Python


code:
fruits = ["apple", "mango", "strawberry", "cherry", "peach","peach pie"]
allergies = ["cherry", "peach"]

okay = [fruit for fruit in fruits if not any(allergy in fruit.split() for allergy in allergies)]
# ['apple', 'mango', 'strawberry']

rawDescription: Ignore the items in the ignore list by name in python


code: from calendar import monthrange

rawDescription: import issue with python/django

description: Import issue with python/django


code:
from webbrowser import open_new
open_new("http://www.google.com")
open_new("file://<YOUR FILE PATH HERE>")

rawDescription: Enthought Canopy: Opening a file in web browser


code:
from lxml import etree
doc = etree.parse("http://genome.ucsc.edu/cgi-bin/das/hg19/dna?segment=chr20:30037432,30038060",parser=etree.XMLParser())
doc.xpath('SEQUENCE/DNA/text()')

rawDescription: python, fetch sequence from DAS by coordinates

description: Python, fetch sequence from DAS by coordinates


code:
from datetime import datetime
{datetime(year=2015, month=x, day=1).strftime('%B'): 1 + (x - 3) % 12 for x in range(1, 13)}

rawDescription: How to assign numbers to months of the year? python

description: Assign numbers to months of the year? python


code:
fig, ax = plt.subplots(figsize=(3,2.25))
ax.plot(df3['difference'],'r-',label="Observations")
ax.plot(df4['difference'],'b-',label='MERRA')
ax.set_xlim(0,205)
ax.set_ylim(-60,60)
ax.set_xlabel('Year')
ax.set_ylabel('Snow Depth Departures(cm)')
ax.set_title('Station '+str(stations[c])+' Snow Depth Correlations R='+str("%0.2f"%corr[0])+'')
ax.autoscale(False)
ax.set_xticks(np.arange(0,193,48))
ax.set_xticklabels(['1979','1983','1987','1991','1995'])
ax.legend(loc='best')

rawDescription: Matplotlib subplots Figure size

description: Matplotlib subplots Figure size


code:
links = soup.select('div.yfi_quote_headline ul > li > a')
for link in links:
    print(link.get_text(strip=True))

rawDescription: Scraping Headlines off of Yahoo! Finance with Python3


code:
class ProductDetail(DetailView):
    model = Producto
    template_name = 'productos/product_detail.html'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(ProductDetail, self).get_context_data(**kwargs)
        if not 'recent' in self.request.session or not self.request.session['recent']:
            self.request.session['recent'] = [self.object.pk]
        else:
            recentList = self.request.session['recent']
            recentList.append(self.object.pk)
            self.request.session['recent'] = recentList
        # Add in a QuerySet of featured products
        context['product_list'] = Producto.objects.filter(featured=True).exclude(pk=self.object.pk)
        context['recent_list'] = Producto.objects.filter(pk__in=recentList)
        return context

rawDescription: Insert request.session in class based Generic view in Django


code:
my_little_list = [w, x, y, z]
cursor.execute("...", my_little_list)

rawDescription: Insert record into SQLite table with large number of columns


code:
count = 0
total = 0
for v in "bonbon":
  count += 1
  if v == 'e' or v == 'o' or v == 'u' or v == 'a':
    total += 1

print('the number of vowel in your word is ' + str(total))

rawDescription: Print, loop, Indentation, Python

description: Print, loop, Indentation, Python


rawDescription: 'NA' value lost after using Python Pandas


code:
# Last-modified: 16 Oct 2013 05:08:28 PM
import numpy as np
import matplotlib.pyplot as plt

# generating fake data
locations = np.arange(0, 50, 1)
medians   = locations/(1.0+(locations/5.0)**2)
disps     = 0.1+0.5*locations/(1.0+(locations/5.0)**2.)
points    = np.empty([50, 100])
for i in xrange(50) :
    points[i,:] = np.random.normal(loc=medians[i], scale=disps[i], size=100)

# finding percentiles
pcts = np.array([20, 35, 45, 55, 65, 80])
layers = np.empty([50, 6])
for i in xrange(50) :
    _sorted = np.sort(points[i,:])
    layers[i, :] = _sorted[pcts]

# plot the layers
colors = ["blue", "green", "red", "green", "blue"]
for i in xrange(5) :
    plt.fill_between(locations, layers[:, i], layers[:, i+1], color=colors[i])
plt.show()

rawDescription: Plotting stochastic processes in Python

description: Plotting stochastic processes in Python


code:
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot
data = np.floor(np.random.random((10,10)) * 6)
cmap = mpl.colors.ListedColormap(['w', 'b', 'g', 'y', '#ff8c00', 'r'])
norm = mpl.colors.BoundaryNorm([0,1,2,3,4,5,6], cmap.N)
pyplot.imshow(data, cmap=cmap, norm=norm, interpolation='none')
pyplot.colorbar()
pyplot.show()

rawDescription: Using matplotlib to draw color bar with distinguishable and uncontinues colors


code:
import collections

class Foo(object):
    handlers = None

    def __init__(self):
        self.handlers = collections.defaultdict(set)

    def register(self, event, callback):
        self.handlers[event].add(callback)

    def fire(self, event, **kwargs):
        for handler in self.handlers.get(event, []):
            handler(**kwargs)

foo = Foo()
foo.register('one', mycallback)
foo.fire('one')

rawDescription: Python reference to callback in dictionary


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

listAct = []
for pos,rem in np.array(db.extractData(mess)):
    act = gen.unixTime_to_dateTime(rem)- gen.unixTime_to_dateTime(pos) ##act is a datetime object
    listAct.append(act.days + act.seconds/float(86400))

bins = range(1,15)
plt.hist(listAct,bins)
plt.show()

rawDescription: Plot a distribution graph in Python

description: Plot a distribution graph in Python


code:
SWIG_POINTER_OWN
SWIG_POINTER_NOSHADOW

rawDescription: what does the last argument to SWIG_NewPointerObj mean?

description: What does the last argument to SWIG_NewPointerObj mean


code:
sp = subprocess.Popen(['./generate_name.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
sp.stdin.write("2\n")
sp.stdin.close()
answer = sp.stdout.read()
status = sp.wait()

rawDescription: Use Python to run interactive python scripts


code:
from scipy.stats import genextreme as gev
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1, 1)

x=np.arange(0.01,120,0.01)
# The order for this is array, shape, loc, scale
F=gev.pdf(x,-0.198,loc=17.44,scale=8.153)

plt.plot(x,F,'g',lw=2)
plt.show()

rawDescription: Why do the Frechet distributions differ in scipy.stats vs R


code:
from django.db import models
from django_countries.fields import CountryField

class Person(models.Model):
    name = models.CharField(max_length=100)
    country = CountryField()

rawDescription: Country choice for users in Django

description: Country choice for users in Django


rawDescription: Django/Python: How to cast an integer into the equivalent enum string?


rawDescription: Access twitter user object using lookup_user


code:
env = jinja2.Environment(
    loader=jinja2.FileSystemLoader(template_path))
env.filters['default_if_none'] = default_if_none  # a function
tmpl = env.get_template(filename)
tmpl.render(**context)

rawDescription: Adding a custom Jinja2 filter in GAE 1.6.0


code:
emp_id = request.GET['Emp_ID']
year = request.GET['Year']

rawDescription: Accessing form values from pure html forms in django views


code:
# Load ctypes, and your library
from ctypes import *
mylib = CDLL("mylibrary.so")

# Declare the function's prototype. This isn't strictly required.
mylib.Add.argtypes = [c_int, c_int]
mylib.Add.restype = c_int

# Call it!
result = mylib.Add(123, 456)

rawDescription: How do I extend Python with C?

description: Extend Python with C


rawDescription: How to merge 2 numpy arrays?

description: Merge 2 numpy arrays


code:
import csv

file = 'c:\\temp\\test.csv'

def GetValuesFromColumn(title):

  values = []
  rownum = 0
  with open(file, 'r') as f:
    reader = csv.reader(f)
    for row in reader:
      if rownum == 0:
        index = row.index(title)
        rownum = 1
      else:
        values.append(row[index])

  return values

values = GetValuesFromColumn('D')

rawDescription: How can I call columns with column names in Python

description: Call columns with column names in Python


code:
def enviarCorreo(fromaddr, toaddr, text, file):
    msg = MIMEMultipart('mixed')
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = 'asunto'

    #This is the part you had missed.
    msg.attach( MIMEText(text) )

    #adjunto
    adjunto = MIMEBase('application', "octet-stream")
    adjunto.set_payload( open(file,"rb").read() )
    Encoders.encode_base64(adjunto)
    adjunto.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
    msg.attach(adjunto)

    server = smtplib.SMTP('localhost')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddr, msg.as_string())
    server.close()

enviarCorreo("x@from.com", ["y@to.com"], "Hello World", ['/tmp/sample.png'])

rawDescription: Python Sendmail with Attachment?

description: Python Sendmail with Attachment


code:
label_from_txt_file = label_from_txt_file.strip()
plt.plot(range(2), line, label=label_from_txt_file)

rawDescription: Matplotlib 1.3.0, legend line and text do not match


code:
def staffed_users(self):
    return User.objects.filter(staff__project=self)

rawDescription: Getting set of users attached to an object


code:
def is_int(foo):
   try:
      return int(foo)
   except ValueError:
      print('{} is not a number'.format(foo))
      return is_int(input('Please enter a number: '))

rawDescription: Issue with trying to limit datatype inputs


code:
import urllib
dls = "http://www.muellerindustries.com/uploads/pdf/UW SPD0114.xls"
urllib.urlretrieve(dls, "test.xls")

rawDescription: downloading an excel file from the web in python

description: Downloading an excel file from the web in python


code:
filefield_defaults = {
    'allow_files':True,
    'allow_folders':True,
    'recursive':True
}

file_one = models.FilePathField(
    path=FIELD_PATH1,
    **filefield_defaults
)

file_two = models.FilePathField(
    path=FIELD_PATH2,
    **filefield_defaults
)

rawDescription: How to stay DRY with Django model field definitions

description: Stay DRY with Django model field definitions


rawDescription: How to write ANSI compatible bytes in Python 3 (0x80 and up)?

description: Write ANSI compatible bytes in Python 3 (0x80 and up)


code:
test2 = "-beginning realization 5 -singlespace -multispaceafter  not-this-one -whitespace\t\n -end"
m = re.findall(r'(?:\s|^)-(\S+)', test2)
m

rawDescription: Python Regex to findall Delimited Substrings


code:
import tkinter

letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
letters += letters.lower()
encryption_code += encryption_code.lower()

window = tkinter.Tk()
encryption_code_entry = tkinter.Entry(window)
entry = tkinter.Entry(window)

enc = dict(zip(letters,encryption_code))

string = 'hello world'

def encrypt():
    encrypt_label.pack()
    entry.pack()
    encrypt_confirm.pack()
    encrypt_button.destroy()

def display_encrypt():
    display_enc = "".join([enc.get(ch, ch) for ch in entry.get()])
    encrypted_label.pack()
    new_message.config(text=str(display_enc))
    new_message.pack()

encrypt_confirm = tkinter.Button(window, text="Confirm", command=display_encrypt)
new_message = tkinter.Label(window, text="", font=('Helvetica', 10))
encrypted_label = tkinter.Label(window, text="Your message " + entry.get() + " has been encrypted into the following: ")
encrypt_button = tkinter.Button(window, text="Encrypt", command=encrypt)
encrypt_button.pack()
encrypt_label = tkinter.Label(window, text="Please enter the message you'd like to encrypt", font=('Helvetica', 14))

window.mainloop()

rawDescription: entry.get() function won't change value of a variable

description: Entry.get() function won't change value of a variable


code:
'''
Registers a special handler for named HTML entities

Usage:
import named_entities
text = u'Some string with Unicode characters'
text = text.encode('ascii', 'named_entities')
'''

import codecs
from htmlentitydefs import codepoint2name

def named_entities(text):
    if isinstance(text, (UnicodeEncodeError, UnicodeTranslateError)):
        s = []
        for c in text.object[text.start:text.end]:
            if ord(c) in codepoint2name:
                s.append(u'&%s;' % codepoint2name[ord(c)])
            else:
                s.append(u'&#%s;' % ord(c))
        return ''.join(s), text.end
    else:
        raise TypeError("Can't handle %s" % text.__name__)

codecs.register_error('named_entities', named_entities)

rawDescription: encoding text to html entity (not the tags)

description: Encoding text to html entity (not the tags)


rawDescription: Why Does Using the Python-YQL Module Change sys.path[0] to sys.path[1]?


code:
begin = 0
end = -1
ret = 1
while (begin > end and ret > 0):
    items = []
    items.append(['text',ITEM_TEXT,"Automatically save the evaluation in data file(s)\n",""])
    items.append(['text',ITEM_TEXT,"Determine the range of timesteps that you want to save:",""])
    items.append(['step_begin',ITEM_INT,"Start timestep:","Start timestep",first_step,first_step,timesteps])
    items.append(['step_end',ITEM_INT,"End timestep:","End timestep",timesteps,first_step,timesteps])
    a = CeiQtGenericDialog(items,None,"Save evaluation","Ok","Cancel")
    ret = a.doit()

    if (ret > 0):
        for i in a.getValues():
            if (i=='step_begin'):
                begin = a.getValue(i)
            if (i=='step_end'):
                end = a.getValue(i)

        if (begin > end):
            items2 = []
            items2.append(['text',ITEM_TEXT,"Start timestep must be smaller than end timestep!!",""])
            a = CeiQtGenericDialog(items2,None,"Error","Ok","Cancel")
            ret = a.doit()

rawDescription: Python - after a certain if loop repeat a certain part of the code


code:
indx = A[:, 1] != -1
A[indx]
A[~indx]

rawDescription: complementary slicing in a numpy array

description: Complementary slicing in a numpy array


code: myString += getattr(eachObject, everyElement)

rawDescription: google app engine - python, iterate through data model properties

description: Google app engine - python, iterate through data model properties


code:
count_cusip = 0
count_name = 0
count_sender = 0
cur_sender = ''
for line in lines:

    m = re.search('[0-9]{3}[a-zA-Z0-9]{6}', line)
    if m:
        count_cusip += 1
        ws.write(count_cusip,0,m.group(0))
        ws.write(count_cusip,2,cur_sender)

    n = re.search('[A-Z]{3,5}\s[0-9]{1,4}\D{1,3}\S{1,3}\s{1,2}\w+', line)
    if n:
        count_name += 1
        ws.write(count_name,1,n.group(0))
        ws.write(count_name,2,cur_sender)

    o = re.search(r"Original Sender:\s\b\w+\s\w+", line)
    if o:
        count_sender += 1
        cur_sender = o.group(0)

rawDescription: Python Parsing - Multiple Emails in One Text File


code:
class square:

    def __init__(self, side_length):
        #self.num_sides = 4
        #self.type = 'regular quadrilateral'
        self.side_length = side_length

    def perim(self):
        return self.side_length * 4
    def area(self):
        return self.side_length ** 2

class circle:
    def __init__(self, radius):
        #self.num_sides = 1
        #self.type = 'ellipsis'
        self.radius = radius

    def area (self):
        return 3.14 * self.radius ** 2

shape2 = circle (5)
print ('test of circle: ',shape2.area ())

shape1 = square(5)
print('test of square:  ', shape1.perim())

rawDescription: Python 3x class methods

description: Python 3x class methods


code:
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 100)

# the comma is to get just the first element of the list returned
plot1, = plt.plot(x, x**2)
plot2, = plt.plot(x, x**3)

title_proxy = Rectangle((0,0), 0, 0, color='w')

plt.legend([title_proxy, plot1, title_proxy, plot2],
           ["$\textbf{title1}$", "label1","$\textbf{title2}$", "label2"])
plt.show()

rawDescription: Multiple titles in legend in matplotlib

description: Multiple titles in legend in matplotlib


rawDescription: Getting filenames matching an extension using BeautifulSoup


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class A(Base):
    __tablename__ = 'a'

    id = Column(Integer, autoincrement=False, primary_key=True)
    firstname = Column(String(50))
    lastname = Column(String(50))
    fullname = Column(String(100), FetchedValue())

e = create_engine("mssql+pyodbc://scott:tiger@ms_2005", echo=True)
Base.metadata.drop_all(e)

e.execute("""
    CREATE TABLE a (
            id INTEGER PRIMARY KEY,
            firstname VARCHAR(50),
            lastname VARCHAR(50)
        )
""")
e.execute("ALTER TABLE a ADD fullname AS firstname + ' ' + lastname")

sess = Session(e)

sess.add_all([
    A(id=1, firstname='ed', lastname='jones'),
    A(id=2, firstname='wendy', lastname='smith'),
    A(id=3, firstname='jack', lastname='bean')
])
sess.commit()

assert [
    fname for fname, in
    sess.query(A.fullname).order_by(A.id)
] == ['ed jones', 'wendy smith', 'jack bean']

e.execute("DROP TABLE a")

rawDescription: update tables with computed columns in sqlalchemy

description: Update tables with computed columns in sqlalchemy


code:
data = {
    'test1': 10,
    'test2': 20,
    'testx': 40,
    'foo': 50,
}

items = data.items()
pd.DataFrame({'keys': [i[0] for i in items], 'values': [i[1] for i in items]})

rawDescription: Creating a panda's dataframe out of a single variable that contains a dict


code:
def my_replace(match):
    match = match.group()
    return match + str(match.index('e'))
re.sub(r'@\w+', my_replace, string)

rawDescription: Python replace string pattern with output of function


code:
def decrypt():

    # we don't need the zero start value, that's the default
    # test all possible shifts
    for i in range(27):

        # initialize the array
        freqlist = []

        # shift all the letters in the input
        for a in inpt:
            b = ord(a)
            b -= i
            if b > ord("Z"):
                b -= 26
            elif b < ord("A"):
                b+=26
            freqlist.append(b)

        # now put the shifted letters back together
        shifted = ""
        for a in freqlist:
           d = chr(a)
           # append the shifted letter onto our output
           shifted += d

        # after we put the decrypted string back together, print it
        # note this is outside the letter loops,
        # but still inside the possible shifts loop
        # thus printing all possible shifts for the given message
        print(d)

rawDescription: caesar cipher brute force decryption

description: Caesar cipher brute force decryption


rawDescription: Python markdown footnote backlink text change


code:
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
        },
        'console':{
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': [],
        }
    },
    'loggers': {
        'django': {
            'handlers': ['null'],
            'propagate': True,
            'level': 'INFO',
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        },
    }
}

rawDescription: How do I define a settings.LOGGING so that gunicorn will find the version value it wants?

description: Define a settings.LOGGING so that gunicorn will find the version value it wants


code:
import os #needed system utils
import numpy as np# for array data processing
import pandas as pd #import the pandas module
datadirectory = input('path to the data directory, ')
working = os.environ.get("WORKING_DIRECTORY", datadirectory)
os.chdir( working)

 ##READ DATA FILE AND and convert it to string
dataset = open(input('dataset_to_be_used, ')).readlines()
data = ''.join(dataset)

df = pd.read_csv(data, sep="\\s+", header=None)
sorted_data = df.groupby(["X.1","X.2","X.5"])["X.8"].mean().reset_index()
tuple_data = [tuple(x) for x in sorted_data.values]
datas = np.asarray(tuple_data)

rawDescription: Average data based on specific columns - python


code:
import numpy as np
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.morphology import generate_binary_structure, binary_erosion
import matplotlib.pyplot as pp

#for some reason I had to reshape. Numpy ignored the shape header.
paws_data = np.loadtxt("paws.txt").reshape(4,11,14)

#getting a list of images
paws = [p.squeeze() for p in np.vsplit(paws_data,4)]

def detect_peaks(image):
    """
    Takes an image and detect the peaks usingthe local maximum filter.
    Returns a boolean mask of the peaks (i.e. 1 when
    the pixel's value is the neighborhood maximum, 0 otherwise)
    """

    # define an 8-connected neighborhood
    neighborhood = generate_binary_structure(2,2)

    #apply the local maximum filter; all pixel of maximal value
    #in their neighborhood are set to 1
    local_max = maximum_filter(image, footprint=neighborhood)==image
    #local_max is a mask that contains the peaks we are
    #looking for, but also the background.
    #In order to isolate the peaks we must remove the background from the mask.

    #we create the mask of the background
    background = (image==0)

    #a little technicality: we must erode the background in order to
    #successfully subtract it form local_max, otherwise a line will
    #appear along the background border (artifact of the local maximum filter)
    eroded_background = binary_erosion(background, structure=neighborhood, border_value=1)

    #we obtain the final mask, containing only peaks,
    #by removing the background from the local_max mask
    detected_peaks = local_max - eroded_background

    return detected_peaks

#applying the detection and plotting results
for i, paw in enumerate(paws):
    detected_peaks = detect_peaks(paw)
    pp.subplot(4,2,(2*i+1))
    pp.imshow(paw)
    pp.subplot(4,2,(2*i+2) )
    pp.imshow(detected_peaks)

pp.show()

rawDescription: Peak detection in a 2D array

description: Peak detection in a 2D array


code:
import sys
message = sys.stdin.readlines()

rawDescription: How to include a newline in the python raw_input() function?

description: Include a newline in the python raw_input() function


code:
# New object, newscenario passed to constructor
world_scenario = RealWordScenario(newscenario)
# Another new object, now world_scenario is passed to constructor
scheduler = ConcreteRealWorldScheduler(world_scenario)
# Call the method
variable = scheduler.method()

rawDescription: Do not understand this line of code in Python?


code:
my_file =  open(file_path, 'r')
response = HttpResponse(my_file.read(), mimetype='text/plain')
response['Content-Disposition'] = 'inline;filename=some_file.txt'
return response

rawDescription: How to open a .txt file in Django?

description: Open a .txt file in Django


code:
import re
...
for line in templ:
    if line.startswith("something"):
        filelist.append(re.sub(r"\s+", "", line))

rawDescription: Whitespace removing in file

description: Whitespace removing in file


code:
def largest_subarray(A, B):
    dims = np.minimum(A.shape, B.shape)         # find smallest dimensions
    idx = tuple(slice(None, dd) for dd in dims) # construct tuple of slice indices
    return A[idx], B[idx]                       # index into A and B

rawDescription: Comparing matrices of different shapes

description: Comparing matrices of different shapes


code:
import bge

dunWidth = 100 #meters/tiles
dunHeight = 100 #meters/tiles
a=0
b=0

add= bge.logic.getCurrentScene().addObject

def main():
    global a,b
    cont = bge.logic.getCurrentController()
    dunMarker = cont.owner
    for b in range(0,dunWidth,2):
        dunMarker.worldPosition=(b,a,0)
        t=add("FloorTile", "DunMarker",0)
        for a in range(0,dunHeight,2):
            dunMarker.worldPosition = (b,a,0)
            add("FloorTile", "DunMarker",0)
main()

rawDescription: addObject() in blender with python

description: AddObject() in blender with python


code:
def Deploy_at():
    ''' This function will deploy nine "at" jobs
    running at an interval of one minute to capture
        swap usage '''

    repeat = 1
    while repeat <= 9:
        c1 = 'at,now + %d min' % repeat
        sched_cmd = list(c1.split(','))
        command = '/usr/bin/python /home/ricky/python-test/cal_swap.py -m trigger\n'

        p = Popen(sched_cmd, stdin=PIPE, stdout=PIPE)
        p.communicate(command)
        repeat += 1

rawDescription: scheduled at jobs deployed via a python script do not append to same log file

description: Scheduled at jobs deployed via a python script do not append to same log file


code:
with open('somefile.txt') as f:
   first_row = next(f).strip().split(';')
   TOTAL_NUMBER = len(first_row[first_row.index('START'):first_row.index('END')+1])
   bits = ''.join(line.rstrip() for line in f).split(';')
   final_array = bits[bits.index('PROVEEDOR'):bits.index('PROVEEDOR')+TOTAL_NUMBER]

rawDescription: Parsing a simple text file in python

description: Parsing a simple text file in python


code: duplicateNotationMoves = list(filter(lambda move : len(m for m in moves if m.notation == move.notation) > 1, moves))

rawDescription: Returning all objects in list which have the same attribute as another object?


code:
import struct
id, first, second = 5, 42, 58
struct.pack('>bhb', id, first, second)

rawDescription: Work with bytes in python

description: Work with bytes in python


code:
for _ in range(n):
  stuff

rawDescription: Does Python have a way to repeat a given number of times without explicitly assigning a counter variable?


code:
import scrapy

from scrapy import Spider
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from stackoverflow.items import NaukriItem

class NaukriSpider(CrawlSpider):
    name = "naukri"
    allowed_domains = ["naukri.com"]
    start_urls = ["http://www.naukri.com/information-technology-jobs?xt=catsrch&qf[]=24"]

    rules = (
        Rule(SgmlLinkExtractor(allow=('information-technology-jobs.*', )), callback="parse_start_url", follow= True),
    )

    def parse_start_url(self,response):
        for sel in response.xpath('//*[@class="content"]'):
            item = NaukriItem()
            item['title'] = sel.xpath('span[@class="desig"]/text()').extract()
            item['location'] = sel.xpath('span[@class="loc"]/span/text()').extract()
            item['organization'] = sel.xpath('span[@class="org"]/text()').extract()
            yield item

rawDescription: Scrapy crawlspider rule not working for next pages


code:
import subprocess
subprocess.Popen(["command", "-a", "arg1", "-b", "arg2"])

rawDescription: Run a child process free of the parent in Python


code:
from collections import Counter
lis = ['*,V*,UV,**,a2*,IR' , 'SB*,V*,UV,**,*,a2*,IR' , '*,V*,a2*']
Counter(y for x in lis for y in x.split(',') if '*' in y)

rawDescription: How to create list of all parts of elements in NumPy array (Python list)

description: Create list of all parts of elements in NumPy array (Python list)


code: print("b'" + ''.join('\\x{:02x}'.format(x) for x in byteval) + "'")

rawDescription: Python3 print in hex representation

description: Python3 print in hex representation


code:
from sqlalchemy import event, create_engine

def before_execute(conn, clauseelement, multiparams, params):
    log.info("Received statement: %s" % clauseelement)

engine = create_engine('postgresql://scott:tiger@localhost/test')
event.listen(engine, "before_execute", before_execute)

rawDescription: how to intercept CRUD in sqlalchemy based app?

description: Intercept CRUD in sqlalchemy based app


code:
# bmi = <whatever>
found_bmi_range = [bmi_range for bmi_range
                   in bmi_ranges
                   if bmi_ranges[2] <= bmi <= bmi_ranges[3]
                  ][0]

rawDescription: Finding a Value within a Range in a List of Tuple Values in Python


code:
child = pexpect.spawn(launchcmd)
while True:
    try:
        child.expect('\n')
        print(child.before)
    except pexpect.EOF:
        break

rawDescription: how to use pexpect to get spontaneous output of subprocess in python

description: Use pexpect to get spontaneous output of subprocess in python


code:
from datetime import timedelta

def get_days_between(datePast, dateFuture):
   difference = dateFuture - datePast
   return difference.total_seconds() / timedelta(days=1).total_seconds()

rawDescription: Dates difference in days as a fraction

description: Dates difference in days as a fraction


code:
import json
graph = {
"random" : [
    {
        "attr1" : "X",
        "attr2" : "Y"
    },
    {
        "attr1" : "Z",
        "attr2" : "V"
    }
    ]
}
json.dumps(graph)

rawDescription: Python encoding graph to json

description: Python encoding graph to json


code:
import re
external_dep = dict()
deps = ' '.join(re.findall(r'(?<=External-dep:\s)[\d ]+(?=\n)', output)).split()
deps
external_dep[Master_change] = list(set(deps))
external_dep

rawDescription: Parsing a text in a variable

description: Parsing a text in a variable


code: df['d'] = df.apply(lambda x: some_func(a = x['a'], b = x['b'], c = x['c']))

rawDescription: Pandas: Map a function using multiple columns


code:
# if you don't want to consider duplicates either
output = set(your_first_list) == set(your_second_list)

# if duplicates matter
output = sorted(your_first_list) == sorted(your_second_list)

rawDescription: Match two lists of letters in Python

description: Match two lists of letters in Python


code:
import imp,sys,string
magic = string.join(["\\x%.2x" % ord(c) for c in imp.get_magic()],"")
reg = ':pyc:M::%s::%s:' % (magic, sys.executable)
open("/proc/sys/fs/binfmt_misc/register","wb").write(reg)

rawDescription: Shebang for compiled Python code

description: Shebang for compiled Python code


code:
import regex
regex.match('(amazing){e<=1}', 'amaging')

rawDescription: Checking fuzzy/approximate substring existing in a longer string, in Python?


code:
import numpy as np

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Prepare sample data - normally distributed
NSamples = 5000
vmin, vmax = -2, 2

X = np.random.normal(loc=-.1, scale=.5, size=(NSamples,))
Y = np.random.normal(loc=.1, scale=.25, size=(NSamples,))
Z = np.random.normal(loc=0, scale=1, size=(NSamples,))

# Create figure, add subplot with 3d projection
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_xlim(vmin, vmax)
ax.set_ylim(vmin, vmax)
ax.set_zlim(vmin, vmax)

# Plot the data cloud
ax.scatter(X, Y, Z, s=.5, alpha=.05, color='k')

hist, binx, biny = np.histogram2d( X, Y)
x = np.linspace(X.min(), X.max(), hist.shape[0])
y = np.linspace(Y.min(), Y.max(), hist.shape[1])
x, y = np.meshgrid(x, y)
ax.contour(x, y, hist, zdir='z', offset=-3.)

hist, binx, biny = np.histogram2d( X, Z)
x = np.linspace(X.min(), X.max(), hist.shape[0])
z = np.linspace(Z.min(), Z.max(), hist.shape[1])
x, z = np.meshgrid(x, z)
ax.contour(x, hist, z, zdir='y', offset=3)

hist, binx, biny = np.histogram2d( Y, Z)
y = np.linspace(Y.min(), Y.max(), hist.shape[0])
z = np.linspace(Z.min(), Z.max(), hist.shape[1])
z, y = np.meshgrid(z, y)
ax.contour(hist, y, z, zdir='x', offset=-3)

ax.set_xlim([-3, 3])
ax.set_ylim([-3, 3])
ax.set_zlim([-3, 3])

rawDescription: How do I plot a projection of 3D scatter data on the XY/XZ/YZ planes?

description: Plot a projection of 3D scatter data on the XY/XZ/YZ planes


code:
os.chdir('/tmp/az')
f = open('/tmp/a.zip', 'wb')
z = zipfile.ZipFile(f, 'w')
for root, dirs, files in os.walk('.'):
  for fn in files:
    if fn.endswith('.pyc'): continue
    fp = os.path.join(root, fn)
    z.write(fp)

z.close()
f.close()

rawDescription: Backup of folder + database - Python

description: Backup of folder + database - Python


code:
from django.contrib import admin
from django.forms.models import BaseInlineFormSet, ModelForm

class AlwaysChangedModelForm(ModelForm):
    def has_changed(self):
        """ Should returns True if data differs from initial.
        By always returning true even unchanged inlines will get validated and saved."""
        return True

class CheckerInline(admin.StackedInline):
    """ Base class for checker inlines """
    extra = 0
    form = AlwaysChangedModelForm

rawDescription: Django Admin not saving pre-populated inline fields which are left in their initial state


code:
import os

cwd = os.getcwd()
folders = ['file1','file2','file3']
subfolders = ['sub1','sub2','sub3']

for folder in folders:
    os.mkdir(os.path.join(cwd, folder))

    # Create sub-folders.
    for sub in subfolders:
        os.mkdir(os.path.join(cwd, folder, sub))

rawDescription: How to makedirs from a list and include a list of subdirectories in python?

description: Makedirs from a list and include a list of subdirectories in python


code:
from StringIO import StringIO
buff = StringIO()
plt.savefig(buff)
buff.seek(0)
from kivy.core.image.img_pygame import ImageLoaderPygame
imgdata = ImageLoaderPygame(buff)._data

rawDescription: Load image from memory in Kivy

description: Load image from memory in Kivy


code:
import sys

overrun = []

data = ["Hello,"] + ( ["buffer"] * 80 )
maxsize = 800

# sys.getsizeof(data) is now 840 in my implementation.

while True:
    while sys.getsizeof(data) > maxsize:
        overrun.append(data.pop())
    do_something_with(data)
    if overrun:
        data, overrun = overrun, []
    else:
        break

rawDescription: Slice a list to max string size

description: Slice a list to max string size


code:
invite = form.save()
send_mail(Subject,message.render(Context()),from_email,[invite.email_address])

rawDescription: Django send_mail function keeps failing

description: Django send_mail function keeps failing


code:
# conftest.py

@pytest.mark.hookwrapper
def pytest_pyfunc_call(pyfuncitem):
    yield
    print('this happens after the test runs')
    if 'watch_logs' in pyfuncitem.funcargs:
        print(pyfuncitem.funcargs['watch_logs']())

rawDescription: How to print stuff in a py.test finalizer

description: Print stuff in a py.test finalizer


code:
from random import randint

digits = int(input("Input amount of digits (>=2): "))

lo = 10 ** (digits - 1)  # ex: 100
hi = (10 ** digits) - 1  # ex: 999
num = randint(lo, hi)

rawDescription: User input that generates numbers with a set amount of digits python


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

#plot your actual data here

plt.subplots_adjust(left=0.07, right=0.8, top=0.9, bottom=0.2)
#change the values above so that your figure and axes labels are all visible

plt.show()

rawDescription: Using tight_layout() in python creates unnecessary whitespace


code:
@bot.message_handler(content_types=['photo'])
def handle_photo(message):
    raw = message.photo[2].file_id
    name = raw+".jpg"
    file_info = bot.get_file(raw)
    downloaded_file = bot.download_file(file_info.file_path)
    with open(name,'wb') as new_file:
        new_file.write(downloaded_file)

rawDescription: Download photo without Telegram bot api

description: Download photo without Telegram bot api


code:
from Crypto.Cipher import DES
obj=DES.new('abcdefgh', DES.MODE_ECB)
plain="Guido van Rossum is a space alien."
len(plain)
obj.encrypt(plain)
ciph=obj.encrypt(plain+'XXXXXX')
ciph
obj.decrypt(ciph)

rawDescription: simple encrypt/decrypt lib in python with private key

description: Simple encrypt/decrypt lib in python with private key


code:
class UserProfileConfig(forms.Form):

    def __init__(self,request,*args,**kwargs):
        super (UserProfileConfig,self).__init__(*args,**kwargs)
        self.fields['username'] = forms.CharField(label='Username',max_length=100,initial=request.session['some_var'])

rawDescription: Django - Access request.session in form

description: Django - Access request.session in form


code:
from matplotlib import pyplot as plt
xval=[151383,151433,175367,178368,183937]
y=[98, 96, 95, 100, 90]
x=range(len(xval))
plt.xticks(x,xval)
plt.plot(x,y)
plt.show()

rawDescription: Change the ticks of x-axis

description: Change the ticks of x-axis


code:
toolzip = zipfile.ZipFile(myzipfile,  'r')
names = toolzip.namelist()
for n in names:
    data = toolzip.read(n)
    # do something with data

rawDescription: How can I extract a zip archive that contains a forbidden file name on Windows using Python?

description: Extract a zip archive that contains a forbidden file name on Windows using Python


code:
class RectangularPrism(object):
    def __init__(self, length, width, height):
        self.length = length
        self.width = width
        self.height = height

    def __repr__(self):
        return 'RectangularPrism({}, {}, {})'.format(
            self.length, self.width, self.height)

    def __str__(self):
        return ('Rectangular Prism with length {} width {} and height {} '
                'Volume = {} Surface Area = {}'.format(
                    self.length, self.width, self.height,
                    self.volume(), self.surfaceArea()))

    def volume(self):
        return self.length * self.width * self.height

    def surfaceArea(self):
        return 2 * (self.length*self.width + self.length*self.height + self.width*self.height)

class Cube(RectangularPrism):
    def __init__(self, side):
        super(Cube, self).__init__(side, side, side)

rawDescription: School Assignment - Classes/Subclasses

description: School Assignment - Classes/Subclasses


code:
class Memory:
    def __init__(self, s):
        if not 'RAM' in s and not 'memory' in s:
            raise ValueError("Not a string that describes RAM.")

        self.capacity = int(re.match(r'(\d+) ?GB', s)[1])

rawDescription: How to parse a loosely structured document

description: Parse a loosely structured document


code:
from decimal import *
getcontext().prec = 100
Decimal(2).sqrt()

rawDescription: how can i show an irrational number to 100 decimal places in python?

description: Show an irrational number to 100 decimal places in python


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

from flask import Flask, send_from_directory

app = Flask(__name__)

@app.route('/open')
def open():
    """Open in browser"""
    return send_from_directory('/tmp/', 'hello.txt')

@app.route('/download')
def download():
    """Download"""
    return send_from_directory('/tmp/', 'hello.txt', as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: How do I open an href link in HTML to a file but not download the file in a Flask app

description: Open an href link in HTML to a file but not download the file in a Flask app


rawDescription: python, best way to convert a pandas series into a pandas dataframe

description: Python, best way to convert a pandas series into a pandas dataframe


code:
num = str(ord(ch)) + w2
en = chr(int(num))

rawDescription: Python 3.3 Unsupported operand type(s) for +: 'int' and 'str'


code:
def resize_image(input, output, size, quality=None, crop=False, force=False):
    if (not force and os.path.exists(output) and
        os.path.getmtime(output) > os.path.getmtime(input)):
        return
    params = []
    if crop:
        params += ["-resize", size + "^"]
        params += ["-gravity", "Center", "-crop", size + "+0+0"]
    else:
        params += ["-resize", size]
    params += ["-unsharp", "0x0.4+0.6+0.008"]
    if quality is not None:
        params += ["-quality", str(quality)]
    subprocess.check_call(["convert", input] + params + [output])

rawDescription: Using ImageMagick's "convert" utility as a Python subprocess


code:
import re

data = '''
# Process_Name     ( 23387) Report at 2011-09-21 15:45:00.001    Type:  Periodic    #\n
some line 1\n
some line 2\n
some other lines\n
succ. statistics |     1438     1439  99 |   3782245    3797376  99 |\n
some lines\n
repeat the pattern several hundred times...
'''

pattern = r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*?succ. statistics\s+\|\s+(\d+)\s+(\d+)'
regex = re.compile(pattern, flags=re.MULTILINE|re.DOTALL)

for match in regex.finditer(data):
    results = match.groups()
    print(results)

    # ('2011-09-21', '1438', '1439')

rawDescription: Python - single vs multiline REGEX

description: Python - single vs multiline REGEX


code:
import Image
def is_grey_scale(img_path="lena.jpg"):
    im = Image.open(img_path).convert('RGB')
    w,h = im.size
    for i in range(w):
        for j in range(h):
            r,g,b = im.getpixel((i,j))
            if r != g != b: return False
    return True

rawDescription: How to check whether a jpeg image is color or gray scale using only Python stdlib

description: Check whether a jpeg image is color or gray scale using only Python stdlib


code:
x_unique  = np.unique(x)
y_means = np.array([np.mean(y[x==u]) for u in x_unique])
y_stds = np.array([np.std(y[x==u]) for u in x_unique])

rawDescription: Performing grouped average and standard deviation with NumPy arrays


code:
import collections

newMap = collections.defaultdict(list)

for key, value in A.iteritems():
    newMap[key].append(value)

rawDescription: Merge dicts and create list if duplicate keys


code:
import xlsxwriter
workbook = xlsxwriter.Workbook("test.xlsx")
sheet = workbook.add_worksheet()
for i in range(1, 70000):
    sheet.write('B' + str(i), "Blub")
workbook.close()

rawDescription: python2.7 xlsxwriter doesn't write more then 65533 rows

description: Python2.7 xlsxwriter doesn't write more then 65533 rows


rawDescription: Python, split list of coordinates, based on x


code:
from itertools import combinations
I, J = np.array(list(combinations([0,1,2], 2))).T
result = np.logical_and(np_data[:, I], np_data[:, J])
result
result.T

rawDescription: How to perform an operation on every two columns of a numpy array?

description: Perform an operation on every two columns of a numpy array


code:
sock.send("POST / HTTP/1.1\r\n")
sock.send("Host: 127.0.0.1\r\n")
sock.send("User-Agent: Python\r\n")
sock.send("Transfer-Encoding: chunked\r\n")
sock.send("Connection: close")
sock.send("\r\n\r\n")

# Now send the body of the message
# Each "chunk" of data must be preceded with the length of the chunk, in hex
s = 'some data'
sock.send(format(len(s), 'x')+'\r\n') # Sending the length of the data in hex
sock.send(s+'\r\n') # Sending the data

sock.send("0\r\n")
sock.send("\r\n")

sock.close()

rawDescription: on('close') events for TCP connections with http vs net - node.js

description: On('close') events for TCP connections with http vs net - node.js


code:
TREND_REGEX = re.compile('(^.*?)(?:\((?:([^-)])-([^)])|(\d+)-(\d+);(\d+)|([^)|]+(?:\|[^)|]+)*))\)(.*))?$')

def expand(trend):
    m = TREND_REGEX.match(trend)
    if m.group(8):
        suffixes = expand(m.group(8))
    else:
        suffixes = ['']
    if m.group(2):
        for z in suffixes:
            for i in range(ord(m.group(2)), ord(m.group(3))+1):
                yield m.group(1) + chr(i) + z
    elif m.group(4):
        for z in suffixes:
            for i in range(int(m.group(4)), int(m.group(5))+1, int(m.group(6))):
                yield m.group(1) + str(i) + z
    elif m.group(7):
        for z in suffixes:
            for s in m.group(7).split('|'):
                yield m.group(1) + s + z
    else:
        yield trend

rawDescription: Python complicated regex string expansion


rawDescription: Comparison of two string arrays in NumPy


rawDescription: Python - Pandas: combination of unique rows and their statistics


code:
import sys
sys.path.append("<path>")

rawDescription: How to import module installed in home directory?

description: Import module installed in home directory


code:
from itertools import izip_longest
a = [[1,2,3,4], [5,6], [7,8,9]]
[i for sublist in izip_longest(*a) for i in sublist if i is not None]
# [1, 5, 7, 2, 6, 8, 3, 9, 4]

rawDescription: Python Iterate through list of list to make a new list in index sequence


code:
import itertools
a = ['a', 'b', 'c']
list(itertools.permutations(a))

rawDescription: Get all combinations from list with and without repeat


code: detectedChanges = {table: [field for field in tableDict[table] if field not in fieldBlackList] for table in modifiedTableDict if table not in tableBlackList if set(tableDict[table])-set(fieldBlackList)}

rawDescription: How can I check if a list in a list comprehension inside a dictionary comprehension is empty?

description: Check if a list in a list comprehension inside a dictionary comprehension is empty


code:
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk

root = Tk()

make_frame = LabelFrame(root, text="Sample Image", width=100, height=100)
make_frame.pack()

stim_filename = "image.png"

# create the PIL image object:
PIL_image = Image.open(stim_filename)

width = 100
height = 100

# You may prefer to use Image.thumbnail instead
# Set use_resize to False to use Image.thumbnail
use_resize = True

if use_resize:
    # Image.resize returns a new PIL.Image of the specified size
    PIL_image_small = PIL_image.resize((width,height), Image.ANTIALIAS)
else:
    # Image.thumbnail converts the image to a thumbnail, in place
    PIL_image_small = PIL_image
    PIL_image_small.thumbnail((width,height), Image.ANTIALIAS)

# now create the ImageTk PhotoImage:
img = ImageTk.PhotoImage(PIL_image_small)
in_frame = Label(make_frame, image = img)
in_frame.pack()

root.mainloop()

rawDescription: How do I place an image (.png) within a `LabelFrame`, and resize it, in Tkinter?

description: Place an image (.png) within a `LabelFrame`, and resize it, in Tkinter


code:
v = ord(data[17])
major = (v & 0xF0) >> 4
minor = (v & 0x0F)

rawDescription: what is the correct way to process 4 bits inside an octet in python

description: What is the correct way to process 4 bits inside an octet in python


code:
class WorkPackage(Base):
    __tablename__ = 'work_package'
    int_id = Column(Integer, primary_key=True)
    wp_prefix = Column(Unicode, default=u'DIVISION_ABC_REQUEST_', primary_key=True)
    data = Column(Unicode)

    @hybrid_property
    def wp_id(self):
        return self.wp_prefix + str(self.int_id)

    @wp_id.expression
    def wp_id(cls):
        return cls.wp_prefix.concat(cls.int_id)

rawDescription: Generating string primary keys with sequence in SQLAlchemy


code: ax.stackplot(x, y, color='b', colors=('red',))

rawDescription: Setting color of stack plot line not working


code:
items = []
for count in range ( 1, runNum + 1):
        print ("Please enter item #", count, "")
        item = input()
        items.append(item)

for item in items:
        print ("<li>",item,"</li>")

rawDescription: How do I store information collected from a for loop and assign it to a variable with the count iteration?

description: Store information collected from a for loop and assign it to a variable with the count iteration


code: [(a - times[0]).total_seconds() for a in times]

rawDescription: Better way to extract duration list from datetime list


code:
l = []
with open('config.txt') as cfg:
    for line in cfg:
        l.extend(line.split())
a, b = zip(*(s.split("~") for s in l))
for w in range(len(a)):
    with open('httpd.conf') as apache:
        for lines in apache:
            if (a[w]) in lines and not lines.startswith("#") and not lines.__contains__("#"):
                if (b[w]) in lines:
                    print(lines.rstrip())

rawDescription: How to check configurations parameters in httpd.conf

description: Check configurations parameters in httpd.conf


rawDescription: How could I print out the nth letter of the alphabet in Python?


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

plt.figure(figsize=[6,6])
x = np.arange(0,100,0.00001)
y = x*np.sin(2*pi*x)
plt.plot(y)
plt.axis('off')
plt.gca().set_position([0, 0, 1, 1])
plt.savefig("test.svg")

rawDescription: How can I get the output of a matplotlib plot as an SVG?

description: Get the output of a matplotlib plot as an SVG


code:
params = {}
for counter, r in enumerate(records):
    a_param = "a%s" % counter
    params[a_param] = r['a']
    b_param = "b%s" % counter
    params[b_param] = r['b']
    pair_text = "(:%s,:%s)" % (a_param, b_param)
    enum_pairs.append(pair_text)
multicol_in_enumeration = ','.join(enum_pairs)
multicol_in_clause = text(
    " (a,b) in (" + multicol_in_enumeration + ")")
q = session.query(Table.id, Table.a,
                            Table.b).filter(multicol_in_clause).params(params)

rawDescription: How to write multi column in clause with sqlalchemy

description: Write multi column in clause with sqlalchemy


rawDescription: How to Compare Frozenset with list of tuple in Python


code:
# With positional arguments
args = (1, 2, 3)
f_1(*args)

# With keyword arguments
kwargs = {'first': 1, 'second': 2}
f_2(**kwargs)

rawDescription: Is there such thing as "apply" in python?


code: np.char.mod("%4.2f", flt_arr)

rawDescription: How to save a mix of strings and numbers into text files in specified format using numpy.savetxt?

description: Save a mix of strings and numbers into text files in specified format using numpy.savetxt


code: pd.pivot_table(df, index='A', columns='gender', values='B').plot(kind='bar')

rawDescription: Pandas: produce a multiple bar plot based on conditional over column


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

class MainWindow(QWidget):
    def __init__(self, parent=None, *args):
        super(MainWindow, self).__init__(parent)
        data = [['00','01','02'],
         ['10','11','12'],
         ['20','21','22']]
        clipTableWidget = QTableWidget()

        self.model = QStandardItemModel(self)
        clipTableView = QTableView()
        count1=0
        for row in data:
            count2 = 0
            for column in row:
                if count2 == 0:
                    item = QStandardItem(column)
                    item.setCheckable(True)
                    item.setCheckState(False)
                    item.setFlags(Qt.ItemIsUserCheckable| Qt.ItemIsEnabled)
                    self.model.setItem(count1,count2,item)
                    count2+=1
                else:
                    item = QStandardItem(column)
                    self.model.setItem(count1,count2,item)
                    count2+=1
            count1+=1

        clipTableView.setModel(self.model)
        layout = QVBoxLayout()
        layout.addWidget(clipTableView)
        self.setLayout(layout)

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

if __name__ == "__main__":
    main()

rawDescription: Make checkbox by QAbstractTableModel

description: Make checkbox by QAbstractTableModel


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver=webdriver.Firefox()
list = driver.find_elements_by_tag_name('input')
for input_field in list:
    input_field.send_keys("enter some text here")
    input_field.send_keys(Keys.TAB)

rawDescription: how to jump through form elements? webdriver

description: Jump through form elements? webdriver


code:
mp3 = MP3(fname)
mp3.delete()
mp3.save()

rawDescription: How can I use mutagen.py to clear mp3 metadata?

description: Use mutagen.py to clear mp3 metadata


code:
from collections import OrderedDict
my_list = [[1, 2, 3, 1], [2, 3, 1, 2], [3, 2, 1, 3]]

seen_combos = OrderedDict()
for sublist in my_list:
    unique_elements = frozenset(sublist)
    if unique_elements not in seen_combos:
        seen_combos[unique_elements] = sublist
my_list = seen_combos.values()

rawDescription: Removing duplicates and preserving order when elements inside the list is list itself


code:
import requests
from bs4 import BeautifulSoup

user='xyzmohsin'
passwd='abcpasswd'

s=requests.Session()
headers={"User-Agent":"Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36"}
s.headers.update(headers)
r=s.get("https://secure.worldpay.com/sso/public/auth/login.html?serviceIdentifier=merchantadmin")
soup=BeautifulSoup(r.content)
jlbz=soup.find("input",{"name":"jlbz"})['value']
maiversion=soup.find(id="maiversion")['value']
formDisplayTime=soup.find("input",{"name":"formDisplayTime"})['value']
formSubmitHash=soup.find("input",{"name":"formSubmitHash"})['value']

data={"jlbz":jlbz,
"username":user,
"password":passwd,
"maiversion":maiversion,
"formDisplayTime":formDisplayTime,
"formSubmitHash":formSubmitHash}

headers={"Content-Type":"application/x-www-form-urlencoded",
"Host":"secure.worldpay.com",
"Origin":"https://secure.worldpay.com",
"Referer":"https://secure.worldpay.com/sso/public/auth/login.html?serviceIdentifier=merchantadmin"}

login_url="https://secure.worldpay.com/sso/public/auth/j_security_check"

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

rawDescription: Python3 - how to login to web form with hidden values?


code:
percent_quota=0  #starting value
for i in range(limit_min,limit_max+1):  #we make sure all lengths are covered
    percent_quota+=(10**i)-1  #we subtract 1 because for length of 2, max is 99

rawDescription: What is the best way to calculate percentage of an iterating operation?


code:
Meta = type('Meta', (), {
    'model': ExampleModel,
})

ExampleForm = type('ExampleForm', (), {
    'Meta': Meta,
})

rawDescription: Create class having django's inner Meta class using type() method


code:
class ProfileSpider( scrapy.Spider ):
    name = 'myspider'

    def start_requests( self ):
        while( True ):
            yield self.make_requests_from_url(
                self._pop_queue()
            )

    def _pop_queue( self ):
        while( True ):
            yield self.queue.read()

rawDescription: How can I make start_url in scrapy to consume from a message queue?

description: Make start_url in scrapy to consume from a message queue


code:
def _foo():
    """You can call this function from your own code, but you
    really shouldn't because I might change or remove it at
    any time without warning"""
    modify_guts_of_module()

def __bar():
    """Hands off. This is for the module implementation, not for
    public consumption. You can't even see this unless you go out
    of your way, and why would you do that?"""
    release_the_hounds()

rawDescription: how to share my python code to other?

description: Share my python code to other


rawDescription: Regex uniform pattern requirements

description: Regex uniform pattern requirements


code: new_queryset = one_queryset | second_queryset

rawDescription: Order a queryset in django by an annotated field and append the rest of the objects that did not fit the criteria


code:
import re
s = '#ff0000 is the hexcode for the color red'
m = re.match(r'(?P<hexcode>.+) is the hexcode for the color (?P<color>.+)', s)
m.groupdict()

rawDescription: Python: Reggular Expressions filtering for Self Learning program


code:
def CiteParser():
    with open("/tmp/content.txt") as myfile:
        soup = BeautifulSoup(myfile)
        result = []
        for cite in soup.find_all('cite'):
            result.append(cite.string)
        return '\n'.join(result)

rawDescription: calling citeparser function in python

description: Calling citeparser function in python


code:
with open('dwn.txt') as f:
    for i in xrange(6):
        f.next()
    for line in f:
        process(line)

rawDescription: Using python, how to read a file starting at the seventh line ?


rawDescription: using a variable whose value is an integer in a regular expression (python)

description: Using a variable whose value is an integer in a regular expression (python)


code:
import xml.dom.minidom
n = xml.dom.minidom.parseString('<n a="1" b="2" />').documentElement
attrs = dict(n.attributes.items())
assert attrs == {'a': '1', 'b': '2'}

rawDescription: Minidom:Get all the attributes of a selected node?


code:
import sublime, sublime_plugin

class Example(sublime_plugin.WindowCommand):
    def run(self):
        """Divide layout"""
        self.window.set_layout({
            "cols": [0.0, 0.4, 1.0],
            "rows": [0.0, 0.6, 1.0],
            "cells": [[0, 0, 2, 1], [0, 1, 1, 2], [1, 1, 2, 2]]
            })

        """Open image in group 1"""
        self.window.focus_group(1)
        self.window.open_file('/home/sergio/Escritorio/images/logo.png')

        """Show output/info in group 2"""
        self.window.focus_group(2)
        v = self.window.new_file()
        self.window.run_command('insert', {'characters': ("Plugin output:\n"
            "-Stackoverflow\n"
            "-is\n"
            "-very\n"
            "-cool\n"
            "-the\n"
            "-best\n"
            "-websites\n"
            "-of\n"
            "-the\n"
            "-world\n")})
        v.show_at_center(0)

        self.window.focus_group(0)

rawDescription: Is it possible to show image in Sublime Text 3 output panel?


code:
def views(self,cr,uid,ids,context):
     for id in ids:
         deg_obj=self.pool.get('deg.form').browse(cr,uid,id)
         my_id=int(deg_obj.my_products)
     ss= int(deg_obj.categ_temp2)
     domain = [('categ_id','=',ss)]
     return {
         'type': 'ir.actions.act_window',
         'name': _('Product'),
         'res_model': 'product.product',
         'view_type': 'form',
         'view_mode': 'tree,form',
         'target': 'current',
         'domain': domain,
               }

rawDescription: Tree view to be called through button in OpenERP-7


code:
dico_list=[{"item1": {"item2": "300"}}, {"item1": {"item3": {"item4": "400"}}}, {"item1": {"item3": {"item6": "16"}}}, {"item1": {"item7": "aaa"}}, {"item1": {"item8": "bbb"}}, {"item1": {"item9": {"item10" : "2.2"}}}, {"item1": {"item9": {"item11" : "xxx"}}}]

def merge(merge_dico,dico_list):
    for dico in dico_list:
        for key,value in dico.items():
            if type(value)==type(dict()):
                merge_dico.setdefault(key,dict())
                merge(merge_dico[key],[value])
            else:
                merge_dico[key]=value
    return merge_dico

print(merge(dict(),dico_list))
#{'item1': {'item7': 'aaa', 'item9': {'item11': 'xxx', 'item10': '2.2'}, 'item8': 'bbb', 'item3': {'item4': '400', 'item6': '16'}, 'item2': '300'}}

rawDescription: Merging multiple dictionaries in python

description: Merging multiple dictionaries in python


code:
global tree #just declare the tree globally -- this is just shorthand
def findMessage(t, s):
    if (s == ""):
        return ""
    if(isinstance(t, str)):
        return t + findMessage(tree[int(s[0])], s[1:])
    return findMessage(t[int(s[0])], s[1:])

rawDescription: Attribute binary code as the path from binary tree in Python


code:
import numpy as np

length = 20000
limit = int(0.75*length)
keep = np.random.permutation(length)[:limit]

newArray = oldArray[keep]

rawDescription: How to delete the same random items from multiple arrays of equal length?

description: Delete the same random items from multiple arrays of equal length


code: stuff = 'GET /\r\n\r\n'

rawDescription: Python problem with sockets

description: Python problem with sockets


code:
from lxml import etree
data = etree.parse(fname)
result = [node.text.strip()
    for node in data.xpath("//AssetType[@longname='characters']/type")]

rawDescription: how to get specific nodes in xml file with python

description: Get specific nodes in xml file with python


code:
@app.template_filter('escape_custom')
def escape_custom(string):
    string = str(jinja2.escape(string))
    return jinja2.Markup(string.replace('\n', '<br/>\n'))

rawDescription: Escaping string and then adding html tags in jinja


code:
import re

replacements = []
def repl(m):
    replacements.append(m.group(0))  # Add found match to the list
    return "";                       # We remove the match found

title_old = "FOO BAR PART 1"
print(re.sub(r"PART [0-9]*$", repl, title_old))
print(replacements)

rawDescription: Find and sub in one line using Python re


code:
import json
with open('file.json') as infile:
  o = json.load(infile)
  chunkSize = 1000
  for i in xrange(0, len(o), chunkSize):
    with open('file_' + str(i//chunkSize) + '.json', 'w') as outfile:
      json.dump(o[i:i+chunkSize], outfile)

rawDescription: What's the best way to load large JSON lists in Python?


code:
result = re.findall('name=(.*?)Smith', s)
result

rawDescription: How do I extract strings between the substrings at their first instance (readable string at all times)

description: Extract strings between the substrings at their first instance (readable string at all times)


rawDescription: What's the best python idiom for grouping a list of items into groups of a specific max size?


code:
chart1.add_series({
    'name':       'My Chart',
    'categories': ['Sheet1', 1, 0, total -1, 0],
    'values':     ['Sheet1', 1, 1, total -1, 1],
    'line':       {'color': 'purple'},
})

rawDescription: Using Python and xlsxwriter to concatenate cell references with cell count


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

plt.plot(np.linspace(-3.0, 3.0, 10), np.random.random(10))
plt.plot(np.linspace(0.0, 7.0, 50), np.random.random(50))

plt.xticks([-4, -2, 0, 2, 4, 6, 8], ['0', '10', '20', '30', '40', '50'])

rawDescription: Change axes after plot

description: Change axes after plot


code:
import SimpleXMLRPCServer

from google.appengine.ext import webapp
from google.appengine.ext import db

class WebService(webapp.RequestHandler):
    def login(self, username, password):

        calls = db.GqlQuery("SELECT * from User ORDER BY username DESC LIMIT 10")

        for call in calls:
            if calls.username == username and calls.password == password:
                return True
        return False

    def register(self, username, password):

        db.GqlQuery("INSERT into User (username, password) value(%s, %s)"%(username, password))
        return True

    server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost',8080))
    server.register_function(login)
    server.register_function(register)
    server.serve_forever()

rawDescription: Can't find the function name

description: Can't find the function name


code:
def continue_prompt():
    while True:  # Continue prompting until valid answer.
        answer = input("Do you want to continue? ")
        if answer.lower() in ['y', 'yes']:
            cont = True
            break
        elif answer.lower() in ['n', 'no']:
            cont = False
            break
        else:
            print("Please answer yes or no.  ", end="")
    return cont
answer = continue_prompt()
assert answer == True
answer = continue_prompt()
assert answer == True
answer = continue_prompt()
assert answer == False
answer = continue_prompt()
assert answer == False

rawDescription: Python regex - Determine answer based on input


code:
import os
dirpath='/path/to/run/'
dirs = [s for s in os.listdir(dirpath) if os.path.isdir(os.path.join(dirpath, s))]
dirs.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)), reverse=True)

for dir_idx in range(0,len(dirs)/2):
    do_something(dirs[dir_idx])

rawDescription: Get a sorted list of folders based on modification date


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

N=5
province=['Ontario','Quebec','BritishColumbia','Manitoba','NovaScoti']
size = [908.607,1356.547,922.509,552.329,651.036]
population = [12851821,7903001,4400057,1208268,4160000]
injuries = [625,752,629,1255,630]

# Choose some random colors
colors=cm.rainbow(np.random.rand(N))

# Use those colors as the color argument
plt.scatter(size,population,s=injuries,color=colors)
for i in range(N):
    plt.annotate(province[i],xy=(size[i],population[i]))
plt.xlabel('Size(*1000km2)')
plt.ylabel('Population(ten million)')

# Move title up with the "y" option
plt.title('The Car Accidents Injuries Rate in 5 Canada Provinces',y=1.05)
plt.show()

rawDescription: Bubble Chart Title and Colors

description: Bubble Chart Title and Colors


code:
list_of_ids = []
list_of_ids.append(my_id)
...
queryset = MyModel.objects.filter(id__in=list_of_ids)

rawDescription: How to add an model instance to a django queryset?

description: Add an model instance to a django queryset


code:
from ast import literal_eval
test = repr({"ham": True, 42: "spam", "foo": "bar"})
test
literal_eval(test)

rawDescription: how to safely eval an urlencode-ed dictionary in Python?

description: Safely eval an urlencode-ed dictionary in Python


code:
class A(models.Model):
    name = models.CharField(...)
    position = models.PositiveSmallIntegerField(...)
    ...

class B(models.Model):
    a_obj = models.ForeignKey(A, verbose_name="A instance that related to B instance")

    @property
    def myfield(self):
        return self.a_obj.position
    ...

rawDescription: Django 1.4.5 . Field relation

description: Django 1.4.5 . Field relation


code:
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
ffmpeg_extract_subclip("video1.mp4", t1, t2, targetname="test.mp4")

rawDescription: Cutting out a portion of video - python

description: Cutting out a portion of video - python


code:
ind=tuple(2,2)
x[ind]

rawDescription: Get a value in a numpy array from a index in a variable


code:
myString = "aaaabbbbbbcccddddd"
[''.join(list(g)) for i,g in itertools.groupby(myString)]

rawDescription: Python - Split sorted string of characters when character is different than previous character


code:
import numpy as np
import pylab as pl
x = np.linspace(0, 2*np.pi, 100)
pl.plot(x, np.sin(x), "-x", label=u"sin")
pl.plot(x, np.random.standard_normal(len(x)), 'o', label=u"rand")
leg = pl.legend(numpoints=3)
l = leg.legendHandles[1]
l._legmarker.set_xdata(l._legmarker.get_xdata()[1:2])
l._legmarker.set_ydata(l._legmarker.get_ydata()[1:2])
##or
#l._legmarker.set_markevery(3)
pl.show()

rawDescription: Matplotlib legend: how to assign multiple scatterpoints values


code:
import numpy as NP
from matplotlib import pyplot as PLT
import matplotlib.patches as patches

N = 10
A = NP.random.randint(10, 100, N * N).reshape(N, N)
mask = NP.tri(A.shape[0], k=-1)
mask = NP.zeros_like(A)
mask[NP.arange(N), NP.arange(N)] = 1
A = NP.ma.array(A, mask=mask)  # mask out the lower triangle
fig, ax = PLT.subplots()

cmap = PLT.get_cmap('jet', 10)  # jet doesn't have white color
cmap.set_bad('w')  # default value is 'k'
ax.imshow(A, interpolation="nearest", cmap=cmap, extent=[0, N, 0, N])

line = ([(0, N - 1), (0, 0), (N - 1, 0)] +
        [(N - 1 - i - j, i + 1) for i in range(N - 1) for j in (0, 1)])
lines = [line, [(N - x, N - y) for x, y in line]]
for line in lines:
    path = patches.Polygon(line, facecolor='none', edgecolor='black',
                           linewidth=5, closed=True, joinstyle='round')
    ax.add_patch(path)
ax.set_xlabel("Correlation Data 1")
ax.xaxis.set_label_position('top')
ax.set_ylabel("Correlation Data 2")
ax.set_yticks([])
ax.set_xticks([])
margin = 0.09
ax.set_xlim(-margin, N + margin)
ax.set_ylim(-margin, N + margin)
ax.set_frame_on(False)
PLT.show()

rawDescription: Border around a upper/lower triangle of imshow


code:
def outer(f):          # any name: function, class, any callable
    return f()         # class will be instantiated within the scope of the function

rawDescription: How can I pass a function's name to a function, and then call it?

description: Pass a function's name to a function, and then call it


code:
from w3lib.html import remove_tags
my_text
remove_tags(my_text)

rawDescription: Removing HTML tags without /text().extract()


code:
hour = pd.DatetimeIndex(df["Date"]).hour
df[(hour >= 12) & (hour <= 16)]

rawDescription: Get dataframe subset by attribute's property in sliced way


rawDescription: Mysql alchemy filter

description: Mysql alchemy filter


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

data = {'Alex': 20, 'Jason': 35}
x = np.arange(len(data))
y = data.values()

plt.bar(x, y)
plt.xticks(x + 0.5, data.keys(), rotation='vertical')
plt.show()

rawDescription: matplotlib plotting dictionary keys as column labels

description: Matplotlib plotting dictionary keys as column labels


rawDescription: get average of difference of datetime fields in django

description: Get average of difference of datetime fields in django


code:
re.sub(r'''(?x)
     .*(
     Chairman | Managing[]Director     # or
     ).*
     ''','Executive Director', row['capacity'])

rawDescription: Cleaning up nested re.sub statements

description: Cleaning up nested re.sub statements


code:
message = ''
if 'form.submitted' in request.params:#form.submitted being the name of the submit of the form
    #check if email exists
    if exists:
         message = 'email already registered'
    else:
         message = 'success'
return dict(message = message)

rawDescription: How can I validate unique form elements in jinja2/pyramid/sqlalchemy?

description: Validate unique form elements in jinja2/pyramid/sqlalchemy


code:
from cx_Freeze import Executable
from cx_Freeze import setup as cx_setup
from distutils.core import setup
from Cython.Build import cythonize

setup(options={'build_ext': {'compiler': 'mingw32'}},
      ext_modules=cythonize("fx.pyx"))

cx_setup(name='myproject',
      version='0.0',
      description='',
      options={"build_exe": {"packages":["pygame","fx"]}},
      executables=[Executable('main.py',targetName="myproject.exe",base = "Win32GUI")],
      requires=['pygcurse','pyperclip','rsa','dill','numpy']
      )

rawDescription: cx_freeze fails to include Cython .pyx module

description: Cx_freeze fails to include Cython .pyx module


code:
import glob
import os.path
import shutil
files_dirs = glob.glob(r'C:\Users\vanstrie\Desktop\ntnu\SCHEMA\2012\07_paper\results\*')
for d in files_dirs:
    head,tail = os.path.split(d)
    try:
        if (0 < int(tail) < 41) and (len(tail) == 3):  #don't want to delete `\results\3\onsets` I guess...
           print("about to delete:",d)
           shutil.rmtree(os.path.join(d,'onsets'),ignore_errors=True)
    except ValueError:  #apparently we got a non-integer.  Leave that directory.
        pass

rawDescription: Python parse dirs, remove subdirectory tree


code:
import matplotlib.pyplot as plt

s1 = [2,3,2]
s2 = [3,2,9]
s3 = [2,9,6]
hws = [1,2,3]

plt.plot(hws,s1)
plt.plot(hws,s2)
plt.plot(hws,s3)

rawDescription: Using matplotlib to graph rows by column of a csv file


code:
import pytz, datetime
pytz.country_timezones['de']
matching_tzs = [t for t in pytz.country_timezones['de'] if pytz.timezone(t)._utcoffset.total_seconds() == 3600]
datetime.datetime.now(tz=pytz.timezone(matching_tzs[0]))

rawDescription: how to findout local time using utcoffset and countryname in python

description: Findout local time using utcoffset and countryname in python


code:
listA = [np.random.rand() for _ in range(3)]
scale = sum(listA)
listA = [i / scale for i in listA]

rawDescription: Generate n random variables whose sum will be 1


code:
db.exam.aggregate([

     # Unwind to de-normalize
     { "$unwind": "$result" },

     # Group back to the document and extract each score
     { "$group": {
         "_id": "$_id",
         "result": { "$push": "$result" },
         "useruid": { "$first": "$useruid" },
         "exam_code": { "$first": "$exam_code" },
         "ess_time": { "$first": "$ess_time" },
         "Total": {
             "$max": {
                 "$cond": [
                     { "$eq": [ "$result.subject", "Total" ] },
                     "$result.score",
                     0
                 ]
             }
         },
         "Physics": {
             "$max": {
                 "$cond": [
                     { "$eq": [ "$result.subject", "Physics" ] },
                     "$result.score",
                     0
                 ]
             }
         },
         "Mathematics": {
             "$max": {
                 "$cond": [
                     { "$eq": [ "$result.subject", "Mathematics" ] },
                     "$result.score",
                     0
                 ]
             }
         },
         "Chemistry": {
             "$max": {
                 "$cond": [
                     { "$eq": [ "$result.subject", "Chemistry" ] },
                     "$result.score",
                     0
                 ]
             }
         },
         "Biology": {
             "$max": {
                 "$cond": [
                     { "$eq": [ "$result.subject", "Biology" ] },
                     "$result.score",
                     0
                 ]
             }
         }
     }},

     # Sort on those scores
     { "$sort": {
         "Total": -1,
         "Physics": -1,
         "Mathematics": -1,
         "Chemistry": -1,
         "Biology": -1
     }},

     # Project final wanted fields
     { "$project": {
         "result": 1,
         "useruid": 1,
         "exam_code": 1,
         "ess_time": 1
     }}
])

rawDescription: How do I sort a collection based on values in an array

description: Sort a collection based on values in an array


code:
import sys
sys.modules.clear()

rawDescription: Jython import or reload dynamically

description: Jython import or reload dynamically


code:
import numpy as np
from scipy.interpolate import Rbf
import matplotlib.pyplot as plt
# Make data repeatable
np.random.seed(1981)

# Generate some random wells with random head (water table) observations
x, y, z = np.random.random((3, 10))

# Interpolate these onto a regular grid
xi, yi = np.mgrid[0:1:100j, 0:1:100j]
func = Rbf(x, y, z, function='linear')
zi = func(xi, yi)

# -- Plot --------------------------
fig, ax = plt.subplots()

# Plot flowlines
dy, dx = np.gradient(-zi.T) # Flow goes down gradient (thus -zi)
ax.streamplot(xi[:,0], yi[0,:], dx, dy, color='0.8', density=2)

# Contour gridded head observations
contours = ax.contour(xi, yi, zi, linewidths=2)
ax.clabel(contours)

# Plot well locations
ax.plot(x, y, 'ko')

plt.show()

rawDescription: Adding water flow arrows to Matplotlib Contour Plot


code:
last_time = 0 # starting time of data, 0 is here as example
total_time = 0 # 0 seconds

for time, switch, state in state_switches:
    if a_on and b_on and c_on:
        total_time += time - last_time

    if switch == "A":
        a_on = state
    if switch == "B":
        b_on = state
    if switch == "C":
        c_on = state

    last_time = time

rawDescription: calculate amount of time intersection when all sequences fullfill certain criteria?

description: Calculate amount of time intersection when all sequences fullfill certain criteria


code:
@ndb.tasklet
def callback(task):
  project= yield tast.project.get_async()
  task.fetched_project = project
  raise ndb.Return(task)

#fetch the tasks, you could do paging here.
tasks = Task.query().fetch_page(20)

#map projects onto tasks
results = yield map(callback, tasks)

#filter tasks based on project (fetched_project now exists on task) status:
tasks = [task for task in results if task.fetched_project.status == "In-Progress"]

rawDescription: NDB query based on Model's KeyProperty instance value


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

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

rawDescription: Save a subplot in matplotlib

description: Save a subplot in matplotlib


code:
import numpy_indexed as npi
idx = np.indices(numpy3D.shape).reshape(numpy3D.ndim, numpy3D.size)
groups = npi.group_by(numpy3D, axis=None)
label, min = groups.min(idx, axis=1)
label, max = groups.max(idx, axis=1)

rawDescription: Detect extreme (most distant) points in numpy-3D array


code:
import urllib2
var = urllib2.urlopen('http://www.stackoverflow.com/')
var.geturl()

rawDescription: How can I determine the final URL after redirection using python / urllib2?

description: Determine the final URL after redirection using python / urllib2


code:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

binary = FirefoxBinary('path/to/binary')
driver = webdriver.Firefox(firefox_binary=binary)

rawDescription: selenium opening the wrong Firefox-based browser

description: Selenium opening the wrong Firefox-based browser


code:
from werkzeug import Local, LocalManager
local = Local()
local_manager = LocalManager([local])

from jinja2 import Environment, FileSystemLoader

# Create a global dict using the local's proxy to the request attribute
global_dict = {'request': local('request')}
jinja2_env = Environment(loader=FileSystemLoader('/'))
jinja2_env.globals.update(global_dict)

def application(environ, start_response):
    """A WSGI Application"""
    # later, bind the actual attribute to the local object
    local.request = request = Request(environ)

    # continue to view handling code
    # ...

application = local_manager.make_middleware(application)

rawDescription: Context processor using Werkzeug and Jinja2


rawDescription: How can you use os.chdir to go to a path minus the last step of it?

description: Use os.chdir to go to a path minus the last step of it


code:
import sys
inputLines = list(sys.stdin)

rawDescription: What is the most Pythonic way of handling standard input?


code:
import subprocess
import urllib2
import sys
source = urllib2.urlopen('http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png')
p = subprocess.Popen(['convert','png:-', 'jpg:-'], stdin=source, stdout=subprocess.PIPE)
p.communicate()[0] # this is your converted image

rawDescription: Using ImageMagick to generate thumbnails for images stored in Amazon S3


code:
def equal3(a, b, c):
  return (c <= a == b) or (b <= a == c) or (a <= b == c)

rawDescription: Python- Finding out if 2 values are equal while one is less than or equal to the other two


code:
field_queryset = Test.objects.all()
for form in formset:
        form.fields['test_field'].queryset = field_queryset

rawDescription: Django inline formsets and choicefields generate too many db queries


code:
from wordsegment import segment
segment("Hellothisisexample")

rawDescription: Split words from not formatted strings

description: Split words from not formatted strings


code:
from django.shortcuts import render_to_response
from django.core import serializers

def my_view(request) :
    json_data = serializers.serialize('json', my_django_object)
    render_to_response('my_template.html', {'json_data' : json_data})

rawDescription: Passing an array in Python to Django template


code:
from itertools import combinations
from subprocess import Popen, PIPE
for pair in combinations(all_ssu, 2):
    out = Popen(
        ['blastn',
        '-query', 'tmp/{0}.fna'.format(pair[0]),
        '-subject', 'tmp/{0}.fna'.format(pair[1]),
        '-outfmt', '6 qseqid sseqid pident'
        ],
        stdout=PIPE
    ).communicate[0]
    print(out)

rawDescription: Capturing output from Popen

description: Capturing output from Popen


code:
l = len(df.columns)
results = np.zeros((l,l))
mask = pd.isnull(df)
for i, ac in enumerate(df):
    for j, bc in enumerate(df):
           results[j,i] = (mask[i] & mask[j]).sum()
results = DataFrame(results,index=df.columns,columns=df.columns)

rawDescription: Fast way to see common observation counts for Python Pandas correlation matrix entries


code:
def sum_elements(l):
    s = l[0]
    for element in l[1:]:
        s += element
    return s

sum_elements([1,2,3])
sum_elements(['hello', 'world'])

rawDescription: In-built sum function in python

description: In-built sum function in python


code:
with open('path/to/input') as infile:
    for line in infile:
        if line.startswith("@"):
            line = line.strip()
            print(line)
            print(line.rsplit("#", 1)[1])
        elif any(line.startswith(e) for e in "#+"):
            print(line.strip())

rawDescription: split a line and print in second line

description: Split a line and print in second line


code:
import win32gui
hwnd = win32gui.GetForegroundWindow()
win32gui.MoveWindow(hwnd, 0, 0, 500, 500, True)

rawDescription: How can I get the window focused on Windows and re-size it?

description: Get the window focused on Windows and re-size it


code: df.groupby(lambda L: (L.year, L.month))

rawDescription: Simplify a date in a Dataframe

description: Simplify a date in a Dataframe


code:
#!/bin/sh
cdsitepackages
ln -s /path/to/system/site-packages/package-name
cdvirtualenv

rawDescription: Including global package into a virtualenv that has been created with --no-site-packages


rawDescription: Flask pass unknown Url Arguments in url_for and redirects


code: stockdata["Close"] == pd.rolling_max(stockdata["Close"], 5)

rawDescription: Determine if closing price is a 5 minute high in pandas dataframe


code: xml = xml.split('</response>', 1)[0] + '</response>'

rawDescription: xml split because of junk python

description: Xml split because of junk python


code: os.path.commonprefix(['abcde', 'abcdf', 'abcef', 'abcnn'])

rawDescription: greatest common divisor for strings in python

description: Greatest common divisor for strings in python


code:
class ExampleModel(ndb.Model):
    DEFAULT_CREATED = datetime(2000, 1, 1)
    property1 = ndb.StringProperty()
    property2 = ndb.StringProperty()
    created = ndb.DateTimeProperty(auto_now_add=True)

    def created2(self):
        if self.created == DEFAULT_CREATED:
            return None
        else:
            return self.created

    def created2(self, value):
        if value is None:
            self.created = DEFAULT_CREATED
        else:
            self.value = value

rawDescription: Including None values in ordered NDB query


code:
for row in reader:
    arg = {
        'name': row[0].strip(),
        'description': row[1].strip(),
        'on_hand': int(float(row[2].strip())) if row[2].strip() else "",
        'on_order': int(float(row[3].strip())) if row[3].strip() else ""
    }

rawDescription: How to check for empty cells in csv before converting to int (Python script)?

description: Check for empty cells in csv before converting to int (Python script)


code:
first, middle, last, dob = 'john..doe.1985'.split('.')
first
middle
last
dob

rawDescription: Splitting string into strings

description: Splitting string into strings


code: sns.lmplot("x", "y", data=df, hue='dataset', fit_reg=False)

rawDescription: Scatterplot without linear fit in seaborn


rawDescription: Creating new numpy matrix from list of rows of existing matrix


code:
try:
    import json
except ImportError:
    import simplejson as json

rawDescription: JSON module for python 2.4?

description: JSON module for python 2.4


code:
Aflag = "<<<A goes here>>>"
Bflag = "<<<B goes here>>>"
Aidx = C.find(Aflag)
Bidx = C.find(Bflag, Aidx+len(Aflag)+1)

newC = "".join((C[:Aidx], A, C[Aidx+len(Aflag)+1:Bidx], B, C[Bidx+len(Bflag)+1:]))

rawDescription: Python - multiple inserts of large text

description: Python - multiple inserts of large text


code:
class ItemForm(Form):
    openid = StringField('openid', validators=[])
    remember_me = BooleanField('remember_me', default=False)

class PurchaseForm(Form):
    item_class = ItemForm
    transaction_items = None

    def __init__(self, item_class, *args, **kwargs):
        super(PurchaseForm, self).__init__(*args, **kwargs)
        self.item_class = item_class
        self.transaction_items = FieldList(FormField(self.item_class),
                                           label='items',
                                           min_entries=1)

rawDescription: Can I add field in __init__ wtforms

description: Add field in __init__ wtforms


code:
out = open(outfile, "w")
for f in in_files:
    ...
    output_string = "{},{},{}\n".format(f, HOMO, LUMO)
    out.write(output_string)

rawDescription: Python extracting first matching instance from multiple files


code:
from django import forms

class StudentForm(ModelForm):
    class Meta:
        model = Student

    subject = forms.CharField(label='New label')

rawDescription: django Model Forms customizing fields

description: Django Model Forms customizing fields


rawDescription: Python regex: Remove a pattern at the end of string


rawDescription: Slicing lists and strings to negative zero


code:
# (make a LEVELS dict out of all the logging levels first)
def indent(self, step = 1):
        "Change the current indent level by the step (use negative to decrease)"
        self._indent_level += step
        if self._indent_level < 0:
            self._indent_level = 0
        self._indent_str = self._indent_str_base * self._indent_level
        for lvl in LEVELS:
            level_name = self._indent_str + LEVELS[lvl]
            logging.addLevelName(lvl, level_name)

rawDescription: Using python logging package, how to insert additional formatting into multiple logger handlers that have their own formatters?


code:
plot_ax1.axhline(y=0, ls='-', color='0.5', zorder=3)
plot_ax1.plot(self.diff_3[:,0],self.diff_3[:,1], zorder=4)
plot_ax1.grid(b=True, which='major', axis='both', c='0.75', ls='-', linewidth=1)

rawDescription: draw order of grid lines and data in pyplot

description: Draw order of grid lines and data in pyplot


code:
import re

def get_values_from_file(filename):
    f = open(filename)
    winpat = re.compile("([\d\.]+)\%")

    values = []
    for line in f.readlines():
        if line.find("Matches") >=0:
            percn = float(winpat.findall(line)[0])
            values.append(percn)

    return values

all_values = []
for filename in ["out0.txt", "out1.txt"]:
    values = get_values_from_file(filename)
    all_values += values

all_values.sort()
all_values.reverse()
print(all_values[0:10])

rawDescription: Comparing file content

description: Comparing file content


code:
mystr = '09. BÃ¡t NhÃ£ TÃ¢m Kinh'
s = mystr.decode('utf8').encode('latin1').decode('utf8')
s
print(s)

rawDescription: Python How to fix broken utf-8 encoding?

description: Python How to fix broken utf-8 encoding


code:
import Tkinter as tk

root = tk.Tk()

button_frame = tk.Frame(root)
button_frame.pack(fill=tk.X, side=tk.BOTTOM)

reset_button = tk.Button(button_frame, text='Reset')
run_button = tk.Button(button_frame, text='Run')

button_frame.columnconfigure(0, weight=1)
button_frame.columnconfigure(1, weight=1)

reset_button.grid(row=0, column=0, sticky=tk.W+tk.E)
run_button.grid(row=0, column=1, sticky=tk.W+tk.E)

root.mainloop()

rawDescription: Tkinter Button Alignment in Grid

description: Tkinter Button Alignment in Grid


code:
data = """<link rel="index" href="/index.php" />
<link rel="contents" href="/getdata.php" />
<link rel="copyright" href="/blabla.php" />
<link rel="shortcut icon" href="/img/all/favicon.ico" />
"""

from lxml import etree

d = etree.HTML(data)

d.xpath('//link[@rel="shortcut icon"]/@href')
['/img/all/favicon.ico']

rawDescription: Getting certain attribute value using XPath


code:
#! /usr/bin/env python3
import cmd

class App(cmd.Cmd):

    prompt = 'Type in a command: '

    def do_a(self, arg):
        print('I am doing whatever action "a" is.')

    def do_b(self, arg):
        print('I am doing whatever action "b" is.')

if __name__ == '__main__':
    App().cmdloop()

rawDescription: main program while loop

description: Main program while loop


code:
strs = "Hello yee valiant ones!"
strs.replace(' yee','')
strs.replace('yee ','')

rawDescription: StringTranslate() function in Python

description: StringTranslate() function in Python


rawDescription: Django: Problem reading multi valued POST variable


code:
for func, args in EVENT_MAPPING:
  func(*args)

rawDescription: How to pass tuple as parameters of a function

description: Pass tuple as parameters of a function


rawDescription: Indexing of array in rpy2

description: Indexing of array in rpy2


rawDescription: can`t connect to Flask web service, connection refused

description: Can`t connect to Flask web service, connection refused


code:
test = "level"+level
d = {test: l_id}
device_level_mapping = DeviceLevelMapping.objects.filter(**d)

rawDescription: How to define a string as a variable in python

description: Define a string as a variable in python


code:
from django.utils import translation

def view(request):

    client_lang = translation.get_language_from_request(request)

rawDescription: Getting the two letter language code of the client


code:
a = collections.Counter('abcdababc')
a.most_common()
a.most_common(2)

rawDescription: retrieving dictionary elements by index rather than key

description: Retrieving dictionary elements by index rather than key


code:
for iteration in range(0, max_iters):
    fig, ax = plt.subplots()
    idx = findClosestCentroids(X, centroids)
    centroids = computeCentroids(X, idx, K)

    if plot is True:
        data = c_[X, idx]
        for i in range(1, K + 1):
            data_1 = data[data[:, n] == i]
            ax.plot(data_1[:, 0], data_1[:, 1], linestyle=' ', color=dict[i - 1], marker='o', markersize=3)

        ax.plot(centroids[:, 0], centroids[:, 1], 'k*', markersize=15)

    fig.show()

rawDescription: How to continue plotting in the same window in python?

description: Continue plotting in the same window in python


code:
class A():
    var = 0
    list = []
a = A()
b = A()
a.var
a.list
b.var
b.list
a.var = 1
b.var
a.list.append('hello')
b.list
b.list = ['newlist']
a.list
b.list

rawDescription: class variables is shared across all instances in python?

description: Class variables is shared across all instances in python


code:
def cluster_feature_importance(X, Y, feature_importances):
    N, M = X.shape
    X = scale(X)

    out = {}
    for c in set(Y):
        out[c] = dict(
            zip(range(N), np.mean(X[Y==c, :], axis=0))
        )

    return out

rawDescription: Printing principal features in clusters (python)


rawDescription: Create a pandas dataframe column based on a logical test


code:
keys = list(d.keys())
keys.sort(reverse=True)
increased_k = keys[0] + 1  # use +1 to increment the largest key
for k in keys:
    if k < new_key: break
    d[increased_k] = d[k]
    increased_k = k

d[new_key] = new_value  # insert the new item

rawDescription: Python: increment dictionary keys

description: Python: increment dictionary keys


code:
import pandas

def A(foo):
    return pandas.do_something(foo)

def B(bar):
    return pandas.do_something_else(bar)

rawDescription: How to initialise a python module?

description: Initialise a python module


rawDescription: python pandas dataframe: transform a column and append it to the end

description: Python pandas dataframe: transform a column and append it to the end


code:
import os
dirs = set()
for dirpath, dirnames, filenames in os.walk('.', followlinks=True):
    st = os.stat(dirpath)
    scandirs = []
    for dirname in dirnames:
        st = os.stat(os.path.join(dirpath, dirname))
        dirkey = st.st_dev, st.st_ino
        if dirkey not in dirs:
            dirs.add(dirkey)
            scandirs.append(dirname)
    dirnames[:] = scandirs
    print(dirpath)

rawDescription: Avoiding infinite recursion with os.walk


code:
import wx
from wx.lib.wordwrap import wordwrap
import wx.lib.agw.ultimatelistctrl as ULC

class Frame(wx.Frame):
    def __init__(self, *args, **kw):
        wx.Frame.__init__(self, *args, **kw)

        self.list = ULC.UltimateListCtrl(self, agwStyle=ULC.ULC_REPORT|ULC.ULC_HAS_VARIABLE_ROW_HEIGHT)
        items = ['A', 'b', 'a really really long line that if would be nice if it could word-wrap']
        colWidth = 100
        self.list.InsertColumn(0, "AA", width=colWidth)
        for item in items:
            item = wordwrap(item, colWidth, wx.ClientDC(self))
            self.list.InsertStringItem(0, item)

app = wx.App(False)
frm = Frame(None, title="ULC wordwrap test")
frm.Show()
app.MainLoop()

rawDescription: Word wrapping in a ListCtrl (or ObjectListView)


rawDescription: Extracting strings in Python in either single or double quotes


rawDescription: how to sort a list using python?

description: Sort a list using python


code: ax.text(bar.get_x()+bar.get_width()/4., 0.65*height, '%.2f'%float(height), rotation='vertical', horizontalalignment='left', va='bottom', weight='bold')

rawDescription: How to modify the text in a bar chart

description: Modify the text in a bar chart


code:
from urllib.request import urlopen
from lxml.html import parse

url = 'https://en.wikipedia.org/wiki/List_of_towns_and_cities_in_Oklahoma_by_population'
response = urlopen(url)
html = parse(response)
root = html.getroot()
span = root.get_element_by_id('Largest_10_cities_by_population')
h2 = span.getparent()

cities = []
current = h2
while current.tag != 'div':
    if current.tag == 'p' and current.find('a') is not None:
        cities.append(current.find('a').text)
    current = current.getnext()

print(cities)

rawDescription: Working with "unclean" text in python

description: Working with "unclean" text in python


code:
class LiveServerTestCase(TransactionTestCase):
    static_handler = _StaticFilesHandler

    @property
    def live_server_url(self):
        return 'http://%s:%s' % (
            self.server_thread.host, self.server_thread.port)

rawDescription: How to run Django 1.6 LiveServerTestCase without HTTPS?

description: Run Django 1.6 LiveServerTestCase without HTTPS