code: sorted(dictionary.iteritems(), key=lambda i: i[1])

rawDescription: How to iterate through keys of a dictionary which is sorted with values?

description: Iterate through keys of a dictionary which is sorted with values


code:
MyTable.objects.extra(select={'int_name': 'CAST(t.name AS INTEGER)'},
                      order_by=['int_name'])

rawDescription: Ordering query result by numeric strings in django (postgres backend)


rawDescription: Reading/Parsing Snort Alert File Using Python


code:
strs = ".foo bar (foo) bar foo-bar foo_bar foo'bar bar-foo bar, foo."
re.findall('[^\w+]foo[^\w+]', strs)

rawDescription: python regex search which not starts and ends with any of specified letters

description: Python regex search which not starts and ends with any of specified letters


code:
import requests
from bs4 import BeautifulSoup

url = 'amazon.com'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')

file = open('file.txt', 'r')
text = file.read()
file.close()

for link in soup.findAll('a', {'class': 'gridItem-trackInfo-title-anchor'}):
    href = link.get('href')

    if href not in text:
        print(href)

rawDescription: Finding text not present in a string

description: Finding text not present in a string


code:
import matplotlib.pyplot as plt
...
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

rawDescription: Change x axes scale in matplotlib

description: Change x axes scale in matplotlib


rawDescription: Extract specific array from multi dimensional array with index sets


code:
import numpy as np
import cv2
import time

def Func_VideoCapture(Float_Time = 10):
    Float_WantedTime = time.time() + Float_Time
    Float_CurentTime = time.time()

    cap = cv2.VideoCapture(0)

    while Float_CurentTime<=Float_WantedTime:
        #get current time
        Float_CurentTime = time.time()

        # Capture frame-by-frame
        ret, frame = cap.read()

        # Display the resulting frame
        cv2.imshow('frame',frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    Float_Time = float(raw_input(">>> "))
    Func_VideoCapture(Float_Time)

rawDescription: Python OpenCV avoid Video Source -> Capture source dialog


code:
import numpy as np

n = 1280
m = 720

# Generate a n * m * 4 matrix with random values
x = np.round(np.random.rand(n, m, 4)*10)

# Calculate the mean value over the first 3 values along the 2nd axix (starting from 0)
xnew = np.mean(x[:, :, 0:3], axis=2)

rawDescription: Python numpy array manipulation

description: Python numpy array manipulation


code:
from cStringIO import StringIO
import gnupg
import logging
import os
import shutil

def generate_key(gpg, first_name, last_name, domain, passphrase=None):
    "Generate a key"
    params = {
        'Key-Type': 'DSA',
        'Key-Length': 1024,
        'Subkey-Type': 'ELG-E',
        'Subkey-Length': 2048,
        'Name-Comment': 'A test user',
        'Expire-Date': 0,
    }
    params['Name-Real'] = '%s %s' % (first_name, last_name)
    params['Name-Email'] = ("%s.%s@%s" % (first_name, last_name, domain)).lower()
    if passphrase is None:
        passphrase = ("%s%s" % (first_name[0], last_name)).lower()
    params['Passphrase'] = passphrase
    cmd = gpg.gen_key_input(**params)
    return gpg.gen_key(cmd)

def init_logging():
    logging.basicConfig(level=logging.DEBUG, filename="gpg.log",
                        filemode="w", format="%(asctime)s %(levelname)-5s %(name)-10s %(threadName)-10s %(message)s")

def print_info(decrypted):
    print('User name: %s' % decrypted.username)
    print('Key id: %s' % decrypted.key_id)
    print('Signature id: %s' % decrypted.signature_id)
    #print('Signature timestamp: %s' % decrypted.sig_timestamp)
    print('Fingerprint: %s' % decrypted.fingerprint)

def main():
    init_logging()
    if os.path.exists('keys'):
        shutil.rmtree('keys')
    gpg = gnupg.GPG(gnupghome='keys')
    key = generate_key(gpg, "Andrew", "Able", "alpha.com",
                            passphrase="andy")
    andrew = key.fingerprint
    key = generate_key(gpg, "Barbara", "Brown", "beta.com")
    barbara = key.fingerprint
    #First - without signing
    data = 'Top secret'
    encrypted = gpg.encrypt_file(StringIO(data), barbara,
                                 #sign=andrew, passphrase='andy',
                                 output='encrypted.txt')
    assert encrypted.status == 'encryption ok'
    # Data is in encrypted.txt. Read it in and verify/decrypt it.
    data = open('encrypted.txt', 'r').read()
    decrypted = gpg.decrypt(data, passphrase='bbrown', output='decrypted.txt')
    print_info(decrypted)
    #Now with signing
    data = 'Top secret'
    encrypted = gpg.encrypt_file(StringIO(data), barbara,
                                 sign=andrew, passphrase='andy',
                                 output='encrypted.txt')
    assert encrypted.status == 'encryption ok'
    # Data is in encrypted.txt. Read it in and verify/decrypt it.
    data = open('encrypted.txt', 'r').read()
    decrypted = gpg.decrypt(data, passphrase='bbrown', output='decrypted.txt')
    print_info(decrypted)

if __name__ == '__main__':
    main()

rawDescription: How to verify gnupg signature with Python gnupg module?

description: Verify gnupg signature with Python gnupg module


code:
filedata = filedata.replace('# DBENGINE=MYSQL', 'DBENGINE=PGSQL')
filedata = filedata.replace('# DBNAME=DB1', 'DBNAME=DB1')
filedata = filedata.replace('# DBRWUSER="user1"', 'DBRWUSER="user1"')
...
f.write(filedata)

rawDescription: Python 3 Replace Lines

description: Python 3 Replace Lines


code:
StoreItems = random.sample(set(['sword','pickaxe','toothpick','hammer','torch','saw']), 5)
#Selects 5 Random strings from the list. ^

XBASE, YBASE, DISTANCE = 300, 340, 50
for i, word in enumerate(StoreItems):
    canvas.create_text(
        (XBASE, YBASE + i * DISTANCE),
        text=word, activefill="Medium Turquoise", anchor=W, fill="White", font=('Anarchistic',40), tags=word)

canvas.tag_bind('sword', '<ButtonPress-1>', BuySword)
canvas.tag_bind('pickaxe', '<ButtonPress-1>', BuyPick)
canvas.tag_bind('toothpick', '<ButtonPress-1>', BuyTooth)
canvas.tag_bind('hammer', '<ButtonPress-1>', BuyHammer)
canvas.tag_bind('torch', '<ButtonPress-1>', BuyTorch)
canvas.tag_bind('saw', '<ButtonPress-1>', BuySaw)

rawDescription: How to add text to canvas from a list as separate canvas.create_text

description: Add text to canvas from a list as separate canvas.create_text


code:
import subprocess

def getLength(filename):
  result = subprocess.Popen(["ffprobe", filename],
    stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  return [x for x in result.stdout.readlines() if "Duration" in x]

rawDescription: How to get the duration of a video in Python?

description: Get the duration of a video in Python


code:
from gi.repository import Gtk, Gdk, GdkPixbuf

class ButtonWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Button Demo")
        self.set_border_width(10)
        self.connect("delete-event", Gtk.main_quit)
        self.connect("check_resize", self.on_check_resize)

        self.box = Gtk.ScrolledWindow()
        self.box.set_policy(Gtk.PolicyType.ALWAYS,
                       Gtk.PolicyType.ALWAYS)
        self.add(self.box)

        self.click = Gtk.Button()
        self.box.add_with_viewport(self.click)

        self.pixbuf = GdkPixbuf.Pixbuf().new_from_file('gtk-logo-rgb.jpg')
        self.image = Gtk.Image().new_from_pixbuf(self.pixbuf)
        self.click.add(self.image)

    def resizeImage(self, x, y):
        print('Resizing Image to ('+str(x)+','+str(y)+')....')
        pixbuf = self.pixbuf.scale_simple(x, y,
                                          GdkPixbuf.InterpType.BILINEAR)
        self.image.set_from_pixbuf(pixbuf)

    def on_check_resize(self, window):
        print("Checking resize....")

        boxAllocation = self.box.get_allocation()
        self.click.set_allocation(boxAllocation)
        self.resizeImage(boxAllocation.width-10,
                         boxAllocation.height-10)

win = ButtonWindow()
win.show_all()
Gtk.main()

rawDescription: how to do automatic image resizing in Python3 with PyGI?

description: Do automatic image resizing in Python3 with PyGI


code:
def find_index(name,l=sav) :
  for i,j in enumerate(l) :
    if name in j :
      print ('index is : {}'.format(i))
find_index('Alex')
find_index('Nat')

rawDescription: How to find the index of a subsection in an array from one string (python 3.4.2)

description: Find the index of a subsection in an array from one string (python 3.4.2)


code:
import csv
writer = csv.writer(open('output.csv', 'wb'))

for item in mydata:  # mydata is your list of tuples, so item is a tuple
    row = [item[0]] + list(item[1])
    writer.writerow(row)

rawDescription: How can I print a list of sets to a file, with python, in a format that is easily put into excel, eliminating all the unwanted characters?

description: Print a list of sets to a file, with python, in a format that is easily put into excel, eliminating all the unwanted characters


code:
xAmount = int(input("How man numbers would you like to input: "))

numList = []
numList_sum = 0

for i in range(0, xAmount):
     inputted_number = int(input("Enter a number: "))
     numList_sum += inputted_number
     numList.append(inputted_number)

print(numList)
print(numList_sum)

rawDescription: Taking the sum of a list without sum()

description: Taking the sum of a list without sum()


code:
import numpy as np
import pandas as pd
from io import StringIO

#StringIO to write to
f = StringIO()

#Write to StringIO
dist = np.random.normal(100, 30, 10000)
for idx,s in enumerate(dist):
    f.write('{}\t{}\t{}\n'.format("label_A-%d" % idx, "label_B-%d" % idx, str(s)))

# rewind the stream
f.seek(0)

#Pandas DataFrame from it
DF = pd.read_table(f,sep="\t",header=None)
#EmptyDataError: No columns to parse from file

rawDescription: How to use pd.read_table with StringIO file object?

description: Use pd.read_table with StringIO file object


code:
def transString(string, reverse=0):
    '''Given a Unicode string, transliterate into Buckwalter. To go from
    Buckwalter back to Unicode, set reverse=1'''

    if not reverse:
        for k,v in buck2uni.iteritems():
            string = string.replace(v,k)

    else:
        for k,v in buck2uni.iteritems():
            string = string.replace(k,v)

    return string

rawDescription: Fast transliteration for Arabic Text with Python


rawDescription: casting raw strings python

description: Casting raw strings python


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

plt.imshow(np.random.random((10,10)))
cb = plt.colorbar()

for l in cb.ax.yaxis.get_ticklabels():
    l.set_family("Comic Sans MS")

plt.show()

rawDescription: Python: how to change font in a colorbar?


code:
from subprocess import check_output as run # >=2.7

path = './'
cmd = ['svn', '--username', XXXX, '--password', XXXX, '--non-interactive', 'info', path]
out = run(cmd).splitlines()
out = (i.split(':', 1) for i in out if i)
info = {k:v.strip() for k,v in out}

# you can access  the other svn info fields in a similar manner
rev = info['Last Changed Rev']

with open('.last-svn-commit', 'w') as fh:
    fh.write(rev)

rawDescription: Using actual branch head revision number in Hudson


code:
df
df.mean(axis=1)

rawDescription: how to get the average of dataframe column values

description: Get the average of dataframe column values


code:
class POINT(Structure):
    _fields_ = [("x", c_int),
               ("y", c_int)]

rawDescription: Passing python class object as parameter to c library


code:
my_list = [
     1, 2, 3,
     4, 5, 6,
     ]
result = some_function_that_takes_arguments(
     'a', 'b', 'c',
     'd', 'e', 'f',
     )

rawDescription: Emacs - Python Indent in parenthesis

description: Emacs - Python Indent in parenthesis


code:
from django.contrib.auth import update_session_auth_hash

def password_change(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
    else:
        ...

rawDescription: Django Authentication issue after reseting password


rawDescription: Double Summation in Python

description: Double Summation in Python


rawDescription: Django - using my context in render_to_response


code:
print(1) == print(2) == print(3)
print(1) == print(2) and print(2) == print(3)

rawDescription: Testing equality of three values

description: Testing equality of three values


code:
import os
import stat
mode = os.stat("/dev/sda2").st_mode
stat.S_ISBLK(mode)
mode = os.stat("/dev/sr0").st_mode
stat.S_ISBLK(mode)

rawDescription: Check if file path is block device in Python


code:
folder = "abc/def/ghi/jkl"

target = ""

for level in folder.split('/'):
    target += "{}/".format(level)
    imap.create(target)

rawDescription: Using imaplib, how can I create a mailbox without the \\NoSelect attribute


code:
from itertools import product
lttrs = ['A', 'B', 'C']
lbl = ['pct']
users = [1,2]
combine = []
for p in product(lttrs, lbl, map(str, users)):
    combine.append(''.join(p))

rawDescription: Recycling operations in Python similar to R vectorization


code:
df[(df.one == 1) | (df.two == 7)]
df[(df.one.isin(checkList)) | (df.two.isin(checkList))]

rawDescription: Using pandas to select rows using two different columns from dataframe?


code:
class MyClass:
    def __init__(self, **kwargs):
        for key in kwargs:
            setattr(self, key, kwargs[key])

x = MyClass(a='test', b='test2')
# x.a == 'test'
# x.b == 'test2'
y = MyClass(c=123, d='something else')
# y.c = 123
# y.d = 'something else'

rawDescription: Any way to initialize attributes/properties during class creation in python?


code:
with open('path/to/input') as infile:
    i = 0
    f = open('outfile%d'%i, 'w')
    for line in infile:
        if line.lstrip().startswith("MOLECULE"):
            f.close()
            i += 1
            f = open('outfile%d'%i, 'w')
        f.write(line)

rawDescription: Read data from one file and write to multiple files


code:
pool = multiprocessing.Pool(num_procs)
results = pool.map(the_function, list_of_objects)
pool.close()

rawDescription: Distribute many independent, expensive operations over multiple cores in python


code:
ax = SubplotZero(fig, 111)

...

for direction in ["left", "right", "bottom", "top"]:
    ax.axis[direction].set_visible(False)

rawDescription: Change axis style python

description: Change axis style python


code:
import numpy as np
import networkx as nx
import matplotlib
matplotlib.use("TkAgg")

import pylab as plt
plt.ion()

fig = plt.figure()

pause = False

def onclick(event):
    global pause
    pause = not pause

fig.canvas.mpl_connect('button_press_event', onclick)

def drawGraph(matrix):
    fig.clear()
    G = nx.DiGraph(np.array(matrix))
    nx.draw_networkx(G)
    plt.draw()

A=[[0,1],[1,0]]
B=[[0,1],[0,0]]
x=1
while True:
    if not pause:
        if x==1:
            drawGraph(A)
            x=0
        else:
            drawGraph(B)
            x=1
    fig.canvas.get_tk_widget().update() # process events

rawDescription: How to pause a pylab figure until a key is pressed or mouse is clicked?

description: Pause a pylab figure until a key is pressed or mouse is clicked


code:
import nltk

read_expr = nltk.sem.Expression.fromstring

teststr = '(race(x) & run(I2,x))'

parsed = read_expr(teststr)
for p in parsed.predicates():
    print(p)

rawDescription: Obtaining the predicates in a Lambda Calculus Expression


code:
import bitarray
b = bitarray.bitarray()
b.fromstring('a')
b
b.to01()
b.fromstring('pples')
b.tostring()
b.to01()

rawDescription: Convert Python str/unicode object to binary/hex blob


code:
s = "<StephenCurry Pro='ThreepointShooter'>MVP1times</StephenCurry>"
re.search(r'(?<=\>)[^<]+(?=\<)', s).group(0)

rawDescription: How to get a string after keyword

description: Get a string after keyword


code:
import matplotlib
xmin, xmax = matplotlib.pyplot.xlim()   # return the current xlim
matplotlib.pyplot.xlim( (xmin, xmax) )  # set the xlim to xmin, xmax
matplotlib.pyplot.xlim( xmin, xmax )    # set the xlim to xmin, xmax

rawDescription: The data aren't visible in the plot

description: The data aren't visible in the plot


code:
import numpy as np
array1 = np.array([1, 2, 3, 4])
view1 = array1[1:]
view1
view1[1] = 5
view1
array1

rawDescription: Python: create sublist without copying

description: Python: create sublist without copying


code:
class URIString(str):
    _default_namespace = "default"

    def __init__(self, value, namespace=_default_namespace):
        self.namespace = namespace

    def __new__(cls, value, namespace=_default_namespace):
        return super().__new__(cls, value)

    @property
    def local_name(self):
        return self[(self.find(self.namespace)+len(self.namespace)):]

rawDescription: Extend str class to take additional parameters


code:
message='To: {}\r\nSubject: {}\r\n\r\n{}'.format('visible@example.com', subject, body)

smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, ['visible@example.com', 'invisible@example.com'], message)
smtp.quit()

rawDescription: python emailing using BCC by default instead of To

description: Python emailing using BCC by default instead of To


code:
"""
Broken axis example, where the x-axis will have a portion cut out.
"""
import matplotlib.pylab as plt
import numpy as np

x = np.linspace(0,10,100)
x[75:] = np.linspace(40,42.5,25)

y = np.sin(x)

f,(ax,ax2) = plt.subplots(1,2,sharey=True, facecolor='w')

# plot the same data on both axes
ax.plot(x, y)
ax2.plot(x, y)

ax.set_xlim(0,7.5)
ax2.set_xlim(40,42.5)

# hide the spines between ax and ax2
ax.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax.yaxis.tick_left()
ax.tick_params(labelright='off')
ax2.yaxis.tick_right()

# This looks pretty good, and was fairly painless, but you can get that
# cut-out diagonal lines look with just a bit more work. The important
# thing to know here is that in axes coordinates, which are always
# between 0-1, spine endpoints are at these locations (0,0), (0,1),
# (1,0), and (1,1).  Thus, we just need to put the diagonals in the
# appropriate corners of each of our axes, and so long as we use the
# right transform and disable clipping.

d = .015 # how big to make the diagonal lines in axes coordinates
# arguments to pass plot, just so we don't keep repeating them
kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)
ax.plot((1-d,1+d), (-d,+d), **kwargs)
ax.plot((1-d,1+d),(1-d,1+d), **kwargs)

kwargs.update(transform=ax2.transAxes)  # switch to the bottom axes
ax2.plot((-d,+d), (1-d,1+d), **kwargs)
ax2.plot((-d,+d), (-d,+d), **kwargs)

# What's cool about this is that now if we vary the distance between
# ax and ax2 via f.subplots_adjust(hspace=...) or plt.subplot_tool(),
# the diagonal lines will move accordingly, and stay right at the tips
# of the spines they are 'breaking'

plt.show()

rawDescription: Break // in x axis of matplotlib

description: Break // in x axis of matplotlib


rawDescription: Multiple regex matching in python

description: Multiple regex matching in python


rawDescription: AMQP / RabbitMQ multiple consumers but only one geting work?


rawDescription: Why can't I store a UserID (users.get_current_user()) in a Session variable in Python in GAE?


code:
def update_tags(ref, new_tag):
    coll.update({'ref': ref}, {'$push': {'tags': new_tag}})

rawDescription: Append item to MongoDB document array in PyMongo without re-insertion


code:
def magic_fun(d):
    return [[(key,el) for el in value] for key,value in d.items()]
    # for key,value in d.items():
    #     element_list = []
    #     for el in value:
    #         element_list.append((key,el))
    #     yield element_list

rawDescription: python unpacked dictionary of list

description: Python unpacked dictionary of list


rawDescription: Pandas remove duplicates with a criteria


code:
from PySide import QtGui, QtCore

class Model(QtCore.QAbstractTableModel):
    def __init__(self, parent=None, *args):
        QtCore.QAbstractTableModel.__init__(self, parent, *args)
        self.items =[
                    ['Row0_Column0','Row0_Column1','Row0_Column2'],
                    ['Row1_Column0','Row1_Column1','Row1_Column2'],
                    ['Row2_Column0','Row2_Column1','Row2_Column2']
                    ]

    def flags(self, index):
        return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable

    def rowCount(self, parent):
        return len(self.items)

    def columnCount(self, parent):
        return 3

    def data(self, index, role):
        if not index.isValid():
            return None

        row=index.row()
        column=index.column()

        if row > len(self.items):
            return None
        if column > len(self.items[row]):
            return None

        if role == QtCore.Qt.EditRole:
            return self.items[row][column]

        if role == QtCore.Qt.DisplayRole:
            return self.items[row][column]

        return None

    def setData(self, index, value, role=QtCore.Qt.EditRole):
        if index.isValid():
            if role == QtCore.Qt.EditRole:

                row = index.row()
                column = index.column()

                if row > len(self.items) or column > len(self.items[row]):
                    return False
                else:
                    self.items[row][column] = value
                    self.dataChanged.emit(index, index) # emit the signal
                    return True
        return False

class MyWindow(QtGui.QWidget):
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)

        tablemodel = Model(self)
        tablemodel.dataChanged.connect(self.data_changed) # connect dataChanged signal
        tableview = QtGui.QTableView(self)
        tableview.setModel(tablemodel)

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(tableview)

        self.button = QtGui.QPushButton('Push Me')
        self.button.setDisabled(True) # initially disabled

        layout.addWidget(self.button)
        self.setLayout(layout)

    def data_changed(self, topleft_index, bottom_right_index):
        # just enable the button
        self.button.setEnabled(True)

