code:
from urllib import urlencode
a = range(3)
urlencode({'test': a})
urlencode({'test': a}, True)

rawDescription: How can i convert the dictionary items into flat strings in python

description: Convert the dictionary items into flat strings in python


code:
for line in open('file'):
    for word in line.split():
        do_stuff(word)

rawDescription: Iterating over full text lines instead of characters


code: Rule(SgmlLinkExtractor(allow=("ShowUserReviews-g.*",), restrict_xpaths=('//*[@id="REVIEWS"]/div[4]/div/div[2]/div/div/div[1]/a[text() = "Next"]',), unique=True), callback='parse_item', follow= True)

rawDescription: Scrapy: re-crawling with the same rule

description: Scrapy: re-crawling with the same rule


code:
test = []

for a in range(2, sh1.nrows):
    row = []
    for b in range(0, sh1.ncols):
        row.append(sh1.cell(a, b).value)
    test.append(row)

print(test)

rawDescription: How do I create an array of multiple values extracted from the rows and columns of excel

description: Create an array of multiple values extracted from the rows and columns of excel


code:
def game_start():
    cr = 100
    while cr > 0:
        bet = input('[- digit the num of coins to bet -] \n or enter q to quit')
        if bet == "q": # if user wants to quit they can enter q
            print("Thanks for playing, you are leaving with ${}".format(cr))
            return # leaves/ends the function
        try: # use try/except to cast to int to catch illegal input
           bet = int(bet)
        except ValueError:
            print("Invalid input")
            continue
        if bet <= cr: # make sure we have enough credit
            cr -= bet
            first_n = random.randint(0, 9)
            second_n = random.randint(0, 9)
            third_n = random.randint(0, 9)
            fourth_n = random.randint(0, 9)
            fifth_n = random.randint(0, 9)
            slot[4][2] = str(first_n)
            slot[4][3] = str(second_n)
            slot[4][4] = str(third_n)
            slot[4][5] = str(fourth_n)
            slot[4][6] = str(fifth_n)
        else: # if we get here we tried to bet too much so use continue to go back to start of loop and ask for bet again
            print("You don't have that much credit")
            continue
        # if we get here all is good
        if len({first_n,second_n,third_n,fourth_n,fifth_n}) == 1: # sets don't have dups so if we have five that are equal we will only have one element
                cr += bet * 100
                time.sleep(1)
                print('[- play simple slot machine game -]')
                time.sleep(1)
                print('[- with five identical n you win -]')
                time.sleep(1)
                print_slot(slot)
                time.sleep(1)
                print('[- with five identical n you win -]')
                time.sleep(1)
                print('[- you won!!! now you have ' + str(cr) + 'cr -]')
        else: # if we did not have a winning spin we will get here
            print("Hard Luck, You have {} credit left".format(cr))
    # this will print if we run out of credit
    print('[- you ran out of money 2 bet :( -]')

rawDescription: Loop issue and odd code in my Python slot machine


code:
pa['a'].str[0] #first value in lists
pa['a'].str[-1] #last value in lists

rawDescription: Python Pandas: selecting element in array column


code:
for job in jobs:
    job.join()

rawDescription: Wait for all multiprocessing jobs to finish before continuing


code:
thing, created = Thing.object.update_or_create(
    unique_id=dict1['unique_key'],
    defaults={'property': dict1['other_key']}
)

rawDescription: django orm - check if dictionary key exists in a model field?

description: Django orm - check if dictionary key exists in a model field


code:
from numpy.lib.stride_tricks import as_strided
arr = np.random.rand(256, 256)
mask = np.random.rand(3, 3)
arr_view = as_strided(arr, shape=(254, 254, 3, 3), strides=arr.strides*2)

arr[1:-1, 1:-1] = np.einsum('ijkl,kl->ij', arr_view, mask)

rawDescription: How to perform iterative 2D operation on 4D numpy array

description: Perform iterative 2D operation on 4D numpy array


code:
import array

BITS_PER_ITEM = array.array('I').itemsize * 8

def make_bit_array(num_bits, initially=0):
    num_items = (num_bits + BITS_PER_ITEM - 1) // BITS_PER_ITEM
    return array.array('I', [initially]) * num_items

def set_bit(bit_array, offset):
    item_index = offset // BITS_PER_ITEM
    bit_index = offset % BITS_PER_ITEM
    bit_array[item_index] |= 1 << bit_index

def clear_bit(bit_array, offset):
    item_index = offset // BITS_PER_ITEM
    bit_index = offset % BITS_PER_ITEM
    bit_array[item_index] &= ~(1 << bit_index)

def get_bit(bit_array, offset):
    item_index = offset // BITS_PER_ITEM
    bit_index = offset % BITS_PER_ITEM
    return (bit_array[item_index] >> bit_index) & 1

rawDescription: Massive Python set of integers using too much memory


code:
from multiprocessing import Process, Queue

def multiply(a,b,que): #add a argument to function for assigning a queue
    que.put(a*b) #we're putting return value into queue

if __name__ == '__main__':
    queue1 = Queue() #create a queue object
    p = Process(target= multiply, args= (5,4,queue1)) #we're setting 3rd argument to queue1
    p.start()
    print(queue1.get()) #and we're getting return value: 20
    p.join()
    print("ok.")

rawDescription: Assigning return value of function to a variable, with multiprocessing? And a problem about IDLE?


code:
class ObjectAdmin(admin.ModelAdmin):
    ordering = ['-order']
    #            ^

rawDescription: Django admin ordering in reverse

description: Django admin ordering in reverse


code:
solutions = sympy.solve(eqs, exclude=[kp1, kp2])
for data_kp1, data_kp2 in data:
    for key, eq in solutions:
        solution = eq.subs([(kp1, data_kp1), (kp2, data_kp2)])
        final_solutions.append("{key}={solution}".format(key=key, solution=solution))

rawDescription: Speed up SymPy equation solver

description: Speed up SymPy equation solver


code:
import re

s = 'word1 word2 My_WORD_HERE word1'
word = 'My_WORD_HERE'
wnb = 3

pat = r'((?:\w+\s+){{0,{0}}}){1}((?:\s+\w+){{0,{0}}})'.format(wnb, word)

res = re.sub(pat, lambda m:
    m.group(1) +
    '? '*(wnb-len(m.group(1).split())) +
    word + m.group(2) +
    ' ?'*(wnb-len(m.group(2).split())), s)

rawDescription: how to keep length of ReqEX output stable in case of missing data, python2.7

description: Keep length of ReqEX output stable in case of missing data, python2.7


code:
if __name__ == "__main__":
    from Bio import SeqIO
    path = '/path/to/sequences.txt'
    sequences = [str(record.seq) for record in  SeqIO.parse(path, 'fasta')]
    sys.argv = ['-f'] + sequences
    main()

rawDescription: How to call module written with argparse in iPython notebook

description: Call module written with argparse in iPython notebook


code:
class TestMonitorWriter(unittest.TestCase):

    @mock.patch('monitor_writer.requests.post')
    def test_conforming_write(self, mock_post):
        xml_frag = """
<InstantaneousDemand>
</InstantaneousDemand>
"""
        response = mock.MagicMock()
        response.status_code = 200
        respone.content = "OK"
        mock_post.return_value = response

        writer = MonitorWriter()
        writer.update(xml_frag)
        self.assertTrue(mock_post.called, "Failed to call requests.post")

rawDescription: How to mock an object returned by a mocked object?

description: Mock an object returned by a mocked object


code:
def f(path):
    if os.path.isdir(path):
        d = {}
        for name in os.listdir(path):
            d[name] = f(os.path.join(path, name))
    else:
        d = os.path.getsize(path)
    return d

rawDescription: dictionary of folders and subfolders

description: Dictionary of folders and subfolders


rawDescription: get django session id before server set the cookie to client

description: Get django session id before server set the cookie to client


code:
new_title = ' '.join(w.title() if w not in common else w for w in lst)
new_title = new_title[0].capitalize() + new_title[1:]

rawDescription: How can i compare two lists of words, change the words that are in common, and print the result in python?

description: Compare two lists of words, change the words that are in common, and print the result in python


code:
x = np.linspace(0, 3*np.pi, 500)
fig, ax = plt.subplots()
a = ax.plot(x, np.sin(x**2), label = 'square')
b = ax.plot(x, np.sin(x**0.5), label = 'square root')
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)

rawDescription: Matplotlib xy line graph legend

description: Matplotlib xy line graph legend


code:
env = {'somevar': 'somevalue'}
exec(code, env)

rawDescription: Use user provided python code during runtime


code:
class A(object):
    def __init__(self, *args, **kwargs):
       try:
           self._drivers = self.createDrivers(*args, **kwargs)
           select(self._drivers)
       except NotImplementedError:
           pass

    def createDrivers(self, *args, **kwargs):
        raise NotImplementedError("This class wasn't implemented")

class B(A):
    def createDrivers(self, *args, **kwargs):
        c1 = circle(sweep=270)[0]
        c2 = circle(sweep=180)[0]
        return c1, c2

class C(A):
    pass

rawDescription: Should I be using abstract methods in this Python scenario?


code:
#!/usr/bin/env python

from sys import argv, stderr, exit
from subprocess import check_output

repo = argv[1]
transaction = argv[2]

def path_history(path, limit=5):
    path = '/%s' % path
    cmd = ('svnlook', 'history', '-l', str(limit), repo, path)
    out = check_output(cmd).splitlines()[2:]

    for rev, _path in (i.split() for i in out):
        if _path == path:
            yield rev

def commit_changes():
    cmd = ('svnlook', 'changed', repo, '-t', transaction)
    out = check_output(cmd).splitlines()

    for line in out:
        yield line.split()

def filesize(path, rev=None, trans=None):
    cmd = ['svnlook', 'filesize', repo, path]
    if rev:     cmd.extend(('-r', str(rev)))
    elif trans: cmd.extend(('-t', str(trans)))

    out = check_output(cmd)
    return out.rstrip()

def filesize_catwc(path, rev=None, trans=None):
    '''A `svnlook filesize` substitute for older versions of svn.
    Uses `svnlook cat ... | wc -c` and should be very inefficient
    for large files.'''

    arg = '-r %s' % rev if rev else '-t %s' % trans
    cmd = 'svnlook cat %s %s %s | wc -c' % (arg, repo, path)

    out = check_output(cmd, shell=True)
    return out.rstrip()

for status, path in commit_changes():
    if status in ('A', 'M', 'U'):
        # get the last 5 revisions of the added/modified path
        revisions = list(path_history(path))
        headrev = revisions[0]

        oldsize = filesize(path, rev=headrev)
        newsize = filesize(path, trans=transaction)

rawDescription: In a pre-commit hook - how to access/compare current and previous versions of files


