rawDescription: How to regex split, but keep the split string?

description: Regex split, but keep the split string


code:
done = set()
while len(queue) > 0 :
   item = queue.pop()
   h = hash(item)
   if h not in done :
      process(item)
      done.add(h)

rawDescription: Python: Set with only existence check?

description: Python: Set with only existence check


code:
import locale
price = '20,355'
locale.setlocale(locale.LC_NUMERIC, '')  # Or any other appropriate locale.
locale.atoi(price)

rawDescription: How to convert a string (with non-digit place value separators) into an integer?

description: Convert a string (with non-digit place value separators) into an integer


code:
class Gallery(models.Model):
    "Represents a set of images."
    # maybe a title or other fields?

class Image(models.Model):
    "Represents one image."
    # field names are usually lowercase, for clarity
    image = models.ImageField(upload_to="gallery")
    gallery = models.ForeignKey(Gallery, related_name='images')
    # you might want more fields here, e.g. title, alt_text, etc

class Tour(models.Model):
    gallery = models.OneToOneField(Gallery)

class Agency(models.Model):
    gallery = models.OneToOneField(Gallery)

rawDescription: how to has n images for each item

description: Has n images for each item


code:
from random import randint

playercount = 2
maxscore = 100
safescore = [0] * playercount
player = 0
score=0

while max(safescore) < maxscore:
    if player == 0:
        rolling = 0
        if score < 17 and score + safescore[player] < maxscore:
            rolling = 1
    else:
        rolling = input("Player %i: (%i, %i) Rolling? (Y) "
            % (player, safescore[player], score)).strip().lower() in {'yes', 'y', ''}
    if rolling:
        rolled = randint(1, 6)
        print('  Rolled %i' % rolled)
        if rolled == 1:
            print('  Bust! you lose %i but still keep your previous %i'
                  % (score, safescore[player]))
            score, player = 0, (player + 1) % playercount
        else:
            score += rolled
    else:
        safescore[player] += score
        if safescore[player] >= maxscore:
            break
        print('  Sticking with %i' % safescore[player])
        score, player = 0, (player + 1) % playercount

print('\nPlayer %i wins with a score of %i' %(player, safescore[player]))

rawDescription: How could I modfiy this game to where I"m playing agains the computer instead of another user?


code:
stri = "text123123text:[852],[456465],[1]"
array = ["one", "two", "three"]
d = {i:j for i,j in zip(re.findall(r'\[[^\]]*\]', stri), array)} # create a dict with values inside square brackets as keys and array list values as values.
d
re.sub(r'\[[^\]]*\]', lambda m: "'" + d[m.group()] + "'", stri) # replaces the key with the corresponding dict value.

rawDescription: Regular Experession

description: Regular Experession


code:
import turtle as tu

# initial radius
radius = 100
# distance between circles
distance = 30

# pen up
tu.up()
# move pen to point x, y
# keeps the center of the circle at canvas center
tu.goto(0, -radius)
# pen down
tu.down()
tu.circle(radius)
# increase the radius value by distance
radius  += distance
# pen up
tu.up()
# move pen to point x, y
# keeps the center of the circle at canvas center
tu.goto(0, -radius)
# pen down
tu.down()
tu.circle(radius)
tu.done() #done

rawDescription: why won't my circle loop work in python

description: Why won't my circle loop work in python


code: df.reindex(range(1492, 1504))

rawDescription: Pandas add NA rows based on index

description: Pandas add NA rows based on index


code:
class MyTestCase(unittest.TestCase):
    def setUp(self):
        self.global_stuff = "whatever"

class TestOne(MyTestCase):
    def test_one(self):
        a = self.global_stuff

class TestTwo(MyTestCase):
    def setUp(self):
        # Other setUp operations here
        super(TestTwo, self).setUp() # this will call MyTestCase.setUp to ensure self.global_stuff is assigned.

    def test_two(self):
        a = self.global_stuff

rawDescription: Django test global setup

description: Django test global setup


code:
import urllib2
import json
# Whatever structure you need to send goes here:
jdata = json.dumps({"username":"...", "password":"..."})
urllib2.urlopen("http://www.example.com/", jdata)

rawDescription: How to use python urllib2 to send json data for login

description: Use python urllib2 to send json data for login


code:
import sys
import datetime

time_tuple = ( 2012, # Year
                  9, # Month
                  6, # Day
                  0, # Hour
                 38, # Minute
                  0, # Second
                  0, # Millisecond
              )

def _win_set_time(time_tuple):
    import pywin32
    # http://timgolden.me.uk/pywin32-docs/win32api__SetSystemTime_meth.html
    # pywin32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds )
    dayOfWeek = datetime.datetime(time_tuple).isocalendar()[2]
    pywin32.SetSystemTime( time_tuple[:2] + (dayOfWeek,) + time_tuple[2:])

def _linux_set_time(time_tuple):
    import ctypes
    import ctypes.util
    import time

    # /usr/include/linux/time.h:
    #
    # define CLOCK_REALTIME                     0
    CLOCK_REALTIME = 0

    # /usr/include/time.h
    #
    # struct timespec
    #  {
    #    __time_t tv_sec;            /* Seconds.  */
    #    long int tv_nsec;           /* Nanoseconds.  */
    #  };
    class timespec(ctypes.Structure):
        _fields_ = [("tv_sec", ctypes.c_long),
                    ("tv_nsec", ctypes.c_long)]

    librt = ctypes.CDLL(ctypes.util.find_library("rt"))

    ts = timespec()
    ts.tv_sec = int( time.mktime( datetime.datetime( *time_tuple[:6]).timetuple() ) )
    ts.tv_nsec = time_tuple[6] * 1000000 # Millisecond to nanosecond

    # http://linux.die.net/man/3/clock_settime
    librt.clock_settime(CLOCK_REALTIME, ctypes.byref(ts))

if sys.platform=='linux2':
    _linux_set_time(time_tuple)

elif  sys.platform=='win32':
    _win_set_time(time_tuple)

rawDescription: Python module to change system date and time


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

x = np.linspace(0,20,100)
cdf = stats.binom.cdf
plt.plot(x,cdf(x, 50, 0.2))
plt.show()

rawDescription: SciPy Cumulative Distribution Function Plotting


code:
import itertools

for x in itertools.product('12','12','23','23','23','345'):
    print(', '.join(x))

rawDescription: Finding all combinations where each digit is picked from a different set


code: pd.rolling_sum(df, window=7, freq='D', min_periods=1)

rawDescription: 7 day window with skipped dates

description: 7 day window with skipped dates


code:
name, ext = s.rsplit('.', 1)
'{}.{}'.format(name.title(), ext)

rawDescription: python regular expression case change

description: Python regular expression case change


code:
import json
json.dumps({'spam': 1, 'eggs': 2, 'bacon': 0})
json.loads('{"eggs": 2, "bacon": 0, "spam": 1}')
json.dumps((1,2,3,4))
json.loads('[1, 2, 3, 4]')

rawDescription: How to MySQL to store multi-params for HTTP POST?


code:
from ntlm3 import ntlm
from suds.client import Client
from suds.transport.https import WindowsHttpAuthenticated

url = "https://web.site.com/sites/Collection/_vti_bin/Lists.asmx"
wsdl = (url + "?WSDL")
domain = 'DOM'
username = 'USER'
password = 'PASS'

transport = WindowsHttpAuthenticated(username=username,
                                     password=password)
client = Client(url=wsdl,
                location=url,
                transport=transport)

negotiate = "%s\\%s" % (domain, username)
ntlmauth = 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(negotiate).decode('ascii')
header = {'Authorization': ntlmauth}
client.set_options(headers=header)
client.service.GetList('Test')

rawDescription: Suds throwing 403 Forbidden on SharePoint


code:
from copy import deepcopy
d = deepcopy(filespecificpayload)
id(d[key]) == id(filespecificpayload[key])

rawDescription: Variables defined in a function - Python


code: df.drop(set(drop_list) & set(df.columns), axis=1)

rawDescription: Drop columns from pandas dataframe, regardless of whether ALL column names are present


code: ''.join('%02x'%i for i in input)

rawDescription: format ints into string of hex

description: Format ints into string of hex


code:
from mymodule import somefunc

class TestingFunctionsTest(unittest.TestCase):
    def test_somefunc(self):
        self.assertEqual(somefunc(), [1, 2, 3])

rawDescription: unittesting(Python), test if function returns an array

description: Unittesting(Python), test if function returns an array


code:
names = ['table1', 'table2', 'table3']

for name in names:
    type(name.title(), (MyDatasetBase, db.Model), { '__tablename__' : name })
# generate <class 'flask_sqlalchemy.Table1'> ...

rawDescription: Multiple Identical Tables in Flask-SQLAlchemy


code:
html_list.append('<img src="cid:image.png">')
img = MIMEImage(my_data)
img.add_header('Content-ID', '<image.png>')
msg.attach(img)

rawDescription: Adding multiple inline parts to an email


code:
#! /usr/bin/python3

class GuitarItem: pass

class PianoItem: pass

class SuperClass:
    def makeItem (self): #or whatever you want to do with the Item class
        return type (self).Item ()

class SubClass (SuperClass): Item = GuitarItem

class SubClass2 (SuperClass): Item = PianoItem

print (SubClass ().makeItem () )
print (SubClass2 ().makeItem () )

rawDescription: Variable containing classobj - good style?


code:
import tkinter as tk