app = QtGui.QApplication([])
w = MyWindow()
w.show()
app.exec_()

rawDescription: How to control other widgets with an QAbstractTableModel model?

description: Control other widgets with an QAbstractTableModel model


code:
email ='your email id'
pwd  = 'your password'
data = urllib.parse.urlencode({'email': email, 'pwd':pwd, 'service': 'nudge'})
data = data.encode('utf-8')
request = urllib.request.Request("https://jawbone.com/user/signin/login")
# adding charset parameter to the Content-Type header.
request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
f = urllib.request.urlopen(request, data)
#print(f.read().decode('utf-8'))
j=(f.read().decode('utf-8'))
b=json.loads(j)

rawDescription: Jawbone API authentication using python

description: Jawbone API authentication using python


code:
from itertools import permutations, chain
beers = ['speights', 'tui', 'export']
list(chain.from_iterable(permutations(beers, i) for i in xrange(1, len(beers) + 1)))

rawDescription: Getting Every Possible combination of each list in a list of list of arbitrary length


code:
def copy_files():
    import os
    for row in db().select(db.product.id, db.product.picture):
        picture = open(os.path.join(request.folder, 'private', row.picture), 'rb')
        row.update_record(picture=db.product.picture.store(picture, row.picture))
    return 'Files copied'

rawDescription: Import csv data to web2py database and process uploads


code:
x = decimal.Decimal('8.00000000000000000000001')
with decimal.localcontext() as ctx:
    ctx.prec=100000000000000000
    ctx.rounding=decimal.ROUND_CEILING
    y = x.to_integral_exact()