code:
tagged_files = [
    [u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur', u'photographer\tNN\tphotographer', u'and\tCC\tand', u'own\tJJ\town', u'three\tCD\tthree', u'DSLR\tNP\tDSLR', u'cameras\tNNS\tcamera', u'with\tIN\twith', u'a\tDT\ta', u'selection\tNN\tselection', u'of\tIN\tof', u'lenses\tNNS\tlens', u'.\tSENT\t.'],
    [u'a\tDT\ta', u'good\tJJ\tgood', u'price\tNN\tprice', u'!\tSENT\t!'],
    [u',\t,\t,', u'but\tCC\tbut', u'at\tIN\tat', u'the\tDT\tthe', u'least\tJJS\tleast', u'I\tPP\tI', u'can\tMD\tcan', u'say\tVV\tsay', u'that\tIN/that\tthat', u'finding\tVVG\tfind', u'them\tPP\tthem', u'was\tVBD\tbe', u'unintuitive\tJJ\tunintuitive', u'for\tIN\tfor', u'me\tPP\tme', u'.\tSENT\t.']
]

for i, l in enumerate(tagged_files, 1):
    with open('new_directory/sub_list{0}.txt'.format(i), 'w') as f:
        f.writelines(l)

rawDescription: How to save a new file, the content of a number of lists?

description: Save a new file, the content of a number of lists


code:
class Word:
    def __init__(self,word,definition,synonyms):
        self.w=word
        self.defi=definition
        self.synonyms=synonyms
    def __repr__(self):  # added to facilitate printing of tuples of Word objects
        return 'Word({}, {}, {})'.format(self.w, self.defi, self.synonyms)

w1=Word("lengthen", "make something taller", "some synonym")
w2=Word("woken", "let someone wake up", "some synonym")
w3=Word("fax", "machine used for communication", "some synonym")
w4=Word("wax", "chemical substance", "some synonym")

dictionary = {'en': (w1, w2), 'ax': (w3, w4)}

def delete(dictionary, word):
    suffix = word[-2:]
    if suffix in dictionary:
        dictionary[suffix] = tuple(word_obj for word_obj in dictionary[suffix]
                                   if word_obj.w != word)

delete(dictionary, 'woken')
print(dictionary)

rawDescription: python-How to delete an object in a list based on its data member

description: Python-How to delete an object in a list based on its data member


code:
import curses

def fillwin(w, c):
    y, x = w.getmaxyx()
    s = c * (x - 1)
    for l in range(y):
        w.addstr(l, 0, s)

def main(stdscr):
    fillwin(stdscr, 'S')
    stdscr.refresh()
    stdscr.getch()

    newwin=curses.newwin(10,20,5,5)
    fillwin(newwin, 'w')
    newwin.touchwin()
    newwin.refresh()
    newwin.getch()
    del newwin

    stdscr.touchwin()
    stdscr.refresh()
    stdscr.getch()

curses.wrapper(main)

rawDescription: How do I delete a curse window in python and restore background window?

description: Delete a curse window in python and restore background window


code:
import numpy as np
from scipy.spatial.distance import cdist
# start year to stop year
years = range(2003,2013)
# this will yield an n_years X n_features array
features = np.array([np.loadtxt('/Datafiles/%s.txt' % year) for year in years])
# compute the euclidean distance from each year to every other year
distance_matrix = cdist(features,features,metric = 'euclidean')

rawDescription: looping through an array to find euclidean distance in python

description: Looping through an array to find euclidean distance in python


code:
class mainWindow(Frame):
        # ...

    def initUI(self):
        # ...

        # note self here
        self.email_entry = Entry(self, exportselection = 0, width = 200).pack()
        # ...

    def send(self):
        # note self here
        body = self.email_entry.get()
        # ...

rawDescription: How to access variables and functions from within a class?

description: Access variables and functions from within a class


code:
import sys
from PyQt4 import QtGui
from PIL import Image

def get_pil_image(w, h):
    clr = chr(0)+chr(255)+chr(0)
    im = Image.fromstring("RGB", (w,h), clr*(w*h))
    return im

def pil2qpixmap(pil_image):
    w, h = pil_image.size
    data = pil_image.tostring("raw", "BGRX")
    qimage = QtGui.QImage(data, w, h, QtGui.QImage.Format_RGB32)
    qpixmap = QtGui.QPixmap(w,h)
    pix = QtGui.QPixmap.fromImage(qimage)
    return pix

class ImageLabel(QtGui.QLabel):
    def __init__(self, parent=None):
        QtGui.QLabel.__init__(self, parent)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Window')

        self.pix = pil2qpixmap(get_pil_image(50,50))
        self.setPixmap(self.pix)

app = QtGui.QApplication(sys.argv)
imageLabel = ImageLabel()
imageLabel.show()
sys.exit(app.exec_())

rawDescription: How to load a bitmap on a window on PyQt

description: Load a bitmap on a window on PyQt


code:
p = re.compile(r'^\w+$')
bool(p.match('str'))
bool(p.match('str}'))

rawDescription: matching regular expression in python

description: Matching regular expression in python


code:
class Deque():
    def __init__(self):
        self.header = None
        self.tailer = None
        self.length = 0

    def __repr__(self):
        if self.header is None:
          return 'Deque<>'
        string = str(self.header.value)
        index = self.header.next
        while index!=None:
            string+=" " + str(index.value)
            index = index.next
        return 'Deque<'+string+'>'

    def head_insert(self, item):
        new = Doubly_linked_node(item)

        new.next=self.header
        if self.length==0:
          self.tailer=new
        else:
          self.header.prev=new

        self.header=new
        self.length+=1

    def tail_insert(self, item):
        new = Doubly_linked_node(item)

        new.prev=self.tailer
        if self.length==0:
          self.header=new
        else:
          self.tailer.next=new

        self.tailer=new
        self.length+=1

rawDescription: Sometimes None is printed - and sometimes it doesn't, can't get why?


code:
d = {}
d['column1name'] = []
d['column2name'] = []
d['column3name'] = []

dictReader = csv.DictReader(open('filename.csv', 'rb'), fieldnames = ['column1name', 'column2name', 'column3name'], delimiter = ',', quotechar = '"')

for row in dictReader:
    for key in row:
        d[key].append(row[key])

rawDescription: Python Parse CSV Correctly

description: Python Parse CSV Correctly


code: items = sorted(d.items(), key=lambda i: len(i[1]), reverse=True)

rawDescription: Grab items from dictionary based on length of lists they are mapped to


code:
integers = filter(lambda x: isinstance(x,int), listEx)

strings = filter(lambda x: isinstance(x,str), listEx)

rawDescription: Separating list elements in Python

description: Separating list elements in Python


rawDescription: Consolidate irregular date values in Python (Pandas)


code:
class MyModel(models.Model):
    # fields here

    def s3_url(self):
        return ... # some calculated URL

class MyAdmin(admin.Admin):
    readonly_fields = ('s3_url',)
    fields = (..., 's3_url')

rawDescription: Add field for dynamically generated url in Django admin


rawDescription: Why are functions running before they are called?


code:
def extract_params(line, names):
    words = line.split()
    result = {}
    for name in names:
        value = 0
        for word in words:
            maybe_name, equals, maybe_value = word.partition('=')
            if maybe_name == name and equals == '=':
                value = maybe_value
        result[name] = value
    return result

rawDescription: dynamic array of parameters to function python

description: Dynamic array of parameters to function python


code:
import re
notag = re.sub("<.*?>", " ", html)

rawDescription: How to remove all html tags from downloaded page

description: Remove all html tags from downloaded page


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

dc = pd.DataFrame({'A' : [1, 2, 3, 4],'B' : [4, 3, 2, 1],'C' : [3, 4, 2, 2]})

plt.plot(dc)
plt.legend(dc.columns)
dcsummary = pd.DataFrame([dc.mean(), dc.sum()],index=['Mean','Total'])

plt.table(cellText=dcsummary.values,colWidths = [0.25]*len(dc.columns),
          rowLabels=dcsummary.index,
          colLabels=dcsummary.columns,
          cellLoc = 'center', rowLoc = 'center',
          loc='top')
fig = plt.gcf()

plt.show()

rawDescription: Python pandas summary table plot

description: Python pandas summary table plot


code:
def xstr(s):
    if s is None:
        return ''
    return str(s)

rawDescription: Python: most idiomatic way to convert None to empty string?


code:
import threading
import time
from flask import Flask, render_template

class myGame(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.board = 1

    def run(self):
        pass

app = Flask(__name__)
game = myGame()

@app.route('/get_updates')
def get_updates():
    return flask.jsonify(game.board)

if __name__ == "__main__":
    game.start()
    app.run(port=81, host='0.0.0.0', debug=False, use_reloader=False)

rawDescription: Running a Flask server parallel to main app


code:
from __future__ import division    # Python 2.x: int/int gives float

MONTHS_PER_YEAR = 12

def monthly_payment(principal, pct_per_year, years):
    months = years * MONTHS_PER_YEAR
    if pct_per_year == 0:
        return principal / months
    else:
        rate_per_year   = pct_per_year / 100.
        rate_per_month  = rate_per_year / MONTHS_PER_YEAR
        rate_compounded = (1. + rate_per_month) ** months - 1.
        return principal * rate_per_month * (1. + rate_compounded) / rate_compounded

rawDescription: Embedded function returns None

description: Embedded function returns None


code:
from gluon.custom_import import track_changes
track_changes(True)

rawDescription: How to make web2py dev server track file changes and restart automatically?

description: Make web2py dev server track file changes and restart automatically


code:
s = 'blah 45 blah 89'
s1, n = s.rsplit(None, 1)
s1, n

rawDescription: How can I split a string with a number at the end?

description: Split a string with a number at the end


code:
logger.debug((
              "Returning a list of Window handles"
              "with specified Windowtitle: {}"
             ).format(title))

rawDescription: How to avoid additional whitespaces in loggerfile, caused by indentions

description: Avoid additional whitespaces in loggerfile, caused by indentions


code:
import sys

print >> sys.__stdout__, 'Opening ODB'

rawDescription: Printing to terminal using Abaqus nogui python interface


code:
def _produce_raw_data():
    return raw_data

@simple_page.route('/raw_data')
def raw_data():
    return jsonify(_produce_raw_data())

@simple_page.route('/score')
def score():
    data = _produce_raw_data()
    # some calculation & return the score (to json)
    return jsonify(calculation_results)

rawDescription: Flask, how to jsonify ONLY when return to browser


code:
grid = Grid(4)
grid.setValue(0,0,1)
grid.setValue(1,1,2)
grid.setValue(2,2,3)
grid.setValue(3,3,4)

rawDescription: Creating a grid

description: Creating a grid


code:
keys = [2, 3, 'd']
{k: values[indexesA.index(k) if k in indexesA else indexesB.index(k)] for k in keys if (k in indexesA) or (k in indexesB)}

rawDescription: How to assemble dictionary out of multiple list with if/elif/else using list comprehension

description: Assemble dictionary out of multiple list with if/elif/else using list comprehension


code:
d
for k,v in d.iteritems():
    d[k] = [",".join(v)]
d

rawDescription: python2: merge a list of csv elements

description: Python2: merge a list of csv elements


code:
class SchoolResource(ModelResource):
    # fields.ToManyField('APP.api.RelatedResource', 'related name')
    policies = fields.ToManyField('places.api.PolicyResource',
        attribute=lambda bundle: Policy.objects.filter(school=bundle.obj)[:10]
    )

    class Meta:
        resource_name = 'school'
        queryset = School.objects.all()
        allowed_methods = ['get']
        authorization = DjangoAuthorization()
        authentication = BasicAuthentication()

rawDescription: Limiting number of nested resources in Django Tastypie?


code: K = self.request.get_all("article_tag")

rawDescription: How to collect values from checkbox in App Engine (python)?

description: Collect values from checkbox in App Engine (python)


code:
i = numpy.arange(i_max)
j = numpy.arange(j_max)
r[i[:,None], j, x, y] = c

rawDescription: Optimize a numpy ndarray indexing operation


code:
ax.fmt_xdata = lambda x: "{0:f}".format(x)
ax.fmt_ydata = lambda x: "{0:f}".format(x)

rawDescription: matplotlib coordinates format

description: Matplotlib coordinates format


code:
import pandas, numpy as np
# Create DataFrame "df" like yours...

df.apply(lambda x: np.all(x==0))

rawDescription: Filter columns of only zeros from a Pandas data frame


code:
from sympy import *
s = symbols("s")
t = symbols("t", positive=True)
h = 1/(s**3 + s**2/5 + s)
inverse_laplace_transform(h,s,t).evalf().simplify()

rawDescription: Getting a better answer from sympy inverse laplace transform


code:
def my_function(n):
    x = [[] for num in range(n)]
    ...

rawDescription: Declaring a quantity of lists in python dependent on function parameter


code:
from PIL import Image
imagefile = 'image.png'

def scale(w, h, x, y, maximum=True):
    nw = y * w / h
    nh = x * h / w
    if maximum ^ (nw >= x):
        return nw or 1, y
    return x, nh or 1

#set up print printer.
printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
#dlg = QtGui.QPrintDialog(printer, self)
printer.setPrinterName('Adobe PDF')

#check image size with PIL:
image = Image.open(imagefile)
imageWidth, imageHeight = image.size

paperPixels = printer.pageRect(QtGui.QPrinter.DevicePixel)
paperPixels = paperPixels.getRect() #get tuple of the "pixels on the paper"
paperWidth = paperPixels[2]
paperHeight = paperPixels[3]

#set margins for paper
paperMargin = 100
#find out the image size
paperWidth = paperWidth - (paperMargin*2) #times two, for left and right..
paperHeight = paperHeight - (paperMargin*2)

#scale image within a rectangle.
paintWidth, paintHeight = scale(imageWidth, imageHeight, paperWidth, paperHeight, True)
#construct the paint dimensions area
paintRect = QtCore.QRectF(paperMargin, paperMargin, paintWidth, paintHeight)

#start painting
image = QtGui.QImage(imagefile)
painter = QtGui.QPainter()
painter.begin(printer)
painter.drawImage(paintRect, image)
painter.end()
#now the page gets printed out and the image should fit the paper.

rawDescription: Printing full document with PySide/Qt

description: Printing full document with PySide/Qt


rawDescription: Proper regex for this URL

description: Proper regex for this URL


code:
class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()

class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

getch = _Getch()

rawDescription: Python read a single character from the user


code:
"""
Example of program with many options using docopt.

Usage:
  myprogram.py -a NUMBERS

Options:
  -h --help            show this help message and exit
  -a NUMBERS           Comma separated list of numbers
"""

from docopt import docopt

if __name__ == '__main__':
    args = docopt(__doc__, version='1.0.0rc2')
    args['-a'] = [int(x) for x in args['-a'].split(',')]
    print(args)

rawDescription: How do I make an argument with unknown n number of values stored in an array when parsed using docopt

description: Make an argument with unknown n number of values stored in an array when parsed using docopt


code:
def get_week(date):
    date = datetime.datetime.strptime(date, '%Y-%m-%d')
    week = date.strftime('%Y%U')

    if week[-2:] == '00':
        year = week[:-2]
        prev_year = int(year) - 1
        week = datetime.date(prev_year, 12, 31).strftime('%Y%U')
    else:
        pass

    return week

rawDescription: Python Week Numbers where all weeks have 7 days, regardless of year rollover


code:
import numpy as np

A=np.arange(16).reshape((4,4))

def neighbors(arr,x,y,n=3):
    ''' Given a 2D-array, returns an nxn array whose "center" element is arr[x,y]'''
    arr=np.roll(np.roll(arr,shift=-x+1,axis=0),shift=-y+1,axis=1)
    return arr[:n,:n]

print(A)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]
#  [12 13 14 15]]

print(neighbors(A,0,0))
# [[15 12 13]
#  [ 3  0  1]
#  [ 7  4  5]]

print(neighbors(A,1,0))
# [[ 3  0  1]
#  [ 7  4  5]
#  [11  8  9]]

rawDescription: How do I select a window from a numpy array with periodic boundary conditions?

description: Select a window from a numpy array with periodic boundary conditions


code:
import re
s = "Hello, World!"
re.match(r"(.+?), World!", s).group(1)

rawDescription: what does this regular expression in python mean (.+?)

description: What does this regular expression in python mean (.+?)


code: t1 = zip(*t)

rawDescription: Cleanest way to replace np.array value with np.nan by user defined index


code: l.sort(key=lambda t: len(t[1]), reverse=True)

rawDescription: Python sort a List by length of value in tuple


code:
from django.db.models import Sum

all_items = Model1.objects.all()
names = Model1.objects.values_list('field1', flat=True)
name_set = set(names)

items = []

color_choices = ['green', 'blue', 'yellow']

for name in name_set:
    name_info = {
        'field1': name,
    }

    for color_choice in color_choices:
        result_sum = all_items.filter(field1=name, field2=color_choice).aggregate(color_sum=Sum('field3'))
        name_info[color_choice] = result_sum['color_sum']

    items.append(name_info)

table = Table2(items)

rawDescription: Render new table with values from a differently modeled queryset


code:
dict_list = [{123123:[0.45, 0.4]},{2332:[0.1, 9]}]
{key: item[key] for item in dict_list for key in item}

rawDescription: Fastest way to convert Python List with dictionaries to one dictionary


code:
def interactive_py_compile(source, filename="<interactive>"):
    c = compile(source, filename, "single")

    # we expect this at the end:
    #   PRINT_EXPR
    #   LOAD_CONST
    #   RETURN_VALUE
    import dis
    if ord(c.co_code[-5]) != dis.opmap["PRINT_EXPR"]:
        return c
    assert ord(c.co_code[-4]) == dis.opmap["LOAD_CONST"]
    assert ord(c.co_code[-1]) == dis.opmap["RETURN_VALUE"]

    code = c.co_code[:-5]
    code += chr(dis.opmap["RETURN_VALUE"])

    CodeArgs = [
        "argcount", "nlocals", "stacksize", "flags", "code",
        "consts", "names", "varnames", "filename", "name",
        "firstlineno", "lnotab", "freevars", "cellvars"]
    c_dict = dict([(arg, getattr(c, "co_" + arg)) for arg in CodeArgs])
    c_dict["code"] = code

    import types
    c = types.CodeType(*[c_dict[arg] for arg in CodeArgs])
    return c

rawDescription: Python: use of eval in interactive terminal. how to get return value. what compile-mode


code:
keyspace = "Keyspace1"
tableName = "Super1"
key = "jdoe"
col1 = Column(name = "commenter", value = "J Doe", timestamp = time.time())
col2 = Column(name = "email", value = "jdoe@example.com", timestamp = time.time())

newData = [Mutation(ColumnOrSuperColumn(None,
                             SuperColumn(str(uuid.uuidl()),
                                        [col1, col2])))]
dataMap = {key : {tableName : newData}}

client.batch_mutate(keyspace=keyspace,
                    mutation_map=dataMap,
                    consistency_level=ConsistencyLevel.ZERO)

rawDescription: How do I insert a SuperColumn with python/thrift?

description: Insert a SuperColumn with python/thrift


code:
def remove_duplicates(d):
    encountered_entries = set()
    for key, entry in d.items():
        if (entry['name'], entry['author']) in encountered_entries:
            del d[key]
        else:
            encountered_entries.add((entry['name'], entry['author']))

rawDescription: Remove duplicate entries from nested dictionary, if two values are the same, in Python


code:
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

rawDescription: Python: Test if an argument is an integer


code:
class Build_ext_first(setuptools.command.install.install):
    def run(self):
        self.run_command("build_ext")
        return setuptools.command.install.install.run(self)

setup(
    ...,
    cmdclass = {'install' : Build_ext_first}
)

rawDescription: setup.py: run build_ext before anything else

description: Setup.py: run build_ext before anything else


code:
with open('yourlog.log', 'w'):
    pass

rawDescription: Python : clear a log file

description: Python : clear a log file


code: autoclass_content = 'both'

rawDescription: How should I document inherited '__init__' parameters of a Python class?


code:
#Define your randomly-distributed variables (I'm assuming they're normal)
q = pymc.Normal(name,mu=mu,tau=tau)
z = pymc.Normal(name2,mu=mu2,tau=tau2)

#Define how you think they generate your data
@pymc.deterministic
def NII_SII_th(q=q, z=z):
    return NII_SII_g(np.array([q, z])) #this fcn is defined somewhere else

#Your data array
f_row['[Nii]6584']=[...]

#Now link your model and your data
obs = pymc.Normal(modelname,mu=NII_SII_th,
                  observed=True, value=f_row['[NII]6584'])

rawDescription: pymc: Inferring parameters based on functions of observables

description: Pymc: Inferring parameters based on functions of observables


code: #!/usr/bin/env python

rawDescription: How to Identify the Python version in #! using environment variables


code: getattr(getattr(a, "b"), "c")

rawDescription: Why does `getattr` not support consecutive attribute retrievals?


code: [dict(zip(d, values)) for values in itertools.product(*d.values())]

rawDescription: Generate a list of dictionaries representing all combinations of the values for each key


code: C = [ A[x] for x in range(len(A)) if B[x] ]

rawDescription: list comprenhension using two list

description: List comprenhension using two list


code:
from nose.tools import assert_equal
from mock import Mock

class TestLoginRequired(object):
    def test_no_user(self):
        func = Mock()
        decorated_func = login_required(func)
        request = prepare_request_without_user()
        response = decorated_func(request)
        assert not func.called
        # assert response is redirect

    def test_bad_user(self):
        func = Mock()
        decorated_func = login_required(func)
        request = prepare_request_with_non_authenticated_user()
        response = decorated_func(request)
        assert not func.called
        # assert response is redirect

    def test_ok(self):
        func = Mock(return_value='my response')
        decorated_func = login_required(func)
        request = prepare_request_with_ok_user()
        response = decorated_func(request)
        func.assert_called_with(request)
        assert_equal(response, 'my response')

rawDescription: Testing Python Decorators?

description: Testing Python Decorators


code: import flask

rawDescription: Flask virtualenv

description: Flask virtualenv


rawDescription: Maze/labirynth game - few questions - Python 2.7.3 Pyglet 1.1.4


code: urllib.urlretrieve(url, filename)

rawDescription: Automated download of NetCDF file

description: Automated download of NetCDF file


code:
import dbus
bus = dbus.SessionBus()
bus.get_object('org.gnome.ScreenSaver','/org/gnome/ScreenSaver')

rawDescription: Python dbus can't find org.(gnome|freedesktop).ScreenSaver


code: {{ csrf_token }}

rawDescription: Django how to get csrf_token value in the template


code:
page = PdfFileReader(file("document.pdf", "rb")).getPage(0)
overlay = PdfFileReader(file("overlay.pdf", "rb")).getPage(0)
page.mergePage(overlay)

rawDescription: How to add image to PDF file in Python?

description: Add image to PDF file in Python


rawDescription: Extracting data from JavaScript (Python Scraper)


code:
map_by_state = collections.defaultdict(list)

for state, address in zip (statefloatingselfips, selfips):
    map_by_state[state].append(address)

rawDescription: dictionary created using zip with combining two list

description: Dictionary created using zip with combining two list


code:
m = re.search( pattern, text )
if m and len( m.group(3) ) > 3:
    text = text.replace( m.group(), m.group(1) + solve( m.group(2) ) )

rawDescription: Equivalent from C# matchObject.Value in Python?


code:
fig,ax = subplots()
ax.plot(range(4))
ax.set_ylabel('my label')
...

rawDescription: Hold is not working for pyplot

description: Hold is not working for pyplot


code:
document.getElementById("country").value = geoip_country_name()
document.getElementById("city").value = geoip_city()

rawDescription: Populating model properties dynamically from a javascript call


code:
from tempfile import mkstemp
from shutil import move
import os

os.chdir(raw_input("Folder with files to remove \" (comma): "))

for files in os.listdir(os.getcwd()):
    #create temp file
    f, p = mkstemp()
    #do the copy with the replace
    with open(p,'w') as new:
       with open(files) as old:
          for line in old:
            new.write(line.replace(('"','')))
    os.close(f)
    #replace the old file by the new one
    os.remove(files)
    move(p, files)

rawDescription: Remove element from multiple files with python


code:
import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')

rawDescription: Change string to lowercase except for first character and copy to clipboard


rawDescription: Passing meta-characters to Python as arguments from command line


code:
import inspect

def a():
    return 25

def b():
    return 50

def c(x, y):
    return x + y

def d(x, y, z):
    return x + y + z

def e(x=100):
    return x * x

def f():
    pass

def execute_function_list(funcs):
    results = []
    for i, fn in enumerate(funcs):
        args_required = len(inspect.getargspec(fn).args)
        if args_required > 0:
            args = results[i-args_required:i]
        else:
            args = ()
        print("calling function %r with args %r" % (fn, args))
        results.append(fn(*args))
        print("after function returned results = %r" % results)
    return results[-1] if len(results) else None

if __name__ == '__main__':
    funcs = [e, a, b, c, d, e]
    print("final result is %r" % execute_function_list(funcs))

rawDescription: Invoking a list of methods with correct arguments in Python


code:
import collections

# Data given in problem description

# Keys are starting nodes, values are destination nodes.

graph = {
            "a0": set(["a1", "b0"]),
            "a1": set(["a2", "b1"]),
            "a2": set(["b2"]),
            "b0": set(["b1", "c0"]),
            "b1": set(["b2", "c1"]),
            "b2": set(["c2"]),
            "c0": set(["c1"]),
            "c1": set(["c2"]),
            "c2": set([]),
}

# Length of every outbound edge from the node

edge_distance = {
                "a0": 0,
                "a1": 4,
                "a2": 12,
                "b0": 2,
                "b1": 1,
                "b2": 4,
                "c0": 7,
                "c1": 2,
                "c2": 1,
                }

def sort_graph():
    ''' Develop a sorted list using Kahn's algorithm
    '''
    # Number of incoming vertices to each node
    incoming = collections.defaultdict(int)

    #All nodes with vertices exiting them
    startnodes = set()

    # All nodes with vertices entering them
    endnodes = set()

    for start in graph:
        for end in graph[start]:
            startnodes.add(start)
            endnodes.add(end)
            incoming[end] += 1

    ordered = []
    startnodes -= endnodes
    while startnodes:
        start = startnodes.pop()
        ordered.append(start)
        for end in graph[start]:
            incoming[end] -= 1
            if not incoming[end]:
                startnodes.add(end)
    if sum(incoming.values()):
        raise ValueError("Graph has at least one cycle")

    return ordered

ordered = sort_graph()

def calc_dists(start):
    ''' Returns a dictionary containing all possible
        distances from a given start node to each other
        node, expressed as a set of possible distances
        for each target node.  The set will be empty
        if the target node is not reachable from the
        start node.
    '''
    dist_to_node = collections.defaultdict(set)
    dist_to_node[start].add(0)
    for start in ordered:
        cumulative = dist_to_node[start]
        dist = edge_distance[start]
        for end in graph[start]:
            dist_to_node[end].update(dist + prev for prev in cumulative)
    return dist_to_node

# Show all possible distances between a0 and c2
print(calc_dists('a0')['c2'])

rawDescription: Find longest path less than or equal to given value of an acyclic, directed graph in Python


code:
role, created = UserToUserRole.objects.get_or_create(
    from_user=current_user, to_user=user, role='follow')

rawDescription: Django: check whether an object already exists before adding


code:
import subprocess
subprocess.Popen(["python", r"C:\code\old_start_training_generic_depth.py", "-i", "10", "-l", "2"])

rawDescription: Running a python script from another script


code:
## This depends on empty resultiterable.ResultIterable
## evaluating to False

intersection_rdd = rdd1.cogroup(rdd2).filter(lambda x: x[1][0] and x[1][1])
intersection_rdd.map(lambda x: (x[0], (list(x[1][0]), list(x[1][1])))).collect()

## [('www.page1.html', (['word1', 'word3'], [7.3])),
##  ('www.page2.html', (['word1'], [1.25]))]

rawDescription: How to find the intersection of two rdd's by keys in pyspark?

description: Find the intersection of two rdd's by keys in pyspark


rawDescription: cumulative divide in array

description: Cumulative divide in array


code:
from odo import odo
odo('hdfstore://path_store_1::table_name',
    'hdfstore://path_store_new_name::table_name')

rawDescription: Concatenate two big pandas.HDFStore HDF5 files


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
for t in soup.find_all('table'):
    t.decompose()

rawDescription:
Python: Remove text between

 from text

description:
Python: Remove text between

 from text


rawDescription: PySpark: spit out single file when writing instead of multiple part files


code:
# Add the b directory to your sys.path

import sys, os
parent_dir = os.getcwd() # find the path to module a
# Then go up one level to the common parent directory
path = os.path.dirname(parent_dir)
# Add the parent to sys.pah
sys.path.append(path)

# Now you can import anything from b.s
from b.s import anything
...

rawDescription: How to call a class which is in other directory in Python

description: Call a class which is in other directory in Python


code:
class AbstractClass(object):
    def amethod(self):
        # some code that should always be executed here
        print(" AbstractClass.amethod()")

        # But, since we're the "abstract" class
        # force implementation through subclassing
        if self.__class__ == AbstractClass:
            raise NotImplementedError

class ActualClass(AbstractClass):
    def amethod(self):
        # Actual class code
        print(" ActualClass.amethod()")

        # And execute the super class code.
        super(ActualClass, self).amethod()

#a = AbstractClass()
#a.amethod()

b = ActualClass()
b.amethod()

rawDescription: Define an abstract method but require a subclass implementation


code:
bom8 = u'\ufeff'.encode('utf8')
bom8
bom8.decode('utf8')
bom8.decode('utf_8_sig')
'abcd'.decode('utf_8_sig')

rawDescription: Why is the first line longer?

description: Why is the first line longer


code:
from django.core.exceptions import ObjectDoesNotExist

@property
def event_type(self):
     for et in ('ticketedevent', 'rsvpevent', 'sillyhatsonlyevent', ...):
         try:
             getattr(self, et)
             return et
         except ObjectDoesNotExist:
             pass

@property
def admin_link(self):
    return reverse('admin:events_%s_change' % self.event_type, args=(self.id,))

rawDescription: How do I know which child class a Django model object is when selected through the parent class?

description: Know which child class a Django model object is when selected through the parent class


code:
import json

data = json.dumps(BIG_STRUCTURE_GOES_HERE)
query = """UPDATE table SET json = %s WHERE id = %s RETURNING id"""
cursor_postgres.execute(query, (data, rowId))
conn_postgres.commit()

rawDescription: What is the right method of escaping string before using it as json object


rawDescription: can I call a method in suds dynamically

description: Call a method in suds dynamically


code:
import numpy as np
a = np.array([[1, 2], [3, 4]])
a.reshape((-1, 1), order="F")

rawDescription: Most Elegant Implementation of MATLAB's "vec" Function in NumPy


code:
filtered = data1[(data1 >= 0) & (data1 < 10)]
sns.distplot(filtered, kde=True, hist=True, hist_kws={"range": [0,10]})
plt.show()

rawDescription: Does Seaborn distplot not support a range?


code:
if __name__ == '__main__':
    import Bob

rawDescription: "Pre-importing" a variable into a module


rawDescription: Tkinter readonly Combobox listener

description: Tkinter readonly Combobox listener


code:
class SpinEndEventManager(object):
    def __init__(self):
        self._controls = []
        self._event_handlers = []
        self._has_spinned = False

    def add(self, control, event_handler):
        self._controls.append(control)
        self._event_handlers.append(event_handler)
        control.Bind(wx.EVT_SPINCTRL, self._on_event)
        control.Bind(wx.EVT_LEFT_UP, self._on_event)
        control.Bind(wx.EVT_KEY_DOWN, self._on_event)
        control.Bind(wx.EVT_KEY_UP, self._on_event)

    def _on_event(self, event):
        is_spin_end_event = False
        event_type = event.GetEventType()
        control = event.GetEventObject()
        if event_type == wx.wxEVT_COMMAND_SPINCTRL_UPDATED:
            self._has_spinned = True
        elif event_type == wx.wxEVT_LEFT_UP:
            if self._has_spinned:
                is_spin_end_event = True
            event.Skip()
        elif event_type == wx.wxEVT_KEY_DOWN:
            key = event.GetKeyCode()
            old_value = control.GetValue()
            if key == wx.WXK_UP:
                value = old_value + 1
            elif key == wx.WXK_DOWN:
                value = old_value - 1
            control.SetValue(value)
            value = control.GetValue()
            if value != old_value:
                self._has_spinned = True
            if key == wx.WXK_DOWN:
                value_string_length = len(str(value))
                control.SetSelection(value_length, value_string_length)
        elif event_type == wx.wxEVT_KEY_UP:
            if self._has_spinned:
                is_spin_end_event = True
        if is_spin_end_event:
            self._has_spinned = False
            index = self._controls.index(control)
            self._event_handlers[index](event)

rawDescription: How to get end of spinning event with wxPython

description: Get end of spinning event with wxPython


code: data = data.replace('\n', '\r\n')

rawDescription: PYSERIAL Convert LF to LF/CR

description: PYSERIAL Convert LF to LF/CR


code:
def simple_app(environ, start_response):
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    return ['Hello world!\n']

application = simple_app

rawDescription: mod_wsgi WSGI script for non-frameworked Python web development

description: Mod_wsgi WSGI script for non-frameworked Python web development


code:
import json
data = json.loads(open("input.json").read())
with open("output.json", "w") as outfile:
        json.dump(data["Stock"]["Vehicule"], outfile)

rawDescription: Erase some lines in json file

description: Erase some lines in json file


code:
import os

with open(os.devnull, 'w') as null:
    subprocess.Popen(['7z', 'e', input_file, '-o', output_dest, '-y'], stdout=null, stderr=null)

rawDescription: Running 7zip command line silently via Python


code:
class BaseClass(object):
    pass

def get_class(num):
    attrs = [('attr_%d' % i, 1) for i in range(num)]
    return type('Test', (BaseClass,), dict(attrs))

rawDescription: Dynamically Create a Python Subclass in a Function


code:
def Webmaster_add(sender, instance, **kwargs):
     #you can put here some condition stuff
     w = Webmasters.objects.all()
     for obj in w:
         obj.news.add(instance)

# register the signal
post_save.connect(webmaster_add, sender=News)

rawDescription: Django M2M save and add relationship for each relative


code:
subject = obj.subject
body = obj.body
for key, value in kwargs.iteritems():
    subject = subject.replace('[%s]' % key.toupper(), value)
    body = body.replace('[%s]' % key.toupper(), value)

return (subject, body, obj.is_html)

rawDescription: loop through kwargs in python

description: Loop through kwargs in python


code: super(UserImages, self).save()

rawDescription: model save method. Resize image before save

description: Model save method. Resize image before save


code:
for fileStr in fileList:
    fileName = fileStr.rstrip('\n')
    openFile = open(fileName)
    openNewFile = open(fileName+'TitleCase.xml','w')
    lines = openFile.readlines()
    for lineIndex in range(0,len(lines)):
        line = lines[lineIndex]
        skip = 0
        if "label=" in line and "const" not in line:
            segs = line.split('"')
            if len(segs) >= 3:
                pass
            else:
                openNewFile.write(lines[lineIndex])
                secondTitleCaseLine = splitAndMakeTitleCase(lines[lineIndex + 1])
                skip = lineIndex + 1
                openNewFile.write(secondTitleCaseLine)
                if '"' not in lines[lineIndex + 1]:
                    thirdTitleCaseLine = splitAndMakeTitleCase(lines[lineIndex + 2])
                    skip = lineIndex + 1
                    openNewFile.write(thirdTitleCaseLine)
        else:
            openNewFile.write(lines[lineIndex])
    openFile.close()
    openNewFile.close()
    #cmd = "mv " + fileName + "TitleCase.xml " + fileName
    #os.system(cmd)

rawDescription: regarding re-factoring python code

description: Regarding re-factoring python code


code:
index=[]
con1 = "First Condition"
con2 = "Second Condition"

file=open("log.txt",'r')

print("Reading.. "+ file)
for line in F:
    for item in line.split("\n"):
            if con1 in item:
                    con1Line=item.strip()
                    if con2 in con1Line:
                            index.append(con1Line)
F.close()
l=index[-1]
print(l)
# do stuff now will value l
del index[:]

rawDescription: Python: log search, for first specific entry print to logfile


code:
def eval(self, env):
    return env.get(self.name)

rawDescription: Python: set variables from environment and retrieve them by name


code:
FlowDict = {(key1,key2):value for key1 in d for key2,value in d[key1].items()}
FlowDict

rawDescription: Transform dict into 2 key dict

description: Transform dict into 2 key dict


code: itertools.product(*[xrange(t) for t in table])

rawDescription: Python itertools product of undefinite dimension


code:
file = open("my_file", "r")
string_found = False
# Loop over the lines of the file
for line in file:
    temp = line.split(":")
    if test_string in temp[index]:
        print('Found it : {}'.format(line))
        string_found = True
# String not found case
if not string_found:
    print("String not found")

rawDescription: Unable to execute the else part of the if in the last line


code:
sentence =input("phrase to be shortened: ")
print (sentence)
text = input("Choose a word from the sentence above: ")
sentence = sentence.upper()
sentence = sentence.split(" ")
text = text.upper ()# this makes the text in capital letters
def lookfor (text):
    indexes = [ idx+1 for word, idx in zip(sentence, range(0,len(sentence))) if text == word ]
    print ("Your word has been found in the sentence at these positions", indexes )

    if not indexes:
         print ("The word that you have typed is not found in the sentence.")

lookfor(text)

rawDescription: How to find a word in a list

description: Find a word in a list


code:
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
     Group.objects.filter(elder.self.elder).update(elder=None)
     super(Group, self).save(force_insert, force_update, using, update_fields)

rawDescription: How to re-asign ForeignKey in Django

description: Re-asign ForeignKey in Django


code:
LANGUAGE_CODE = 'de'
LANGUAGES = (
    ('de', u'Deutsch'),
)

rawDescription: Django - how to permanently set I18N

description: Django - how to permanently set I18N


code:
#!/usr/local/cpython-3.3/bin/python

import re

def give_string():
    string = '''
eth0      Link encap:Ethernet  HWaddr 22:33:0a:e9:15:76
          inet addr:10.244.21.118  Bcast:10.244.21.127  Mask:255.244.255.192
          inet6 addr: fe80::0050:aff:fee9:1576/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:807304 errors:0 dropped:0 overruns:0 frame:0
          TX packets:611741 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:253087331 (241.3 MiB)  TX bytes:167902811 (160.1 MiB)
    '''
    return string

def main():
    string = give_string()
    regex = re.compile('^.*inet addr:\s*(\d+\.\d+\.\d+\.\d+) .*Mask:\s*(\d+\.\d+\.\d+\.\d+).*$', re.MULTILINE | re.DOTALL)
    match = regex.match(string)
    ip_address = match.group(1)
    subnet_mask=match.group(2)
    print(ip_address, subnet_mask)

main()

rawDescription: Searching in a text and save in string, python


code:
class IncludeHandler(SimpleHTTPRequestHandler):

    def do_GET(self):
        # self.path is the requested file
        complete_file = process_included_files(self.path)  # include the included files

        # serve the file. These lines come
        # straight from the http.server source code

        self.send_response(200)
        self.send_header("Content-type", "text/html") # or whatever the mime type is
        fs = os.fstat(complete_file.fileno())
        self.send_header("Content-Length", str(fs[6]))
        self.end_headers()

        self.copyfile(complete_file, self.wfile)

rawDescription: includes with SimpleHTTPServer?

description: Includes with SimpleHTTPServer


code:
class foo:
        def __init__(self):
                self.var_a = 2
                self.var_b = 3

        def __call__(self, x):
                return self.var_a + self.var_b + x

localClosure = foo()

# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6

# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
localClosure.var_a = 0

# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4

rawDescription: Modify bound variables of a closure in Python


code:
import random
List_Of_Words = ["these","are","the","words"]
random.shuffle(List_Of_Words)

rawDescription: Passage Scrambler

description: Passage Scrambler


code:
for line in tailer.follow(open('some_log.log')):
    emit(line)

rawDescription: How to get the diff of a file asynchronously in Python

description: Get the diff of a file asynchronously in Python


code:
from jnius import autoclass
autoclass('java.lang.System').out.println('Hello world')

rawDescription: Native bridge between Python and Dalvik or AAF


rawDescription: Print statement alignment and padding

description: Print statement alignment and padding


code: [s for s in strings if any(re.match(f, s) for f in filters)]

rawDescription: Lisp's "some" in Python?

description: Lisp's "some" in Python


code:
if 'is' in str1.split(): # 'is' in ['This', 'string']
    print(str1) # never printed

if 'is' in str2.split(): # 'is' in ['This', 'is', 'a', 'string']
    print(str2) # printed

rawDescription: Python: Find a word within a string

description: Python: Find a word within a string


code:
from django.utils import timezone
timezone.activate('US/Central')

rawDescription: Django 1.4 and timezones

description: Django 1.4 and timezones


code:
i = 0
x=lambda z = i : c[z]() #assign the current value of `i` to a local variable inside lambda
i+=1
y =lambda z = i : c[z]()
x()
y()

rawDescription: lambda functions and list of functions in Python

description: Lambda functions and list of functions in Python


rawDescription: Python: Converting from ISO-8859-1/latin1 to UTF-8


code:
def test_bitvector_set_block_id_slice(self):
    bv = bitvector(VECTOR_SIZE)
    bv.setall(False)

    print("BitVector[{len}]: {bv}".format(len=bv.length(),
                                          bv=bv.to01()))
    print("set block id: current {bid} --> {nbid}".format(bid=bv[52:VECTOR_SIZE].to01(),
                                                          nbid=inttobitvector(12, 1).to01()))

    # set blockVector.blockId (last 12 bits)
    bv[52:VECTOR_SIZE] = inttobitvector(12, 1)

    block_id = bv[52:VECTOR_SIZE]

    self.assertTrue(bitvectortoint(block_id) == 1)
    print("BitVector[{len}] set block id: {bin} [{val}]".format(len=bv.length(),
                                                                bin=block_id.to01(),
                                                                val=bitvectortoint(block_id)))
    print("BitVector[{len}]: {bv}".format(len=bv.length(),
                                          bv=bv.to01()))
    print()

# utility methods
def bitvectortoint(bitvec):
    out = 0
    for bit in bitvec:
        out = (out << 1) | bit

    return out

def inttobitvector(size, n):
    bits = "{bits}".format(bits="{0:0{size}b}".format(n,
                                                      size=size))

    print("int[{n}] --> binary: {bits}".format(n=n,
                                               bits=bits))

    return bitvector(bits)

rawDescription: How to pack & unpack 64 bits of data?

description: Pack & unpack 64 bits of data


code:
# The ``_log`` argument is only meant to be used by ``_g_copy_as_child()``
# to avoid logging the creation of children nodes of a copied sub-tree.

rawDescription: What does "_log" mean in pytables classes?


code:
class WorkerThread(QThread):
    # define a new signal which will be emitted when data loading finishes
    load_data_finished = pyqtSignal(list)

    def __init__(self):
        QThread.__init__(self)

    def run(self):
        # load data in new thread
        self.load_data()

    def load_data(self):
        data = []
        #
        # load your data here ...
        # example:
        data.append(1)
        data.append(2)
        data.append(3)
        #
        # when loading data finishes, emit the signal
        self.load_data_finished.emit(data)

class QtApp(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        # load UI...
        self.show()

        self.workerThread = WorkerThread()
        # connect the thread signal to a slot defined in this class
        self.workerThread.load_data_finished.connect(self.on_load_data_finished)
        self.workerThread.start()

    def on_load_data_finished(self, data):
        print("data loaded: ", data)

app = QApplication(sys.argv)
main_window = QtApp()

rawDescription: How to use QThread when application starts

description: Use QThread when application starts


code:
txt = '''

db access alpha customer1
 deny bla bla
db access beta customer99
 permit bla bla
 permit bla bla
 permit bla bla
 permit bla bla
db access game customer14
 permit no
!'''
re.findall('db\s+access.*?(?=db\s+access|!)',s,re.M|re.S)

rawDescription: Python find text using regex for this pattern


code: int(''.join(your_list), 16)

rawDescription: Python: Compare a list to a integer

description: Python: Compare a list to a integer


code:
from pandas.tseries.holiday import Holiday, AbstractHolidayCalendar
from datetime import datetime

class ItalianHolidaysCalendar(AbstractHolidayCalendar):
    rules = [Holiday('Pasquetta', month=4, day=21),
         Holiday('Liberation day', month=4, day=25),
         Holiday('Workers day', month=5, day=1),
         Holiday('Republic day', month=6, day=2)
   ]

cal = ItalianHolidaysCalendar()

holidays_df = pd.DataFrame({})
dd = pd.date_range(datetime(2014,1,1,0), periods=24, freq='H', tz='Europe/Rome')

holidays = cal.holidays(sliceSum.datetime.min().date(), sliceSum.datetime.max().date())
for day in holidays:
    dd = dd.append(pd.date_range(day, day + pd.DateOffset(hours=23), freq='H'))

sliceSum['holiday'] = False
sliceSum.loc[sliceSum.index.isin(dd),['holiday']] = True
sliceSum[sliceSum.holiday].head(50)

rawDescription: How to set Holidays with Pandas in a timezone-aware way

description: Set Holidays with Pandas in a timezone-aware way


code:
with open("mysqldump.txt",'w') as out:
    subprocess.check_call(["mysqldump", "-u", "usernmae", "-ppassword",
                           "-h", "dbserver_name", database_name],
                          stdout=out)

rawDescription: using subprocess.call with mysqldump

description: Using subprocess.call with mysqldump


code:
import sys
from PyQt4 import QtCore, QtGui

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

        msgBox = QtGui.QMessageBox()
        msgBox.setText('What to do?')
        msgBox.addButton(QtGui.QPushButton('Accept'), QtGui.QMessageBox.YesRole)
        msgBox.addButton(QtGui.QPushButton('Reject'), QtGui.QMessageBox.NoRole)
        msgBox.addButton(QtGui.QPushButton('Cancel'), QtGui.QMessageBox.RejectRole)
        ret = msgBox.exec_()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

rawDescription: How to add custom button to a QMessageBox in PyQt4

description: Add custom button to a QMessageBox in PyQt4


code:
likert_scale = {'strongly agree':2, 'agree':1, 'neither':0, 'disagree':-1, 'strongly disagree':-2}
df['categorical_data'] = df.EasyToUseQuestion.apply(lambda x: likert_scale[x])

rawDescription: pandas: Convert string column to ordered Category?

description: Pandas: Convert string column to ordered Category


code:
with open(outputfile,'w') as out, open(inputfile) as f:
    for line in f:
        out.write(line)
        if tag_match(line):  #Somehow determine if this line is a match where we want to insert text.
           out.write('\n'.join(fruits)+'\n')

rawDescription: Pythonic way of inserting lines to a file


code:
# first code a function to generate the axis labels you want
# ie, turn numbers greater than 1000 into commified strings (12549 => 12,549)

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
fnx = lambda x : locale.format("%d", x, grouping=True)

from matplotlib import pyplot as PLT
import numpy as NP

data = NP.random.randint(15000, 85000, 50).reshape(25, 2)
x, y = data[:,0], data[:,1]

fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y, "ro")
default_xtick = range(20000, 100000, 10000)

# these two lines are the crux:
# create the custom tick labels
new_xtick = map(fnx, default_xtick)
# set those labels on the axis
ax1.set_xticklabels(new_xtick)

PLT.show()

rawDescription: Matplotlib digit grouping (decimal separator)


code:
from glob import glob
import os, csv, pdb

masterCount = {}
masterLocations = {}

for i in glob('*.csv'):
    filename = os.path.split(i)[1]

    for animal, count in csv.reader(open(i)):
        masterCount[animal] = masterCount.get(animal, 0) + int(count)
        masterLocations[animal] = masterLocations.get(animal, []) + [filename]

writer = csv.writer(open('MasterAnimalCount.csv', 'wb'))

for animal in masterCount.keys():
    writer.writerow([animal, masterCount[animal], ', '.join(masterLocations[animal])])

rawDescription: Extract information from multiple CSV files, write to new CSV with third column


rawDescription: What is the space complexity of a prime sieve with data in proportion to number of primes?


code:
import random
stats = [0,0,0,0,0,0]
def single_roll(n,fixed=(),sides=6):
    for x in range(0,n):
        dice = random.randint(1,6)
        if dice == 1:
            stats[0] += 1
        elif dice == 2:
            stats[1] += 1
        elif dice == 3:
            stats[2] += 1
        elif dice == 4:
            stats[3] += 1
        elif dice == 5:
            stats[4] += 1
        elif dice == 6:
            stats[5] +=1
single_roll(6)

rawDescription: Why is my for loop not updating a given variable?


rawDescription: Regular expression Python for Splitting at all whitespaces


code:
class BusinessEntity(models.Model):
    title = models.CharField(max_length=180)

    class Meta:
        abstract = True

rawDescription: Django Models: Common Ancestor Inheritance & Migration


code:
d1 = {"dog":"woof", "cat":"meow"}
d2 = d1.copy() # make a copy, not a reference to the same dictionary
d2["dog"] = "bark"
for i in d1:
    print(i, d1[i])

# dog woof
# cat meow

rawDescription: Python: Dictionaries linked data

description: Python: Dictionaries linked data


rawDescription: How do I change the look and feel of the wxPython tool bar?

description: Change the look and feel of the wxPython tool bar


code: missing = [b for a,b in itertools.izip_longest(l1,l2,fillvalue=object()) if a != b]

rawDescription: Finding mismatched item for same index in a python list


code:
def to_hex_string(unsigned_64bit_int):
    return '{:016x}'.format(my_unsigned_64bit_int)

def to_unsigned_64bit_int(hex_string):
    return int(hex_string, 16)

rawDescription: How can I use 64 bit unsigned integers as entity keys in App Engine's datastore and retain sort order?

description: Use 64 bit unsigned integers as entity keys in App Engine's datastore and retain sort order


code: return t

rawDescription: Birthday Paradox List is nonetype

description: Birthday Paradox List is nonetype


code:
import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)