class HelloWorld(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="What's your input?", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        answer = self.entry.get()
        if answer == "a":
            print("Hello World")
        elif answer == "b":
            print("Hello World 2")
        elif answer == "c":
            root.destroy()

root = HelloWorld()
root.mainloop()

rawDescription: mainloop() function in python

description: Mainloop() function in python


code:
''' Rest of your docstring and then...

    >>> '%.2f' % funcreturningfloat()
    '123.45'

'''

rawDescription: How to test floats results with doctest?

description: Test floats results with doctest


code:
fragment = '
adrresstext of address
'
soup = BeautifulSoup(fragment)
soup.div.span.nextSibling

rawDescription: Parsing html in Beautiful soup

description: Parsing html in Beautiful soup


code:
import numpy as np
import pylab as pl

x = np.linspace(-1, 1, 100)
y = np.zeros((5, 100))
for i in range(5):
    y[i] = x**i

ax = []
kw = {}
for i in range(5):
    if i > 0:
        kw ={'sharex': ax[0], 'sharey': ax[0]}
    ax.append(pl.subplot(3, 2, i+1, **kw))
    ax[i].plot(x, y[i])

rawDescription: How to plot 5 subplots sharing x and y axes in Python

description: Plot 5 subplots sharing x and y axes in Python


code: lambda pkt:((pkt.chksumpresent == 1) or (pkt.special == 1))

rawDescription: Python Lambda with Or

description: Python Lambda with Or


rawDescription: Python Regex - How to remove text between 2 characters


code:
with open('file.txt') as myfile:
    d = dict(line.rstrip().split(None, 1) for line in myfile)

rawDescription: extracting words from dictionary-python

description: Extracting words from dictionary-python


code:
try:
    json.dumps(my_object)
except TypeError:
    print("Unable to serialize the object")

rawDescription: python check if json.dumps is possible

description: Python check if json.dumps is possible


code:
import re
s="2-sec"
re.match('(\d).(m|s)',s).group(1,2)
s='2-min'
re.match('(\d).(m|s)',s).group(1,2)

rawDescription: time formats to keyword replacement using python

description: Time formats to keyword replacement using python


code:
# '0' is appended so that swapping values is still possible
items = [item for item in scores] + ['0']

for indx in range(6):
    # don't change the box which triggered the update
    if not indx == indx_in_combo_list:
        # I'm not 100% sure that this next line is correct, but it should be close
        existing_values = [model_item[0] for model_item in combolist[indx].get_model()]

        if existing_values != items:
            # the idea is to clear each list and then repopulate it with the
            # remaining available items
            combo_list[indx].get_model().clear()
            for item in items:
                combo_list[indx].append_text(item)

rawDescription: How to stop infinite recursion when Python objects trigger each other's updates?

description: Stop infinite recursion when Python objects trigger each other's updates


code:
from django.db import connection

with transaction.atomic():
    cursor = connection.cursor()
    cursor.execute('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ')
    # logic

rawDescription: In Django, how to achieve repeatable reads for a transaction?


code:
def range_inclusive(start, stop=None, step=1):
    if stop is None:
        start, stop = 0, start
    return range(start, stop + step, step)

rawDescription: Python - Is there a built-in function that creates a list of numbers, given the min, the max and the step?


code:
from xlutils.copy import copy
from xlrd import open_workbook

# open the file you're interested
rb = open_workbook('some_document.xlsx')

# copy it to a writable variant
wb = copy(rb)

# find the index of a sheet you wanna rename,
# let's say you wanna rename Sheet1
idx = rb.sheet_names().index('Sheet1')

# now rename the sheet in the writable copy
wb.get_sheet(idx).name = u'Renamed Sheet1'

# save the new spreadsheet
wb.save('new_some_document.xlsx')

# done

rawDescription: change name of an excel worksheet after reading the file in python

description: Change name of an excel worksheet after reading the file in python


code:
from win32api import SendMessage
result = SendMessage(self.GetHandle(), EM_POSFROMCHAR, 0, 0)

rawDescription: How to get chars that are actually displayed in wx.TextCtrl?

description: Get chars that are actually displayed in wx.TextCtrl


code:
from datetime import timedelta
str(timedelta(microseconds=49503757))

rawDescription: convert microseconds into a human readable time

description: Convert microseconds into a human readable time


rawDescription: Difference in output between numpy linspace and numpy logspace


code:
from pprint import pprint
pprint(the_dict)

rawDescription: how to pretty-format an output string of a python object

description: Pretty-format an output string of a python object


code:
import os
files = glob.glob('*.tar.gz')

for f in files:
    with tarfile.open(f, 'r:gz') as tar:
        tar.extractall()
        extracted_files = os.listdir(".") #retrieves the lists of all files and folders in the current directory
        for file in extracted_files:
            if file.endswith(".tar.gz"): # do not process tar.gz files
                continue
            absolute_path = os.path.abspath(file) # get the absolute path
            if os.path.isdir(absolute_path): # test if the path points to a directory
                shutil.rmtree(absolute_path)
            else: # normal file
                os.remove(absolute_path)

rawDescription: how to delete every files extracted after extracting and doing required tasks?

description: Delete every files extracted after extracting and doing required tasks


code:
query = "INSERT INTO shData("
query_v = "VALUES ("
for key in q_i:
    query += key + ','
    if isinstance(q_i[key],str):
        query_v += "'{" + key + "}',"
    else:
        query_v += "{" + key + "},"
query = query.rstrip(",")
query_v = query_v.rstrip(",")
query = query + ") " + query_v + ") "
cur.execute(query.format(**q_i))

rawDescription: Database query as variable in Python using MySQLdb library


code:
import pylab as plt
import numpy as np

x=np.arange(1,1e5)

# Normal plot
#plt.plot(x,x,'o-')

# Log plot
idx=np.logspace(0,np.log10(len(x)),10).astype('int')-1
plt.plot(x[idx],x[idx],'o-')
plt.xscale('log')
plt.yscale('log')
plt.show()

rawDescription: Line markers density

description: Line markers density


code:
if success:
    # On Success - Mark message as processed.
    ch.basic_ack(delivery_tag=method.delivery_tag)
else:
    # Else - Mark message as rejected and move it back to the queue.
    ch.basic_reject(delivery_tag=method.delivery_tag, requeue=True)

rawDescription: Force workers to instantly pick up failed messages when persistent delivery mode is enabled


code:
re.sub(r'[-\s]+', '-',
            unicode(
                re.sub(r'[^\w\s-]', '',
                    unicodedata.normalize('NFKD', string)
                    .encode('ascii', 'ignore'))
                .strip()
                .lower()))

rawDescription: Advance slug/url parameterization (incl. transliteration) library in Python


code: string1="""blah blah blah "  some'  thi'ng "  end of string """

rawDescription: python: how to set a string equal quotes?

description: Python: how to set a string equal quotes


code:
class SparseList(list):
  def __setitem__(self, index, value):
    missing = index - len(self) + 1
    if missing > 0:
      self.extend([None] * missing)
    list.__setitem__(self, index, value)
  def __getitem__(self, index):
    try: return list.__getitem__(self, index)
    except IndexError: return None

__test__ = dict(allem='''
>>> l = SparseList()
>>> l
[]
>>> l[2] = "hello"
>>> l
[None, None, 'hello']
>>> print l[5]
None
>>> l[4] = 22
>>> l
[None, None, 'hello', None, 22]
>>> len(l)
5
>>> for i in l: print i
None
None
hello
None
22
''')
import doctest
doctest.testmod(verbose=1)

rawDescription: sparse assignment list in python

description: Sparse assignment list in python


code:
class DBExamplestart(Examplestart):
    variable = ndb.KeyProperty(kind=DBUser, default=ndb.Key(DBUser, 776))
    statement = ndb.StringProperty(indexed=False, default='First')

rawDescription: Hardcoding values into ndb model

description: Hardcoding values into ndb model


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

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15], dtype=float)
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

def piecewise_linear(x, x0, y0, k1, k2):
    return np.piecewise(x, [x < x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0])

p , e = optimize.curve_fit(piecewise_linear, x, y)
xd = np.linspace(0, 15, 100)
pl.plot(x, y, "o")
pl.plot(xd, piecewise_linear(xd, *p))

rawDescription: How to apply piecewise linear fit in Python?

description: Apply piecewise linear fit in Python


rawDescription: How can I convert this string to list of lists?

description: Convert this string to list of lists