rawDescription: getting Ceil() of Decimal in python?

description: Getting Ceil() of Decimal in python


code:
import imp

search_paths = [path_to_spam]
modfile, modpath, description = imp.find_module('spam', search_paths)
with modfile:
    spam = imp.load_module('spam', modfile, modpath, description)

rawDescription: Restrict import to specific path, without restricting the imported module's path


code:
a = "switchport port-security mac-address 000a.1111.2222 vlan 43"
splitted = a.split()
[x for i,x in enumerate(splitted) if i > 0 and splitted[i-1] in ["mac-address", "vlan"]]

rawDescription: regex to find these values?

description: Regex to find these values


code:
class Car:
    pass
audi = Car()
myCar = Car()
myBrothersCar = Car()

rawDescription: What would be the proper naming convention for a Python module, class and instance variable having the same base name?


code: lst1, lst2, lst3 = map(list, zip(*tuple_of_lists))

rawDescription: load array 'columns' into array variables quickly

description: Load array 'columns' into array variables quickly


code: [int(match.group(0)) for match in re.finditer(r'\w+', input())]

rawDescription: Reading space-separated integers efficiently


code:
import traceback
from collections import defaultdict
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.orm.interfaces import SessionExtension

# TODO cleanup commited sessions
class MySessionUsageInspector(SessionExtension):

    def __init__(self):
        self.connections = defaultdict(list)

    def after_begin(self, session, transaction, connection):
        self.connections[connection].append(traceback.format_stack()[0])

    def repr_usage(self):
        for cnn, callers in self.connections.items():
            print(cnn)
            for index, caller in enumerate(callers):
                print('\t', index, caller)

if __name__ == '__main__':
    engine = create_engine('sqlite://')
    session_inspector = MySessionUsageInspector()
    Session = scoped_session(sessionmaker(bind=engine,
        extension=session_inspector)
    )
    session = Session()

    session.execute('select 1;')
    session.commit()
    session.execute('select 2;')

    print('Session usage:')
    session_inspector.repr_usage()

rawDescription: How to monitor/log sqlalchemy scoped sessions?

description: Monitor/log sqlalchemy scoped sessions


code:
def main():
    numbers = []
    times = int(input('How many times will you do this: '))
    for i in range(times):
        num = int(input('Enter a number: '))
        numbers.append(num)
    print(str(max(numbers)) + ' is the biggest number.')
main()

rawDescription: Get the Biggest (int) Input From a Loop and Print it


code:
cfg_defaults = {'watch-dir' : '/home/pi/shared/ups',
                'poi-dir' : '/home/pi/shared/POI History',
                'oor-dir' : '/home/pi/shared/117 History'}

config = ConfigParser(cfg_defaults)
config.read('config.ini')

return config

rawDescription: Python ConfigParser

description: Python ConfigParser


code: result = [(x+dx, y+dy) for x,y in points for dx,dy in offsets]

rawDescription: Add tuple to list of tuples in Python

description: Add tuple to list of tuples in Python


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

fig,(ax1,ax2) = plt.subplots(2)

sns.set_style("whitegrid")
tips = sns.load_dataset("tips")

sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set1", ax=ax1)
sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set1", ax=ax2)

for i,artist in enumerate(ax2.artists):
    # Set the linecolor on the artist to the facecolor, and set the facecolor to None
    col = artist.get_facecolor()
    artist.set_edgecolor(col)
    artist.set_facecolor('None')

    # Each box has 6 associated Line2D objects (to make the whiskers, fliers, etc.)
    # Loop over them here, and use the same colour as above
    for j in range(i*6,i*6+6):
        line = ax2.lines[j]
        line.set_color(col)
        line.set_mfc(col)
        line.set_mec(col)

# Also fix the legend
for legpatch in ax2.get_legend().get_patches():
    col = legpatch.get_facecolor()
    legpatch.set_edgecolor(col)
    legpatch.set_facecolor('None')

plt.show()

rawDescription: How to edit properties of whiskers, fliers, caps, etc. in Seaborn boxplot

description: Edit properties of whiskers, fliers, caps, etc. in Seaborn boxplot


code:
import re

mult = {'h': 60*60, 'mn': 60}
res = sum(int(num) * mult.get(val, 1) for num, val in re.findall('(\d+)(\w+)', '1h 34mn 2s'))
# 5642

rawDescription: Extract values from H mn s format time in python


code:
import urlparse

class PunyCodeU8RefererFixerMiddleware(object):
    def process_request(self, request):
        servername = request.META['SERVER_NAME']
        if 'xn--' not in servername:
            return None

        referer = request.META.get("HTTP_REFERER")
        if not referer:
            return None

        url = urlparse.urlparse(referer)
        try:
            netloc = url.netloc.decode('u8')
        except UnicodeDecodeError:
            return None

        def isascii(txt):
            return all(ord(ch) < 128 for ch in txt)

        netloc = '.'.join([
            str(p) if isascii(p) else 'xn--' + p.encode('punycode')
            for p in netloc.split('.')
        ])
        url = url._replace(netloc=netloc)
        request.META['HTTP_REFERER'] = urlparse.urlunparse(url)
        return None

rawDescription: How do I handle utf-8 vs. punycode issues in Django's csrf middleware?

description: Handle utf-8 vs. punycode issues in Django's csrf middleware


code:
from django.core.files.temp import NamedTemporaryFile
def send_file(request):
    newfile = NamedTemporaryFile(suffix='.txt')
    # save your data to newfile.name
    wrapper = FileWrapper(newfile)
    response = HttpResponse(wrapper, content_type=mime_type)
    response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(modelfile.name)
    response['Content-Length'] = os.path.getsize(modelfile.name)
    return response

rawDescription: Removing tmp file after return HttpResponse in django


code:
f = open("text.txt", "r")
listBill = []
for line in f:
    print(line)

    splitParagraph = line.split()
    print(splitParagraph)
    for eachBill in splitParagraph:
        if eachBill == "Bill":
            listBill.append("Bill")

print(listBill)

rawDescription: My python program splits only the last paragraph of my text file, does someone know why this happens?


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

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setMinimumSize(640, 480)
        self.container_widget = QWidget()
        self.container_layout = QVBoxLayout()
        self.container_widget.setLayout(self.container_layout)
        self.setCentralWidget(self.container_widget)
        self.grid_scrollarea = ScrollArea(self)
        self.test_group = QGroupBox("Results")
        self.test_layout = QVBoxLayout()
        self.test_group.setLayout(self.test_layout)
        self.test_layout.addWidget(self.grid_scrollarea)
        self.container_layout.addWidget(self.test_group)

class ScrollArea(QScrollArea):
    def __init__(self, parent=None):
        QScrollArea.__init__(self, parent)
        self.grid_widget = QWidget()
        self.grid_layout = QGridLayout()
        self.grid_widget.setLayout(self.grid_layout)
        self.setWidgetResizable(True)
        self.setWidget(self.grid_widget)
        # save the margin values
        self.margins = QMargins(0, 30, 0, 0)
        self.setViewportMargins(self.margins)
        self.headings_widget = QWidget(self)
        self.headings_layout = QGridLayout()
        self.headings_widget.setLayout(self.headings_layout)
        self.headings_layout.setContentsMargins(1,1,0,0)
        self.heading_label1 = QLabel("Column 1")
        self.heading_label1.setContentsMargins(16,0,0,0)
        self.heading_label2 = QLabel("Col 2")
        self.heading_label2.setAlignment(Qt.AlignCenter)
        self.heading_label2.setMaximumWidth(65)
        self.heading_label3 = QLabel("Column 3")
        self.heading_label3.setContentsMargins(8,0,0,0)
        self.headings_layout.addWidget(self.heading_label1,0,0)
        self.headings_layout.addWidget(self.heading_label2,0,1)
        self.headings_layout.addWidget(self.heading_label3,0,2)
        self.headings_widget.setStyleSheet(
            "background: green; border-bottom: 1px solid black;" )
        rows_to_add = 10
        for i in range(rows_to_add):
            col1 = QLineEdit()
            col2 = QLineEdit()
            col2.setMaximumWidth(65)
            col3 = QLineEdit()
            row = self.grid_layout.rowCount()
            self.grid_layout.addWidget(col1,row,0)
            self.grid_layout.addWidget(col2,row,1)
            self.grid_layout.addWidget(col3,row,2)

    def resizeEvent(self, event):
        rect = self.viewport().geometry()
        self.headings_widget.setGeometry(
            rect.x(), rect.y() - self.margins.top(),
            rect.width() - 1, self.margins.top())
        QScrollArea.resizeEvent(self, event)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    form = MainWindow()
    form.show()
    sys.exit(app.exec_())

rawDescription: How to add a fixed header to a QScrollArea?

description: Add a fixed header to a QScrollArea


code:
urlpatterns = [
    url(
        '^change-password/',
        'django.contrib.auth.views.password_change',
        {'template_name': 'change-password.html'}
    )
]

rawDescription: Change template name for Django's auth views


code:
for x in filter(long_word.startswith, list1):
    for y in filter(long_word[len(x):].startswith, list2):
        z = long_word[len(x)+len(y):]
        if z in list3:
            print('Found: {}, {}, {}'.format(x, y, z))
            break
    else:
        continue
    break
else:
    print('Not found')

rawDescription: Finding three parts of string in Python using regex


code:
if value in object1.followers.all():
    ...

rawDescription: How to check if object value in manytomany field?

description: Check if object value in manytomany field


code:
def intToBytes(integer):
    hex_form = hex(integer)[2:]; # 2: gets rid of leading 0x
    if hex_form[-1:] == 'L':
        # Remove final `L` from arbitrary precision integers
        hex_form = hex_form[:-1]
    if (len(hex_form) % 2):
        hex_form = '0' + hex_form;
    return bytearray.fromhex(hex_form)

rawDescription: (python) How to convert long into raw string?


code: L = [int("".join([str(y) for y in x])) for x in L]

rawDescription: Convert list of lists to list of integers


code:
def unsigned_number_to_slashed_byte_array_string(number, little_endian, digits_count):
        """
        Convert given unsigned number into a string that represents it as a sequence of bytes in given order (either little or big Endian).
        In case the total number of digits in the string is greater than given digits count, the string is left-padded with zeroes.
        Each such byte is represented by a substring that's composed of a preceding slash character followed by two (uppercase) hexadecimal digits (e.g., "\\0A").
        :param number: An unsigned non-negative integer.
        :param little_endian: A flag that says whether little Endian order is requested; otherwise, big Endian order is selected.
        :param digits_count: The total count of hexadecimal digits in the resulting possibly left-padded string, which is twice the number of bytes.
        :except ValueError: In case given number isn't a non-negative number, or given digits count isn't a positive even number.
        :return: A string that represents given number as a sequence of bytes in given order.
        """
        if number < 0: raise ValueError("{0}: Argument number must be a non-negative! ({1})".format(func_name(), number))
        if (digits_count <= 0) or ((digits_count % 2) != 0): raise ValueError("{0}: Argument digits_count must be an even positive! ({1})".format(func_name(), digits_count))

        zero_padded_hex_number_str = "{0:0{1}X}".format(number, digits_count) # Format: no leading "0x", zero-padded digits_count digits (or half digits_count bytes), uppercase hexadecimal letters.
        number_byte_array_str = ""
        byte_starter_digits_indices_list = range(len(zero_padded_hex_number_str))[::2]
        if little_endian: byte_starter_digits_indices_list = reversed(byte_starter_digits_indices_list)
        for byte_starter_digit_index in byte_starter_digits_indices_list:
            number_byte_array_str = "{0}\\{1}".format(number_byte_array_str, zero_padded_hex_number_str[byte_starter_digit_index:(byte_starter_digit_index + 2)])
        return number_byte_array_str