while 1:
    schedule.run_pending()
    time.sleep(1)

rawDescription: Run Python script every 10 seconds

description: Run Python script every 10 seconds


code:
#This is rough extract from my actual code. Probably not work as is, but outline the idea
import dispatch #Decoupled send of messages, identical to django signals

def monitorBackup(self):
    return self.selectSql(SQL_MONITOR)

def backup(sql):
    con = self.getCon() #Get new connection, we are in another thread!
    con.execute_query("HERE THE BACKUP SQL")

result = threading.Thread(target=partial(backup, sql))

result.start()

while result.isAlive():
    time.sleep(5) # with the monitor SQL result, is possible to get a estimated time to complete and adjust this...
    rows = self.monitorBackup()

    if len(rows) > 0:
        percentage = rows[0].Percent

        self.send(
            msg="%d %%" % percentage,
            action="progress",
            progress=percentage
        )

rawDescription: Not getting all InfoMessage Events with Python and win32com


code:
def words(d, auxList):
    # Variables to save state between lines
    curKey = None
    values = []

    for line in auxList:
        items = line.split()
        # Check if we have values already from a previous line
        if curKey is None:
            # Check if we see a continuation symbol (+)
            if items[-1][-1] == '+':
                # and remove it from the value
                items[-1] = items[-1][:-1]
                # Save the info in this line
                curKey = items[1]
                values = items[2:]
            else:
                # If all the information is in one simple line
                d[items[1]] = items[2:]
        else:
            # Check if we see a continuation symbol (+)
            if items[-1][-1] == '+':
                # and remove it from the value
                items[-1] = items[-1][:-2]
                # Save the info in this line and accumulate it
                # with the previous ones
                values.extend(items[1:])
            else:
                # Update dictionary when we have all the values
                d[curKey] = values + items[1:]
                # and reset state
                curKey = None
                values = []

    # Be sure to save the last line if there is no more info
    # Maybe it is not necessary
    if curKey is not None:
        d[curKey] = values