code:
class GenAsyncHandler(RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        http_client = AsyncHTTPClient()
        response = yield gen.Task(http_client.fetch, "http://example.com")
        do_something_with_response(response)
        self.render("template.html")

rawDescription: Tornado Blocking Code

description: Tornado Blocking Code


code:
pages = [page1, page2] # page1 and page2 are Page objects
Page.objects.filter(site=site).exclude(pk__in=[p.pk for p in pages])

rawDescription: Exclude by object in queryset

description: Exclude by object in queryset


code: root.attributes("-alpha", 0)

rawDescription: Using Tkinter, is there a way to get the usable screen size without visibly zooming a window?


rawDescription: SqlAlchemy Reflection of Oracle Table Not Owned


code:
from IPython.frontend.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.frontend.qt.inprocess import QtInProcessKernelManager
from IPython.lib import guisupport
from PyQt4.QtGui import QApplication

app = QApplication(sys.argv)

kernel_manager = QtInProcessKernelManager()
kernel_manager.start_kernel()
kernel = kernel_manager.kernel
kernel.gui = 'qt4'

kernel_client = kernel_manager.client()
kernel_client.start_channels()

def stop():
    kernel_client.stop_channels()
    kernel_manager.shutdown_kernel()
    # here you should exit your application with a suitable call
    sys.exit()

widget = RichIPythonWidget()
widget.kernel_manager = kernel_manager
widget.kernel_client = kernel_client
widget.exit_requested.connect(stop)
widget.setWindowTitle("IPython shell")

ipython_widget = widget
ipython_widget.show()

app.exec_()
sys.exit()

rawDescription: Embedding Ipython into a PyQt4 App

description: Embedding Ipython into a PyQt4 App


code:
# _*_ coding: utf-8

import xlsxwriter

workbook    = xlsxwriter.Workbook('unicode_vertical.xlsx')
worksheet   = workbook.add_worksheet()

text_format = workbook.add_format({'rotation': 270})

worksheet.write('B2', u'こんにちは世界', text_format)

workbook.close()

rawDescription: Xlsxwriter: Is it possible to do East Asian Language Vertical Text on a cell?


code:
response = requests.get('http://bit.ly/bllsht')
response.url

rawDescription: Return last URL in sequence of redirects


code:
with open('somefile') as fin:
    points = [line.split()[1] for line in fin if line.startswith('something')]

rawDescription: How can I more easily save value in txt file to variable? python line.split

description: More easily save value in txt file to variable? python line.split


code:
def perm(s):
    indexes = {x:i+1 for i,x in enumerate(sorted(set(s)))}
    return ''.join(str(indexes[x]) for x in s)

print(perm('abc'))
print(perm('zad'))

rawDescription: How to make string into permutation?

description: Make string into permutation


code:
from gi.repository import GdkPixbuf

lv = Gtk.ListStore (str, GdkPixbuf.Pixbuf)

rawDescription: GDK_TYPE_PIXBUF in Gtk 3

description: GDK_TYPE_PIXBUF in Gtk 3


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
soup.div.div.extract()
soup.div

rawDescription: Extract outer div using BeautifulSoup

description: Extract outer div using BeautifulSoup


rawDescription: Getting python regexp for data

description: Getting python regexp for data


code: format(math.floor(number), '.0f')

rawDescription: Moving decimal without rounding

description: Moving decimal without rounding


code:
list=[1,2,3,4]
i=0  #your index
if i==(len(list)-1):
   j=0
else:
   j=i+1
list[i], list[j] = list[j], list[i]

rawDescription: how to swap item in a list of Python

description: Swap item in a list of Python


code:
Food.objects.filter(foodeaten__day__in=days,
                    foodeaten__day__user=request.user) \
            .order_by('foodeaten__day__date')

rawDescription: How to retrieve a set of objects, filtered and ordered by fields of other objects, for which the desired object is a foreign key?

description: Retrieve a set of objects, filtered and ordered by fields of other objects, for which the desired object is a foreign key


rawDescription: indexing two dimentational array

description: Indexing two dimentational array


code:
class ProbSVC(SVC):
    def predict(self, X):
        return super(ProbSVC, self).predict_proba(X)

rawDescription: grid search cross-validation on SVC probability output in sci-kit learn

description: Grid search cross-validation on SVC probability output in sci-kit learn


code:
import pyqtgraph as pg
import pandas as pd
import numpy as np

bottom10 = pd.DataFrame({'amount':-np.sort(np.random.rand(10))})
top10 = pd.DataFrame({'amount':np.sort(np.random.rand(10))[::-1]})
maxtick=max(top10.amount.max(),-bottom10.amount.min())*1.3

win1 = pg.plot()
axtop=pg.BarGraphItem(x=range(len(top10)),height=top10.amount,width=0.6,brush='r')
axtop.rotate(-90)
win1.addItem(axtop)
axbt=pg.BarGraphItem(x=range(len(top10)),height=-bottom10.amount,y0=maxtick+bottom10.amount,width=0.6,brush='g')
axbt.rotate(-90)
win1.addItem(axbt)

rawDescription: how to plot two barh in one axis in pyqtgraph?

description: Plot two barh in one axis in pyqtgraph


code:
## ================================================================

def normalizePrice(price, minimum, maximum):
    return ((2*price - (maximum + minimum)) / (maximum - minimum))

def denormalizePrice(price, minimum, maximum):
    return (((price*(maximum-minimum))/2) + (maximum + minimum))/2

## ================================================================

def rollingWindow(seq, windowSize):
    it = iter(seq)
    win = [it.next() for cnt in xrange(windowSize)] # First window
    yield win
    for e in it: # Subsequent windows
        win[:-1] = win[1:]
        win[-1] = e
        yield win

def getMovingAverage(values, windowSize):
    movingAverages = []

    for w in rollingWindow(values, windowSize):
        movingAverages.append(sum(w)/len(w))

    return movingAverages

def getMinimums(values, windowSize):
    minimums = []

    for w in rollingWindow(values, windowSize):
        minimums.append(min(w))

    return minimums

def getMaximums(values, windowSize):
    maximums = []

    for w in rollingWindow(values, windowSize):
        maximums.append(max(w))

    return maximums

## ================================================================

def getTimeSeriesValues(values, window):
    movingAverages = getMovingAverage(values, window)
    minimums = getMinimums(values, window)
    maximums = getMaximums(values, window)

    returnData = []

    # build items of the form [[average, minimum, maximum], normalized price]
    for i in range(0, len(movingAverages)):
        inputNode = [movingAverages[i], minimums[i], maximums[i]]
        price = normalizePrice(values[len(movingAverages) - (i + 1)], minimums[i], maximums[i])
        outputNode = [price]
        tempItem = [inputNode, outputNode]
        returnData.append(tempItem)

    return returnData

## ================================================================

def getHistoricalData(stockSymbol):
    historicalPrices = []

    # login to API
    urllib2.urlopen("http://api.kibot.com/?action=login&user=guest&password=guest")

    # get 14 days of data from API (business days only, could be < 10)
    url = "http://api.kibot.com/?action=history&symbol=" + stockSymbol + "&interval=daily&period=14&unadjusted=1&regularsession=1"
    apiData = urllib2.urlopen(url).read().split("\n")
    for line in apiData:
        if(len(line) > 0):
            tempLine = line.split(',')
            price = float(tempLine[1])
            historicalPrices.append(price)

    return historicalPrices

## ================================================================

def getTrainingData(stockSymbol):
    historicalData = getHistoricalData(stockSymbol)

    # reverse it so we're using the most recent data first, ensure we only have 9 data points
    historicalData.reverse()
    del historicalData[9:]

    # get five 5-day moving averages, 5-day lows, and 5-day highs, associated with the closing price
    trainingData = getTimeSeriesValues(historicalData, 5)

    return trainingData

rawDescription: Python Neural Network and Stock Prices: What to use for input?


code:
import numpy as np

mask = np.ones_like(Data_v_co, dtype='int8')
mask[Data_v_co < 0] = 0

# count zeros
counter = np.prod(mask.shape) - mask.sum()

rawDescription: Python mask for 2D array

description: Python mask for 2D array


code:
offset = dz + np.abs(dz.min())
fracs = offset.astype(float)/offset.max()
norm = colors.normalize(fracs.min(), fracs.max())
colors = cm.jet(norm(fracs))

ax.bar3d(xpos,ypos,zpos,1,1,dz, color=colors)

rawDescription: apply color map to mpl_toolkits.mplot3d.Axes3D.bar3d

description: Apply color map to mpl_toolkits.mplot3d.Axes3D.bar3d


code:
tel = "meh"
validChars = '+-0123456789'
valid = False
while not valid:
    print("Type your Phone Number, then press enter.")
    tel= input("+509-")
    valid = True
    for char in tel:
        if not char in validChars:
            valid = False
            break

rawDescription: Input, raw_input, Iteration

description: Input, raw_input, Iteration


rawDescription: Python numpy broadcasting 3 dimensions (multiple weighted sums)


code:
import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import *

class SelectionWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.ILCheck = False

        ILCheckbox = QCheckBox(self)
        ILCheckbox.setCheckState(Qt.Unchecked)

        ILCheckbox.stateChanged.connect(self.ILCheckbox_changed)

        MainLayout = QGridLayout()
        MainLayout.addWidget(ILCheckbox, 0, 0, 1, 1)

        self.setLayout(MainLayout)

    def ILCheckbox_changed(self, state):
        self.ILCheck = (state == Qt.Checked)

        print(self.ILCheck)

if __name__ == '__main__':
  app = QApplication(sys.argv)
  window = SelectionWindow()

  window.show()
  sys.exit(app.exec_())

rawDescription: Python3 PyQt4 Creating a simple QCheckBox and changing a Boolean variable


code:
data = """a,b,c
d,e,f
g,h,i
j,k,l"""
data.splitlines()

rawDescription: Split string using a newline delimeter with Python


code:
clients = {}
with open('clientdata.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    numbers = []
    for row in reader:
       name = row['Client Name']
       earnings = float(row['Earnings'])
       if name in clients:
           clients[name] += earnings
       else:
           clients[name] = earnings
    for client in sorted(clients):
          print("%s:%.2f" % (client, clients[client]))

rawDescription: python csv list compare and addition

description: Python csv list compare and addition


code:
from decimal import Decimal, getcontext

getcontext().prec = 5

a = Decimal(1)

for x in range(5):
    a += Decimal(0.1)
    print(a)

rawDescription: Python Float Precision about decimals

description: Python Float Precision about decimals


code:
with open('log_file') as f:
    for line in f:
        fields = line.split('\t')
        for field in fields:
            key,_,val = field.partition('=')
            # Do something with each key and val

rawDescription: What is the best way to parse a log file into a python list?


code:
def ballPickerTwo():

    a = random.randint(1, 59)

    b = a
    while b == a:
        b = random.randint(1, 59)

    c = b
    while c == b or c == a:
        c = random.randint(1, 59)

    d = c
    while d == c or d == b or d == a:
        d = random.randint(1, 59)

    ...

rawDescription: Generating Unique Numbers in Python without Using Lists, Sets, Etc


code:
process = subprocess.Popen(['cshift', str(file), str(x_c), str(y_c), str(area)],
                           stdout=subprocess.PIPE)
output = process.stdout.read()

rawDescription: In python, subprocess call using string values


rawDescription: Is there a way to convert integer to a list of integers counting upwards?


rawDescription: Where python variable was defined

description: Where python variable was defined


code:
portfolios['windsorized'] = portfolios.groupby(by='Date')['ROE'].transform(lambda x: (stats.zscore(mstats.winsorize(x[~np.isnan(x)],0.03))))
portfolios

rawDescription: how to merge a groupby output (series) back to the dataframe

description: Merge a groupby output (series) back to the dataframe


code:
def get_all_files(path):
    ## get a generator with all file names
    import os
    import glob
    return glob.iglob(os.path.join(path,'*.opd'))

def get_all_data(files):
    ## get a generator with all the data from all the files
    for fil in files:
        with open(fil, 'r') as the_file:
            for line in the_file:
                yield line

def write_lines_to_file(lines, outfile):
    with open(outfile, 'w') as the_file:
        for line in lines:
            ## add here an if statement if not all lines should be written to outfile
            the_file.write(line+'\n')

path = 'blah blah'
outfile = 'blah.csv'
files = get_all_files(path)
lines = get_all_data(files)
write_lines_to_file(lines, outfile)

rawDescription: Grabbing data from certain files

description: Grabbing data from certain files


code:
import numpy as np
from scipy.spatial import cKDTree

tree = cKDTree(points)
rows_to_fuse = tree.query_pairs(r=30)

print(rows_to_fuse)
# {(8, 9)}

print(points[list(rows_to_fuse.pop())])
# [[ 820.57417943   84.27702407]
#  [ 806.71416007  108.50307828]]

rawDescription: Fast fuse of close points in a numpy-2d (without a for loop)


rawDescription: File Not Showing

description: File Not Showing


code: from __future__ import absolute_import

rawDescription: What's the order Python used to import module?


code:
from django.db.models.signals import post_save

from .... import Apks

def fill_version(sender, instance, created, **kwargs):
    if instance and created:
        instance.version = instance.apk2version()
        instance.save()
post_save.connect(fill_version, sender=Apks)

rawDescription: Filling fields based on uploaded file from the same model


code:
plt.vlines([1,2,3], 0, 1, label='test')
plt.legend()

rawDescription: Matplotlib vline label parameter not showing


code:
import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

rawDescription: Python 3 - Using randint without some values


code:
import requests
from bs4 import BeautifulSoup

user='USERNAME'
pw='PASSWORD'
url='https://www.okcupid.com/login'

session=requests.session()

values = {'username': user, 'password': pw, 'okc_api': '1'}
session.post(url, data=values)
page = session.get('http://www.okcupid.com/')

soup = BeautifulSoup(page.content)
print(soup.title.string)

session.close()

rawDescription: Python: Logging into website with python using GET request


code:
tbl.index.name
tbl.columns.name

rawDescription: How/where does pd.pivot_table store or reference the names of its index and column variables?


code: logFile = open('Dump.log', 'a+')

rawDescription: Checking file if exist then append record


code:
from jinja2 import Template
template = Template('Hello {{ name }}!')
for n in ["John", "Doe"]:
    with open(n + ".txt", "w") as f:
        print >> f, template.render(name=n)

rawDescription: Render to a custom output filename with a single template


rawDescription: Querying objects in a View in DJANGO

description: Querying objects in a View in DJANGO


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

# an array of parameters, each of our curves depend on a specific
# value of parameters
parameters = np.linspace(0,10,11)

# norm is a class which, when called, can normalize data into the
# [0.0, 1.0] interval.
norm = matplotlib.colors.Normalize(
    vmin=np.min(parameters),
    vmax=np.max(parameters))

# choose a colormap
c_m = matplotlib.cm.cool

# create a ScalarMappable and initialize a data structure
s_m = matplotlib.cm.ScalarMappable(cmap=c_m, norm=norm)
s_m.set_array([])

# plotting 11 sines of varying amplitudes, the colors are chosen
# calling the ScalarMappable that was initialised with c_m and norm
x = np.linspace(0,np.pi,31)
for parameter in parameters:
    plt.plot(x,
             parameter*np.sin(x),
             color=s_m.to_rgba(parameter))

# having plotted the 11 curves we plot the colorbar, using again our
# ScalarMappable
plt.colorbar(s_m)

# That's all, folks
plt.show()

rawDescription: Drawing a colorbar aside a line plot, using Matplotlib


code:
def topological_sort(source):
    """perform topo sort on elements.

    :arg source: list of ``(name, [list of dependancies])`` pairs
    :returns: list of names, with dependancies listed first
    """
    pending = [(name, set(deps)) for name, deps in source] # copy deps so we can modify set in-place
    emitted = []
    while pending:
        next_pending = []
        next_emitted = []
        for entry in pending:
            name, deps = entry
            deps.difference_update(emitted) # remove deps we emitted last pass
            if deps: # still has deps? recheck during next pass
                next_pending.append(entry)
            else: # no more deps? time to emit
                yield name
                emitted.append(name) # <-- not required, but helps preserve original ordering
                next_emitted.append(name) # remember what we emitted for difference_update() in next pass
        if not next_emitted: # all entries have unmet deps, one of two things is wrong...
            raise ValueError("cyclic or missing dependancy detected: %r" % (next_pending,))
        pending = next_pending
        emitted = next_emitted

rawDescription: Python: sorting a dependency list

description: Python: sorting a dependency list


code:
from os import listdir
from os.path import abspath, dirname, isfile, join
# get location of __init__.py
init_path = abspath(__file__)
# get folder name of __init__.py
init_dir = dirname(init_path)
# get all python files
py_files = [file_name.replace(".py", "") for file_name in listdir(init_dir) \
           if isfile(join(init_dir, file_name)) and ".py" in file_name and not ".pyc" in file_name]
# remove this __init__ file from the list
py_files.remove("__init__")

__all__ = py_files

rawDescription: Import all modules from the package

description: Import all modules from the package


code:
from jug import TaskGenerator
evaluate = TaskGenerator(evaluate)

for p0 in [1,2,3]:
    for p1 in xrange(10):
        for p2 in xrange(10,20):
             for p3 in [True, False]:
                for p4 in xrange(100):
                    results.append(evaluate(p0,p1,p2,p3,p4))

rawDescription: what is the neat way to divide huge nested loops to 8(or more) processes using Python?

description: What is the neat way to divide huge nested loops to 8(or more) processes using Python


code:
def launch_in_background(args):
    try:
        subprocess.CREATE_NEW_PROCESS_GROUP
    except AttributeError:
        # not Windows, so assume POSIX; if not, we'll get a usable exception
        p = subprocess.Popen(args, start_new_session=True)
    else:
        # Windows
        p = subprocess.Popen(args, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)

rawDescription: python run external program and continue its execution indepentently

description: Python run external program and continue its execution indepentently


code:
from django.contrib import admin
from django.db import models
from django import forms

from .models import Log

class LogAdmin(admin.ModelAdmin):

    formfield_overrides = {
        models.DateTimeField: {'widget': forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S.%f')},
    }

admin.site.register(Log, LogAdmin)

rawDescription: Saving model instance with DateTimeField in Django Admin loses microsecond resolution


code:
files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

rawDescription: python requests file upload

description: Python requests file upload


code:
a = dict()
b = dict()
a[1] = None; b[9] = None
a[9] = None; b[1] = None
a
b

rawDescription: Run .py generates different output whereas .exe is fine


code:
known = {'d': 'dval', 'e': 'eval'}
unknown = ['a', 'b', 'c']
# instead of
"SELECT * FROM table WHERE (a like ? OR b like ? OR c like ?) AND (d like :d AND e like :e)"
known.update(dict((str(i), v) for i, v in enumerate(unknown)))
# and use
"SELECT * FROM table WHERE (a like :1 OR b like :2 OR c like :3) AND (d like :d AND e like :e)"

rawDescription: Python sqlite3 execute with both named and qmark parameters


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: How do I get a Cron like scheduler in Python?

description: Get a Cron like scheduler in Python


code:
class Channel(db.Model):
    name = db.StringProperty(required = True)
    subscriber_list = db.ListProperty(users.User)

    @classmethod
    def addChannelWithName(cls,name):
        channel = cls()
        channel.name = name
        channel.put()

rawDescription: GAE - Datastore model class with function that put()s itself in the database?


code:
for i in href_tags:
    if 'watch' in str(i):
        ff.write(str(i))
    ff.close()

rawDescription: python- youtube. Get url video list

description: Python- youtube. Get url video list


code:
listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}]
[item["id"] for item in listDict]

rawDescription: Getting a list of specific index items from a list of dictionaries in python (list comprehension)


code:
def method1():
    pass

def method2():
    pass

methods = [method1, method2]

rawDescription: How to call a function from a list?

description: Call a function from a list


code:
import sys
sys.path.remove('<path to 2.7>')
sys.path.append('<path to 3.3>')

rawDescription: How do I write a script to change my Path environment?

description: Write a script to change my Path environment


code:
import tagger

id3 = tagger.ID3v2(r'whatever.mp3')

tagged = False
# Try to find a TCON frame to replace the contents
for frame in id3.frames:
    if frame.fid == 'TCON':
        frame.set_text('Blues')
        tagged = True
# There were no TCON frames, add one
if not tagged:
    genre = id3.new_frame('TCON')
    genre.set_text('Blues')
    id3.frames.append(genre)

id3.commit()

rawDescription: how to view and edit meta tags in python programming

description: View and edit meta tags in python programming


code:
import testtools
import unittest

class SampleTestCase(testtools.TestCase):
    def test_it(self):
        self.assertTrue(True)

if __name__ == '__main__':
    unittest.main()

rawDescription: Is it possible to run tests under testtools framework within Python script just like unittest?


code:
class ChartAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ChartAdminForm, self).__init__(*args, **kwargs)
        if self.instance.module_id:
            self.fields['parent'].queryset = self.fields['parent'].queryset.filter(module=self.instance.module)