def sid_str_to_byte_array_str(sid_str):
    """
    :param sid_str: An active-directory SID string (e.g., "S-1-5-21-1241979920-1440912824-1533017923-1106").
    :return: A string that represents given SID string as a byte array string (e.g., "\\01\\05\\00\\00\\00\\00\\00\\05\\15\\00\\00\\00\\10\\1C\\07\\4A\\B8\\95\\E2\\55\\43\\FF\\5F\\5B").
    """
    dashes_count = sid_str.count("-")
    sid_numbers_str = sid_str[2:] # Removes the preceding "S-"
    sid_number_strings = sid_numbers_str.split("-")
    sid_numbers = [int(sid_number_string) for sid_number_string in sid_number_strings]
    sid_byte_array_str  = unsigned_number_to_slashed_byte_array_string(sid_numbers[0],       True,   2)
    sid_byte_array_str += unsigned_number_to_slashed_byte_array_string((dashes_count - 2),   True,   2)
    sid_byte_array_str += unsigned_number_to_slashed_byte_array_string(sid_numbers[1],       False, 12)
    sid_byte_array_str += unsigned_number_to_slashed_byte_array_string(sid_numbers[2],       True,   8)
    sid_byte_array_str += unsigned_number_to_slashed_byte_array_string(sid_numbers[3],       True,   8)
    sid_byte_array_str += unsigned_number_to_slashed_byte_array_string(sid_numbers[4],       True,   8)
    sid_byte_array_str += unsigned_number_to_slashed_byte_array_string(sid_numbers[5],       True,   8)
    return sid_byte_array_str

rawDescription: Python ldap3 code to get username from SID


code:
A = []
B = []
with open('indexes') as infile:
    for line in infile:
        line = line.strip()
        if not line: continue
        className, fname = line.split(None,1)
        A.append(className)
        mat = scipy.io.loadmat('filenameX')
        var = np.concatenate((mat['dataL'], mat['dataR']), axis=0).reshape(1,387200)
        B.append(var)

rawDescription: How to extract data of a file that is pointed by another file

description: Extract data of a file that is pointed by another file


code: depthImage[depthImage==0] = 2880

rawDescription: how to change pixel values in python (opencv) without for loops

description: Change pixel values in python (opencv) without for loops


code:
# Nonsense Model for Fish numbers ###
''' Fish numbers, in 100,000 tonnes in coastal waters. Those in the North Sea
   increase by 10% every year.
Those in the Irish Sea increase by 15%. Those in the   Channel are currently decreasing
the difference by 5%. Also want a total for each  year for 10 year prediction.'''
# master list
fish = []
# ask questions
northFish = int(input('How many fish in first year the North Sea?'))
irishFish = int(input('How many fish in first year the Irish Sea?'))
channelFish = int(input('How many fish in first year in The Channel?'))

# add to the list
fish = [northFish, irishFish, channelFish]
# display the start
print(fish)
year = int(input('how many years would you like to model?'))
# run the model

factors = (1.1, 1.15, 0.95)

# initialize fish_trend with population of first year
fish_trend = [tuple(fish)]

# iterate through years
for _ in range(year):
    # iterate through fish types
    for i in range(len(fish)):
        fish[i] *= factors[i]

    # append current population to fish_trend
    fish_trend.append(tuple(fish))

# you can use pprint for better visualization
import pprint
pprint.pprint(fish_trend)

# if you want the sum of the population per year, you can do that easily by using this:
sum_per_year = [sum(f) for f in fish_trend]

print(sum_per_year)

rawDescription: Python doing calculations over a list and adding into the list


code:
class BackendTests:
    def make_backend(self):
        raise NotImplementedError

    def test_one(self):
        backend = self.make_backend()
        # perform a test on the backend

class FooBackendTests(unittest.TestCase, BackendTests):
    def make_backend(self):
        # Create an instance of the "foo" backend:
        return foo_backend

class BarBackendTests(unittest.TestCase, BackendTests):
    def make_backend(self):
        # Create an instance of the "bar" backend:
        return bar_backend

rawDescription: How to run the same unittest suite with several backends

description: Run the same unittest suite with several backends


code:
with open('ip_list.txt') as f:
    IP_list = [line for line in f]

rawDescription: Comparing a set of IP addresses against subnets using python and netaddr module


code:
r = john
m.execute('SELECT in FROM table WHERE name=%s', (r, ))

date_in = m.fetchone()[0]
print(date_in)

rawDescription: (python and mysql) how do I manage to make the time spent between curent datetime and a certain datetime from mysql table?


code:
attrs = {field: CharField() for field in dict}
Dict2db = type('Dict2db', (Model,), attrs)

rawDescription: How create fields(columns in db) from a dictionary(iterating) with peewee


rawDescription: Easier way to produce a list out of a nested list?


code:
mylist = [{'id':1,'value':4},{'id':1,'value':6},{'id':2,'value':6},{'id':3,'value':9},{'id':3,'value':56},{'id':3,'v    alue':67},]
import itertools
[{'id': key, 'value': [x['value'] for x in grp]}
 for key, grp in itertools.groupby(mylist, key=lambda d: d['id'])]

rawDescription: how to merge values of python dict in a list of dictionaries

description: Merge values of python dict in a list of dictionaries


rawDescription: Perform a Django query on a part of a field


code:
import io
from zope.interface import implementer
from twisted.logger import (globalLogBeginner, Logger, jsonFileLogObserver,
                            ILogObserver, textFileLogObserver)

class Something(object):
    log = Logger()

    def doSomething(self, value):
        self.log.info("Doing something to {value}",
                      value=value)

@implementer(ILogObserver)
class RealTimeStatistics(object):
    def __init__(self):
        self.stats = []

    def __call__(self, event):
        if 'value' in event:
            self.stats.append(event['value'])

    def reportCurrent(self):
        print("Current Sum Is: " + repr(sum(self.stats)))

if __name__ == "__main__":
    stats = RealTimeStatistics()
    globalLogBeginner.beginLoggingTo([
        jsonFileLogObserver(io.open("log1.json", "ab")),
        textFileLogObserver(io.open("log2.txt", "ab")),
        stats, # here we pass our log observer
    ], redirectStandardIO=False)
    something = Something()
    something.doSomething(1)
    something.doSomething(2)
    something.doSomething(3)
    stats.reportCurrent()

rawDescription: How to Log to a variable or write observer that sends messages to variable in Twisted / Autobahn


code:
import numpy as np
a = np.arange(10)
a
b = a[::2]
b

rawDescription: numpy irregularly strided array

description: Numpy irregularly strided array


rawDescription: Querydict a string

description: Querydict a string


code:
import inspect

def get_class_that_defined_method(meth):
    for cls in inspect.getmro(meth.im_class):
        if meth.__name__ in cls.__dict__:
            return cls
    return None

rawDescription: Get class that defined method

description: Get class that defined method


code: from ftplib import FTP

rawDescription: SSH/SCP (Or similar) with python on raspberry pi


code:
parser_run = sub_parsers.add_parser("run")
parser_run.add_argument("-c", "--config", dest="config", required=True,
    help="specify the config file to use", )

parser_batch = sub_parsers.add_parser("batch")
parser_batch.add_argument("-b", "--batch-config", dest="config", required=True,
    help="specify the batch config file to use", )

for sub_parser in (parser_run, parser_batch):
    sub_parser.add_argument("--from", dest="start_step", default=0, type=int,
        help="Only step after this number will be processed")
    sub_parser.add_argument("--to", dest="end_step", default=100, type=int,
        help="Only step before this number will be processed ")
    sub_parser.add_argument("--skip", dest="skip_step", default="",
        help="Steps to skip, use comma as seperator")

    sub_parser.add_argument("-v", "--verbose-level", dest="verbose_level", type=int, default=2)
    sub_parser.add_argument("--dry-run", dest="dry_run", action="store_true", default=False)
    sub_parser.add_argument("--allow-dangling", dest="allow_dangling", action="store_true", default=False)
    sub_parser.add_argument("--resume", dest="resume", action="store_true", default=False)
    sub_parser.add_argument("--remove", dest="clean", action="store_true", default=False)

rawDescription: How to share args in two sub commands for argparser?

description: Share args in two sub commands for argparser


code: action = getattr(a, convert)

rawDescription: Python: Variable to access object orientation?


code:
class Tournament(db.Model):
   name = db.StringProperty(required = True)
   place = db.GeoPt()

class Teams(db.Model):
   belongs_to_tournament = db.ReferenceProperty(Tournament, collection_name =  'tournament_teams')
   name = db.StringProperty(required = True)
   players = db.IntegerProperty(required = True)
   price = db.FloatProperty(indexed=False)

rawDescription: Datastore modeling hierarchy for efficient queries


code:
def update(screen, entities, is_paused):
    if is_paused:
        if is_clicked_button(BUTTON_TO_UNPAUSE):
            is_paused = False
        return
    # Logic on screen, entities and so on...

rawDescription: How to make a pause screen in Pygame?

description: Make a pause screen in Pygame


code:
query_args = { 'origins':'2097 Honeysuckle Lane Southwest, Atlanta, GA 30311, USA',
           'destinations':'67 Fitzgerald Street Southeast, Atlanta, GA 30312, USA',
           'client':client_id,
           'departure_time':calendar.timegm(time.gmtime())
     }

rawDescription: Departure_time on Google Maps Distance Matrix API (Web Service) WITH Business license


code: print("Hello\rP")

rawDescription: stdout doesn't flushes on windows command prompt but works on osx and linux

description: Stdout doesn't flushes on windows command prompt but works on osx and linux


code:
import os
os.nice(20)

rawDescription: Nicing a running python process?

description: Nicing a running python process


code:
bin_of_aa = "{:b}".format(0xaa)
reg[2048:2055] = bitarray(bin_of_aa,endian="big")

rawDescription: Placing a new value into a section of a big Python bitarray


code:
fonts = doc.getElementsByTagName('font')

for font in fonts:
    # Create a new span
    span = doc.createElement("span")
    # Give it a class name based on the color (colors is a map)
    span.setAttribute("class", colors[font.getAttribute("color")])

    # Place all the children inside
    while(font.firstChild):
        span.appendChild(font.firstChild)
    # end while

    # Replace the <font> with a the <span>
    font.parentNode.replaceChild(span, font)

rawDescription: Python MiniDom not removing elements properly


code: call(["/bin/sed", "-i", "s/key=$/&val/", confPath])

rawDescription: adding value to key=value iff value not present, from python

description: Adding value to key=value iff value not present, from python


code:
IMAGES_STORE = 'you dir path where you want to download images'
ITEM_PIPELINES = ['scrapy.contrib.pipeline.images.ImagesPipeline'] #enable image pipline

rawDescription: downloading dynamic webcontent through Scrapy (python 2.7)

description: Downloading dynamic webcontent through Scrapy (python 2.7)


code:
from itertools import groupby
words = ['this', 'is', '', 'an', 'example']
[list(g) for k, g in groupby(words, ''.__ne__) if k]
[list(g) for k, g in groupby(words, 'is'.__ne__) if k]

rawDescription: Does Python come with a function to split a list using a delimiter?


code: user = 'Anonymous' if completion.is_anonymous else completion.user

rawDescription: Way to convert if-else statement into one-liner


code:
a2b2c = {}
for name in NameA5:
    a = int(name[43:47])
    b = int(name[48:53])
    c = int(name[55:58])

    if a not in a2b2c2name:
        a2b2c2name[a] = {}
    if b not in a2b2c2name[a]:
        a2b2c2name[a][b] = {}
    a2b2c2name[a][b][c] = True