d = {}
a2 = [line.strip() for line in myfile.readlines()]
words(d, a2)

rawDescription: Append data into dictionary

description: Append data into dictionary


code:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel, QCheckBox,
            QVBoxLayout, QWidget, QLineEdit, QHBoxLayout)
class MainWindow(QMainWindow):

    def __init__(self):

        super().__init__()
        self.initUI()

    def initUI(self):
        hboxa = QHBoxLayout()
        a = QCheckBox()
        # size policy
        not_resize = a.sizePolicy();
        not_resize.setRetainSizeWhenHidden(True);
        a.setSizePolicy(not_resize);
        a.setVisible(False)

        aa = QLineEdit()
        hboxa.addWidget(a)
        hboxa.addWidget(aa)
        hboxb = QHBoxLayout()
        b = QCheckBox()
        bb = QLineEdit()
        hboxb.addWidget(b)
        hboxb.addWidget(bb)
        vbox = QVBoxLayout()
        vbox.addLayout(hboxa)
        vbox.addLayout(hboxb)
        w = QWidget()
        w.setLayout(vbox)

        self.setCentralWidget(w)

        self.setWindowTitle('Window Title')
        self.show()

if __name__ == '__main__':

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

rawDescription: How to add a spacing whose size is of a combobox in Qt