class ChartAdmin(admin.ModelAdmin):
    form = ChartAdminForm
    ...

rawDescription: Django admin: how do I filter a ForeignKeyField widget based on the object's (not request.user's) data?


code:
my_list = [1,2,3,4,5]
my_set = {*my_list}
my_set

rawDescription: Create a set from a list using {}

description: Create a set from a list using {}


code: os.environ["LD_LIBRARY_PATH"] = ...

rawDescription: change current process environment

description: Change current process environment


code:
class WeightClass(models.Model):
    class_name = models.CharField(max_length=100, unique=True)
    class_info = models.CharField(max_length=50)
    class_group = models.ForeignKey(WeightGroup)

class WeightGroup(models.Model):
    name = models.CharField(max_length=100, unique=True)

rawDescription: Django forms ForeignKey groups

description: Django forms ForeignKey groups


code:
from sys import argv
from zipfile import ZipFile

def unzip(source=None, destination=None):
    zip = ZipFile(source)
    return zip.extractall(destination)

if __name__ == '__main__':
    unzip(source=argv[1], destination=argv[2])

rawDescription: How would I make my Python program unpack a compressed file I drag over it?


rawDescription: How to securely store database password in Python?

description: Securely store database password in Python


code:
import subprocess

os.environ['OMP_NUM_THREADS'] = '{:d}'.format(thread)
proc = subprocess.Popen(["numpy_test"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

rawDescription: How do I automate an environment variable dependent benchmark of BLAS in python/numpy?

description: Automate an environment variable dependent benchmark of BLAS in python/numpy


code:
def pairwise(ListX):
    a = iter(ListX)
    b = iter(ListX)
    next(b, None)
    return izip(a, b)

rawDescription: Iterate through pairs in a Python list and update the pairs during the iteration


code:
values_sum = 0
for key in sorted(dict1,reverse=True):
    values_sum +=dict1[key]
    del dict1[key]
    if values_sum >= 6:
        break

rawDescription: python remove keys whose values add up to a total

description: Python remove keys whose values add up to a total


code:
from itertools import izip

with open("textfile1") as textfile1, open("textfile2") as textfile2:
    for x, y in izip(textfile1, textfile2):
        x = x.strip()
        y = y.strip()
        print("{0}\t{1}".format(x, y))

rawDescription: Read two textfile line by line simultaneously -python


code:
def remote_window_mgr():
    remote_window = client_gui()

class client_gui(object):

    def __init__(self):

        self.root = Tk()
        self.root.title('Client Manager')

        # Create main Frame in Window
        main_frame = ttk.Frame(self.root, borderwidth = 5, relief = 'ridge')
        main_frame.grid(column = 0, row = 0, sticky = (N, W, E, S))
        main_frame.columnconfigure(0, weight = 1)
        main_frame.rowconfigure(0, weight = 1)

        # Create Notebook widget to host Client Tabs
        self.tab_frame = ttk.Notebook(main_frame)
        self.tab_frame.grid(column = 1, row = 1)

        self.root.after(1000, func=self.gui_update)
        self.root.mainloop()

    def gui_update(self):

        for client_id in list(Client_Records.keys()):
            # Check for new Client
            if client_id not in list(Client_Tabs.keys()):
                client_data = Client_Records[client_id]
                # Create Client Tab
                self.add_tab(client_id)

        for client_id in list(Client_Tabs.keys()):
            # Check if Client Record has been purged...
            if client_id not in list(Client_Records.keys()):
                # Client Record no longer exists, delete Client Tab
                self.remove_tab(client_id)
                del Client_Tabs[client_id]

        for client_id in list(Client_Tabs.keys()):
            # Refresh client tabs for all active clients
            self.update_tab(client_id)

        self.root.after(1000, func=self.gui_update)

rawDescription: Dynamically add, hide or forget Tkinter Frames based on Dictionary Record values?


code:
o = subprocess.popen(['cmd','/c',r'programThatRuns.exe'])
o.wait()
subprocess.popen(['cmd','/c',r'otherProgramThatRuns.exe'])

rawDescription: Run an executable, wait for it to produce output, run another program


code: self.mirror_playlist = temp_playlist[:]

rawDescription: Python -- var getting set without me setting it, I may be losing my mind


code:
import socket
socket.getprotobyname('tcp')
socket.getprotobyname('udp')
socket.getprotobyname('icmp')

rawDescription: Any way to map transportation layer protocol name with number？


code:
import celery
import celery.bin.base
import celery.bin.celery
import celery.platforms

app = celery.Celery('tasks', broker='redis://')

status = celery.bin.celery.CeleryCommand.commands['status']()
status.app = status.get_app()

def celery_is_up():
    try:
        status.run()
        return True
    except celery.bin.base.Error as e:
        if e.status == celery.platforms.EX_UNAVAILABLE:
            return False
        raise e

if __name__ == '__main__':
    if celery_is_up():
        print('Celery up!')
    else:
        print('Celery not responding...')

rawDescription: How to check if Celery/Supervisor is running using Python

description: Check if Celery/Supervisor is running using Python


code:
if __name__ == '__main__':
    if len(sys.argv) > 1:
        file_to_process = sys.argv[1]
    else:
        file_to_process = raw_input("Enter file to process: ").strip()

rawDescription: Converting Command line argument to standard input in Python


code: d.setdefault(key, {'idx': []})['idx'] += [2] if d[key]['idx'] else [1]

rawDescription: Request for yet another one liner in Python


code:
s
s.find('3a')

rawDescription: Perl index function equivalent in Python


code:
def index(request):
    latest_player_list = Player.objects.all().order_by('id')[:20]
    total_amount_won = Stakes.objects.filter(player__user_name).aggregate(Sum('amount_won'))
    return render_to_response('stakeme/index.html', {
        'latest_player_list':     latest_player_list,
        'total_amount_won': total_amount_won
     })

rawDescription: Attempting to calculate total in views - displaying blank in template


code:
import MySQLdb
pool = ConnectionPool("MySQLdb", ..., cursorclass=MySQLdb.cursors.DictCursor)
...

rawDescription: Twisted MySQL adbapi return dictionary

description: Twisted MySQL adbapi return dictionary


code:
import subprocess

hostname = "192.168.1.4"
output = subprocess.Popen(["ping","-c","5", hostname],stdout = subprocess.PIPE).communicate()[0]

if ('100% packet loss' in output):
    print("Offline")

rawDescription: How to ping in local network using python?

description: Ping in local network using python


code:
import encodings
import os
import pkgutil

modnames=set([modname for importer, modname, ispkg in pkgutil.walk_packages(
    path=[os.path.dirname(encodings.__file__)], prefix='')])
aliases=set(encodings.aliases.aliases.values())

print(modnames-aliases)
# set(['charmap', 'unicode_escape', 'cp1006', 'unicode_internal', 'punycode', 'string_escape', 'aliases', 'palmos', 'mac_centeuro', 'mac_farsi', 'mac_romanian', 'cp856', 'raw_unicode_escape', 'mac_croatian', 'utf_8_sig', 'mac_arabic', 'undefined', 'cp737', 'idna', 'koi8_u', 'cp875', 'cp874', 'iso8859_1'])

print(aliases-modnames)
# set(['tactis'])

codec_names=modnames.union(aliases)
print(codec_names)
# set(['bz2_codec', 'cp1140', 'euc_jp', 'cp932', 'punycode', 'euc_jisx0213', 'aliases', 'hex_codec', 'cp500', 'uu_codec', 'big5hkscs', 'mac_romanian', 'mbcs', 'euc_jis_2004', 'iso2022_jp_3', 'iso2022_jp_2', 'iso2022_jp_1', 'gbk', 'iso2022_jp_2004', 'unicode_internal', 'utf_16_be', 'quopri_codec', 'cp424', 'iso2022_jp', 'mac_iceland', 'raw_unicode_escape', 'hp_roman8', 'iso2022_kr', 'cp875', 'iso8859_6', 'cp1254', 'utf_32_be', 'gb2312', 'cp850', 'shift_jis', 'cp852', 'cp855', 'iso8859_3', 'cp857', 'cp856', 'cp775', 'unicode_escape', 'cp1026', 'mac_latin2', 'utf_32', 'mac_cyrillic', 'base64_codec', 'ptcp154', 'palmos', 'mac_centeuro', 'euc_kr', 'hz', 'utf_8', 'utf_32_le', 'mac_greek', 'utf_7', 'mac_turkish', 'utf_8_sig', 'mac_arabic', 'tactis', 'cp949', 'zlib_codec', 'big5', 'iso8859_9', 'iso8859_8', 'iso8859_5', 'iso8859_4', 'iso8859_7', 'cp874', 'iso8859_1', 'utf_16_le', 'iso8859_2', 'charmap', 'gb18030', 'cp1006', 'shift_jis_2004', 'mac_roman', 'ascii', 'string_escape', 'iso8859_15', 'iso8859_14', 'tis_620', 'iso8859_16', 'iso8859_11', 'iso8859_10', 'iso8859_13', 'cp950', 'utf_16', 'cp869', 'mac_farsi', 'rot_13', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'shift_jisx0213', 'johab', 'mac_croatian', 'cp1255', 'latin_1', 'cp1257', 'cp1256', 'cp1251', 'cp1250', 'cp1253', 'cp1252', 'cp437', 'cp1258', 'undefined', 'cp737', 'koi8_r', 'cp037', 'koi8_u', 'iso2022_jp_ext', 'idna'])

rawDescription: How can I programmatically find the list of codecs known to Python?

description: Programmatically find the list of codecs known to Python


code:
course_name = ('English', 'Maths',)
from model_utils import Choices
class Course(models.Model):
    course_document = models.ForeignKey(Document,null=True,blank=True)
    name = models.CharField(max_length=255, choices=Choices(*course_name))
    subject = models.CharField(max_length = 255)

rawDescription: Displaying objects as a choice inside a template


code:
csvdata = pkgutil.get_data("curve", "ntc.10k.csv")
csvio = StringIO(csvdata)
raw = csv.reader(csvio)

rawDescription: how to use pkgutils.get_data with csv.reader in python?

description: Use pkgutils.get_data with csv.reader in python


code:
from itertools import combinations, product
seq = [1, (2, 3), (4, 5), 6]
seq = [x if isinstance(x, tuple) else (x,) for x in seq]
[sel for subseq in combinations(seq, 3) for sel in product(*subseq)]

rawDescription: Create all combinations of lists from a list of lists in python


rawDescription: Python: Sum rows in Pandas dataframe which match a column value?


code:
from itertools import product
from re import match

the_lists = []

with open("filename.txt", "r") as file:
    for line in file:
        m = match(r'(.*) \((\d+)\)', line)
        word = m.group(1)
        num = int(m.group(2))
        the_list = [word[i:i+num] for i in range(len(word) - num + 1)]
        the_lists.append(the_list)

combinaisons = product(*the_lists)

final_list = ["".join(c) for c in combinaisons]

rawDescription: Sum of lists for each element of list1 with all in list2


code:
def std_output(stdout,outfile=''):
    out = 0
    f = codecs.open(outfile,'w','UTF-8')
    for line in iter(stdout.readline, ''):
        f.write('%s\n'%(line.rstrip().decode('UTF-8')))
        out += 1
        if i == out: break
    stdout.close()
    f.close()

outfile = '/path/myout'
infile = '/path/mydata'

subproc = subprocess.Popen(args,**kw)
t = threading.Thread(target=std_output,args=[subproc.stdout,outfile])
t.daemon = True
t.start()

i = 0
f = codecs.open(infile,'r','UTF-8')
for line in f:
    subproc.stdin.write('%s\n'%(line.strip().encode('UTF-8')))
    i += 1
subproc.stdin.write('%s\n'%(' '*4096)) ### push dummy data ###
f.close()
t.join()
subproc.terminate()

rawDescription: How can I use Python to pipe stdin/stdout to Perl script

description: Use Python to pipe stdin/stdout to Perl script


code:
class ProductAdminForm(ModelForm):
   email_users = forms.ModelMultipleChoiceField(queryset=User.objects.order_by('username'))

   class Meta:
      model = Product

class ProductAdmin(admin.ModelAdmin):
   list_display = ('name','platform')
   form = ProductAdminForm

admin.site.register(Product, ProductAdmin)

rawDescription: Ordering a Many-To-Many field in Django Admin


code:
def test_should_get_403_when_csrf_enforced(self):
    self.client = test.Client(enforce_csrf_checks=True)
    self.client.cookies[settings.CSRF_COOKIE_NAME] = 'asdf'
    response = self.client.post(url, {'name': 'foobar'})
    self.assertEqual(403, response.status_code)

rawDescription: How to set the _dont_enforce_csrf_checks using the django test client

description: Set the _dont_enforce_csrf_checks using the django test client


code:
for i in string:
      if i == '\\':
            do_something

rawDescription: '\' wont close quotes

description: '\' wont close quotes


code:
import struct
struct.unpack(">h",'\x41\x42')
struct.unpack(">h",'\x41\x42')[0]

rawDescription: Python string to integer value

description: Python string to integer value


code: output = np.einsum('ijk,ikl->ijl', a, b)

rawDescription: Single operation to take the matrix product along only the last two dimensions


code:
def set_attribute(*args):
    driver.execute_script("arguments[0].setAttribute(arguments[1], arguments[2]);", *args)

elm = driver.find_element_by_class_name("shot-circle")
set_attribute(elm, "cx", "150")
set_attribute(elm, "cy", "150")

rawDescription: Changing cx/cy values using selenium

description: Changing cx/cy values using selenium


code:
class BiomSearchJob(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    completed = models.BooleanField(default=False)
    criteria = models.ManyToManyField('EcosystemChoices', related_name='%(app_label)s_%(class)s_prs', blank=True)
    otu_text = models.TextField(default=None)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def set_completed(self, completed):
        self.completed = completed

class EcosystemChoices(models.Model):
    ecosystem = models.CharField(verbose_name=u'Ecosystem Type', max_length=60, help_text='Select all that apply')

rawDescription: How to validate array of choices in Django ModelForm against preset list of choices

description: Validate array of choices in Django ModelForm against preset list of choices


code:
def Load(self):
    self.webView.page().setViewportSize(
        self.webView.page().mainFrame().contentsSize())

rawDescription: PyQt QWebKit frame bug?

description: PyQt QWebKit frame bug


code:
self.connect(button3, SIGNAL("clicked()"),
    lambda who="Three": self.anyButton(who))

rawDescription: PyQt sending parameter to slot when connecting to a signal


rawDescription: What is a better way to deal with unknown list structures in python?


code:
with open("outputHorizontal.{0}.txt".format(lat), 'w') as file:
    for item in I_list:
        file.write("{}\n".format(item))

rawDescription: naming txt output files python

description: Naming txt output files python


code:
import requests

response = requests.get(url, auth=(username, password))
# search for your string in response.contents

rawDescription: using webbrowser in python to authenticate

description: Using webbrowser in python to authenticate


code:
class UnicodeMatcherWrapper(object):
    def __init__(self, matcher):
        if hasattr(matcher, 'matcher'):
            matcher.matcher = UnicodeMatcherWrapper(matcher.matcher)

            if hasattr(matcher, 'matchers'):
                matcher.matchers = [UnicodeMatcherWrapper(nested_matcher) for nested_matcher in matcher.matchers]

        self.matcher = matcher

    def __getattr__(self, item):
        return getattr(self.matcher, item)

    def __str__(self):
        return unicode(StringDescription().append_description_of(self.matcher))

rawDescription: Python 2.7 PyHamcrest 1.8.5 Matchers with unicode symbols


code:
opts = argparse.ArgumentParser(prog='foo', description=__doc__)
group.add_argument('-v', '--version', action='version',
                   version=__version__)
opts.add_argument('--log', default='warning',
                  choices=['debug', 'info', 'warning', 'error'],
                  help="logging level (defaults to 'warning')")
opts.add_argument("files", metavar='file', nargs='*',
                  help="one or more files to process")
args = opts.parse_args(argv)
logging.basicConfig(level=getattr(logging, args.log.upper(), None),
                    format='%(levelname)s: %(message)s')

rawDescription: Do I need to explicitly check for __name__ == "__main__" before calling getLogger in Python?


code:
lst = [False] * 10
lst
lst[:] = [not x for x in lst]
lst
lst[1::2] = [not x for x in lst[1::2]]
lst

rawDescription: Change Boolean Value Python 3

description: Change Boolean Value Python 3


rawDescription: str object in Python 2.7 doesn't have __iter__, yet it act like iterable. Why?

description: Str object in Python 2.7 doesn't have __iter__, yet it act like iterable. Why


code:
saved_sieve_map = {}
def saved_sieve(x):
  if x not in saved_sieve_map:
    saved_sieve_map[x] = sieve(x)
  return saved_sieve_map[x]

rawDescription: How do I store results of a computation in Python so my program doesn't compute the same thing twice?

description: Store results of a computation in Python so my program doesn't compute the same thing twice


code:
from collections import defaultdict

rooms = defaultdict(Room)

rooms[0].addPlayer("joe")
rooms[0].addPlayer("bob")
rooms[32].addPlayer("alice")

rawDescription: Python Converting a class into an Array of specific functions for each criteria


code:
for path, dirs, files in os.walk('randomDir'):
    for fpath in files:
        im = Image.open(os.path.join(path, fpath))
        print(im.format, im.size)

rawDescription: using im.format and im.size for a whole directory rather than a single jpeg file

description: Using im.format and im.size for a whole directory rather than a single jpeg file


code:
my_lists = [[3,2,2,3,4,1,3,4], [1,2,3,4,5,6]]
my_tuple_list = [(3,5), (6, 7)]
my_dict = dict(my_tuple_list)
my_dict
my_lists = [[my_dict.get(x,x) for x in somelist] for somelist in my_lists]
my_lists

rawDescription: python replace list values using a tuple

description: Python replace list values using a tuple


code: query1 | query2

rawDescription: Union of 2 SearchQuerySet in django haystack


code:
import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
book = excel.Workbooks.Add()
sheet = book.Worksheets(1)

excel.ActiveWindow.DisplayGridlines = False

rawDescription: Python win32com, How to Hide Gridlines

description: Python win32com, How to Hide Gridlines


code:
class ExampleSpider(scrapy.Spider):
    name = 'example.com'
    start_urls = ['http://www.example.com/FormPage.php']

    def parse(self, response):
        request = scrapy.FormRequest.from_response(
            response,
            callback=self.parse_response_from_Form
        )
        request.replace(url='http://www.other-site.com/')
        return request

    def parse_response_from_Form(self, response):
        # go on here...
        pass

rawDescription: scrapy form-filling when form posts to a second web page

description: Scrapy form-filling when form posts to a second web page


code:
depth = 0 #To count nested blocks
word = "" #To keep track of the code we find before delving into another block
resultString = "" #To keep track of all code in the outermost block
inputJS = "var test = require(\"./test\");\n{\nvar test2 = require(\"./test2\");\n}\n" #input string
for i in inputJS: #Loop through one letter at a time
    if i == "{": #If it is an opening brace then increase depth
        resultString += word
        depth += 1
        word = ""
    elif i == "}": #If it is a closing brace decrease depth
        depth-=1
    elif depth == 0: #If we are at the top scope then keep track of the character
        word += i

#Parse resultString Normally

rawDescription: Regular expressions - unmatch if inside braces


rawDescription: creating data for matplotlib

description: Creating data for matplotlib


code:
import networkx as nx
import matplotlib.pyplot as plt

def print_graph(graph):
    """ prints the graph"""

    # stores the nodes and their name attributes in a dictionary
    nodes_names = nx.get_node_attributes(graph, "name")
    plt.ion()
    pos = nx.spring_layout(graph)

    # draw without labels, cuz it would label them with their adress, since we
    nx.draw(graph, pos, with_labels=False)

    # draw the label with the nodes_names containing the name attribute
    labels = nx.draw_networkx_labels(graph, pos, nodes_names)
    plt.show()

def setup_sending(graph):
    print_graph(graph)

    ###some code doing calculations....

    raw_input('Press enter to continue')

def main():
    G=nx.dodecahedral_graph()
    setup_sending(G)

if __name__ == '__main__':
    main()

rawDescription: interactive graph with matplotlib and networkx

description: Interactive graph with matplotlib and networkx


code:
class Test():
    def __init__(self):
        self.base = numpy.zeros(6)
        self.slice = slice(-3, self.base.size)
        self.view = self.base[self.slice]

    def __len__(self):
        return len(self.view)

    def update(self):
        self.view[0] += 1

    def add(self):
        self.slice = slice(-len(self.view) - 1, self.base.size)
        self.view = self.base[self.slice]
        self.view[0] = 1

    def __getstate__(self):
        return {'base': self.base, 'slice': self.slice}

    def __setstate__(self, state):
        self.base = state['base']
        self.slice = state['slice']
        self.view = self.base[self.slice]

    def __repr__(self):
        return str(self.view)

rawDescription: Unexpected behavior serializing Numpy array


code:
while True:
    x = input("Enter the message you would like to encrypt via a Caeser shift; or type 'exit': ")
    if x == 'exit': break
    y = int(input("Enter the number by which you would like to have the message Caeser shifted: "))
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    encoded = ''
    for c in x:
        if c.lower() in alphabet:
            i = (alphabet.index(c.lower()) + y) % 26
            encoded += alphabet[i] if c.islower() else alphabet[i].upper()
        else:
            encoded += c
    print(encoded)

rawDescription: Shifting within a list when past end range?


code:
def sum_neighbors(list):
    new_list = []
    new_list.append(list[0] + list[1])
    x = 1
    while x < len(list) - 1:
        new_list.append(list[x - 1] + list[x] + list[x + 1])
        x += 1
    new_list.append(list[x - 1] + list[x])

    return new_list

rawDescription: Python Code to Create Sum of Neighbors and itself in the original list


code:
t = [1,2,3,4]
f = ['apples', 'oranges','grapes','pears']
l = []
l.append(['Fruit', 'Total'])
l.extend([list(a) for a in zip(f, t)])
l

rawDescription: Create nested list from two lists

description: Create nested list from two lists


code:
dfrm
dfrm1 = dfrm.copy()
dfrm1.ix[3, 'D'] = 888
dfrm1
pandas.merge(dfrm, dfrm1, left_on='D', right_on='D', how='outer')

rawDescription: Is there a "pandas" way to identify which rows from a DataFrame are not present in a merge result?


rawDescription: Combine certain elements of a list

description: Combine certain elements of a list


code:
import itertools
for rm_file in itertools.chain.from_iterable(rm_file_list):
    os.remove(rm_file)

rawDescription: loop in 2-dimension array in Python(list)

description: Loop in 2-dimension array in Python(list)


code:
result = []
for each in run_time_results:
    result.append(each)

rawDescription: In python how can we append run time reults to a list?


code:
fp = open('myfile')
last_pos = fp.tell()
line = fp.readline()
while line != '':
  if line == 'SPECIAL':
    fp.seek(last_pos)
    other_function(fp)
    break
  last_pos = fp.tell()
  line = fp.readline()

rawDescription: Python: Undo a Python file readline() operation so file pointer is back in original state


code:
class Course(models.Model):
    name = models.CharField(max_length=100)
    attendance = models.CharField(max_length=100)

    def __unicode__(self):
        return "%s (%s)" % (self.name, self.attendance)

rawDescription: Django admin, show 2 or more attributes in a field


code:
import wx
import wx.grid as gridlib

########################################################################
class LeftPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        grid = gridlib.Grid(self)
        grid.CreateGrid(25,12)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 0, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class RightPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        txt = wx.TextCtrl(self)

class MyForm(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Splitter Tutorial")

        splitter = wx.SplitterWindow(self)
        leftP = LeftPanel(splitter)
        rightP = RightPanel(splitter)

        # split the window
        splitter.SplitVertically(leftP, rightP)
        splitter.SetMinimumPaneSize(20)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

rawDescription: wxPython Splitter windows and Panels

description: WxPython Splitter windows and Panels


code:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active

for row in range(1,10):
        value = ws.cell(row=row,column=1).value = row+5

for row in range(1,10):
        value2 = ws.cell(row=row,column=2).value = row

wb.save("SampleChart.xlsx")

from openpyxl.charts import Reference, Series,LineChart

# setup the chart
chart = LineChart()
chart.drawing.name = 'This is my chart'

# setup and append the first series
values = Reference(ws, (1, 1), (9, 1))
series = Series(values, title="First series of values")
chart.append(series)

# setup and append the second series
values = Reference(ws, (1, 2), (9, 2))
series = Series(values, title="Second series of values")
chart.append(series)

ws.add_chart(chart)
wb.save("SampleChart.xlsx")

rawDescription: How we can draw two series of data in "openpyxl" package of python (line-chart)


code:
self.testbed.setup_env(
    USER_EMAIL = 'test@example.com',
    USER_ID = '123',
    USER_IS_ADMIN = '1',
    overwrite = True)

rawDescription: Google App Engine set up a user when using testbed


code:
import web

urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:
    def GET(self, name):
        if not name:
            name = 'World'
        return 'Hello, ' + name + '!'

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

rawDescription: python code to echo ajax requests

description: Python code to echo ajax requests


code: getvalues['DLT'] = data

rawDescription: Can I replace a column with values that are in a text file (space delemited) with values that are in a np.array

description: Replace a column with values that are in a text file (space delemited) with values that are in a np.array


code:
import posixpath
posixpath.join
posixpath.join('a','b')
posixpath.commonprefix

rawDescription: Using os.path for Posix Path Operations on Windows


code:
def data(self , index , role):
    if role == Qt.ToolTipRole:
        return self.d

    if role == Qt.DisplayRole:
        return self.d.text()

    return QStandardItemModel.data(self, index, role)

rawDescription: Custom QStandardItemModel with custom data method


code:
import numpy as np
from scipy.integrate import ode

def func(t, y, z):
    return y+z

t = np.linspace(0, 1.0, 100)
dt = t[1]-t[0]
z = np.random.rand(100)
output = np.empty_like(t)
r = ode(func).set_integrator("dop853")
r.set_initial_value(0, 0).set_f_params(z[0])

for i in xrange(len(t)):
    r.set_f_params(z[i])
    r.integrate(r.t+dt)
    output[i] = r.y

rawDescription: Current iteration in scipy odeint

description: Current iteration in scipy odeint


rawDescription: How to use numpy's hstack?

description: Use numpy's hstack


code: result = [(elem, i) for i, elem in enumerate(point[1:])]

rawDescription: create tuple list of key,val from another list of values in Python

description: Create tuple list of key,val from another list of values in Python


rawDescription: Matplotlib heat map, vertical bottom label


code:
import aiohttp
import asyncio

async def fetch(session, url):
    with aiohttp.Timeout(10):
        async with session.get(url) as response:
            return await response.text()

async def fetch_all(session, urls, loop):
    results = await asyncio.wait([loop.create_task(fetch(session, url))
                                  for url in urls])
    return results

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    urls = ['http://cnn.com',
            'http://google.com',
            'http://twitter.com']
    with aiohttp.ClientSession(loop=loop) as session:
        htmls = loop.run_until_complete(
            fetch_all(session, urls, loop))
        print(htmls)

rawDescription: Fetching multiple urls with aiohttp in Python 3.5


code:
def is_member(value, array):
    if len(array) == 0:
        return False
    return value == array[0] or is_member(value, array[1:])

rawDescription: List membership in Python without "in"

description: List membership in Python without "in"


code:
# call job_function with arguments 'hello' and 'world'
sched.add_cron_job(job_function, args=('hello', 'world'), month='1', day='1st fri', hour='0')

rawDescription: function pointer with parameters in python?

description: Function pointer with parameters in python


code:
class Foo(generics.RetrieveDestroyAPIView):
    serializer_class = FooSerializer

    def get_object(self):
        return Foo.objects.all()[self.kwargs['foo_if_in_url'] - 1]

rawDescription: Overriding how a generic class based looks up an object from the URL arguments


code:
@register.assignment_tag(takes_context=True)
def comment_metadata(context, parent):
    comments_queryset = parent.comments.visible()
    # Perform whatever analysis you want on the comments,
    # and return a variable that will be available in your template context.

rawDescription: Access inclusion_tag context variables before included template is rendered


code:
import datetime
def back_in_the_past(start_year):
    start_date = datetime.datetime(start_year, 12, 31)
    for i in range(0, 5):
      new_date = start_date - datetime.timedelta(i)
      print(new_date.strftime("%Y-%m-%d"))

back_in_the_past(2014)

rawDescription: decrease the days in python

description: Decrease the days in python


code:
class Hop(models.Model):
    migration = models.ForeignKey('Migration')
    host = models.ForeignKey(User, related_name='host_set')

    class Meta:
        unique_together = (("migration", "host"),)

rawDescription: How can set two field primary key for my models in django


code:
index_list = []
for n, item in enumerate(list):
    if len(item) == 0:
        index_list.append(n)

rawDescription: Python: Create a list of nonmatching values


code:
from datetime import datetime
t = datetime.strptime('07 Aug 2008, 16:25', '%d %b %Y, %H:%M')
t.strftime('%Y-%m-%d %H:%M:%S')

rawDescription: Most Efficient Way in Python to Convert String with Whitespaces to DateTime for MySql


code:
def func(*args):
    return all('a' in str(x) for x in args)

rawDescription: python- with an undetermined tuple (str), how to find if a letter is in each one of the strings

description: Python- with an undetermined tuple (str), how to find if a letter is in each one of the strings


code:
# Import required alphabet
from Bio.Alphabet import IUPAC

# Pass imported alphabet as an argument for `SeqIO.parse`:
records = list(SeqIO.parse(handle, 'fasta', IUPAC.extended_protein))

rawDescription: BioPython: How to convert the amino acid alphlabet to


code:
import os

# no more than 100 million items in memory at a time
MAXINMEM = int(1e8)

class bigarray(object):
  def __init__(self):
    self.f = open('afile.dat', 'w+')
    self.a = array.array('L')
  def append(self, n):
    self.a.append(n)
    if len(self.a) > MAXINMEM:
      self.a.tofile(self.f)
      del self.a[:]
  def pop(self):
    if not len(self.a):
      try: self.f.seek(-self.a.itemsize * MAXINMEM, os.SEEK_END)
      except IOError: return self.a.pop()  # ensure normal IndexError &c
      try: self.a.fromfile(self.f, MAXINMEM)
      except EOFError: pass
      self.f.seek(-self.a.itemsize * MAXINMEM, os.SEEK_END)
      self.f.truncate()
    return self.a.pop()

rawDescription: Alternatives to keeping large lists in memory (python)


code:
from django.http import QueryDict
form = Myform(QueryDict(my_model.querystring).dict())

rawDescription: Is there a way to populate a form with a querystring?


code:
scratch = open("mcs_scratch.txt","wb")
scratch.write(str(y))
scratch = open("mcs_scratch.txt","r")
y = str(scratch.read())

rawDescription: issues turning a dict element into a string to search w/ regex

description: Issues turning a dict element into a string to search w/ regex


code:
for k in filter(lambda k: not k.startswith('_'), dir(other)): # avoid copying private items
    setattr(self, k, getattr(other, k))

rawDescription: Python: Fusing two separate objects into one?


code:
from selenium import webdriver
from selenium.webdriver import ActionChains

driver = webdriver.Chrome()
actionChains = ActionChains(driver)

actionChains.context_click(your_link).perform()

rawDescription: How to perform right click using Selenium ChromeDriver?

description: Perform right click using Selenium ChromeDriver


code: print('        %-40s%s' % (self.serverrqs()*int(self.nbpro), self.servernbrqs()))

rawDescription: python how to align data with pprint or another module

description: Python how to align data with pprint or another module


code:
import inspect
import sys
inspect.getmembers(sys.modules[__name__], inspect.isfunction)

rawDescription: auto collect information in sub_modules when import in python?

description: Auto collect information in sub_modules when import in python


code:
def program():
    return "Hello World!"

rawDescription: Writing the results of a function to a file in Python 2.7


code:
@classmethod
def _init_args(cls):
    return getargspec(cls.__init__).args[1:]

rawDescription: Get the method on a class or its parents


code:
from django import forms

_choices = ['to be', 'not to be']
class SomeForm(forms.Form):
    field = forms.ChoiceField(choices=[(item, item) for item in _choices],
                   widget=forms.HiddenInput()) # the real field

    mock_field = forms.ChoiceField(required=False, # doesn't get submitted
                        choices=[(item, item) for item in _choices],
                        label="The question",
                        widget=forms.Select(attrs={'disabled':'disabled'}))

    def __init__(self, *args, **kwargs):
        super(SomeForm, self).__init__(*args, **kwargs)
        mock_initial = kwargs['initial']['field']
        self.fields['mock_field'].choices = [(mock_initial, mock_initial),]

rawDescription: Django forms: making a disabled field persist between validations


code:
from dateutil import parser
...
my_date = parser.parse(my_object.date)
proper_date_string = my_date.strftime('%d-%m-%Y')

rawDescription: How to change field.date format in OpenERP 7 (Odoo)

description: Change field.date format in OpenERP 7 (Odoo)


code:
print_fn = partial(a_func, 'A', 'B')
print_fn.__closure__
print_fn.__closure__[0].cell_contents

rawDescription: python : understaning partial functions

description: Python : understaning partial functions


code:
command = raw_input(">>>    ")
exec(command)

rawDescription: Python: Making raw_input execute

description: Python: Making raw_input execute


code:
def myfunc(*args, **kwargs):
    ...

rawDescription: what if the key in kwargs has conflict with the function keyword

description: What if the key in kwargs has conflict with the function keyword


code:
files = glob.glob('/Users/andreasportelli/Desktop/sqldata/*')

customer = {"customer_id":[],"order_id":[]}  #create a dictionary

for file in files:
    customer["customer_id"].append(file)
    for line in open(file, 'r', encoding='ascii', errors='replace'):
        customer["order_id"].append(line[:7])

rawDescription: How to read multiple lines in a txt file in a loop?

description: Read multiple lines in a txt file in a loop


code:
progress = 0
lastLine = ''
n = 5 # seconds
while progress < 100:
    with open('path/to/logfile') as logfile:
        for newLine in logfile:
            pass
        if newLine.strip() != lastLine:
            lastLine = newLine.strip()
            writeToDatabase(lastLine)
    time.sleep(n)

rawDescription: Real-time progress from log file

description: Real-time progress from log file


rawDescription: How can I fetch the page source of a webpage using Python?

description: Fetch the page source of a webpage using Python


code:
txheaders = { "User-Agent": UA, "Host": nohttp_url }
robots = urllib2.Request("http://" + ip  + "/robots.txt", txdata, txheaders)

rawDescription: Set Host-header when using Python and urllib2


code:
import textwrap
s = '0100100001101001'
textwrap.wrap(s, 8)

rawDescription: Iterating through a string in Python in 8-character chunks


code:
DATABASES = {
    'default': {
        'NAME': 'app_data',
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'USER': 'postgres_user',
        'PASSWORD': 's3krit'
    },
    'users': {
        'NAME': 'user_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    }
}

rawDescription: interacting with an external django project from within another django project

description: Interacting with an external django project from within another django project


code:
import ast
my_list = ast.literal_eval("[[1, 2, 3],[4, 5, 6]]")
print(my_list)
print(type(my_list))

rawDescription: How can I read a python list from a text file?

description: Read a python list from a text file


code:
dshape = discover(resource('report_2015.csv'))
t = odo('report_2015.csv', 'sqlite:///report.db::report', dshape=dshape)

rawDescription: Using odo to migrate data to SQL

description: Using odo to migrate data to SQL


code:
def set_value(redis, key, value):
    redis.set(key, pickle.dumps(value))

def get_value(redis, key):
    pickled_value = redis.get(key)
    if pickled_value is None:
        return None
    return pickle.loads(pickled_value)

rawDescription: get object from redis without eval?

description: Get object from redis without eval


code:
def clean_custom_title(self):
    title = self.cleaned_data.get('custom_title')
    if title:
        title = "<foo>%s</foo>"%title
        title = lxml.html.fromstring(title)
        # title = lxml.some_function(title)  # strip <foo> in a 'proper' way
        title = lxml.etree.tostring(title)
        title = title[5:-6] # This is a hack to illustrate the premise
    return title

rawDescription: Close open tags without wrapping in <p>

description: Close open tags without wrapping in <p>


code:
from functools import wraps

def logging_decorator(fn):
    @wraps(fn)
    def wrapped(self, *a, **kw):
        if self.log:
            print("Calling %s.." % fn.__name__)
        return fn(self, *a, **kw)
    return wrapped

class Tricky(object):
    def __init__(self, log):
        self.log = log

    @logging_decorator
    def say_hi(self):
       print("Hello, world!")

i1 = Tricky(log=True)
i2 = Tricky(log=False)

i1.say_hi()
i2.say_hi()

rawDescription: Python: Anything wrong with dynamically assigning instance methods as instance attributes


code: obj = Foo.objects.latest('id')

rawDescription: How do you find a lastest pk in a Django Table?

description: Find a lastest pk in a Django Table


code:
import Image
import ImageDraw

im = Image.open("image.jpg")
im.thumbnail((300,300))
box = im.getbbox()
im2=im.crop((box[0], box[1], box[2], box[3]+50))
draw=ImageDraw.Draw(im2)
draw.text((box[2]-100,box[3]+10), "Copyright")
im2.show()

rawDescription: Python PIL create thumbnail image with copyright text


code:
from django.core.cache import cache

# set cached data
cache.set('data', data)
# get cached data
cache.get('data')

rawDescription: How to deal with unstable data received from RFID reader?

description: Deal with unstable data received from RFID reader


code:
from operator import itemgetter
lst = [589, 354, 692, 474, 739, 731, 259, 723, 497, 48]
# temp is list as pairs of original index and value, sorted by value
temp = [[i, e] for i, e in sorted(enumerate(lst), key=itemgetter(1))]
last = None
for item in temp:
    while last is not None and item[1] < last + 10:
        item[1] += 10
    last = item[1]
# sort the list back to original order using the index from the tuple
lst_new = [e for i, e in sorted(temp, key=itemgetter(0))]

rawDescription: How to (efficiently) check if any two elements differ by 10


code:
from datetime import datetime
from datetime import timedelta

now = datetime.now()
start_of_day = datetime(now.year,now.month,now.day)
delta_since_start_of_day = now - start_of_day
delta_till_end_of_day = timedelta(days=1) - delta_since_start_of_day
end_of_day = start_of_day + timedelta(days=1)

rawDescription: Expand date to the beginning and end datetime for the day


code:
i = 0
while i < len(z):
    j = i+1
    while j < len(z):
        if any([z[i][n]==z[j][n] for n in range(len(z[0]))]):
            del z[j] # Shift all values, so no need to update j
        else:
            j += 1
    i += 1

rawDescription: Python: List of tuples: compare all tuples and retrive tuples where the elements of tuples are not equal to any other tuple


code:
db = MySQLdb.connect(host="xxx.xx.xx.x",
                     user="xxx",
                     passwd="xxx",
                     db="xxxx")
cursor = db.cursor()
cursor.executemany('Insert Query',json_data)
db.commit()
cursor.close()
db.close()

rawDescription: Optimising mysql insert query via python


rawDescription: Python: List of integers to datetime?

description: Python: List of integers to datetime


code:
axScatter_Scatter.text(0.1, 0.1, r'$\mathrm{(a)}$', fontsize=12,
        transform=axScatter_Scatter.transAxes)
axScatter_Hist.text(0.1, 0.1, r'$\mathrm{(b)}$', fontsize=12,
        transform=axScatter_Hist.transAxes)

rawDescription: Placing of text by specifying distance from axes


rawDescription: Right-to-left string replace in Python?

description: Right-to-left string replace in Python


code:
start = self.TextWidg("insert linestart")
end = self.TextWidg("insert lineend")

rawDescription: Swapping lines in a Tkinter text widget

description: Swapping lines in a Tkinter text widget


code:
import xlwt as xlwt
from os.path import join
import xlrd

output = xlwt.Workbook()

path = r'C:\data_path\\'

xls1 = 'file1.xls'
xls2 = 'file2.xls'
xls3 = 'file3.xls'

Sheet1 = 'file1_data'
Sheet2 = 'file2_data'
Sheet3 = 'file3_data'

names = [Sheet1, Sheet2, Sheet3]
dataset = [path + xls1, path + xls2, path + xls3]

for n, data in enumerate(dataset):
    book = xlrd.open_workbook(data, formatting_info=True)

    sheet = book.sheet_by_index(0)
    r = output.add_sheet(names[n])

    for row in range(sheet.nrows):
        for column in range(sheet.ncols):
            cell_val = sheet.cell_value(rowx=row, colx=column)
            r.write(row, column, cell_val)

output.save(join(path,'test.xls'))

rawDescription: Use with..open to read a list of xls files to copy into a single workbook with multiple sheets


code:
from django.db.models import Max
Product.objects.values('product_id').annotate(latest=Max('updated_on'))

rawDescription: Django ORM: How to query for the latest row based on a another attribute


rawDescription: Ironpython Array[byte] to byte string

description: Ironpython Array[byte] to byte string


code:
outputstream = StringIO.StringIO()
PDF = output.write(outputstream)

class PDFHandler(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = 'attachment; filename=Myfile.pdf'
        self.response.headers['Content-Transfer-Encoding'] = 'binary'
        self.response.out.write(PDF.getvalue())

rawDescription: User downloadable PDFs in Google App Engine returning corrupted PDFs


code:
import Image

background = Image.open("bg.png")
overlay = Image.open("ol.jpg")

background = background.convert("RGBA")
overlay = overlay.convert("RGBA")

new_img = Image.blend(background, overlay, 0.5)
new_img.save("new.png","PNG")

rawDescription: Overlay two same sized images in Python

description: Overlay two same sized images in Python


code:
import plotly
import plotly.graph_objs

plotly.offline.plot({
"data": [
    plotly.graph_objs.Bar(x=['food','service','environment'],y=[3.4,4.2,4.3])
]
})

rawDescription: How to draw bar chart using Plotly Offline mod in python?

description: Draw bar chart using Plotly Offline mod in python


code:
import numpy as np

def find_closest(A, target):
    #A must be sorted
    idx = A.searchsorted(target)
    idx = np.clip(idx, 1, len(A)-1)
    left = A[idx-1]
    right = A[idx]
    idx -= target - left < right - target
    return idx

def random_data(shape):
    # Generate some random data.
    return np.random.uniform(0., 10., shape)

def main(data, target):
    order = data[2, :].argsort()
    key = data[2, order]
    target = target[(target >= key[0]) & (target <= key[-1])]
    closest = find_closest(key, target)
    return data[:, order[closest]]

N1 = 1500
array1 = random_data((3, N1))
array2 = random_data(1000)
array2[[10, 20]] = [-1., 100]

array4 = main(array1, array2)

rawDescription: Find closest float in array for all floats in another array


code:
wheel_dX, wheel_dY = myMouse.getWheelRel()*4
if any([wheel_dX, wheel_dY]):
    lastTime = clock.getTime()

rawDescription: psychopy record time of last mouse scroll wheel movement

description: Psychopy record time of last mouse scroll wheel movement


code:
string = 'Wazzup1'
result = any(c.isdigit() for c in string)
print(result) # True

rawDescription: How to find out if str has any number

description: Find out if str has any number


code:
lines=['G17 G3 X387.9385 Y200.0000 Z268.4040 R187.9385',
  'G17 G3 X200.0000 Y387.9385 Z268.4040 R187.9385',
  'G17 G3 X200.0000 Y387.9385 Z268.4040 R187.9385',
  'G17 G3 X200.0000 Y353.2089 Z328.5575 R153.2089']

def lines_equal(curr_line, prev_line, compare_char):
   curr_line_parts = curr_line.split(' ')
   prev_line_parts = prev_line.split(' ')

   for item in zip(curr_line_parts, prev_line_parts):
       if item[0].startswith(compare_char):
           return item[0] == item[1]

results = []
prev_line = lines[0]

for line in lines[1:]:
    results.append(lines_equal(line, prev_line, 'Z'))
    prev_line = line

print(results)

rawDescription: find if part of previous line is equal to part of current line in Python

description: Find if part of previous line is equal to part of current line in Python


code:
for key in bucket.list(prefix='/your/directory/'):
    key.delete()

rawDescription: Amazon S3 boto - how to delete folder?

description: Amazon S3 boto - how to delete folder


code:
from threading import Thread
import psutil

def countdown():
    n = 100000000
    while n > 0:
        n -= 1

t1 = Thread(target=countdown)
t2 = Thread(target=countdown)
t1.start(); t2.start()
t1.join(); t2.join()

print(psutil.Process().cpu_times())

rawDescription: Why is my Python app stalled with 'system' / kernel CPU time


code:
from csv import DictWriter
values = [{'Name': 'John Doe', 'Age': 26, 'ID': '1279abc'},
          {'Name': 'Jane Smith', 'Age': 35, 'ID': 'bca9721'}]
keys = values[0].keys()
with open("new-file.tsv", "w") as f:
    dict_writer = DictWriter(f, keys, delimiter="\t")
    dict_writer.writeheader()
    for value in values:
        dict_writer.writerow(value)

rawDescription: Write list of dictionary values to file

description: Write list of dictionary values to file


code:
result = default.copy()
result.update((k, v) for k, v in user.iteritems() if v is not None)

rawDescription: Delete None values from Python dict

description: Delete None values from Python dict


code:
def node_cut(input_file):
    NODE_LENGTH = 500
    count_output = 0
    node_list=[]

    for line in input_file.readlines():
        if len(node_list) >= NODE_LENGTH :
            count_output += 1
            yield( node_list,count_output )
            node_list=[]

        node,t=line.split(',')
        node_list.append(node)

if __name__ =='__main__':
    with open('all_nodes.txt','r') as input_data:
      for node_list, count_output in node_cut(input_data):
        some_process(node_list)

rawDescription: How to continue after the return command in python?

description: Continue after the return command in python


code:
import SocketServer

PORT = 5000

class Server(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    daemon_threads = True

class Handler(SocketServer.BaseRequestHandler):
    def handle(self):
        # TODO: handle this client
        # this sample acts as an echo server
        while True:
            data = self.request.recv(1024)
            if not data:
                break
            self.request.sendall(data)

if __name__ == '__main__':
    server = Server(('', PORT), Handler)
    server.serve_forever()

rawDescription: Multithreading in such a way that I am able to accept multiple clients in Python


code: V = [[map(int, j.split()) for j in i.split(',')] for i in s.split(';')]

rawDescription: Python: Split String into list of lists of lists


code:
from django.core.urlresolvers import reverse

def addResults(request):
    form = ResultsForm(request.POST or None)

    if request.method == 'POST' and form.is_valid():
        form.save()

        if 'Save_and_add_another' in request.POST:
            subjectID = form.cleaned_data.get('subjectID', [])
            if subjectID:
                subjectID = subjectIDs.split(',')
            form = ResultsForm(initial={'subjectID': subjectID})

        elif 'Save_and_return' in request.POST:
            return HttpResponseRedirect(reverse('home'))  # don't hard code

    return render(request, 'slideAdmin/addResults.html', {'form': form})

rawDescription: "save and add another" in Django (not admin): submit then pre-populate one field of form


code:
import csv
import sys
import os

if __name__ == '__main__':
    total = 0
    source = '.'
    with open(os.path.join(source, 'data.csv'), 'r') as f:
        rows = csv.reader(f)
        for row in rows:
            try:
                t = row[1].split('_')
            except IndexError:
                continue
            if len(t) >= 4 and t[3] == '001':
                total += int(row[13])
    print ('Club 001' + '\t' + str(total))

rawDescription: I made a selection from a csv file and need to sum up one of the columns in python


code:
from scipy.interpolate import interp1d

fint = interp1d(depth, data.T, kind='cubic')
newdata = fint(newdepth).T

rawDescription: interpolation with matplotlib pcolor

description: Interpolation with matplotlib pcolor


code:
for i in os.listdir(os.getcwd()):
    if i.endswith(".asm") or i.endswith(".py"):
        ##print i
        continue
    else:
        continue

rawDescription: How can I iterate over files in a given directory?

description: Iterate over files in a given directory


code:
def cachFront(update=False, prepend=None):
    key="top"
    entradas=memcache.get(key)
    if entradas is None or update:
        logging.error("DB QUERY")
        post= db.GqlQuery("select * from dbEntradas order by fecha_creacion desc limit 10")
        entradas=list(post)
        # manually prepend item to cache if it isn't available yet because
        # of eventual consistency
        if prepend and (not entradas or not entradas[0].key == prepend.key):
            entradas.insert(0, prepend)
            entradas = entradas[0:10]
        memcache.set(key, entradas)
    return entradas

class MainHandler(Handler):
    def get(self):
        entradas= cachFront()
        self.render("index.html", entradas=entradas)

class NewPostHandler(Handler):

    def renderizar(self, error="", titulo="", post=""):
        self.render("entradas.html", titulo=titulo, post=post, error=error)

    def get(self):
        self.render("entradas.html")

    def post(self):
        titulo= self.request.get("title")
        topic= self.request.get("topic")
        post= self.request.get("post")

        if titulo and post  and (topic!="Choose one.."):
            entrada= post_db.dbEntradas(title=titulo, post=post, topic=topic)
            entrada.put()
            cachFront(update=True, prepend=entrada)
            self.redirect('/')

rawDescription: How do i get strongly consistency in GAE in Python enviroment

description: Get strongly consistency in GAE in Python enviroment


code:
lst = ["AAA", "STACK_OVERFLOWAAAAAAA", "123AAAAA45678", "123456", "FOO", "DIR", "ITEM"]

lst

rawDescription: Remove (from list) all the items which contains other item - Python


code:
O = []
for i in o:
   O1 = []
   for k in range(int(i[0])):
       O2 = []
       for j in range(int(i[0][1])):
           O2.append(-1)
       O1.append(O2)
   O.append(O1)

rawDescription: how is die Interpretation of this comprehension list

description: How is die Interpretation of this comprehension list


code:
inputstr="""/abc{3,}zz/
        the quick brown fox
No match

/The quick brown fox/i
        the quick brown fox
 0: the quick brown fox

/a*abc?xyz+pqr{3}ab{2,}xy{4,5}pq{0,6}AB{0,}zz/
        the quick brown fox
No match"""

inputlst=inputstr.split('\n')
for i in range(2,len(inputlst)):
    if inputlst[i].strip().startswith('0:'):
        print(i - 1)

rawDescription: Parsing python output

description: Parsing python output


rawDescription: Store password in DB with django

description: Store password in DB with django


code:
def getVal(x):
    try:
        return l[x][0]

    except KeyError:
        return 0

data['F'] = data['B'].map(getVal)

rawDescription: Add column to a specific CSV row using Python pandas


rawDescription: Get rows based on my given list without revising the order or unique the list


code:
def base2dec(nums, base):
    if len(nums) == 1:
        return nums[0]
    else:
        return nums[-1] + base * base2dec(nums[:-1], base)

rawDescription: Recursively Converting a List of Digits to a Number


code:
text.tag_configure("highlight", background="yellow")
for start, end in offsets:
    text.tag_add("highlight", "1.0 + %sc"%start, "1.0 + %sc"%end)

rawDescription: Python Tkinter change Text background of some textual spans


code:
myVal = Word(alphas+nums+'_')

myExpr = Forward()
mySubExpr = (
    (Suppress('(') + Group(myExpr) + Suppress(')'))
    | myVal + Suppress('(') + Group(delimitedList(myExpr)) + Suppress(')')
    | myVal
    )
myExpr << mySubExpr + ZeroOrMore( oneOf('+ - / * =') + mySubExpr )

print(myExpr.parseString('blah(foo+bar)'))

rawDescription: PyParsing simple language expressions

description: PyParsing simple language expressions


code:
variables = {}
for i in myListOfFile:
    variables[i] = 0

rawDescription: String to Variable then increment in a loop


code:
for row in rows:
    while True:
        try:
            something
            break
        except Exception: # Try to catch something more specific
            pass

rawDescription: Can you "restart" the current iteration of a Python loop?


code: max(list, key=f)

rawDescription: Pythonic maxby function?

description: Pythonic maxby function


code: output = filter(lambda k: 5 <= dict1[k] <= 8, dict1)

rawDescription: Use filter method and find the keys with values between 5 to 8 from the given dictionary


code:
from numpy import array, sign, zeros
from scipy.interpolate import interp1d
from matplotlib.pyplot import plot,show,hold,grid

s = array([1,4,3,5,3,2,4,3,4,5,4,3,2,5,6,7,8,7,8]) #This is your noisy vector of values.

q_u = zeros(s.shape)
q_l = zeros(s.shape)

#Prepend the first value of (s) to the interpolating values. This forces the model to use the same starting point for both the upper and lower envelope models.

u_x = [0,]
u_y = [s[0],]

l_x = [0,]
l_y = [s[0],]

#Detect peaks and troughs and mark their location in u_x,u_y,l_x,l_y respectively.

for k in xrange(1,len(s)-1):
    if (sign(s[k]-s[k-1])==1) and (sign(s[k]-s[k+1])==1):
        u_x.append(k)
        u_y.append(s[k])

    if (sign(s[k]-s[k-1])==-1) and ((sign(s[k]-s[k+1]))==-1):
        l_x.append(k)
        l_y.append(s[k])

#Append the last value of (s) to the interpolating values. This forces the model to use the same ending point for both the upper and lower envelope models.

u_x.append(len(s)-1)
u_y.append(s[-1])

l_x.append(len(s)-1)
l_y.append(s[-1])

#Fit suitable models to the data. Here I am using cubic splines, similarly to the MATLAB example given in the question.

u_p = interp1d(u_x,u_y, kind = 'cubic',bounds_error = False, fill_value=0.0)
l_p = interp1d(l_x,l_y,kind = 'cubic',bounds_error = False, fill_value=0.0)

#Evaluate each model over the domain of (s)
for k in xrange(0,len(s)):
    q_u[k] = u_p(k)
    q_l[k] = l_p(k)

#Plot everything
plot(s);hold(True);plot(q_u,'r');plot(q_l,'g');grid(True);show()

rawDescription: python - How to get high and low envelope of a signal?

description: Python - How to get high and low envelope of a signal