for k in range(len(tbdata)):
    a = tbdata[k]['a']
    b = tbdata[k]['b']
    c = tbdata[k]['c']
    if a in a2b2c2name and b in a2b2c2name[a] and c in a2b2c2name[a][b]:
        Data.append(tbdata[k])

rawDescription: python fastest way to match strings with huge data size

description: Python fastest way to match strings with huge data size


code: print(mylist[:-n or None])

rawDescription: How to slice (in Python) "all but the last n" items when n may be zero?

description: Slice (in Python) "all but the last n" items when n may be zero


code:
for url in student_urls:
    yield Request(
        url=BASE_URL+url,
        callback=self.extract_person,
        priority=1
    )

rawDescription: Chaining requests with scrapy

description: Chaining requests with scrapy


code:
from igraph import Graph, mean
g = Graph.GRG(100, 0.2)
mean(g.degree())

rawDescription: Calculate average degree distribution

description: Calculate average degree distribution


code: df.C[df.B == 'x'] = df.C.shift(-1)

rawDescription: Can I set dataframe values without using iterrows()?

description: Set dataframe values without using iterrows()


code:
def __init__(self, rooms = None):
    if rooms is None:
        rooms = []
    self.rooms = rooms
    print('house created')

rawDescription: Object appended to a list instance appears in a different instance of that list


code:
import hashlib
s = "plain"
h = hashlib.sha1(s).hexdigest()

rawDescription: How to authenticate hashed(sha1) password in Python?

description: Authenticate hashed(sha1) password in Python


rawDescription: GUI: passing arguments to a function when pressing button


code:
bin_width = 0.1 # Depending on how narrow you want your bins

def get_avg(rad):
    average_intensity = intensities[(radius>=rad-bin_width/2.) & (radius<rad+bin_width/2.)].mean()
    return average_intensities

# This will return the average intensity in the bin: 27.95 <= rad < 28.05
average = get_avg(28.)

rawDescription: Python: histogram/ binning data from 2 arrays.


code:
with open('output.csv', 'wb') as output:
    writer = csv.writer(output)
    for each in stock_data:
        for key, value in each.iteritems():
            writer.writerow([key, value])

rawDescription: Writing list of dictionaries to CSV with each dictionary's values in a new column


code:
values = [1.4,1.5,1.6,1.8]
indices = [0,1]
a.newvalues = [values[i] for i in indices] if indices else [-1]

rawDescription: List comprehension- fill arbitrary value if list is empty


rawDescription: How to check if a path is absolute path or relative path in cross platform way with Python?

description: Check if a path is absolute path or relative path in cross platform way with Python


code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.0.1', 0))
s.connect(('...'))

rawDescription: Can Python select what network adapter when opening a socket?


code:
class Employee: pass
def foo(self): pass
Employee.foo = foo

rawDescription: python empty class object

description: Python empty class object


code:
from PIL import Image

png_image = Image.open('input.png')
saved_mode = png_image.mode
saved_size = png_image.size

# write string containing pixel data to file
with open('output.data', 'wb') as outf:
    outf.write(png_image.tostring())

# read that pixel data string back in from the file
with open('output.data', 'rb') as inf:
    data = inf.read()

# convert string back into Image and display it
im = Image.fromstring(saved_mode, saved_size, data)
im.show()

rawDescription: Displaying image from image raw data

description: Displaying image from image raw data


code:
from ctypes import CDLL
import Foo
try:
    MyLib = CDLL(Foo.__path__[0] + '/lib/libwhatever.so')
except OSError:
    from Foo import bar as MyLib

rawDescription: Path-independant management of shared C libs inside a Python package


code:
sphere = vtk.vtkSphereSource()
sphere.SetRadius(4)
sphere.SetCenter(0,0,1)
writer = vtk.vtkPolyDataWriter()
writer.SetInputData(sphere.GetOutput())
writer.SetFileName('mysphere.vtk')
writer.Update()

rawDescription: How to save a vtkSphere to a VTK file?

description: Save a vtkSphere to a VTK file


code:
from Tkinter import *

def odd_even():
    value1 = var1.get()
    value2 = var2.get()
    value3 = var3.get()
    chk_btn_value = value1 + value2 + value3

    if chk_btn_value == 0:
        changeable_label['text'] = "Null"
    elif chk_btn_value % 2 != 0:
        changeable_label['text'] = "Odd"
    else:
        changeable_label['text'] = "Even"

# Create a window
the_window = Tk()

# Give the window a title
the_window.title('Odd or Even')

##Some global variables
margin = 8
text = 'Null'

##Changing the size of the window
the_window.geometry("350x150")

##Making the label frame
labelframe = LabelFrame(the_window, bd = 3)
labelframe.grid(columnspan = 3, padx = margin, pady = margin)

##Adding the Label
changeable_label = Label(labelframe, text = text, font = ('Arial', 60),
                           fg = ('black'))
changeable_label.pack(side = TOP)

##Addind the Check Buttons

var1 = IntVar()
var2 = IntVar()
var3 = IntVar()

alpha = Checkbutton(the_window, text = 'Alpha', variable = var1,
                     command = odd_even)
alpha.grid(row = 1, column = 1)

beta = Checkbutton(the_window, text = 'Beta', variable = var2,
                     command = odd_even)
beta.grid(row = 1, column = 2)

gamma = Checkbutton(the_window, text = 'Gamma', variable = var3,
                     command = odd_even)
gamma.grid(row = 1, column = 3)

# Start the event loop
the_window.mainloop()

rawDescription: Can't get the function to work with checkbuttons using tkinter


code:
from easygui import msgbox, multenterbox

fieldNames = ["Name", "Street Address", "City", "State", "ZipCode"]
fieldValues = list(multenterbox(msg='Fill in values for the fields.', title='Enter', fields=(fieldNames)))
msgbox(msg=(fieldValues), title = "Results")

rawDescription: Python EasyGui : Returning User Input In TextBoxes


code:
for n, item in enumerate(player_hand):
    screen.blit(pygame.image.load(os.path.join('Images',item.name+'.png')), (100+n*10, 100))

rawDescription: Change image AND image position by using loops [python]


code:
from visual import *

floor = box (pos=(0,0,0), length=4, height=0.5, width=4, color=color.blue)
ball = sphere (pos=(0,4,0), radius=1, color=color.red)
ball.velocity = vector(0,-1,0)
dt = 0.01

while 1:
    rate (100)
    ball.pos = ball.pos + ball.velocity*dt
    if ball.y < ball.radius:
        ball.velocity.y = abs(ball.velocity.y)
    else:
        ball.velocity.y = ball.velocity.y - 9.8*dt

rawDescription: 3D animation using matplotlib that shows a body rotating about a fixed point


code:
from IPython.display import clear_output

for i in range(10):
    clear_output()
    print("Hello World!")

rawDescription: ipython notebook clear cell output in code

description: Ipython notebook clear cell output in code


code:
def f_create_port_data(a_swichport_data):
    v_port_data=[{}]
    v_switch_ports=[]
    for l_device_port_list in a_swichport_data:
        v_device_port_data=[]
        for device,key in l_device_port_list.iteritems():
            for vlan in l_device_port_list[device]:
                for port in l_device_port_list[device][0]['switch_ports']:
                    v_switch_ports.append(port['switch_name']+"="+port['name'])
            v_switch_ports_list=list(set(v_switch_ports))
            for l_port in v_switch_ports_list:
                v_vlan_list=[]
                v_location=l_port.split('=')
                for l_vlan in l_device_port_list[device]:
                    for l_switchport in l_vlan['switch_ports']:
                        if (v_location[0]==l_switchport['switch_name'] and v_location[1]==l_switchport['name']):
                            v_vlan_list.append(l_vlan['vlan_number'])
                if (not v_port_data[0].has_key(device)):
                    v_port_data[0][device]=list()
                    v_port_data[0][device].append(dict())
                if (not v_port_data[0][device][0].has_key(v_location[0])):
                    v_port_data[0][device][0][v_location[0]]=list()
                    v_port_data[0][device][0][v_location[0]].append(dict())
                if (not v_port_data[0][device][0][v_location[0]][0].has_key(v_location[1])):
                    v_port_data[0][device][0][v_location[0]][0][v_location[1]]=v_vlan_list

    return v_port_data

rawDescription: Python parse data for switch configuration


rawDescription: How to check if request type is ajax in flask

description: Check if request type is ajax in flask


code:
from glob import glob
from scipy import ndimage
from tifffile import imread, imsave

for filename in glob('*.tif'):
    i = imread(filename)
    i = ndimage.gaussian_filter(i[0], sigma=3)
    imsave('blurred_' + filename, i)

rawDescription: tifffile in Python not writing 16bit tiff

description: Tifffile in Python not writing 16bit tiff


code:
import matplotlib.ticker as ticker

# a is an axes object, from figure.get_axes()

# Hide major tick labels
a.xaxis.set_major_formatter(ticker.NullFormatter())

# Customize minor tick labels
a.xaxis.set_minor_locator(ticker.FixedLocator([1.5,2.5,3.5,4.5,5.5]))
a.xaxis.set_minor_formatter(ticker.FixedFormatter(['1','2','3','4','5']))

rawDescription: Centering x-tick labels between tick marks in matplotlib


rawDescription: Boolean subset in pandas

description: Boolean subset in pandas


code:
import re
inp = 'data[0][value]=123&data[0][Type]=Range&data[1][value]=345&data[1][Type]=Fixed'

matches = re.findall(r'\[([0-9]+)\]\[([a-zA-Z]+)\]=([a-zA-Z0-9]+)', inp)

out = {}
for match in matches:
    index, key, value = match
    if out.get(index) is None:
        out[index] = {}
    out[index][key] = value

data = out.values()

rawDescription: Convert String to Python List of Dictionary


code:
#!/usr/bin/python

import re

file_name = "" # put the txt file you're working on

new_header = None

for line in open(file_name,"r").readlines():
    if re.search("^[*][0-9]+[-][0-9]+[;]", line):
        if new_header:
            new_header.close()
        new_header = open("%s_section:%s" % (file_name, line), "w")
    if new_header:
        new_header.write(line)

if new_header:
    new_header.close

rawDescription: How can I split a text file by a specific string that has wilcards?

description: Split a text file by a specific string that has wilcards


code:
from PyQt4 import Qt, QtCore, QtGui
import threading
import socket
import Queue
import time

# Object of this class has to be shared between
# the two threads (Python and Qt one).
# Qt thread calls 'connect',
# Python thread calls 'emit'.
# The slot corresponding to the emitted signal
# will be called in Qt's thread.
class SafeConnector:
    def __init__(self):
        self._rsock, self._wsock = socket.socketpair()
        self._queue = Queue.Queue()
        self._qt_object = QtCore.QObject()
        self._notifier = QtCore.QSocketNotifier(self._rsock.fileno(),
                                                QtCore.QSocketNotifier.Read)
        self._notifier.activated.connect(self._recv)

    def connect(self, signal, receiver):
        QtCore.QObject.connect(self._qt_object, signal, receiver)

    # should be called by Python thread
    def emit(self, signal, args):
        self._queue.put((signal, args))
        self._wsock.send('!')

    # happens in Qt's main thread
    def _recv(self):
        self._rsock.recv(1)
        signal, args = self._queue.get()
        self._qt_object.emit(signal, args)

class PythonThread(threading.Thread):
    def __init__(self, connector, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)
        self.connector = connector
        self.daemon = True

    def emit_signal(self):
        self.connector.emit(QtCore.SIGNAL("test"), str(time.time()))

    def run(self):
        while True:
            time.sleep(1)
            self.emit_signal()