description: Add a spacing whose size is of a combobox in Qt


code:
string = "501.92secs: iPhone 5s_DownStream HTTP_TCP_Downlink_1 : ILOAD = **12.000** Mbps OLOAD = **4.999** Mbps FRATE = 4.980 Mbps L4 Goodput = 4.788 Mbps Packet Loss = 0.38 SLA Result = **FAIL**<font color=white>"

import re
def getnumbers(string,patterns):
 results = []
 for pattern,number in patterns.items():
    match = re.search(pattern,string)
    valuestart = match.span()[1]
    results.append([pattern,(string[valuestart+3:valuestart+number+3])])
 return results

#If you need obtain more values, add them to the dictionary in the argument.
#The number next to each pattern indicates the expected size of the result.
print(getnumbers(string,{"ILOAD =":7,"OLOAD =":7,"Result =":4})) #[['Result =', 'FAIL'], ['OLOAD =', '4.999**'], ['ILOAD =', '12.000*']]

rawDescription: Python Extract variable data from lines

description: Python Extract variable data from lines


code:
PSI_i = numpy.sin((arange(1,1026)-0.5)*DI)
PSI_j = numpy.sin((arange(1,1026)-0.5)*DJ)
PSI = A*outer(PSI_i, PSI_j)

P_i = numpy.cos(2.*arange(1,1026)*DI)
P_j = numpy.cos(2.*arange(1,1026)*DJ)
P = PCF*outer(P_i, P_j) + 50000

rawDescription: Performing operations on all values of a numpy array, referencing i and j


code:
import imp

moduleB = imp.load_source('moduleB', '/ModuleBPath/B.py')
moduleB.MyClass()

rawDescription: Python to specify which module to import from if there are duplicate module names?


code:
import os
with open("your_file") as f, open("new_file", "w") as f1:
    f1.write("Emojis:\n")
    for line in f:
        line = line.strip()
        name = os.path.basename(line)
        f1.write("\t- name: {}\n\t  src:{}\n".format(name, line))

rawDescription: Python: Take a list of filenames and convert them to a specific format


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

datamap = {
    1: 'real bad',
    2: 'bad',
    3: 'meh',
    4: 'good',
    5: 'way good'
}

df = pandas.DataFrame(data=np.random.choice(range(1,6), size=37), columns=['score'])
df['rating'] = df.score.map(datamap.get)

fig, ax = plt.subplots()
df.rating.value_counts().plot(kind='bar', ax=ax)
## alternatively:
# df.groupby(by='rating').count().plot(kind='bar', ax=ax)
fig.tight_layout()

rawDescription: Improving simple bar chart using matplotlib


code:
import pygame

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 400

HALF_WIDTH = int(SCREEN_WIDTH / 2)
HALF_HEIGHT = int(SCREEN_HEIGHT / 2)

def main():
    screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])

    pygame.display.set_caption("RPG")
    global cameraX, cameraY

    pygame.init()

    #player = pygame.image.load("Textures(Final)\Whoo_For_Testing.bmp").convert()
    player = pygame.Surface((40,40))
    player.fill((255,0,0))

    playerrect = player.get_rect()
    player.set_colorkey(WHITE)

    #grasstile = pygame.image.load("Textures(Final)\Grass_Tile.bmp").convert()
    #watertile = pygame.image.load("Textures(Final)\Water_Tile.bmp").convert()
    #waterbeach = pygame.image.load("Textures(Final)\Water_Beach.bmp").convert()
    grasstile = pygame.Surface((40,40))
    watertile = pygame.Surface((40,40))
    waterbeach = pygame.Surface((40,40))
    grasstile.fill((0,200,0))
    watertile.fill((0,0,200))
    waterbeach.fill((200,200,250))

    grassrect = grasstile.get_rect()
    waterrect = watertile.get_rect()
    waterb = waterbeach.get_rect()

    TILE_WIDTH = 32
    TILE_HEIGHT = 32

    tilemap = [
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile],
                [grasstile, grasstile, grasstile, grasstile, waterbeach, watertile, watertile, watertile, watertile]
            ]

    total_level_width = len(tilemap[0]) * 32
    total_level_height = len(tilemap)*32

    camera = Camera(simple_camera ,total_level_width, total_level_height)

    map_surface = pygame.Surface(( len(tilemap[0])*TILE_WIDTH, len(tilemap)*TILE_HEIGHT))

    for y,row in enumerate(tilemap):
        for x,tile_surface in enumerate(row):
            map_surface.blit(tile_surface,(x*TILE_WIDTH,y*TILE_HEIGHT))

    map_surface = pygame.transform.scale(map_surface, (1200, 800))
    player = pygame.transform.scale(player, (50, 100))

    done = False

    clock = pygame.time.Clock()

    move_speed = 5
    x, y = 100, 100

    entities = pygame.sprite.Group()

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            y -= move_speed
        elif keys[pygame.K_DOWN]:
            y += move_speed
        elif keys[pygame.K_LEFT]:
            x -= move_speed
        elif keys[pygame.K_RIGHT]:
            x += move_speed

        screen.fill(BLACK)

        screen.blit(map_surface, camera.apply(grassrect))
        screen.blit(player, camera.apply(pygame.Rect(x,y,50,100)))

        camera.update(player.get_rect().move((x,y)))

        clock.tick(20)

        pygame.display.flip()