if __name__ == '__main__':
    app = QtGui.QApplication([])
    mainwin = QtGui.QMainWindow()
    label = QtGui.QLabel(mainwin)
    mainwin.setCentralWidget(label)

    connector = SafeConnector()
    python_thread = PythonThread(connector)
    connector.connect(QtCore.SIGNAL("test"), label.setText)
    python_thread.start()

    mainwin.show()
    app.exec_()

rawDescription: Emit signal in standard python thread

description: Emit signal in standard python thread


code:
import os
os.write(fd, os.linesep)

rawDescription: How to write native newline character to a file descriptor in Python?

description: Write native newline character to a file descriptor in Python


code:
def blank_to_count(iterable):
    counter = 0
    for val in iterable:
        if val == '':
            counter += 1
        else:
            if counter > 0: yield counter  # yield count of blank elements
            counter = 0
            yield val  # yield current non-blank element
    if counter > 0: yield counter  # in case last element was blank

py = ['','','','','monty','','','','python',]
print(list(blank_to_count(py)))  # [4, 'monty', 3, 'python']

py = ['monty','','','','python']
print(list(blank_to_count(py)))  # ['monty', 3, 'python']

py = ['','','','','monty','','','','python','','']
print(list(blank_to_count(py)))  # [4, 'monty', 3, 'python', 2]

rawDescription: replacing blank strings with count

description: Replacing blank strings with count


code:
def do_POST(s):
  global postVars
  s.send_response(200)
  s.end_headers()
  varLen = int(s.headers['Content-Length'])
  postVars = s.rfile.read(varLen)

rawDescription: Extending BaseHTTPRequestHandler - getting the posted data


code:
class A(object):
    @classmethod
    def test(cls):
       print("nope")

    @classmethod
    def test2(cls):
        cls.test()

class B(A):
    @classmethod
    def test(cls):
        print("It Works")

    @classmethod
    def run(cls):
        cls.test2()

if __name__ == "__main__":
    B.run()

rawDescription: Static inheritance python

description: Static inheritance python


code:
class Bspline(object):
    ...

    # Python2.7
    @memoize
    # or, Python3*
    @functools.lru_cache()
    def op(self, args):
        return self._internal_op(xi)

rawDescription: Memoize a single argument in Python method


code:
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import pyqtSlot

import matplotlib
matplotlib.use('Qt5Agg')
matplotlib.rcParams['backend.qt5'] = 'PyQt5'
matplotlib.rcParams.update({'figure.autolayout': True})
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

import numpy as np

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, **kwargs):
        super(MainWindow, self).__init__(**kwargs)

        # Construct the plots
        playout = QtWidgets.QGridLayout()
        playout.setContentsMargins(0, 0, 0, 0)
        for row in range(0, 10):
            for col in range(0, 10):
                fig = Figure()
                ax = fig.add_subplot(111)
                canvas = FigureCanvas(fig)
                canvas.mpl_connect('figure_enter_event', self.enterFigure)
                playout.addWidget(canvas, row, col, 1, 1)

                t = np.arange(-2*np.pi, 2*np.pi, step=0.01)
                ax.plot(t, np.sin(row*t) + np.cos(col*t))

        # Assign toolbar to first plot
        self.navbar = NavigationToolbar(playout.itemAtPosition(0, 0).widget(), self)

        cwidget = QtWidgets.QWidget()
        layout = QtWidgets.QVBoxLayout(cwidget)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.navbar)
        layout.addLayout(playout)
        self.setCentralWidget(cwidget)

    def enterFigure(self, event):
        self.navbar.canvas = event.canvas
        event.canvas.toolbar = self.navbar
        self.navbar._idDrag = event.canvas.mpl_connect('motion_notify_event', self.navbar.mouse_move)

        # Toggle control off and then on again for the current canvas
        if self.navbar._active:
            if self.navbar._active == 'PAN':
                self.navbar.pan()
                self.navbar.pan()
            elif self.navbar._active == 'ZOOM':
                self.navbar.zoom()
                self.navbar.zoom()

app = QtWidgets.QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()

rawDescription: How can I improve scrolling speed in matplotlib when a figure contains many axes?

description: Improve scrolling speed in matplotlib when a figure contains many axes


code:
while True:
   firstWord=words(stringIn)
   restWords=wordstrip(stringIn)
   #if the word to processed is the same as the input word then break
   if(restWords==stringIn) : break
   print(palindrome(firstWord))
   stringIn=restWords
   print(restWords)

rawDescription: Python How to Stop my Loop

description: Python How to Stop my Loop


code:
def Result(request):
    skills = request.GET['skill']
    country = request.GET['country']
    query_skills = Q(jsskills__skill__icontains=skills)
    query_country = Q(jspersonal__country__icontains=country)
    query_visibility = Q(jsdetails__visiblity=True)
    users = User.objects.filter(query_skills | query_country, query_visibility)
    return render_tor_response('sometemplate.html', {'users': users})

rawDescription: Django Filter data from multiple Models

description: Django Filter data from multiple Models


code:
import re
pattern = re.compile(r'foo\(.*?\)')
test_str = 'foo(123456) together with foo(2468)'

for match in re.findall(pattern, test_str):
    print(match)

rawDescription: Python - Extract pattern from string using RegEx


code:
import numpy as np
rfn.join_by('id', a, b, jointype='inner', usemask=False)

rawDescription: SQL join or R's merge() function in NumPy?


code:
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class MyUserAdmin(UserAdmin):

    def save_model(self, request, obj, form, change):
        # do whatever you want.
        # obj - the User instance to change
        # request.user - admin
        obj.save()

admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)

rawDescription: How to detect when admin modifies User in Django

description: Detect when admin modifies User in Django


code:
class Item (models.Model):
    capacity = models.IntegerField(
        default=500,
        validators=[MinValueValidator(0)],
        help_text="Total remaining quantity in stock."
    )
    total_purchased = models.IntegerField(
        default=0,
        help_text="Total items purchased."
    )

    def clean(self):
        """
        Ensures that total_purchased does not exceed the capacity
        """
        if self.total_purchased > self.capacity:
            raise ValidationError(
                'Total purchased can not exceed the capacity'
            )

rawDescription: Django 1.7.2 migration changes continuously detected


code:
ser = pd.Series([5,6,7,5,4], index=[3,2,1,4,5])
ser
ser._update_inplace(ser.sort_index())
ser

rawDescription: pandas: How to Series.sort_index() in-place?

description: Pandas: How to Series.sort_index() in-place


rawDescription: cupsfilter Does Not Work With Python subprocess.call()

description: Cupsfilter Does Not Work With Python subprocess.call()


code:
import sqlite3
import pandas as pd

# Open the file
f = open('output.csv', 'w')
# Create a connection and get a cursor
connection = sqlite3.connect('mydata.sql')
cursor = connection.cursor()
# Execute the query
cursor.execute('select * from mydata')
# Get data in batches
while True:
    # Read the data
    df = pd.DataFrame(cursor.fetchmany(1000))
    # We are done if there are no data
    if len(df) == 0:
        break
    # Let's write to the file
    else:
        df.to_csv(f, header=False)

# Clean up
f.close()
cursor.close()
connection.close()

rawDescription: export very large sql file into csv with Python or R

description: Export very large sql file into csv with Python or R


code: vpathways[k] = copy.deepcopy(v)

rawDescription: Copying compound objects in python

description: Copying compound objects in python


code:
on_off_status = 600

def Status (data):
    if data <= on_off_status:
        status = True
    elif data > on_off_status:
        status = False
    return (status)

while True:
    data = int(input("what is the status?: "))
    status = Status(data)
    print (status)

rawDescription: Using def and return in python 3

description: Using def and return in python 3


code:
Topiccenter.objects.annotate(num_books=Count('tc_books'),
                             num_journals=Count('tc_journals')
                             ).extra(
                                 select={'sum_entries':'num_books+num_journals'},
                                 order_by=('sum_entries',)
                             )

rawDescription: The annotation 'xy' conflicts with a field on the model - django


code:
l=[1,2,3]
' '.join(map(str,l))
string=' '.join(map(string,l))
map(int,string.split())

rawDescription: Changing up the contents of a list

description: Changing up the contents of a list


code:
list_val = '["apple", "blue", "green", "orange", "cherry", "white", "red", "violet"]'

from ast import literal_eval
list_val = literal_eval(list_val)
list_val[0]

rawDescription: Convert strings to list Python

description: Convert strings to list Python


code: from util import *

rawDescription: Instantiate all functions in Python

description: Instantiate all functions in Python


code:
date1 = datetime.datetime.utcnow()-datetime.timedelta(minutes=15)
for cursor in sensors.find({'Date':{"$gte": date1}}):
    ...

rawDescription: MongoDB and PyMongo - Searching for documents from a given date and time


code:
def consecutiveLetters(word):
    currentMaxCount = 1
    maxChar = ''
    tempCount = 1

    for i in range(0, len(word) - 2):
        if(word[i] == word[i+1]):
            tempCount += 1
            if tempCount > currentMaxCount:
                currentMaxCount = tempCount
                maxChar = word[i]
        else:
            currentMaxCount = 1

    return [maxChar,tempCount]

result = consecutiveLetters("TATAAAAAAATGACA")

print("The max consecutive letter is ", result[0] , " that appears ", result[1], " times.")

rawDescription: Finding consecutive letters in a list

description: Finding consecutive letters in a list


code:
import unicodedata
import urllib
name = u"Müller.jpg"
urllib.quote(unicodedata.normalize('NFD', name).encode('utf-8'))
urllib.quote(unicodedata.normalize('NFKD', name).encode('utf-8'))

rawDescription: AWS S3 special characters encoding

description: AWS S3 special characters encoding


code:
import numpy
from PIL import Image, ImageDraw

# read image as RGB and add alpha (transparency)
im = Image.open("crop.jpg").convert("RGBA")

# convert to numpy (for convenience)
imArray = numpy.asarray(im)

# create mask
polygon = [(444,203),(623,243),(691,177),(581,26),(482,42)]
maskIm = Image.new('L', (imArray.shape[1], imArray.shape[0]), 0)
ImageDraw.Draw(maskIm).polygon(polygon, outline=1, fill=1)
mask = numpy.array(maskIm)

# assemble new image (uint8: 0-255)
newImArray = numpy.empty(imArray.shape,dtype='uint8')

# colors (three first columns, RGB)
newImArray[:,:,:3] = imArray[:,:,:3]

# transparency (4th column)
newImArray[:,:,3] = mask*255

# back to Image from numpy
newIm = Image.fromarray(newImArray, "RGBA")
newIm.save("out.png")

rawDescription: Polygon crop/clip using Python / PIL

description: Polygon crop/clip using Python / PIL


code:
search_terms = ['word', 'cow', 'horse']

library = [['desk', 'chair', 'lamp'],
           ['cow', 'horse', 'word 223', 'barn']]

hits = [l for l in library if
        all(any(t in s for s in l)
            for t in search_terms)]

rawDescription: print a sublist that contains all strings in another list, without necessarily being a direct match

description: Print a sublist that contains all strings in another list, without necessarily being a direct match


code:
if sys.platform.startswith('win') or sys.platform.startswith('cygwin'):
    do_windows_stuff()
elif sys.platform.startswith('darwin'):
    do_osx_stuff()
elif sys.platform.startswith('linux'):
    do_linux_stuff()
else:
    raise Exception("Nobody's written the stuff for {}, sorry".format(sys.platform))

rawDescription: Create python script that runs at startup


code:
s = your_string
s.split()
url = [i for i in s.split() if i.startswith('http://')]
url
tags = [i for i in s.split() if i.startswith('#')]
tags
' '.join(i for i in s.split() if i not in url+tags)

rawDescription: Split Twitter RSS string using Python

description: Split Twitter RSS string using Python