class Camera(object):
    def __init__(self, camera_func, width, height):
        self.camera_func = camera_func
        self.state = pygame.Rect(0, 0, width, height)

    def apply(self, rect):
        return rect.move(self.state.topleft)

    def update(self, target_rect):
        self.state = self.camera_func(self.state, target_rect)

def simple_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera

    return pygame.Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)

def complex_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h

    l = min(0, l)                           # stop scrolling at the left edge
    l = max(-(camera.width-SCREEN_WIDTH), l)   # stop scrolling at the right edge
    t = max(-(camera.height-SCREEN_HEIGHT), t) # stop scrolling at the bottom
    t = min(0, t)                           # stop scrolling at the top
    return pygame.Rect(l, t, w, h)

if __name__ == "__main__":
    main()

pygame.quit()

rawDescription: How would I make a scrolling camera in Pygame?


code:
dd = {'78:a3:e4:3b:bd:3d' : 'Joe Smith',
      'dc:9f:db:1a:60:64' : 'Server1',
      'dc:9f:db:1a:2d:95' : 'Server1'}

dat = '[2014-07-22 10:21:06,821] <inform_stat-3> WARN  event  - [event] User[78:a3:e4:3b:bd:3d] roams from AP[dc:9f:db:1a:60:64] to AP[dc:9f:db:1a:2d:95] on "channel 11(ng)"'
aps = []
for elem in dat.split():
    if elem.startswith('User['):
        uname = dd.get(elem[5:-1], 'Unknown')
    if elem.startswith('AP['):
        aps.append(dd.get(elem[3:-1], 'Unknown'))

rawDescription: Python Parse log file string into txt file


code:
url(r'^comment/add/$', CommentCreate.as_view(), name='comment-add'),
url(r'^comment/edit/(?P<pk>\d+)/$', CommentUpdate.as_view(), name='comment-edit')

rawDescription: Django - why is edit form posting to edit url + create url on top of each other?


rawDescription: matplotlib plot integers on X Axis

description: Matplotlib plot integers on X Axis


code:
from functools import partial
from Queue import Queue
import math
import sys
import time

class Worker(QtCore.QObject):

    termino = pyqtSignal()

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

    def run(self, m=30000):
        print('worker thread id: {}'.format(QtCore.QThread.currentThreadId()))
        for x in xrange(m):
            #y = math.sin(x)
            y = x**2
            #time.sleep(0.001) # Weird, plotting stops if this is not present...
            self.q.put((x,y,y))
        print('Worker finished')

        self.termino.emit()

class MainWindow(QtGui.QWidget):

    relay = pyqtSignal(int)

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

        self.q = Queue()
        self.termino = False

        self.worker = Worker(self.q)

        self.workerThread = None
        self.btn = QtGui.QPushButton('Start worker')
        self.pw = pg.PlotWidget(self)
        pi = self.pw.getPlotItem()
        pi.enableAutoRange('x', True)
        pi.enableAutoRange('y', True)
        self.ge1 = pi.plot(pen='y')
        self.xs = []
        self.ys = []

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.pw)
        layout.addWidget(self.btn)

        self.resize(400, 400)

    def run(self):
        self.workerThread = QtCore.QThread()
        self.worker.termino.connect(self.setTermino)
        self.worker.moveToThread(self.workerThread)
        # moveToThread doesn't work here
        # self.btn.clicked.connect(partial(self.worker.run, 30000))
        # moveToThread will work here
        # assume def worker.run(self): instead of def worker.run(self, m=30000)
        #self.btn.clicked.connect(self.worker.run)
        self.relay.connect(self.worker.run)
        self.btn.clicked.connect(self.relay_signal)
        self.btn.clicked.connect(self.graficar)

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

    def relay_signal(self):
        self.relay.emit(500)

    def setTermino(self):
        self.termino = True

    def graficar(self):
        if not self.q.empty():
            e1,e2,ciclos = self.q.get()
            self.xs.append(ciclos)
            self.ys.append(e1)
            self.ge1.setData(y=self.ys, x=self.xs)

        if not self.termino or not self.q.empty():
            QtCore.QTimer.singleShot(1, self.graficar)

if __name__ == '__main__':

    app = QtGui.QApplication([])
    window = MainWindow()

    QtCore.QTimer.singleShot(0, window.run);
    sys.exit(app.exec_())

rawDescription: PyQt: moveToThread does not work when using partial() for slot


code:
from myapp.models import Property
Property.objects.all()
Property.objects.filter(sold=False)
Property.objects.filter(sold=True)
Property.objects.create(sold=False, my='other', fields=1)
Property.objects.filter(sold=False)

rawDescription: Django Boolean Queryset Filter Not Working


code:
def fake_data(n):

    # xy coordinates for an n-by-n grid
    grid = np.indices((n,n),dtype=np.float32).reshape(2,-1).T

    # interpolated coordinates
    xy_i = grid.copy()
    # not monotonically increasing
    np.random.shuffle(xy_i)

    # values
    z = np.random.rand(n**2)

    # input coordinates
    xy = grid.copy()
    # not regularly gridded
    xy += np.random.rand(*xy_i.shape)*0.25

    # pick n random points to use
    inc = np.random.choice(np.arange(n**2),(n,),replace=False)
    xy = grid[inc,:]
    z = z[inc]

    return xy, z, xy_i

rawDescription: python interpolation takes a long time

description: Python interpolation takes a long time


code:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

wd = webdriver.Firefox()
wd.get("https://www.leforem.be/particuliers/offres-emploi-recherche-par-criteres.html?exParfullText=&exPar_search_=true&    exParGeographyEdi=true")

wd.switch_to.frame("cible")

wait = WebDriverWait(wd, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'td.resultatIntitule')))

print(wd.page_source)

rawDescription: Return html code of dynamic page using selenium


code:
import glob
import os
import xlrd
import csv

ROOTDIR = r'C:\Users\username\Desktop\Mults'
wb_pattern = os.path.join(ROOTDIR, '*.xlsx')

workbooks = glob.glob(wb_pattern)
start_rownum = 3 # or wherever you want to start copying
with open('merged.csv', 'wb') as outcsv:
    writer = csv.writer(outcsv)
    for wb in workbooks:
        book_path = os.path.join(ROOTDIR, wb)
        book =  xlrd.open_workbook(book_path)
        sheet = book.sheet_by_index(0)
        for rownum in xrange(start_rownum, sheet.numrows):
            row = sheet.row_values(rownum)
            writer.writerow(row)

rawDescription: Python/Excel - Slice extracted excel data - exclude rows maintain structure


code:
import pygame
from pygame.locals import *

import numpy
import numpy.linalg

from OpenGL.GL import *
from OpenGL.GL.shaders import *

RESOLUTION = (800,600)

POSITIONS = numpy.array([[-1.0, -1.0], [+1.0, -1.0], [-1.0, +1.0], [+1.0, +1.0]], dtype=numpy.float32)
TEXCOORDS = numpy.array([[0.0, 1.0], [1.0, 1.0], [0.0, 0.0], [1.0, 0.0]], dtype=numpy.float32)

from PIL import Image

tex0 = 0
tex1 = 0

def loadTexture(path):
    img = Image.open(path)
    img = img.convert("RGBA")
    img_data = numpy.array(list(img.getdata()), numpy.int8)

    texture = glGenTextures(1)
    glPixelStorei(GL_UNPACK_ALIGNMENT,1)
    glBindTexture(GL_TEXTURE_2D, texture)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.size[0], img.size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data)

    return texture

def init():
    global tex0
    global tex1

    tex0 = loadTexture("texture0.png")
    tex1 = loadTexture("texture1.png")

    glViewport(0, 0, *RESOLUTION)

    aspect = RESOLUTION[0]/float(RESOLUTION[1])

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-aspect, +aspect, -1.0, +1.0, -1.0, +1.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glClearColor(0.0, 0.0, 0.0, 1.0);

    glVertexPointer(2, GL_FLOAT, 0, POSITIONS);
    glEnableClientState(GL_VERTEX_ARRAY);

    glClientActiveTexture(GL_TEXTURE0);
    glTexCoordPointer(2, GL_FLOAT, 0, TEXCOORDS);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glClientActiveTexture(GL_TEXTURE1);
    glTexCoordPointer(2, GL_FLOAT, 0, TEXCOORDS);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

def draw():
    glClear(GL_COLOR_BUFFER_BIT);

    glActiveTexture(GL_TEXTURE0);
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, tex0);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

    glActiveTexture(GL_TEXTURE1);
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, tex1);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

def main():
    pygame.init()

    screen = pygame.display.set_mode(RESOLUTION, OPENGL | DOUBLEBUF)

    init()

    while True:
        for event in pygame.event.get():
            if event.type == QUIT: return

        draw()

        pygame.display.flip()

if __name__ == "__main__":
    main()

rawDescription: pyopengl set multipass texture blending mode

description: Pyopengl set multipass texture blending mode


code:
from matplotlib import pyplot as plt
from fractions import Fraction

X = np.array([0,1/3.,2/3.,1])
Y = 2*X
X_tick = np.array([])
for item in X:
    X_tick = np.append(X_tick,Fraction(item).limit_denominator())
plt.xticks(np.unique(X),X_tick)
plt.plot(X,Y)

rawDescription: How to plot fraction values in a graph x-axis using matplotlib?

description: Plot fraction values in a graph x-axis using matplotlib


code:
'FOO'.lower() in set(('foo', 'bar', 'baz'))
'Quux'.lower() in set(('foo', 'bar', 'baz'))

rawDescription: How use regular expressions to compare an input with a set?


code:
def main(self):
    [...]
    self.stopwatch_value = IntVar()
    stopwatch = ttk.Label(root, textvariable=self.stopwatch_value)
    stopwatch.grid(row=1, column=2)
    root.after(self.update, 500)

def update(self):
    self.stopwatch_value.set(self.timed)
    root.after(self.update, 500)

rawDescription: The Label Isn't Upadting

description: The Label Isn't Upadting


code:
from lxml import html
root = html.fromstring('<msgCode>1111</msgCode>asdasdad<errorId>2222</errorId>')
root.xpath('//*[self::msgcode or self::errorid]/text()')

rawDescription: Python regex multiple matches with grouping


code:
import urllib
from bs4 import BeautifulSoup as Soup

base_url = "http://www.galactanet.com/oneoff/theegg_mod.html"

url = (base_url)
content = urllib.urlopen(url)
soup = Soup(content)
# print soup.original_encoding
theegg_text = soup.get_text().encode("windows-1252")

f = open("somefile.txt", "w")
f.write(theegg_text);
f.close()

rawDescription: Grabbing the info from beautiful soup and putting it into a text file?


code:
CONSTANT_LIST = []    # Put a comment here to tell the reader that these
DIFFERENT_LIST = []   # are constants that are filled in elsewhere
"""
Here is an example of what CONSTANT_LIST looks like
...
Here is an example of what DIFFERENT_LIST looks like
...
"""

for item in get_some_data_slowly():
    if meets_criteria_one(item):
        CONSTANT_LIST.append(item)
    elif meets_criteria_two(item):
        DIFFERENT_LIST.append(item)

rawDescription: Clearest way to initialize module-level lists in Python


code:
if 'retweeted_status' in an_original_tweet:
    print('FAIL')
else:
    print('Tweet is original')

rawDescription: Is this a good method for filtering retweets from a search?


rawDescription: Running doctests using a different function


code: os.chown, (some_path, int(os.getenv('SUDO_UID')), int(os.getenv('SUDO_GID')))

rawDescription: How to execute os.* methods as root?

description: Execute os.* methods as root


code:
def partial(func, *args, **kwds):
    "Emulate Python2.6's functools.partial"
    return lambda *fargs, **fkwds: func(*(args+fargs), **dict(kwds, **fkwds))

rawDescription: functools.wraps for python 2.4

description: Functools.wraps for python 2.4


code:
def writebytes(bytes):
    self.spi.transfer("".join(chr(i) for i in bytes))

rawDescription: Python fastest byte to string conversion


code:
logging.basicConfig(format='%(asctime)s %(message)s',
                datefmt='%m/%d/%Y %I:%M:%S %p',
                filename='logs.log',
                filemode='w',
                level=logging.INFO)

rawDescription: Is there a way to overwrite log files in python 2.x


rawDescription: Whats more random, hashlib or urandom?

description: Whats more random, hashlib or urandom


code:
#get idealDate
items = idealDate.split("-")
your_tuple =  (items[2],month[items[1]],items[0])
#convert from strings to ints if you wish

rawDescription: Input date in dd-MMM-yy and output in a tuple of (y,m, d)


code:
from urllib.request import urlopen; print(int(str(urllib.request.urlopen("http://ir.eia.gov/ngs/wngsr.txt").read()).split("\\n")[4].split(" ")[2]))
#              note the semi-colon ^

rawDescription: Python How To Import And Use Module With One Line


code:
from igraph import Graph
g = Graph.Full(10)
g.es.select(_within=range(4)).delete()

rawDescription: Remove all edges between a subset of nodes


code:
class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.initImages()                                #Prepare images
        self.master.resizable(width=False, height=False)
        self.index = 0
        self.grid()

    def initImages(self):
        self.images = {}
        buf = Image.open("Classic.png")
        buf = buf.resize((20, 20), Image.ANTIALIAS) #The (250, 250) is (height, width)
        self.images['Classic'] = ImageTk.PhotoImage(buf)

        buf = Image.open("Jeopardy.png")
        buf = buf.resize((20, 20), Image.ANTIALIAS) #The (250, 250) is (height, width)
        self.images['Jeopardy'] = ImageTk.PhotoImage(buf)

        buf = Image.open("On-site.png")
        buf = buf.resize((20, 20), Image.ANTIALIAS) #The (250, 250) is (height, width)
        self.images['On-site'] = ImageTk.PhotoImage(buf)

        buf = Image.open("On-line.png")
        buf = buf.resize((20, 20), Image.ANTIALIAS) #The (250, 250) is (height, width)
        self.images['On-line'] = ImageTk.PhotoImage(buf)

    def ShowImages(self, frame_in, type_img, place_img):
        label = tk.Label(frame_in, image=self.images[type_img])
        label.pack(side="right")

        label = tk.Label(frame_in, image=self.images[place_img])
        label.pack(side="right")

    def createWidgets(self, dict_of_data):
        frame = tk.Frame(self, relief='sunken')
        frame.grid(row=0, column=self.index, sticky="WN")
        frame_in = tk.Frame(frame)
        frame_in.grid(row=0, sticky="WE", column=self.index)
        #some other code here

rawDescription: Images disappearing in Tkinter

description: Images disappearing in Tkinter


code:
from collections import namedtuple
def CheckForJiraIssueRecord(object):
    options = namedtuple('Options', 'user password')('user', 'password')
    # 'user password' are the field names, and ('user', 'password') are the
    # initialization values. This code creates a type similar to what you had
    # before, naming it 'Options' internally, but doesn't bind it to a variable.

    # As you were...

rawDescription: Can I declare a class within a function in Python?

description: Declare a class within a function in Python


code:
''' Column block 0'''
checklabel1 = Label(master, textvariable=moneytkinter)
checklabel1.grid(row=0, column=0, columnspan=3) # columnspan = overlap 3 columns

mpslabel = Label(master, textvariable=mpstkinter)
mpslabel.grid(row=1,  column=0)

clickbutton = Button(master, textvariable=inctkinter, command=collectmoney)
clickbutton.grid(row=2, column=0, sticky="WE")

incbutton1 = Button(master, textvariable=autopricetkinter, command=deduction1)
incbutton1.grid(row=3, column=0, sticky="WE")

''' Column block 1'''
checklabel2 = Label(master, textvariable=autoclicktkinter)
checklabel2.grid(row=1, column=1)

incbutton2 = Button(master, textvariable=printpricetkinter, command=deduction2)
incbutton2.grid(row=2, column=1, sticky="WE")

''' Column block 2'''
checklabel3 = Label(master, textvariable=printmoneytkinter)
checklabel3.grid(row=1, column=2)

clickboost1 = Button(master, text="Click Boost (Costs: $2000)", command=clickboost1)
clickboost1.grid(row=2, column=2, sticky="WE")

boostbutton1 = Button(master, text="Auto Clicker Boost (Costs: $5000)", command=boostauto1)
boostbutton1.grid(row=3, column=2, sticky="WE")

boostbutton2 = Button(master, text="Money Printer Boost (Costs: $100000)", command=boostauto2)
boostbutton2.grid(row=4, column=2, sticky="WE")

rawDescription: Tkinter problems with grid

description: Tkinter problems with grid


code:
if request.method == 'POST':
    form_limit = LimitQueryForm(request.POST)
    ...
else:
    form_limit = LimitQueryForm()

rawDescription: Django form not valid

description: Django form not valid


code:
my_funcs = {}
for i in range(len(data)-1):
    def foo(x, y):
        x = data[i]['body']
        y = data[i+1]['body']
        tfidf = vectorizer.fit_transform([x, y])
        return ((tfidf * tfidf.T).A)[0,1]

    foo.func_name = "cosine_sim%d" % i
    my_funcs["cosine_sim%d" % i] = foo

globals().update(my_funcs) # Export to namespace

rawDescription: list index out of range loop Python

description: List index out of range loop Python


code:
def setUp(self):
    self.rpc_patcher = patch('listeners.RpcClient')
    self.MockClass = rpc_patcher.start()

def tearDown(self):
    self.rpc_patcher.stop()

rawDescription: Avoid passing second param to every unit test using mock.patch


code:
from threading import Semaphore
sem = Semaphore(10)
with sem:
    make_multiprocessing_call()

rawDescription: Python - question regarding the concurrent use of `multiprocess`


code:
import csv

def update_scores(name, new_score):
    new_file = []    # This will hold our information for later (since we can't both read and write simultaneously)
    with open('scores.csv', 'rb') as f:
        reader = csv.reader(f)
        for line in reader:
            if line[0] == name:    # We have found the row that matches the name we put in
                highest = max(int(new_score), int(line[1]), int(line[2]))   # Form the new highest score
                avg = round((int(new_score) + int(line[1]) + int(line[2])) / 3.00, 2)    # Form the new average score
                new_file.append([line[0], new_score, line[1], line[2], highest, avg])    # Write all of this new information to our new_file
            else:
                new_file.append(line)    # If the line doesn't need to be updated, just add it to our new_file

    with open('scores.csv', 'wb') as f:
        writer = csv.writer(f)
        for line in new_file:    # Write all of our new information back into the new file.
            writer.writerow(line)

update_scores('foo', '4')   # Send in the name and it's newest score

rawDescription: move along/replace certain rows csv python

description: Move along/replace certain rows csv python


code:
for line in f:
  if bar(line):
    break
else:
  # will only be called if for loop terminates (all lines read)
  baz()

rawDescription: How to detect end of file in Python after iterating the file object with "for" statement

description: Detect end of file in Python after iterating the file object with "for" statement


code:
df
df_norm = (df - df.mean()) / (df.max() - df.min())
df_norm
df_norm.mean()
df_norm.max() - df_norm.min()

rawDescription: Normalize data in pandas

description: Normalize data in pandas


code:
import clr
clr.AddReference("assembly_name")
from EnumTest import EnumTest
from EnumTest.EnumTest import FooEnum

rawDescription: Access C# Enums and Classes from other namespaces in IronPython


code:
lis = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ylist = [(3, "three"),(4, "four"),(5, "five")]
dic = dict(ylist)
[x if x not in dic else (x, dic[x])  for x in lis]

rawDescription: Combining two different iterable types in Python


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

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

x = np.linspace(-50,50,100)
y = np.arange(25)
X,Y = np.meshgrid(x,y)
Z = np.zeros((len(y),len(x)))

for i in range(len(y)):
    damp = (i/float(len(y)))**2
    Z[i] = 5*damp*(1 - np.sqrt(np.abs(x/50)))
    Z[i] += np.random.uniform(0,.1,len(Z[i]))
ax.plot_surface(X, Y, Z, rstride=1, cstride=1000, color='w', shade=False, lw=.5)

ax.set_zlim(0, 5)
ax.set_xlim(-51, 51)
ax.set_zlabel("Intensity")
ax.view_init(20,-120)
plt.show()

rawDescription: Python plotting 2d data on to 3d axes

description: Python plotting 2d data on to 3d axes


code:
from brew.base import Ensemble
from brew.base import EnsembleClassifier
from brew.combination.combiner import Combiner

# create your Ensemble
clfs = your_list_of_classifiers # [clf1, clf2]
ens = Ensemble(classifiers = clfs)

# create your Combiner
# the rules can be 'majority_vote', 'max', 'min', 'mean' or 'median'
comb = Combiner(rule='mean')

# now create your ensemble classifier
ensemble_clf = EnsembleClassifier(ensemble=ens, combiner=comb)
ensemble_clf.predict(X)

rawDescription: Sklearn: How to make an ensemble for two binary classifiers?


code:
def __init__(self, name):
    self.name = name

rawDescription: Getting an instance name inside class __init__()


code:
def import_r(lib, cache={}):
    if lib not in cache:
        cache[lib] = importr(lib)
    return cache[lib]

rawDescription: Variation of "running a function only once" in Python 3


code:
import keyring

keyring.set_password('your_application_name', username, password)

rawDescription: how to save a password in a file of configuration in python

description: Save a password in a file of configuration in python


code:
class ARedirect(RedirectView):
    def get_redirect_url(self, pk):
        filler = get_filler_somehow()
        return reverse('a_detail_slug', args=(pk, filler))

rawDescription: Use Django's RedirectView with a named url


code:
class ReportForm(forms.ModelForm):
    manual_date = forms.DateField(input_formats=['%m/%d/%Y','%d/%m/%Y'],
                      widget=forms.DateInput(attrs={'size':'15','id':'datepicker'},format=["%m/%d/%Y","%d/%m/%Y"]))
    manual_time = forms.TimeField(input_formats=['%H:%M','%I:%M %p'],
                      widget=forms.TimeInput(attrs={'size':'8','class':'time_field'},format=["%H:%M","%I:%M %p"]))

rawDescription: date and time input format not working

description: Date and time input format not working


code:
STATUS_RANK = {"ACTIVE": 1, "DEACTIVE": 2, "COMING": 3}

courses.sort(key=lambda x: STATUS_RANK[x['status']])

rawDescription: How to sort list of dicts by dict value in pre-defined format?

description: Sort list of dicts by dict value in pre-defined format


code:
x = 'Test'

x == 'Test1' or 'Test2'
x == 'Test1' or 'Test'
x == 'Test' or 'Test1'
x == 'Test1' or x == 'Test'

rawDescription: python : if statement and multiple variable values

description: Python : if statement and multiple variable values