code:
def title():
    text = """
     A children song
    """
    print(text)

def verse1():
    text = """
    There was an old lady who swallowed a fly.
    I don't know why she swallowed the fly.
    Perhaps she'll die.
    """
    print(text)

def verse2():
    text = """
    There was an old lady who swallowed a spider,
    That wriggled and jiggled and tickled inside her.
    She swallowed the spider to catch the fly.
    I don't know why she swallowed the fly.
    Perhaps she'll die.
    """
    print(text)
def verse3():
    text = """
    There was an old lady who swallowed a bird.
    How absurd to swallow a bird.
    She swallowed the bird to catch the spider,
    That wriggled and jiggled and tickled inside her.
    She swallowed the spider to catch the fly.
    I don't know why she swallowed the fly.
    Perhaps she'll die.
    """
    print(text)

def verse4():
    text = """
    There was an old lady who swallowed a cat.
    Imagine that to swallow a cat.
    She swallowed the cat to catch the bird.
    She swallowed the bird to catch the spider,
    That wriggled and jiggled and tickled inside her.
    She swallowed the spider to catch the fly.
    I don't know why she swallowed the fly.
    Perhaps she'll die.
    """
    print(text)
def verse5():
    text = """
    There was an old lady who swallowed a dog.
    My, what a hog, to swallow a dog.
    She swallowed the dog to catch the cat.
    She swallowed the cat to catch the bird.
    She swallowed the bird to catch the spider,
    That wriggled and jiggled and tickled inside her.
    She swallowed the spider to catch the fly.
    I don't know why she swallowed the fly.
    Perhaps she'll die.
    """
    print(text)

def lastverse():
    text = """
    There was an old lady who swallowed a horse.
    She's dead, of course.
    """
    print(text)

def main():
    title()  # print the title
    verse1()  # fly verse
    verse2()  # spider verse
    verse3()  # bird verse
    verse4()  # cat verse
    verse5()  # dog verse
    lastverse()  # horse verse

main()

rawDescription: Writing a script for Python 3: A children song


code: b = lambda:0

rawDescription: struct objects in python

description: Struct objects in python


code:
import copy

def group_and_split(mydata, static_mapping):
    remainder = copy.deepcopy(mydata)
    couples = []
    for couple in static_mapping:
        if couple[0] in mydata and couple[1] in mydata:
            remainder.remove(couple[0])
            remainder.remove(couple[1])
            couples.append(couple)
    return [couples, remainder]

rawDescription: Python: group a list basing on pairs of items


rawDescription: Connect QPushButton of QWizardPage with NextButton of QWizard


code:
ALLOWED_ARGS = {"repr", "str", "unicode"}
funcs = {f: getattr(__builtins__, f) for f in ALLOWED_ARGS}
# funcs.update({"custom": custom_func})

# I'd also assert on all functions having the same arity,
# but this is tricky with builtins...

func = funcs[sys.argv[1]]

rawDescription: Using global dictionary seems bad, but why exactly?


code:
def application(environ, start_response):
    os.environ['ssl_client_s_dn'] = environ['ssl_client_s_dn']
    return _application(environ, start_response)

rawDescription: Django not recognizing ssl related os.environ


code:
s = Sound()
s.read('mymusic.mp3')
s.play()

rawDescription: Sound on [every global] keypress (linux)


rawDescription: Python min() function grabbing highest number


code: status, output = commands.getstatusoutput("mvn clean install -s./../../foo/bar/settings.xml -Dportal -Dmain.dir=%s/../.. -o" % os.getcwd ())

rawDescription: What is the correct way to "pipe" Maven's output in Python to the screen when used in a Python shell script?


code:
DATE_FORMAT = '%m/%d/%y'

class DatePickerWidget(widgets.Widget):
    def render(self, name, value, attrs=None):
        if value is None:
            vstr = ''
        elif hasattr(value, 'strftime'):
            vstr = datetime_safe.new_datetime(value).strftime(DATE_FORMAT)
        else:
            vstr = value
        id = "id_%s" % name
        args = [
            "<input type=\"text\" value=\"%s\" name=\"%s\" id=\"%s\" />" % \
            (vstr, name, id),
            "<script type=\"text/javascript\">$(\"#%s\").datepicker({dateFormat:'mm/dd/y'});</script>" % id
            ]
        return mark_safe("\n".join(args))

rawDescription: What should "value_from_datadict" method of a custom form widget return?


code:
A = [1,1,1,-1,-1,-1,-1,1,1,1,-1,-1]
AA = ['a','a','b','b','b','a','b','b','b','b','b','a','a']
var = 0
counter = 0
B = []
BB = []
for num, val in enumerate(A):
    if var:
        if var==val:
            count = count + val
        else:
            var = val
            B.append(count)
            count = val
    else:
        var = val
        count = val
    if num == len(A) - 1:
        B.append(count)

var = 0
counter = 0
for num, val in enumerate(AA):
    if var:
        if var==val:
            count = count + 1
        else:
            BB.append([var, count])
            var = val
            count = 1
    else:
        var = val
        count = 1
    if num == len(AA) - 1:
        BB.append([val, count])

rawDescription: Count the elements in list & array in succession


code: retval, foundPattern = next(((True, pattern) for pattern in patterns  if pattern in text), (False, None))

rawDescription: Doing an assigment within python next()

description: Doing an assigment within python next()


code:
# For sequences
any(y is item for item in container)

# For sets, short circuit first for the not-present case:
# (note that you normally should not need this as you are supposed to rely on the hash)
y in setcontainer and any(y is item for item in setcontainer)

# For mappings, y is a key
y in mapping

# For mappings, y is a value, and you do not have a key, fall back to any
any(y is item for item in mapping.itervalues())

rawDescription: Do python lists have an equivalent for __contains__ that tests for identity?


code:
from folder1 import module_name as mod

for name, cls in mod.__dict__.items():
                if isinstance(cls, type):
                    klass = getattr(mod, name)

rawDescription: Get a list of custom classes in Python?

description: Get a list of custom classes in Python


code: package-cleanup -y --oldkernels

rawDescription: Continue execution of a Python update script without waiting for user input


code:
with open('list1.txt', 'r') as l1, open('list2.txt', 'r') as l2, open('list3.txt', 'w') as l3:
    for left_part in l1:
        for right_part in l2:
            l3.write('%s%s\n' % (left_part.replace("\n",""), right_part.replace("\n","")))
        l2.seek(0)

rawDescription: Generate Cartesian product of each word from file1 x file2


code:
for keypoint in kp:
    print(keypoint.angle)
    print(keypoint.class_id)
    # ...

rawDescription: Extracting pixel values from keypoints generated by ORB in OpenCV Python


rawDescription: Python Image Library convert from Jpeg to PDF


code:
from lxml import etree
print(etree.tostring(root, pretty_print=True))

rawDescription: Get the inner HTML of a element in lxml

description: Get the inner HTML of a element in lxml


code:
#!/usr/bin/env python
__author__ = "Luke Jones"
__copyright__ = "Copyleft, do what you want with it"
__license__ = "GPL"
__version__ = "0.0.1"

while True:
    startV = int(input("Enter a size : "))
    array1=[]
    array2=[]
    for i in range(1,startV+1,2):
        array1.append(i)
    array2 = list(array1)
    array2.reverse()
    n = len(array1)

    for i in range(n*2): # ROWS
        for j in range(n*2): # COLUMNS
            if j < n-i: # TOP LEFT
                print(array1[j+i], end=" ")

            elif j >= n+i: # TOP RIGHT
                print(array2[j-n-i], end=" ")

            elif i >= n+j: # BOTTOM LEFT
                print(array2[i-n-j], end=" ")

            elif i >= n*2-j+n-1 and not i >= n*2-j+n:
                #print("X",end=" ")
                for q in range(n*2-j):
                    print(array2[q], end=" ")
            else:
                print(" ", end=" ")
        print()

rawDescription: Console print a scaling square with roatated square in the middle


code:
class Dummy(object):
    pass
foo = Dummy()
if False:
    foo()
foo.__call__ = lambda self: 'meow'
foo.x = 'y'
foo()

rawDescription: vim syntax highlighting for python variables and functions?

description: Vim syntax highlighting for python variables and functions


code:
import wx
import  wx.lib.scrolledpanel as scrolled

class ImageDlg(wx.Dialog):
    def __init__(self, parent, title):
        wx.Dialog.__init__(self, parent=parent,title=title, size=wx.DefaultSize)

        self.scrollPnl = scrolled.ScrolledPanel(self, -1, size=(200, 200), style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)

        self.addBtn = wx.Button(self, id=wx.ID_ADD)
        self.Bind(wx.EVT_BUTTON, self.on_add, self.addBtn)

        self.mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.scrollPnlSizer = wx.BoxSizer(wx.VERTICAL)
        img = wx.Image("image.jpg", wx.BITMAP_TYPE_ANY)
        staticBitmap = wx.StaticBitmap(self.scrollPnl, wx.ID_ANY, wx.BitmapFromImage(img))
        self.scrollPnlSizer.Add(staticBitmap, 1, wx.EXPAND | wx.ALL, 3)

        self.mainSizer.Add(self.addBtn)
        self.mainSizer.Add(self.scrollPnl)

        self.SetSizerAndFit(self.mainSizer)

    def on_add(self, event):
        img = wx.Image("image.jpg", wx.BITMAP_TYPE_ANY)
        staticBitmap = wx.StaticBitmap(self.scrollPnl, wx.ID_ANY, wx.BitmapFromImage(img))
        self.scrollPnlSizer.Add(staticBitmap, 1, wx.EXPAND | wx.ALL, 3)
        self.scrollPnl.SetSizer(self.scrollPnlSizer)
        self.scrollPnl.SetAutoLayout(1)
        self.scrollPnl.SetupScrolling()

        self.Refresh()
        self.Layout()

class TestPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent)

        openDlg_btn = wx.Button(self, label="Open Dialog")
        self.Bind(wx.EVT_BUTTON, self.onBtn)

        mainSizer = wx.BoxSizer(wx.HORIZONTAL)
        mainSizer.Add(openDlg_btn, 0, wx.ALL, 10)
        self.SetSizerAndFit(mainSizer)
        self.Centre()

    def onBtn(self, event):
        dlg = ImageDlg(self, title='Image Dialog')
        dlg.SetSize((300,300))

        dlg.CenterOnScreen()
        dlg.ShowModal()
        dlg.Destroy()

class TestFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        TestPanel(self)

if __name__ == "__main__":

    app = wx.PySimpleApp()
    frame = TestFrame(None)
    frame.Show()
    app.MainLoop()

rawDescription: How to add items to wx.ScrolledPanel?

description: Add items to wx.ScrolledPanel


code:
#!/usr/local/bin/python3
word=input("Enter string: ")
with open('input.txt') as f:
  key = {}
  for line in f:
    first, second = line.split()
    key[first] = second
for replacement in key:
    word=word.replace(replacement,key[replacement])

print(word)

rawDescription: replacing values from file python

description: Replacing values from file python


code:
x.value = 3
Si[0].value

rawDescription: Python: How do i find an equation's value for a given input


code:
categories_to_count = [('tito', 'puente'),
                       ('bar',),
                       ('feep',)]

df['has_category'] = np.where(X['category'].isin(categories_to_count), 1, 0)

df.groupby('group')['has_category'].apply(lambda x: x.expanding().sum())

rawDescription: Pandas expanding count of string occurrence by group


code:
def update_label(self):
    self.label.configure(cpuTemp)
    self.root.after(1000, self.update_label)

rawDescription: Make tkinter label refresh at set time intervals without input


code:
from collections import defaultdict

by_token = defaultdict(lambda: defaultdict(set))

for tag, token_values in d.items():
    for token, value in token_values.items():
        by_token[token][value].add(tag)

for token, by_value in by_token.items():
    value, tags = max(by_value.items())
    for tag in tags:
        print('{} {} {}'.format(token, tag, value))

rawDescription: check if two inner keys in nested dictionaries are duplicates and retrieve only the highest value

description: Check if two inner keys in nested dictionaries are duplicates and retrieve only the highest value


code:
foo = type('Foo', (), {})()
foo

rawDescription: Create a blank class instance without class definition


code:
boolean_array = np.array([True, False, False, True])
float_array = np.ones(4) * 1.0
float_array
float_array[boolean_array] = 0
float_array

rawDescription: Conditionally Replace Elements of an Array Depending on the Contents of Another Array


code: sent = [word for line in f for word in line.lower().split()]

rawDescription: Converting sentences in a file to word tokens in a list


code: process = subprocess.Popen([path_to_acrobat, '/n', '/A', 'page=' + page, path_to_pdf], shell=False, stdout=subprocess.PIPE)

rawDescription: How to change page of already open pdf in python

description: Change page of already open pdf in python


rawDescription: Creating labels where line appears in matplotlib figure


code:
def maximum (A, B):
    BisBigger = A-B
    BisBigger.data = np.where(BisBigger.data < 0, 1, 0)
    return A - A.multiply(BisBigger) + B.multiply(BisBigger)

rawDescription: Element-wise maximum of two sparse matrices


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

df = pd.DataFrame({'x':range(0, 100, 20),
                   'y':np.random.randint(0,100,5)})

rows, cols = df.shape
fig, ax = plt.subplots(figsize=(50/10,25/10))
df.plot(ax=ax)

for col in range(cols):
    for i in range(rows):
        ax.annotate('{}'.format(df.iloc[i, col]), xy=(i, df.iloc[i, col]))
plt.xticks(rotation=45, fontsize=8)
plt.yticks(fontsize=8)

plt.show()

rawDescription: Add text annotation to matplotlib plot from a pandas dataframe


code:
original = parser.close()
...

thumb1 = original.copy()
size = (75,75)
thumb1.thumbnail(size, Image.ANTIALIAS)
...

thumb2 = original.copy()
thumbnail2 = original.resize(size2, Image.ANTIALIAS)
...

rawDescription: Resize image twice in Django using PIL

description: Resize image twice in Django using PIL


code:
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class Combo(QtGui.QComboBox):
    def __init__(self, *args, **kwargs):
        super(Combo, self).__init__()
        self.addItems(['Item_1','Item_2','Item_3','Item_4','Item_5'])
        self.show()

    def hidePopup (self):
        pass

inst=Combo()
sys.exit(app.exec_())

rawDescription: How to cause QComboBox pull-down menu to stay open

description: Cause QComboBox pull-down menu to stay open


rawDescription: In Python, how can you get the name of a member function's class?


code:
import os
chidren = []
for job in jobs:
    child = os.fork()
    if child:
        children.append(child)
    else:
        pass  # really should exec the job
for child in children:
    os.waitpid(child, 0)

rawDescription: What is the best way to run multiple subprocesses via fork()?


code:
class MyFoo(object):
    def __init__(self):
        self._data = {}
    def __setitem__(self, a, b):
        self._data[a] = b
    def __getitem__(self, a):
        return self._data[a]
    def __delitem__(self, a):
        del self._data[a]
    def populate(self, d):
       if d:
          for k,v in d.iteritems():
              self[k] = v
headers = {'User-Agent': 'Python/2.7.5'}
a = MyFoo()
a.populate(headers)
a['User-Agent']

rawDescription: Python what does self[name] = value means?


code:
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import pyqtSignal
import time
import sys
import threading

def logthread(caller):
    print('%-25s: %s, %s,' % (caller, QtCore.QThread.currentThread(), int(QtCore.QThread.currentThreadId())))
    print('%-25s: %s, %s,' % (caller, threading.current_thread().name, threading.current_thread().ident))

class Worker(QtCore.QObject):
    done = pyqtSignal()

    def __init__(self, parent=None):
        logthread('worker.__init__')
        super(Worker, self).__init__(parent)

    def run(self, m=10):
        logthread('worker.run')
        for x in range(m):
            y = x + 2
            time.sleep(0.001)
        logthread('worker.run finished')

        self.done.emit()

class MainWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        logthread('mainwin.__init__')
        super(MainWindow, self).__init__(parent)

        self.worker = Worker()
        self.workerThread = None

        self.btn = QtGui.QPushButton('Start worker in thread')
        self.btn2 = QtGui.QPushButton('Run worker here')
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.btn)
        layout.addWidget(self.btn2)

        self.run()

    def run(self):
        logthread('mainwin.run')

        self.workerThread = QtCore.QThread()
        self.worker.moveToThread(self.workerThread)
        self.worker.done.connect(self.workerDone)
        self.btn.clicked.connect(self.worker.run)
        self.btn2.clicked.connect(self.runWorkerHere)

        self.workerThread.start()
        self.show()

    def workerDone(self):
        logthread('mainwin.workerDone')

    def runWorkerHere(self):
        logthread('mainwin.runWorkerHere')
        worker = Worker()
        worker.done.connect(self.workerDone)
        worker.run()
        # self.worker.run()

if __name__ == '__main__':
    app = QtGui.QApplication([])
    logthread('main')

    window = MainWindow()
    sys.exit(app.exec_())

rawDescription: Proper use of QThread.currentThreadId()

description: Proper use of QThread.currentThreadId()


code:
#!/usr/bin/env python
import urllib
from multiprocessing import Pool
from posixpath import basename
from urllib import unquote
from urlparse import urlsplit

download_dir = "grabNew"

def url2filename(url):
    return basename(unquote(urlsplit(url).path).decode('utf-8'))

def download_image(url):
    filename = None
    try:
        filename = os.path.join(download_dir, url2filename(url))
        return urllib.urlretrieve(url, filename), None
    except Exception as e:
        return (filename, None), e

def main():
    pool = Pool(processes=10)
    for (filename, headers), error in pool.imap_unordered(download_image, get_urls()):
        pass # do something with the downloaded file or handle an error

if __name__ == "__main__":
   main()

rawDescription: Python Multithreading Not Functioning

description: Python Multithreading Not Functioning


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

from PyQt4 import QtCore, QtGui

class myWindow(QtGui.QWidget):

    def __init__(self, parent=None):
        super(myWindow, self).__init__(parent)

        self.setStyleSheet( """ QListWidget:item:selected:active {
                                     background: blue;
                                }
                                QListWidget:item:selected:!active {
                                     background: gray;
                                }
                                QListWidget:item:selected:disabled {
                                     background: gray;
                                }
                                QListWidget:item:selected:!disabled {
                                     background: blue;
                                }
                                """
                                )

        self.listWidget = QtGui.QListWidget(self)
        self.listWidget.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)

        self.button = QtGui.QPushButton(self)
        self.button.setText("Disable the list!")
        self.button.clicked.connect(self.on_button_clicked)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.button)
        self.layout.addWidget(self.listWidget)

        for itemNumber in range(5):
            item = QtGui.QListWidgetItem(self.listWidget)
            item.setText("Item {0}".format(itemNumber))
            self.listWidget.addItem(item)

    @QtCore.pyqtSlot()
    def on_button_clicked(self):
        enable = False if self.listWidget.isEnabled() else True

        self.listWidget.setEnabled(enable)

if __name__ == "__main__":
    import sys

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

    main = myWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: How do I achieve consistent highlighting of QListWidget items across widget states?

description: Achieve consistent highlighting of QListWidget items across widget states


code:
max_len = max_size / bytes_per_char
s = ''
i = 0
while len(s) < max_len:
    s += str(i) + '\r\n'
    i += 1
if len(s) > max_len: # because it may not divide evenly
    s = s[:max_len]
open(filename, "wb").write(s)

rawDescription: Creating a file of a specific size with incrementing alphabets/numbers in python.


code: sorted((value, id1, id2) for id1, d1 in d.items() for id2, value in d1.items())

rawDescription: reverse sort a 2d dict by value

description: Reverse sort a 2d dict by value


code:
import pygame
from tkinter import *  # not advisable to import everything with *
from tkinter import filedialog

pygame.mixer.init() # initializing the mixer

root = Tk()

audio_file_name = ''

def open_masker():
    global audio_file_name
    audio_file_name = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"),   ("All Files", "*.*")))

def masker_screen():
    # we will also use the audio_file_name global variable
    global m_screen, audio_file_name

    m_screen = Toplevel(root)
    m_screen.geometry('600x600')
    m_screen.transient(root)
    m_label = Label(m_screen, text = "Playing New Masker Noise")
    m_label.pack(anchor = CENTER)

    if audio_file_name: # play sound if just not an empty string
        noise = pygame.mixer.Sound(audio_file_name)
        noise.play(0, 5000)

b1 = Button(root, text = 'open file',command = open_masker)
# does not make sense to call pack directly
# and stored the result in a variable, which would be None
b1.pack(anchor=CENTER)

Button(root, text = 'continue', command = masker_screen).pack(anchor = E)

root.mainloop()

rawDescription: Loading an audio file using file dialog and playing it with pygame


code:
def parse(self, response):
    ...
    yield Request(Link,
                  meta={'date': Date},
                  callback = self.parseOneCar)

def parseOneCar(self, response):
    ...
    Date = response.meta['date']

rawDescription: python scrapy sending data from function to function

description: Python scrapy sending data from function to function


code:
import re
re.findall("^[0-9]{3}[a-zA-Z]{3}$", yourString)

rawDescription: How to match this expression with regex

description: Match this expression with regex


code:
from jug import TaskGenerator
import pandas as pd
import numpy as np

@TaskGenerator
def gendata():
    return pd.DataFrame(np.arange(343440).reshape((10,-1)))

@TaskGenerator
def compute(x):
    return x.mean()

y = compute(gendata())

rawDescription: Pandas memoization

description: Pandas memoization


code:
from collections import defaultdict

data = [['A','B','C','D','E'],
        ['A','B','C'],
        ['A','B','C','E'],
        ['C','D','E'],
        ['C','D','E','B','A']]
characters = [i for j in data for i in j]
counts = {}
combinations = defaultdict(int)
for character in set(characters):
    counts[character] = characters.count(character)
    for character2 in set(characters):
        for entry in data:
            combination = [character, character2]
            if "".join(combination) in "".join(entry):
                combinations[tuple(combination)] += 1
probability = {i: combinations[i]/float(counts[i[0]]) for i in combinations}
probability

{('A', 'B'): 0.75,
  ('B', 'A'): 0.25,
  ('B', 'C'): 0.75,
  ('C', 'D'): 0.6,
  ('C', 'E'): 0.2,
  ('D', 'E'): 1.0,
  ('E', 'B'): 0.25}

rawDescription: Probability of consecutive occurrences of characters


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

from __future__ import print_function

import readline
import threading

PROMPT = '> '

def interrupt():
    print() # Don't want to end up on the same line the user is typing on.
    print('Interrupting cow -- moo!')
    print(PROMPT, readline.get_line_buffer(), sep='', end='')

def cli():
    while True:
        cli = str(raw_input(PROMPT))

if __name__ == '__main__':
    threading.Thread(target=cli).start()
    threading.Timer(2, interrupt).start()

rawDescription: How to implement a python REPL that nicely handles asynchronous output?

description: Implement a python REPL that nicely handles asynchronous output


code: request = urllib2.Request('http://localhost:8080/manager/deploy?path=/war_file', data=war_file_contents)

rawDescription: deploying a war to tomcat using python

description: Deploying a war to tomcat using python