code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import Locator

class MinorSymLogLocator(Locator):
    """
    Dynamically find minor tick positions based on the positions of
    major ticks for a symlog scaling.
    """
    def __init__(self, linthresh):
        """
        Ticks will be placed between the major ticks.
        The placement is linear for x between -linthresh and linthresh,
        otherwise its logarithmically
        """
        self.linthresh = linthresh

    def __call__(self):
        'Return the locations of the ticks'
        majorlocs = self.axis.get_majorticklocs()

        # iterate through minor locs
        minorlocs = []

        # handle the lowest part
        for i in xrange(1, len(majorlocs)):
            majorstep = majorlocs[i] - majorlocs[i-1]
            if abs(majorlocs[i-1] + majorstep/2) < self.linthresh:
                ndivs = 10
            else:
                ndivs = 9
            minorstep = majorstep / ndivs
            locs = np.arange(majorlocs[i-1], majorlocs[i], minorstep)[1:]
            minorlocs.extend(locs)

        return self.raise_if_exceeds(np.array(minorlocs))

    def tick_values(self, vmin, vmax):
        raise NotImplementedError('Cannot get tick locations for a '
                                  '%s type.' % type(self))

x = np.linspace(-5, 5, 100)
y = x

plt.plot(x, y)
plt.yscale('symlog', linthreshy=1e-1)

yaxis = plt.gca().yaxis
yaxis.set_minor_locator(MinorSymLogLocator(1e-1))

plt.show()

rawDescription: How to place minor ticks on symlog scale?

description: Place minor ticks on symlog scale


code:
cost1 = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(output_potentials, y))
cost2 = tf.reduce_sum(
    tf.pow(tf.sub(tf.nn.sigmoid(output_potentials), y), 2.0))
sess.run([cost1])
sess.run([cost2])

rawDescription: Parameterized model over output functions using tensorflow


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

import csv

def get_file_name():
    # this func gets the name of the file to be renamed
    before_rename = open('C:/Users/my.path/before_rename.txt', 'r')
    to_be_renamed_unf = before_rename.readline()[1:]
    # remove the end CRs & LFs off of the string
    to_be_renamed = to_be_renamed_unf.strip()
    print("File name: " + to_be_renamed)
    return to_be_renamed

def get_fname():
    # get farmer name
    file_name = get_file_name()
    farmer_name = re.sub('[^A-Z]', ' ', file_name).rstrip().lstrip()
    print(farmer_name)
    return farmer_name

def get_id_from_file():
    # search csv for COOP & Name to find the FID
    csvfile = 'C:/Users/my.path/csv_file_to_read_from.csv'
    # create a dictionary from the csv
    csv_dict = csv.DictReader(open(csvfile))

    fname = get_fname()
    coop_name = 'CALMAN'
    for row in csv_dict:
        if fname in row:
            if coop_name in row:
                farmer_id = int(row['FID'])
                print(farmer_id)

get_id_from_file()

rawDescription: Python functions to read a .csv file

description: Python functions to read a .csv file


code:
import pylab as plt
from matplotlib.mlab import griddata
import numpy as np

# data on a grid
r = np.linspace(0, 1, 100)
t = np.linspace(0, 2*np.pi, 100)
r, t = np.meshgrid(r, t)
z = (t-np.pi)**2 + 10*(r-0.5)**2

plt.subplot(121)
plt.contour(r*np.cos(t), r*np.sin(t), z)

# ungrid data, then re-grid it
r = r.flatten()
t = t.flatten()
x = r*np.cos(t)
y = r*np.sin(t)
z = z.flatten()
xgrid = np.linspace(x.min(), x.max(), 100)
ygrid = np.linspace(y.min(), y.max(), 100)
xgrid, ygrid = np.meshgrid(xgrid, ygrid)
zgrid = griddata(x,y,z, xgrid, ygrid)

plt.subplot(122)
plt.contour(xgrid, ygrid, zgrid)

plt.show()

rawDescription: Polar contour plot in Matplotlib

description: Polar contour plot in Matplotlib


code:
from objc import YES
from AppKit import NSBundle
bundle = NSBundle.mainBundle()
info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
info['NSAppTransportSecurity'] = {'NSAllowsArbitraryLoads': YES}

rawDescription: How to disable App Transport Security for a script?

description: Disable App Transport Security for a script


code:
def foo():
    return 1, 2, 3

a, b, c = foo()  # parentheses on left side of = are optional
a
b
c
a, b, c

rawDescription: Finite State Machine: Explain what the following line of code does


code:
def get_lines(dic):
    brand = ''
    model = ''
    parameter = ''
    with open('testinput.txt', 'r') as fil:
        for line in fil:
            if line[1:].strip().isdigit() and brand in dic and model in dic[brand] and parameter in dic[brand][model]:
                yield '&{0}\n'.format(dic[brand][model][parameter])
            elif line.startswith('&Brand:'):
                brand = line.split(': ')[-1].strip()
                yield line
            elif line.startswith('&Model:'):
                model= line.split(': ')[-1].strip()
                yield line
            elif line.startswith('&Parameter:'):
                parameter= line.split(': ')[-1].strip()
                yield line
            else:
                yield line

params = {'Ford': {'Sedan': {'Cost': 17000, 'Stock': 43}}, 'Honda':{'Sedan': {'Cost': 19000, 'Stock': 12}, 'Truck': {'Cost': 33000, 'Stock': 5}}}

with open('output.txt', 'w') as fil:
    for line in get_lines(params):
        fil.write(line)

rawDescription: Changing line in file based on previous lines - Python


code:
def unique(a):
    b = set()
    r = []
    for x in a:
        if x not in b:
            r.append(x)
            b.insert(x)
    return r

rawDescription: Python - large list efficiency

description: Python - large list efficiency


code:
import unittest

import re

# Verbose regular expression!  http://docs.python.org/library/re.html#re.X
p = r"""

(?P<name>[^(]+)         # Match the pre-open-paren name.
\(                      # Open paren
(?P<fields>             # Comma-separated fields
    (?:
        [a-zA-Z0-9_-]+
        (?:,\ )         # Subsequent fields must separated by space and comma
    )*
    [a-zA-Z0-9_-]+       # At least one field. No trailing comma or space allowed.
)

\)                      # Close-paren
"""

# Compiled for speed!
cp = re.compile(p, re.VERBOSE)

class Foo(object):
    pass

def validateAndBuild(s):
    """Validate a string and return a built object.
    """
    match = cp.search(s)
    if match is None:
        raise ValueError('Bad schema: %s' % s)

    schema = match.groupdict()
    foo = Foo()
    foo.name = schema['name']
    foo.fields = schema['fields'].split(', ')

    return foo

class ValidationTest(unittest.TestCase):
    def testValidString(self):
        s = "schema(field1, field2, field3, field4, fieldn)"

        obj = validateAndBuild(s)

        self.assertEqual(obj.name, 'schema')

        self.assertEqual(obj.fields, ['field1', 'field2', 'field3', 'field4', 'fieldn'])

    invalid = [
        'schema field1 field2',
        'schema(field1',
        'schema(field1 field2)',
        ]

    def testInvalidString(self):
        for s in self.invalid:
            self.assertRaises(ValueError, validateAndBuild, s)

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

rawDescription: Regex in Python

description: Regex in Python


code:
from PyQt4.QtCore import Qt, QVariant
from PyQt4.QtGui import QApplication, QTableWidget, QTableWidgetItem

class MyTableWidgetItem(QTableWidgetItem):
    def __lt__(self, other):
        if ( isinstance(other, QTableWidgetItem) ):
            my_value, my_ok = self.data(Qt.EditRole).toInt()
            other_value, other_ok = other.data(Qt.EditRole).toInt()

            if ( my_ok and other_ok ):
                return my_value < other_value

        return super(MyTableWidgetItem, self).__lt__(other)

if ( __name__ == '__main__' ):
    app = None
    if ( QApplication.instance() is None ):
        app = QApplication([])

    widget = QTableWidget()
    widget.setWindowFlags(Qt.Dialog)
    widget.setSortingEnabled(True)

    widget.setRowCount(50)
    widget.setColumnCount(3)
    for row in range(50):
       # create a normal QTableWidgetItem
       a = QTableWidgetItem()
       a.setText(str(row))
       widget.setItem(row, 0, a)

       # create a proper sorted item
       b = QTableWidgetItem()
       b.setData(Qt.EditRole, QVariant(row))
       widget.setItem(row, 1, b)

       # create a custom sorted item
       c = MyTableWidgetItem()
       c.setData(Qt.EditRole, QVariant(row))
       widget.setItem(row, 2, c)

    widget.show()
    if ( app ):
        app.exec_()

rawDescription: Sorting in pyqt tablewidget

description: Sorting in pyqt tablewidget


code: df = df.loc[:,['timestamp', 'user_id', 'val1', 'val2', 'val3']]

rawDescription: How to re-order dataframe fields?

description: Re-order dataframe fields


title: test

type: object

enum: spice vnc

type: string

format: ip-address

rawDescription: JSON Schema validating ip-address is not working


code:
# -*- coding: utf-8 -*-
import pypyodbc
cnxn = pypyodbc.connect(
    r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};' +
    r'DBQ=C:\Users\Public\Database1.accdb')
crsr = cnxn.cursor()
res = crsr.execute("SELECT * FROM Clients WHERE 1=0")
columnList = [tuple[0] for tuple in res.description]
crsr.close()
cnxn.close()
print(columnList)

rawDescription: How to fetch column names of a table to a list or tuple

description: Fetch column names of a table to a list or tuple


code:
def callback(event):
    print(event.num)#I have always seen one of (1,2,3,'??')

rawDescription: Input from a Art Design Graphic Drawing Tablet


code:
test = hashlib.sha512('test')
dir(test)

rawDescription: Hashlib hashes not comparing properly

description: Hashlib hashes not comparing properly


code:
import csv
with open("filename", encoding="utf8", errors="replace") as f:
  for row in csv.reader(f):
    print(", ".join(row))

rawDescription: BeautifulSoup Unable to Parse Unexpected Encodings


code:
import new
from types import MethodType

class Proxy(object):

    def __init__(self, target):
        self._target = target

    def __getattr__(self, aname):
        target = self._target
        ### Beginning of special logic ###
        if aname[:4]!='set_' and aname[:4]!='get_':
        ### End of special logic ###
            # Rebind the method to the target.
            return new.instancemethod(f.im_func, self, target.__class__)
        else:
            return f

rawDescription: python IDispatch client without type library

description: Python IDispatch client without type library


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

fig = plt.figure()
ax = fig.add_subplot(111)

# some X and Y data
x = np.arange(10000)
y = np.random.randn(10000)

li, = ax.plot(x, y)

# draw and show it
fig.canvas.draw()
plt.show(block=False)

# loop to update the data
while True:
    try:
        y[:-10] = y[10:]
        y[-10:] = np.random.randn(10)

        # set the new data
        li.set_ydata(y)

        fig.canvas.draw()

        time.sleep(0.01)
    except KeyboardInterrupt:
        break

rawDescription: python real time plotting

description: Python real time plotting


rawDescription: Force label line wrap

description: Force label line wrap


rawDescription: How to return N largest numbers for each row in a pd.Dataframe without evaluating the diagonal values?

description: Return N largest numbers for each row in a pd.Dataframe without evaluating the diagonal values


rawDescription: Python: Replacing modified Pandas Series elements based on index


code:
import subprocess

#simple caller, disguard output

subprocess.call("php /path/to/my/old/script.php")

# if you want output

proc = subprocess.Popen("php /path/to/my/script.php", shell=True,
stdout=subprocess.PIPE)

script_response = proc.stdout.read()

rawDescription: Calling .php within a Django/Python file


code: from sqlite3 import *

rawDescription: Upgrade sqlite3 version using python 2.7.3 and pysqlite2 2.6.3


code:
from django import template
from django.utils.html import escape
from django.utils.safestring import mark_safe

register = template.Library()

import re

readmore_showscript = ''.join([
"this.parentNode.style.display='none';",
"this.parentNode.parentNode.getElementsByClassName('more')[0].style.display='inline';",
"return false;",
]);

@register.filter
def readmore(txt, showwords=15):
    global readmore_showscript
    words = re.split(r' ', escape(txt))

    if len(words) <= showwords:
        return txt

    # wrap the more part
    words.insert(showwords, '')
    words.append('')

    # insert the readmore part
    words.insert(showwords, '... read more')
    words.insert(showwords+3, '')

    # Wrap with

    words.insert(0, '
')
    words.append('
')

    return mark_safe(' '.join(words))

readmore.is_safe = True

rawDescription: Is there a Django template filter that handles "...more" and when you click on it, it shows more of the text?


code: Nums = list(range(1, Top_Num + 1))

rawDescription: Adding Numbers to a list using variable

description: Adding Numbers to a list using variable


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

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
           frames=200, interval=20, blit=True)

plt.show()

rawDescription: Python animation graph

description: Python animation graph


code:
import ldap
...
ldap_connection.search_s('CN=Somebody, OU=Department, DC=example, DC=com',
    ldap.SCOPE_BASE,
    '(objectClass=*)')

rawDescription: How do I search for an object in LDAP based on its dn, in python-ldap?

description: Search for an object in LDAP based on its dn, in python-ldap


rawDescription: python parse file for ip addresses

description: Python parse file for ip addresses


code:
import json
from glob import glob
from pymongo import Connection

db = Connection().test

for filename in glob('~/Tweets/*.txt'):
    with open(filename) as fp:
        doc = json.load(fp)

    db.tweets.save(doc)

rawDescription: Python: Converting Entire Directory of JSON to Python Dictionaries to send to MongoDB


code:
import cv

cv.NamedWindow("w1")
camera = cv.CaptureFromCAM(-1)

while True:
    image = cv.QueryFrame(camera)
    key = cv.WaitKey(33)

    if key == 'q':
        break
    elif key != -1:
        cv.ShowImage("w1", image)

cv.DestroyWindow("w1")

rawDescription: How to capture a frame from a camera stream exactly when a key is hit using opencv in python?

description: Capture a frame from a camera stream exactly when a key is hit using opencv in python


code:
mypatterns = [
    url(...),
    url(...),
]

extrapatterns = [
    url(...),
    url(...),
]

# define urlpatterns by adding two lists
urlpatterns = mypatterns + extrapatterns

# extend the urlpatterns
urlpatterns += [
    url(...),
    url(...),
]

rawDescription: what is the alternative of 'urlpatterns += ' in django 1.8?

description: What is the alternative of 'urlpatterns += ' in django 1.8


code:
from PyQt4 import QtGui, QtCore

class TableWidget(QtGui.QTableWidget):
    cellExited = QtCore.pyqtSignal(int, int)
    itemExited = QtCore.pyqtSignal(QtGui.QTableWidgetItem)

    def __init__(self, rows, columns, parent=None):
        QtGui.QTableWidget.__init__(self, rows, columns, parent)
        self._last_index = QtCore.QPersistentModelIndex()
        self.viewport().installEventFilter(self)

    def eventFilter(self, widget, event):
        if widget is self.viewport():
            index = self._last_index
            if event.type() == QtCore.QEvent.MouseMove:
                index = self.indexAt(event.pos())
            elif event.type() == QtCore.QEvent.Leave:
                index = QtCore.QModelIndex()
            if index != self._last_index:
                row = self._last_index.row()
                column = self._last_index.column()
                item = self.item(row, column)
                if item is not None:
                    self.itemExited.emit(item)
                self.cellExited.emit(row, column)
                self._last_index = QtCore.QPersistentModelIndex(index)
        return QtGui.QTableWidget.eventFilter(self, widget, event)

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        QtGui.QWidget.__init__(self)
        self.table = TableWidget(rows, columns, self)
        for column in range(columns):
            for row in range(rows):
                item = QtGui.QTableWidgetItem('Text%d' % row)
                self.table.setItem(row, column, item)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        self.table.setMouseTracking(True)
        self.table.itemEntered.connect(self.handleItemEntered)
        self.table.itemExited.connect(self.handleItemExited)

    def handleItemEntered(self, item):
        item.setBackground(QtGui.QColor('moccasin'))

    def handleItemExited(self, item):
        item.setBackground(QtGui.QTableWidgetItem().background())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window(6, 3)
    window.setGeometry(500, 300, 350, 250)
    window.show()
    sys.exit(app.exec_())

rawDescription: How to catch mouse over event of QTableWidget item in pyqt?

description: Catch mouse over event of QTableWidget item in pyqt


code:
# level, time and conc are previously read from a file

X,Y=[level,time]
Z=conc.transpose() # Create the data to be plotted

cax = matshow(Z, origin='lower', vmin=0, vmax=500)
    # I am telling all the Z values above 500 will have the same color
    # in the plot (if vmin or vmax are not given, they are taken from
    # the input’s minimum and maximum value respectively)
grid(True)
cbar = colorbar(cax)

rawDescription: Contour plot in square points

description: Contour plot in square points


code:
# file: migration.py

from myoldcrm.models import User as UserOLD
from myoldcrm import Session as SessionOLD

from mynewcrm.models import User
from mynewcrm import Session

def migrate_users():
    users = SessionOLD.query(UserOLD).all()
    for user in users:
        ser = user.serialize() # or any other way you have to do this
        des = User.deserialize(ser) # deserialize using new model class
        Session.add(des)
    Session.commit()

rawDescription: How to migrate Python models to new models?

description: Migrate Python models to new models


code: '^[work|accus*|planet]'

rawDescription: Using Mongo Find() with $in and Regex

description: Using Mongo Find() with $in and Regex


code:
add = driver.find_element_by_css_selector('input.add')
SearchButton = driver.find_element_by_css_selector('input.add1')

Hover = ActionChains(driver).move_to_element(add).move_to_element(SearchButton)
Hover.click().build().perform()

rawDescription: Selenium/Python - hover and click on element


code:
v = [8.4, 12.1, 36.2]
print("What v do you want to be zero?")
print("    1 = v1")
print("    2 = v2")
print("    3 = v3")
a = int(input("Enter your choice: "))
v[a - 1] = 0
print(v)

rawDescription: Python exec() command working in IDLE, not in program


code: from PyQt4.QtGUI import QApplication, QFileDialog

rawDescription: How do I figure out what to import from PyQt4 specifically?

description: Figure out what to import from PyQt4 specifically


rawDescription: How to overlay dat in python arrays

description: Overlay dat in python arrays


code:
import csv
import json
import time
import urllib2

PAGE_DELAY = 5.    # time between loading pages
PAGE_LOAD  = 0.3   # how long it takes to load a page

make_url = 'http://www.imdb.com/title/tt{}/'.format

def get_csv_column(csv_fname, col, **kwargs):
    with open(csv_fname, 'rb') as inf:
        incsv = csv.reader(inf, **kwargs)
        column = [row[col] for row in incsv]
    return column

def get_data_by_id(id):
    url = make_url(id)
    response = urllib2.urlopen(url)
    data = json.load(response)
    return id,data

def delayed(delay, fn, *args):
    time.sleep(delay)
    return fn(*args)

def human_time(seconds):
    if seconds >= 86400:
        return '{:0.1f} days'.format(seconds / 86400.)
    elif seconds >= 3600:
        return '{:0.1f} hours'.format(seconds / 3600.)
    elif seconds >= 60:
        return '{:0.1f} minutes'.format(minutes / 60.)
    else:
        return '{:0.1f} seconds'.format(seconds)

def main():
    ids = get_csv_column('outputrows2.csv', 0)

    expected = (PAGE_DELAY + PAGE_LOAD) * len(ids)
    print('This will take about {}.'.format(human_time(expected)))

    results = (delayed(PAGE_DELAY, get_data_by_id, id) for id in ids)
    moviedata = dict(results)     # => gives dict of {id:data}

if __name__=="__main__":
    main()

rawDescription: Trying to run a defined function with a delay


code:
import difflib
a = ['line 1\n', 'line 2\n', 'line 3']
b = ['line 1\n', 'line 5\n', 'line 3']
delta = list(difflib.unified_diff(a, b, n=0))
delta

rawDescription: How calculate Diff in python

description: How calculate Diff in python


code:
scipy.io.savemat(file_name, mdict, appendmat=True, format='5',
    long_field_names=False, do_compression=False, oned_as='row')

rawDescription: Why does saving mat files with scipy result in larger file size than with Matlab?


code:
foo = {}
with patch.dict(foo, {'newkey': 'newvalue'}):
    assert foo == {'newkey': 'newvalue'}
assert foo == {}

rawDescription: How to mock.patch a plain dictionary in python?

description: Mock.patch a plain dictionary in python


code:
data = "D\x08DA\x08AT\x08TA\x08A\n" #  DATA bigsection header from pydoc
pydoc.render_doc(module).replace(data, '')

rawDescription: What parameters can Python pydoc.render_doc() take?


code:
import numpy as np
img = np.zeros([100,100,3],dtype=np.uint8)
img.fill(255) # or img[:] = 255

rawDescription: How to create a white image in Python?

description: Create a white image in Python


code:
df = pandas.DataFrame({'month': np.random.randint(0,11, 100), 'A': np.random.randn(100), 'B': np.random.randn(100)})
df.join(df.groupby('month')['A'].sum(), on='month', rsuffix='_r')

rawDescription: Python Pandas How to assign groupby operation results back to columns in parent dataframe?


code:
for col in row:
    Label(..., anchor="w").grid(...)

rawDescription: How to left justify Python tkinter grid columns while filling entire cell

description: Left justify Python tkinter grid columns while filling entire cell


code:
#!/usr/bin/env python
#

import codeWriter
import vmTranslator
import parser

# Add code here to parse arguments and call into the imported code.

rawDescription: Makefile on python

description: Makefile on python


rawDescription: Plotting a horizontal line, y = constant in matplotlib


code:
from subprocess import Popen, PIPE

p = Popen([script_name, "-"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate("this is some input")

rawDescription: passing data to subprocess.check_output

description: Passing data to subprocess.check_output


code:
import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for response in cur:
    print(response)
cur.close()
conn.close()

rawDescription: Python MySQL database

description: Python MySQL database


code:
import pandas as pd

df = pd.read_table("input.txt", names="xy", sep=r'\s+')
# reset index first - we need named column
new = df.reset_index().pivot(index="index", columns='x', values='y')
new.fillna(0, inplace=True)
new.to_csv("output.csv", sep='\t')      # tab separated

rawDescription: how to convert link list to matrix in python

description: Convert link list to matrix in python


code:
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import AsyncImage

class Application(App):

    def build(self):
        box_layout = BoxLayout(orientation='vertical')
        img = AsyncImage(source='http://pl.python.org/forum/Smileys/default/cheesy.gif')
        img._coreimage.bind(on_load=self.on_image_loaded)

        box_layout.add_widget(img)
        return box_layout

    def on_image_loaded(self, *args):
        print('Very importatn stuff executed afer image has been downloaded by img widget.')

app = Application()
app.run()

rawDescription: How to detect end of picture download in AsyncImage in Kivy?

description: Detect end of picture download in AsyncImage in Kivy


code:
from sqlalchemy.sql import func
...
# add another group_by to your existing query:
rows = ...
group_by(func.year(Download.time),
         60 * func.HOUR(Download.time) + func.MINUTE(Download.time)
)

rawDescription: SQLAlchemy group by minute

description: SQLAlchemy group by minute


code:
for index, name in enumerate(nameList):
    ...

rawDescription: Finding the index of a list in a loop

description: Finding the index of a list in a loop


code:
from Tkinter import *
root = Tk()

aValue = "5"
spam = StringVar()
spam.set(aValue)

class MyScale(Scale):
    def __init__(self,var,*args,**kwargs):
        self.var_pointer = var
        Scale.__init__(self,*args,**kwargs)
        self.bind("<ButtonRelease-1>",self.getValue)
        self.set(var.get())
    def getValue(self,event):
        ## spam gets changed to the new value set
        ## by the user manipulating the scale
        self.var_pointer.set(self.get())

eggs = MyScale(spam)
eggs.pack(anchor=CENTER)

rawDescription: Tkinter: Changing a variable within a function


code:
def TanimotoFilter(molist, namelist, threshold):
    # molist is the smiles list
    # namelist is the name list (SURPRISE!) is this some global variable name?
    # threshold is the tanimoto threshold (SURPRISE AGAIN!)
    smilesout=[]
    names=[]
    tans=[]
    exclude=[]

    for i in range(0, len(molist)):
        if i not in exclude:
            temp_exclude = []
            for j in range(i + 1, len(molist)):
                tanimoto = tanimoto_calc(molist[i], molist[j])
                if tanimoto > threshold:
                    temp_exclude.append(j)
            if temp_exclude:
                temp_exclude.append(i)
                exclude.extend(temp_exclude)
            else:
                smilesout.append(molist[i])
                names.append(namelist[i])

    return smilesout, names

rawDescription: A python function that discards molecules that are too similar based on Tanimoto coefficient?


code:
@sync
def send_confirmation_email(recipient):
    """Send registration email to the provided recipient."""

    with app.app_context():
        subject = 'Account confirmation e-mail'
        sender = 'some.mail.for.testing@domain.com'
        recipients = [recipient]
        activation, deletion = confirmation_links(recipient) #construct hashed links
        text_body = render_template('confirmation_email.txt',
                                activation = activation,
                                deletion = deletion)
        html_body = render_template('confirmation_email.html',
                                activation = activation,
                                deletion = deletion)
        send_email(subject, sender, recipients, text_body, html_body)

rawDescription: Want to decorate email sending with new thread


code:
def auto_str(cls):
    def __str__(self):
        return '%s(%s)' % (
            type(self).__name__,
            ', '.join('%s=%s' % item for item in vars(self).items())
        )
    cls.__str__ = __str__
    return cls

@auto_str
class Foo(object):
    def __init__(self, value_1, value_2):
         self.attribute_1 = value_1
         self.attribute_2 = value_2

str(Foo('bar', 'ping'))

rawDescription: Is there a way to auto generate a __str__() implementation in python?


code:
from tastypie.authorization import Authorization
from django.contrib.auth.models import Group
from extendedusers.models import ExtendedUser

class CustomAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        clinician_group = Group.objects.get(name='clinician')
        if bundle.request and hasattr(bundle.request, 'user'):
            if clinician_group in bundle.request.user.groups.all():
                patients = ExtendedUser.objects.filter(clinician_id=bundle.request.user.id)
                object_list = object_list.filter(author__id__in=patients)
            else:
                object_list = object_list.filter(author=bundle.request.user)
            return object_list
        else:
            return object_list.none()

rawDescription: Restrict access to only owned content django


code:
import ssl
import base64
from socket import *

cc = socket(AF_INET, SOCK_STREAM)
cc.connect(("smtp.gmail.com", 587))
# cc.read(..)

cc.send('helo tester.com\r\n')
cc.send('starttls\r\n')
# cc.read(..) If the server responds ok to starttls
#             tls negotiation needs to happen and all
#             communication is then over the SSL socket

scc = ssl.wrap_socket(cc, ssl_version=ssl.PROTOCOL_SSLv23)
scc.send('auth login\r\n')
# scc.read(..)

scc.send(base64.b64encode('username')+'\r\n')
scc.send(base64.b64encode('password')+'\r\n')

# css.send(
#  mail from:
#  rcpt to:
#  data
#  etc

rawDescription: How to start TLS on an active connection in python?

description: Start TLS on an active connection in python


code: StoreOpening = nestedformset_factory(StoreData,StoreOpening,nested_formset=nestedformset_factory(StoreOpening,OpeningDays,nested_formset=inlineformset_factory(StoreOpening, OpeningHours,extra = 0, can_delete=False), extra = 0, can_delete=False),extra = 0, can_delete=False)

rawDescription: How can I iterate inside a iteration with formfields?

description: Iterate inside a iteration with formfields


code: t1 = wx.TextCtrl(self, -1, "my text", style=wx.BORDER_NONE)

rawDescription: Is it possible to do a wx.TextCtrl with no border?


code:
plot(range(80))
xlabel('foo')
ylabel('bar')
legend(['myline'])
axis([0, 80, 0, 120])
savefig('sample.pdf')

rawDescription: How to export figures to files from IPython Notebook

description: Export figures to files from IPython Notebook


code:
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import authenticated_userid
from pyramid.view import forbidden_view_config

@forbidden_view_config()
def forbidden_view(request):
    if authenticated_userid(request):
        # user is already logged in, they are really forbidden
        return request.context # the forbidden 403 response

    url = request.route_url('login', _query={'came_from': request.path})
    return HTTPSeeOther(url)

rawDescription: How flexible is Pyramids auth system?

description: How flexible is Pyramids auth system


code:
state_obj = State.objects.get(name="Alaska")
province_obj = state_obj.provinces({"name": "Juneau"})
for city in province_obj.cities:
    if city.name == "Test_City" and city.population == 10000:
        province_obj.cities.remove(city)

rawDescription: How to remove an item of embedded document in another embedded document of a document in mongoengine

description: Remove an item of embedded document in another embedded document of a document in mongoengine


code: print(list(itertools.product(['a', 'b'], ['c', 'd'])))

rawDescription: Python: "Distributing" strings from two lists into one list


code:
def content_file_name(instance, filename):
    return '/'.join(['content', instance.user.username, filename])

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=content_file_name)

rawDescription: Django FileField with upload_to determined at runtime


code:
def checkuser(request):
    if request.method == "POST":
        conn = Connection('localhost', 27017)
        db = conn['user-data']
        userTable = db["logins"]

        userToCheck = request.form['usertocheck']

        #search for user to check if it already exists
        doesExist = str(userTable.find_one({"username": userToCheck}))
        conn.close()

        if doesExist == "None":
            return "Username is available"
        elif doesExist.find("ObjectId") != -1:
            return "Username already taken."
        else:
            return "Error"

@app.route('/register/checkuser', methods=['POST'])
def func():
    return checkUser(request)

rawDescription: Exposing reusable functions to deal with HTTP POST methods


code:
def onButton(self, event):
    if yourRadioButton.GetValue() == True:
        self.Unbind(wx.EVT_BUTTON, handler=self.onButton, source=self.myButton)
        self.Bind(wx.EVT_BUTTON, self.someOtherHandler, self.myButton)

rawDescription: Rebind button with wxpython

description: Rebind button with wxpython


code:
from random import randrange
def lowHigh():
    l = input ("Please input the low number range.")
    numl = eval(l)
    h = input ("Please input the high number range.")
    numh = eval(h)
    lowest = l
    highest = h
    while True:
        guess = randrange(lowest,highest+1)
        print (guess)
        ask = input("Is this number correct? y for yes or n for no.")
        if ask == 'y':
            print("Yay! I guessed right!")
            break
        else:
            lowOrHigh = input ("Is this number too high or low? h for high, l for low.")
            if lowOrHigh == 'h':
               highest = guess - 1
            else:
               lowest = guess

rawDescription: Python numbers game reverse

description: Python numbers game reverse


code: sum(map(len, liste_groupe))

rawDescription: size of a whole list containing tuple

description: Size of a whole list containing tuple


code:
def my_func(a):
    """Average first and last element of a 1-D array"""
    return (a[0] + a[-1]) * 0.5
b = np.array([[1,2,3], [4,5,6], [7,8,9]])
np.apply_along_axis(my_func, 0, b)
np.apply_along_axis(my_func, 1, b)

rawDescription: Removing list comps from numpy code

description: Removing list comps from numpy code


code:
class Product(models.Model):
    ...

class ProductQuantity(models.Model):
    product = models.ForeignKey('Product')
    invoice = models.ForeignKey('Invoice')
    quantity = models.IntegerField()

class Invoice(models.Model):
    ...
    products = models.ManyToManyField(Product, through=ProductQuantity)

rawDescription: Inline editing of ManyToMany relation in Django


code:
def iter_tree(root):
    to_explore = [root]
    while to_explore:
        node = to_explore.pop()
        yield node
        for child in node.children:
            to_explore.append(child)

def size(root):
    count = 0
    for node in iter_tree(root):
        count += 1
    return count

rawDescription: Size of subtree in Python

description: Size of subtree in Python


code:
class GsThemeWindow(gtk.Window):
    __gtype_name__ = 'GsThemeWindow'

def __init__(self):
    super(GsThemeWindow, self).__init__()
    self.connect("destroy", gtk.main_quit)

def do_realize(self):
    ident = os.environ.get('XSCREENSAVER_WINDOW')
    if not ident is None:
        self.window = gtk.gdk.window_foreign_new(int(ident, 16))
        self.window.set_events(gtk.gdk.EXPOSURE_MASK |
                               gtk.gdk.STRUCTURE_MASK)
        x, y, w, h, depth = self.window.get_geometry()
        self.size_allocate(gtk.gdk.Rectangle(x, y, w, h))
        self.set_default_size(w, h)
        self.set_decorated(False)
    else:
        self.window = gtk.gdk.Window(
            self.get_parent_window(),
            width=self.allocation.width,
            height=self.allocation.height,
            window_type=gtk.gdk.WINDOW_TOPLEVEL,
            wclass=gtk.gdk.INPUT_OUTPUT,
            event_mask=self.get_events() | gtk.gdk.EXPOSURE_MASK)
    self.window.set_user_data(self)
    self.style.attach(self.window)
    self.set_flags(self.flags() | gtk.REALIZED)

rawDescription: Python Clutter: Set display?

description: Python Clutter: Set display


code: [x for a in arg if dictAll.has_key(a) for x in dictAll[a]]

rawDescription: Unpack List in List Comprehension

description: Unpack List in List Comprehension


code:
poller = zmq.Poller()
poller.register(sys.stdin, zmq.POLLIN)
poller.register(mysocket, zmq.POLLIN)
evts = dict(poller.poll(1000))
stdin_ready = evts.get(sys.stdin.fileno(), False)
socket_ready = evts.get(mysocket, False)

rawDescription: zeromq zmq.Poller & stdin

description: Zeromq zmq.Poller & stdin


rawDescription: How to print scientific notation number into same scale

description: Print scientific notation number into same scale


code:
from collections import defaultdict

my_dict = defaultdict(int)

for k,v in mylist:
    my_dict[k] += v

print(my_dict)
# defaultdict(<class 'int'>, {'USD': 4500, 'THB': 25})

rawDescription: Sum in list with the same name

description: Sum in list with the same name


code:
import requests
session = requests.session
payload = {'uname': 'name', 'password': 'pswd123'}
r = session.post('http://localhost/python', data=payload)
r = session.get('http://localhost/authenticated/resource')
#   ^^^^^^^

rawDescription: How to login to a website with python

description: Login to a website with python


code: L2 = [sum(L1[0:n+1]) for n in range(len(L1))]

rawDescription: tuple operation in python 3.5

description: Tuple operation in python 3.5


code:
lst = [1, 2]
lst.append(3)
lst.append(4)
lst
lst.extend([5, 6, 7])
lst.extend((8, 9, 10))
lst
lst.extend(range(11, 14))
lst

rawDescription: How to append multiple values to a list in Python

description: Append multiple values to a list in Python


rawDescription: How do I ensure I always get a list of matches from Python's Regular Expressions?

description: Ensure I always get a list of matches from Python's Regular Expressions


code: tempfile = open(tempFilePath, 'wb')

rawDescription: Boto "get byte range" returns more than expected


code:
def check(value, min="0", max=""):
    regex = "[a-z]{" + min + "," + max + "}$"
    return re.match(regex, value)

rawDescription: repetition "{}" on fly for regex

description: Repetition "{}" on fly for regex


code:
for line in nlines:
    line = line.strip()
    if line == '':
        continue # skip empty lines

    line = line.replace('\t',' ')
    x, y, z = line.split()

    if x > somevalue:
        continue # skip line if x > somevalue

    X.append(x)
    Y.append(y)
    Z.append(z)

rawDescription: Built in Python function to skip row of data


code:
while True:
    dbstr = ser.readline()
    fo.write(str(dbstr));
    if not dbstr:
        break

rawDescription: Python: Serial timeout not working when using readline


code:
import pkg_resources
version = pkg_resources.get_distribution("nose").version

rawDescription: How do i get the version of an installed module in python programatically

description: Get the version of an installed module in python programatically


code:
import os
my_output_file = os.readlink('/proc/%d/fd/1' % os.getpid())

rawDescription: Is there a way to find out the name of the file stdout is redirected to in Python


code:
self.myDropDown = QComboBox()
self.myDropDown.setEditable(True)
self.myDropDown.lineEdit().setMaxLength(45)

rawDescription: pyqt4 QComboBox setEditable(True) - How to setMaxLength?

description: Pyqt4 QComboBox setEditable(True) - How to setMaxLength


rawDescription: How do I make the built-in password_reset view use django-mailer?

description: Make the built-in password_reset view use django-mailer


code:
X = np.dstack([megadatalist[i].variables['analysed_sst'][0]
        for i in range(0,140)])

res = np.mean(X, axis=2)

rawDescription: Numpy: using np.mean in 3 dimensions

description: Numpy: using np.mean in 3 dimensions


code:
x = 'fruit'
getattr(x, '__str__')()
getattr(x, '__str__')() == 'fruit'

rawDescription: Get string contents though attribute

description: Get string contents though attribute


code:
def OutputMostPopularDestination( ):
    test = int(input("How many lines?"))
    inputs =[]
    for i in range(test):
        string_input = input()
        inputs.append(string_input)

    return inputs

print(OutputMostPopularDestination())

rawDescription: write input of string in list in python

description: Write input of string in list in python


code:
class xyz(object):

    def __init__(self):
        self.model_type = ensemble.RandomForestClassifier
        self.model_types = {}
        self.model = {}
        for x in range(0,5):
            self.model_types[x] = self.model_type()

    def fit_model():
        for x in range(0,5):
            self.model[x] = self.model_types[x].fit(data[x])

    def score_model():
        for x in range(0,5):
            self.pred[x] = self.model[x].predict(data[x])

rawDescription: Create classes in a loop

description: Create classes in a loop


code: sorted(d.items(), key=lambda v: int(v[0].split("-")[0]))

rawDescription: Sorting a dictionary by a split key

description: Sorting a dictionary by a split key


code:
import os.path
from Foundation import *

def target_of_alias(path):
    url = NSURL.fileURLWithPath_(path)
    bookmarkData, error = NSURL.bookmarkDataWithContentsOfURL_error_(url, None)
    if bookmarkData is None:
        return None
    opts = NSURLBookmarkResolutionWithoutUI | NSURLBookmarkResolutionWithoutMounting
    resolved, stale, error = NSURL.URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(bookmarkData, opts, None, None, None)
    return resolved.path()

def resolve_links_and_aliases(path):
    while True:
        alias_target = target_of_alias(path)
        if alias_target:
            path = alias_target
            continue
        if os.path.islink(path):
            path = os.path.realpath(path)
            continue
        return path

rawDescription: What replaces the now-deprecated Carbon.File.FSResolveAliasFile in Python on OSX?


code:
rst_prolog = '''
.. highlight:: python
   :linenothreshold: 0

'''

rawDescription: Setting linenothreshold globally

description: Setting linenothreshold globally


code:
import h5py as h5
hf1 = h5.File("f1.h5")
hf2 = h5.File("f2.h5")
hf1.create_dataset("val", data=35)
hf1.create_group("g1")
hf1.get("g1").create_dataset("val2", data="Thing")
hf1.flush()
h5.h5o.copy(hf1.id, "g1", hf2.id, "newg1")
h5.h5o.copy(hf1.id, "val", hf2.id, "newval")
hf2.values()
hf2.get("newval").value
hf2.get("newg1").values()
hf2.get("newg1").get("val2").value

rawDescription: Combining hdf5 files

description: Combining hdf5 files


code:
def combine(n, m):
    return (n << 16) | m

def extract(c):
    return (c >> 16), c & 0xffff

rawDescription: Python: Creating a Single Integer From Two Integers?


code:
import urlparse
urllib.urlretrieve(urlparse.urljoin(url, img['src']), 'captcha.bmp')

rawDescription: python Script for getting a captcha

description: Python Script for getting a captcha


rawDescription: Getting distinct columns from postgresql in django model


rawDescription: How to convert arraylist to tuple?

description: Convert arraylist to tuple


code:
m = np.ma.masked_array([1,2,3,4],[1,0,0,1])
m
m.data
m.mask

rawDescription: is Numpy's masked array memory efficient?

description: Is Numpy's masked array memory efficient


code:
import pexpect
import getpass

HOST = "10.203.4.1"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

child = pexpect.spawn ('telnet '+HOST)
child.expect ('Username: ')
child.sendline (user)
child.expect ('Password: ')
child.sendline (password)
# If the hostname of the router is set to "deep"
# then the prompt now would be "deep>"
routerHostname = "deep" #example - can be different
child.expect (routerHostname+'>')
child.sendline ('enable')

rawDescription: Telnet cisco switch using python

description: Telnet cisco switch using python


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

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

        self.list = ULC.UltimateListCtrl(self, agwStyle=ULC.ULC_REPORT|ULC.ULC_HAS_VARIABLE_ROW_HEIGHT)
        self.items = ['list', 'list', 'I want to wrap words and content shold be placed in multiple lines for each item as the window is resized']
        colWidth = 200
        self.colWidthPad = 5
        self.list.InsertColumn(0, "test", width=colWidth)
        for item in self.items[::-1]:
            item = wordwrap(item, colWidth - self.colWidthPad, wx.ClientDC(self))
            self.list.InsertStringItem(0, item)

        self.list.Bind(wx.EVT_LIST_COL_DRAGGING, self.onDrag)

    def onDrag(self, evt):
        col = evt.GetItem().GetColumn()
        width = self.list.GetColumnWidth(col)
        itemCount = self.list.GetItemCount()

        for i in range(0, itemCount):
            text = wordwrap(self.items[i], width - self.colWidthPad, wx.ClientDC(self))
            self.list.SetStringItem(i, col, text)

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

rawDescription: wxPython ListCtrl wrap words on resize

description: WxPython ListCtrl wrap words on resize


code:
from itertools import combinations_with_replacement
import numpy as np

x = np.empty((3,3), dtype=int)

for comb in combinations_with_replacement(range(10),9):
    x.flat[:] = comb

rawDescription: Brute force all possible matrix combinations in python


code:
langs = win32api.GetFileVersionInfo(ExecutablePath, r'\VarFileInfo\Translation')
key = r'StringFileInfo\%04x%04x\FileDescription' %(langs[0][0], langs[0][1])
print (win32api.GetFileVersionInfo(ExecutablePath, key))

rawDescription: grabbing the file description from details tab

description: Grabbing the file description from details tab


code:
class ActiveObjectResource(ModelResource):
    class Meta:
        queryset = Object.objects_active.all()

    def get_object_list(self, request):
        return Object.objects_active.all()

rawDescription: Tastypie resource not showing newly created objects (date filtering issue)


code:
class TestingDatabaseThing(DatabaseThing):
     def __init__(self, connection):
          self.connection = connection

rawDescription: Mocking __init__() for unittesting

description: Mocking __init__() for unittesting


code:
def render(self, notification, my_subtask):
    """
    @type notification: full.path.to.Notification
    @type my_subtask: celery.canvas.subtask
    """
    return NotificationRepresentation(notification).to_dict()
    # some irrelevant code

rawDescription: Type hinting class not yet imported

description: Type hinting class not yet imported


code:
NumGiven = ''
while not NumGiven.isnumeric():
    NumGiven = (input('Please enter a 7 or 8 digit number:'))
while len(NumGiven) < 7 or len(NumGiven) > 8:
    NumGiven = (input('Please enter a 7 or 8 digit number:'))

if len(NumGiven) == 8:
    my_list = [int(i) for i in NumGiven]
    temp = sum([int(i) for i in NumGiven])
    ans = temp / 10.0

    if temp % 10 == 0:
        print("int")
    else:
        print("float")

rawDescription: Checking if a sum is an integer or float


code:
d = {'dict1':
         {'part1':
              {'.wbxml': 'application/vnd.wap.wbxml',
               '.rl': 'application/resource-lists+xml'},
          'part2':
              {'.wsdl': 'application/wsdl+xml',
               '.rs': 'application/rls-services+xml',
               '.xop': 'application/xop+xml',
               '.svg': 'image/svg+xml'}},
     'dict2':
         {'part1':
              {'.dotx': 'application/vnd.openxmlformats-..',
               '.zaz': 'application/vnd.zzazz.deck+xml',
               '.xer': 'application/patch-ops-error+xml'}}}

def demo():
    mime_type = 'image/svg+xml'
    try:
        key_chain = find_mime_type(d, mime_type)
    except KeyError:
        print ('Could not find this mime type: {0}'.format(mime_type))
        exit()
    print ('Found {0} mime type here: {1}'.format(mime_type, key_chain))
    nested = d
    for key in key_chain:
        nested = nested[key]
    print ('Confirmation lookup: {0}'.format(nested))

def find_mime_type(d, mime_type):
    reverse_linked_q = list()
    reverse_linked_q.append((list(), d))
    while reverse_linked_q:
        this_key_chain, this_v = reverse_linked_q.pop()
        # finish search if found the mime type
        if this_v == mime_type:
            return this_key_chain
        # not found. keep searching
        # queue dicts for checking / ignore anything that's not a dict
        try:
            items = this_v.items()
        except AttributeError:
            continue  # this was not a nested dict. ignore it
        for k, v in items:
            reverse_linked_q.append((this_key_chain + [k], v))
    # if we haven't returned by this point, we've exhausted all the contents
    raise KeyError

if __name__ == '__main__':
    demo()

rawDescription: Search for a value in a nested dictionary python


code: vr, vl = map(op.GetTangent(id).get, ('vr', 'vl'))

rawDescription: Can I be sure about the order in a dictionary?

description: Be sure about the order in a dictionary


code:
if random.random() > 0.5:
    # your app does this
    pass
else:
    # your app does that
    pass

rawDescription: Randomness in Python

description: Randomness in Python


code:
class TestFoo(unittest.TestCase):
    def setUp(self):
        self.f = Foo()

    def test_bar(self):
        # assertEquals is deprecated, use assertEqual instead
        self.assertEquals(self.f.bar(3), 4)

    def test_missing_argument(self):
        self.assertRaises(TypeError, self.f.bar)

rawDescription: What is the canonical way to isolate unit tests in Python with assertion-style tests?


code:
from tkinter import Tk, Label
import random

root = Tk()
label = Label(root)
label.pack()

def replace_text():
    label.config(text=str(random.random()))
    root.after(1000, replace_text)

replace_text()
root.mainloop()

rawDescription: Random number in label in python 3 and tkinter


code:
from skimage.transform import PolynomialTransform

class PolyTF_4(PolynomialTransform):
    def estimate(*data):
        return PolynomialTransform.estimate(*data, order=4)

rawDescription: Robustly estimate Polynomial geometric transformation with scikit-image and RANSAC


code:
with open('oneptdm.dat') as f:
    line = next(f).split()
    for i in range(len(line)):
        print('{0}\t{1}'.format(i+1, line[i]))
        try:
            line = next(f).split()
        except StopIteration:
            break

rawDescription: Alternative to bash (awk command) with python


code:
import codecs

f = codecs.open('goldstandard-answer-utf-8.txt', 'r', encoding='utf-8')

rawDescription: Reading text in python weird error [Solved]


rawDescription: Extract a specific number from a string

description: Extract a specific number from a string


code:
for line in open('filename'):
    line = line.strip()
    if line:
        print(line)

rawDescription: Mass deleting white spaces with very large data arrays


code:
s = pd.Series(['a','b','c'])
labels, levels = pd.factorize(s)
labels

rawDescription: Convert pandas series from string to unique int ids


code:
from urllib2 import urlopen
from bs4 import BeautifulSoup
url = "http://www.baseball-reference.com/players/split.cgi?id=aardsda01&year=2015&t=p"
soup = BeautifulSoup(urlopen(url))
soup.find("b", text='Throws:').next_sibling.strip()

rawDescription: Grabbing text data from Baseball-reference Python


code:
from dateutil.parser import parse
l = [u'Posted by Kendra E. on 3/17/2016', u'Posted by Jasmine B. on 3/16/2016', u'Posted by Chris H. on 3/17/2016', u'Posted by Katie S. on 3/17/2016', u'Posted by Samidha K. on 3/17/2016', u'Posted by Melissa W. on 3/20/2016', u'Posted by Travis S. on 3/18/2016', u'Posted by Lilla L. on 3/16/2016']
[parse(item, fuzzy=True) for item in l]

rawDescription: Regxp to strip out everything except numbers and slashes


code:
from sympy.matrices.dense import MutableDenseMatrix
from sympy.matrices import Matrix
a = MutableDenseMatrix([[1,0,0], [0,0,0], [2, -2, 3]])
b = Matrix(a)
b.eigenvals()

rawDescription: How to determine the eigenvalues of sympy.matrices.dense.MutableDenseMatrix?

description: Determine the eigenvalues of sympy.matrices.dense.MutableDenseMatrix


code:
from mutagen import File

file = File('some.mp3') # mutagen can automatically detect format and type of tags
artwork = file.tags['APIC:'].data # access APIC frame and grab the image
with open('image.jpg', 'wb') as img:
   img.write(artwork) # write artwork to new image

rawDescription: How do I read album artwork using python?

description: Read album artwork using python


code:
class Foo(object):
   def __repr__(self):
       return str(self)

   def __str__(self):
       return self.name

rawDescription: Python instance string in a list

description: Python instance string in a list


code:
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, Div

class AuthenticationForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(AuthenticationForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-8'
        self.helper.layout = Layout(
            Fieldset(
               'fieldset description text',
               'username',
               'password',
            ),
            Div(
               Submit('submit', 'Log Me In', css_class='btn btn-default'),
               css_class='col-lg-offset-3 col-lg-9',
            )
        )

rawDescription: Django Crispy Forms Add Div Around Submit Button


code:
def fmt(t):
    tenths = t % 10
    t //= 10
    sec = t % 60
    t //= 60
    min = t
    return '%d:%02d.%d' % (min, sec, tenths)

print(fmt(1234))

rawDescription: Formatting time for a digital clock

description: Formatting time for a digital clock


code:
class ThisFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(0, 0))
        dlg = ThisClass(self, -1, "buttons.py")

        if dlg.ShowModal() == 1:
            from otherfile import MyFrame
            mf = MyFrame(self, "MyFrame")
            mf.Show()

app = wx.App(0)
frame = ThisFrame(None, 'ThisFrame')
app.MainLoop()

rawDescription: wxpython link and open new window apps

description: Wxpython link and open new window apps


code:
if not {10, 20, 30} <= set(comb):
    print(comb)

rawDescription: Exactly check if tuple contains certain values


rawDescription: access widget by Tk widget/window path name

description: Access widget by Tk widget/window path name


rawDescription: Pandas: print column name with missing values


code:
import itertools
for s in itertools.product(*somelist):
    function(something=s)

rawDescription: Smart syntax for this issue

description: Smart syntax for this issue


code:
a = inputstring.split('(')[1].split(':')[0]
b = inputstrint.split(':')[1].split(')')[0]

rawDescription: Python- How to separate input entries separated by delimiters and use them separately later in the code i


rawDescription: Append two multiindexed pandas dataframes


code:
def sub_combinations(segment, max_offset=None):
   data = tuple([e] for e in segment)
   def _sub_combinations(segment):
      if len(segment) == 1:
         yield (segment,)
      else:
         for j in _sub_combinations(segment[1:]):
            yield ((segment[0],),)+j
            for k in range(len(j)):
               if max_offset and data.index(j[k][0]) - data.index(segment[0]) > max_offset:
                  break
               yield (((segment[0],)+j[k]),) + (j[:k]) +(j[k+1:])
   for combination in _sub_combinations(data):
      yield tuple(tuple(e[0] for e in t) for t in combination)

rawDescription: Yield sub combinations with limit

description: Yield sub combinations with limit


code:
from PIL import Image
from PIL import ImageFilter

i = Image.open("gImage1.jpg")
im2 = i.filter(ImageFilter.EMBOSS)
im3 = i.filter(ImageFilter.FIND_EDGES)

im2.save("gImage1_EMBOSS.jpg")
im3.save("gImage1_FIND_EDGES.jpg")

rawDescription: Encode strings to image using Python

description: Encode strings to image using Python


rawDescription: Running a groupby on a pivot table with Pandas


code:
import Image

im = Image.open('Foto.jpg')
im.save('Foto.png')

rawDescription: Converting .jpg images to .png

description: Converting .jpg images to .png


code:
ax = pyplot.gca()
ax.get_xaxis().get_major_formatter().set_useOffset(False)

rawDescription: Matplotlib axis tick format changes after zoom in ipython figure window


code:
import re
txt = re.sub('\n+','\n',txt)

rawDescription: Replace continuous occurrence of "\n" with a single "\n" in python


code:
# Create some random test data
axis = -2
shape = np.random.randint(10, size=(5,))
data = np.random.rand(*shape)
data = np.sort(data, axis=axis)
z = np.random.rand(*shape)
dists = np.linspace(0,1, num=100)

data = np.rollaxis(data, axis, data.ndim)
new_shape = data.shape
data = data.reshape(-1, data.shape[-1])
z = np.rollaxis(z, axis, z.ndim)
z = z.reshape(-1, z.shape[-1])

out = np.empty(z.shape[:1]+dists.shape)
for o, x, f in zip(out, data, z):
    o[:] = np.interp(dists, x, f)

out = out.reshape(new_shape[:-1]+dists.shape)
out = np.rollaxis(out, -1, axis)

rawDescription: A 1D numpy/scipy interpolation that's not quite 1D


code:
import numpy as np
from scipy.fftpack import dct, idct

# Lets create a 3D array and fill it with some values
a = numpy.random.rand(3,3,3)

f,x,y = a.shape
b = np.zeros((f,x,y))

b = dct(dct(dct(a).transpose(0,2,1)).transpose(1,2,0)).transpose(1,2,0).transpose(0,2,1)

rawDescription: Use Python's Scipy DCT-II to do 2D or ND DCT


code:
from tkinter.filedialog import askopenfilename
## OR  from tkinter.filedialog import *

from tkinter import *

root = Tk()
foo = askopenfilename()
root.destroy()
print(foo)

rawDescription: file opening dialog & drag and drop in pygame

description: File opening dialog & drag and drop in pygame


code: "hello.world.foo.bar".rsplit('.', 1) # <-- 1: maxsplit

rawDescription: python, how split string with limit by the end

description: Python, how split string with limit by the end


rawDescription: Python regular expression problems

description: Python regular expression problems


rawDescription: Replace value in array when greater than x


code: re.findall(r'[\d\-]+', myString)

rawDescription: re.findall multiple literals

description: Re.findall multiple literals


code:
query = (session.query(Ip, func.count(Client.id)).
    outerjoin(ClientIp, ClientIp.ip_id==Ip.id).
    outerjoin(Client, Client.id==ClientIp.client_id).
    group_by(Ip.id)
)

rawDescription: SQLAlchemy force Left Join

description: SQLAlchemy force Left Join


code:
import pygame
import math
from pygame.locals import *
background_colour = (122, 100, 155)
(width, height) = (500, 500)

pygame.init()

#ship = pygame.image.load('lolol.jpeg')\
rship = pygame.image.load('js.jpg')
mis = pygame.image.load('lot.jpg')
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('A.N.T.O.N.I.A.')
screen.fill(background_colour)
pygame.display.flip()
running = True

MAX_MISSILES = 5

ls = 250  # Horizontal ship location

LEFT = False
RIGHT = False

def move(ls, RIGHT, LEFT):
    '''Moves the ship 3 pixels to the left or right.

    Only moves if just one direction key is down, and not both.
    Also, will not move if the ship is at either horizontal screen edge.

    ls is the ship location.

    '''
    if LEFT and not RIGHT:
        if ls >= 10:
            ls -= 3
    elif RIGHT and not LEFT:
        if ls <= 440:
            ls += 3
    return ls

def fire_missile(ls, missiles):
    '''Fire a missile, as long as we are not at the maximum number.

    We use a list to hold our missile locations.

    '''
    if len(missiles) >= MAX_MISSILES:
        return
    else:
        missiles.append((ls, 460))

def draw_missiles(missiles):
    '''Draw all the missiles.'''
    if missiles:
        for missile in missiles:
            screen.blit(mis, (missile))

def move_missiles(missiles):
    '''If there are any missiles, move them up 1 pixel, and append
    them to the newlist.  The new list will replace the old list.

    '''
    if missiles:
        newmissiles = []
        for missile in missiles:
            # Do not append the missile to the new list if it is going
            # off the screen
            if missile[1] > 0:
                newmissiles.append((missile[0], missile[1] - 1))
        return newmissiles
    else:
        return missiles

missiles = []

while running:
    screen.blit(rship, (ls, 450))
    pygame.display.flip()
    screen.fill(background_colour)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False
        if event.type == pygame.KEYDOWN and event.key == K_ESCAPE:
            # You can now quit with the escape key.
            pygame.quit()
            running = False
        if event.type == pygame.KEYDOWN and event.key == K_LEFT:
            LEFT = True
        # LEFT is True untli you let up in the LEFT key
        if event.type == pygame.KEYUP and event.key == K_LEFT:
            LEFT = False
        if event.type == pygame.KEYDOWN and event.key == K_RIGHT:
            RIGHT = True
        if event.type == pygame.KEYUP and event.key == K_RIGHT:
            RIGHT = False
        if event.type == pygame.KEYDOWN and event.key == K_SPACE:
            fire_missile(ls, missiles)
    ls = move(ls, RIGHT, LEFT)
    draw_missiles(missiles)
    missiles = move_missiles(missiles)

rawDescription: Multiple missiles/bullets in a space invader clone (First go at a game with python)


code: number += 1

rawDescription: Python integer incrementing with ++

description: Python integer incrementing with ++


code:
import turtle
screen = turtle.Screen()
screen.setup(500, 500)
screen.bgcolor('green')

rawDescription: Getting python to open a window

description: Getting python to open a window


rawDescription: pandas series filtering between values

description: Pandas series filtering between values


code:
from bs4 import BeautifulSoup

with open('test.html') as f:
    html = f.read()

soup = BeautifulSoup(html, "html.parser")

tag = soup.find('p', {'id': "thislist"})
tag.insert(0, "bla bla bla...")

rawDescription: How to insert text in a file in a specific location?

description: Insert text in a file in a specific location


code:
def add_children_ids(ids, children):
    for child in children:
        ids.append(child.id)
        add_children_ids(ids, child.children)

children = obj.children
data['children_ids'] = []
add_children_ids(data['children_ids'], children)

rawDescription: Automizing deeply nested function python


code:
def sjoin(x): return ';'.join(x[x.notnull()].astype(str))
df.groupby(level=0, axis=1).apply(lambda x: x.apply(sjoin, axis=1))

rawDescription: Python Pandas merge samed name columns in a dataframe


code:
with open("filename.txt", "r") as file:
    data = file.read()

if data.strip():
    print("empty")
else:
    print("full")

rawDescription: How can I check that a text file has at least 1 character

description: Check that a text file has at least 1 character


rawDescription: Writing data from a sensor to a file

description: Writing data from a sensor to a file


code: cursor.execute("SET SESSION query_cache_type = OFF")

rawDescription: Not able to get latest rows when re-rerunning same query at regular interval


rawDescription: WX Python and Raw Input on Windows (WM_INPUT)


code:
@app.route('/api/v1/do/something', methods=['POST'])
def api_v1_do_something():
    return json_response(json.dumps({
      "result": "success",
      "data": {"a": 1, "b": 2},
    }))

rawDescription: What pure perf choice for a rest API?

description: What pure perf choice for a rest API


code:
import struct
struct.pack('d', float('nan'))

rawDescription: How do I convert float('nan') to binary in python?

description: Convert float('nan') to binary in python


code:
from tkinter import *

# Actual model would be imported. "Dummy" model for testing below.
def dummy_model(dic):
    """
    A "dummy" model for testing the ability for a toolbar to ping the model.
    Argument:
    -dic: a dictionary whose values are numbers.
    Result:
    -prints the sum of dic's values.
    """
    total = 0
    for value in dic.values():
        total += value
    print('The total of the entries is: ', total)

class ToolBar(Frame):
    """
    A frame object that contains entry widgets, a dictionary of
    their current contents, and a function to call the appropriate model.
    """
    def __init__(self, parent=None, **options):
        Frame.__init__(self, parent, **options)
        self.vars = {}

    def call_model(self):
        print('Sending to dummy_model: ', self.vars)
        dummy_model(self.vars)

class VarBox(Frame):
    """
    A customized Frame containing a numerical entry box
    Arguments:
    -name: Name of the variable; appears above the entry box
    -default: default value in entry
    """
    def __init__(self, parent=None, name='', default=0.00, **options):
        Frame.__init__(self, parent, relief=RIDGE, borderwidth=1, **options)
        Label(self, text=name).pack(side=TOP)
        self.widgetName = name  # will be key in dictionary

        # Entries will be limited to numerical
        ent = Entry(self, validate='key')  # check for number on keypress
        ent.pack(side=TOP, fill=X)
        self.value = StringVar()
        ent.config(textvariable=self.value)
        self.value.set(str(default))
        ent.bind('<Return>',   lambda event: self.to_dict(event))
        ent.bind('<FocusOut>', lambda event: self.to_dict(event))

        # check on each keypress if new result will be a number
        ent['validatecommand'] = (self.register(self.is_number), '%P')
        # sound 'bell' if bad keypress
        ent['invalidcommand'] = 'bell'

    @staticmethod
    def is_number(entry):
        """
        tests to see if entry is acceptable (either empty, or able to be
        converted to a float.)
        """
        if not entry:
            return True  # Empty string: OK if entire entry deleted
        try:
            float(entry)
            return True
        except ValueError:
            return False

    def to_dict(self, event):
        """
        On event: Records widget's status to the container's dictionary of
        values, fills the entry with 0.00 if it was empty, tells the container
        to send data to the model, and shifts focus to the next entry box (after
        Return or Tab).
        """
        if not self.value.get():    # if entry left blank,
            self.value.set(0.00)    # fill it with zero
        # Add the widget's status to the container's dictionary
        self.master.vars[self.widgetName] = float(self.value.get())
        self.master.call_model()
        event.widget.tk_focusNext().focus()

root = Tk()  # create app window
BarParentFrame = ToolBar(root)  # holds individual toolbar frames
BarParentFrame.pack(side=TOP)
BarParentFrame.widgetName = 'BarParentFrame'

# Pad out rest of window for visual effect
SpaceFiller = Canvas(root, width=800, height=600, bg='beige')
SpaceFiller.pack(expand=YES, fill=BOTH)

Label(BarParentFrame, text='placeholder').pack(expand=NO, fill=X)
A = VarBox(BarParentFrame, name='A', default=5.00)
A.pack(side=LEFT)
B = VarBox(BarParentFrame, name='B', default=3.00)
B.pack(side=LEFT)

root.mainloop()

rawDescription: tkinter GUI design: managing variables from multiple widgets/toolbars

description: Tkinter GUI design: managing variables from multiple widgets/toolbars


code:
test = int(input("Enter in a number '1-10' "))
roman = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"]
if 0 < test <= 10:
     i = roman[test-1]
     print(test, i)

rawDescription: Print a value from a list based on user input


code:
for ixr, row in enumerate(leresults):
    for ixe, el in enumerate(row):
        if len(el)==1:
            leresults[ixr][ixe] = el[0]

rawDescription: Convert single-element sub-lists to normal elements


rawDescription: How to show Matrix in Sphinx Docs?

description: Show Matrix in Sphinx Docs


rawDescription: How do I access the name of the class of an Object in Python?

description: Access the name of the class of an Object in Python


code:
import numpy as np

def hessian(x):
    """
    Calculate the hessian matrix with finite differences
    Parameters:
       - x : ndarray
    Returns:
       an array of shape (x.dim, x.ndim) + x.shape
       where the array[i, j, ...] corresponds to the second derivative x_ij
    """
    x_grad = np.gradient(x)
    hessian = np.empty((x.ndim, x.ndim) + x.shape, dtype=x.dtype)
    for k, grad_k in enumerate(x_grad):
        # iterate over dimensions
        # apply gradient again to every component of the first derivative.
        tmp_grad = np.gradient(grad_k)
        for l, grad_kl in enumerate(tmp_grad):
            hessian[k, l, :, :] = grad_kl
    return hessian

x = np.random.randn(100, 100, 100)
hessian(x)

rawDescription: numpy second derivative of a ndimensional array

description: Numpy second derivative of a ndimensional array


code:
import pylab, glob

txt_files = glob.iglob("./*.txt")

for data in txt_files:
    data = pylab.loadtxt(data)
    pylab.plot(data[:,1], data[:,2])

pylab.show()

rawDescription: loading all the files on a folder

description: Loading all the files on a folder


code:
urlpatterns = patterns('',
    (r'^', include(admin.site.urls)),
)

rawDescription: Viewing and filtering models: admin panel or not admin panel?


code:
import fnmatch
my_list = [2345, 3245, 2343, 8746]
fnmatch.filter(map(str, my_list), "2*4*")
my_list = ['barrow', 'yellow', 'green', 'red', 'mellow']
fnmatch.filter(map(str, my_list), "*ow")

rawDescription: Find words in lists using python by entering part of them


code:
xlsW = pd.ExcelWriter(finalReportFileName)
rptMatchingDoe.to_excel(xlsW,'Room Counts Not Matching',index=False)
workbook = xlsW.book
rptMatchingSheet = xlsW.sheets['Room Counts Not Matching']
formatShadeRows = workbook.add_format({'bg_color': '#a9c9ff',
                                       'font_color': 'black'})
rptMatchingSheet.conditional_format('A1:'+xlsAlpha[rptMatchingDoeColCount]+matchingCount,{'type': 'formula',
                                                                                'criteria': '=MOD(ROW(),2) = 0',
                                                                                'format': formatShadeRows})
xlsW.save()

rawDescription: Shade Every Other Row

description: Shade Every Other Row


rawDescription: Check for a valid domain name in a string?


code:
a = [1, 2, 3]
b = a
b is a
b == a
b = a[:]
b is a
b == a

rawDescription: What is the difference between keyword: is and == in python


code:
for l in ax.xaxis.get_ticklabels()+ax.yaxis.get_ticklabels():
    if 'A' in l.get_text():
        l.set_color('r')
    elif 'B' in l.get_text():
        l.set_color('g')

rawDescription: Change color of heatmap labels in Python (matplotlib)


code:
q = 50

for start in xrange(0, allfiles.shape[1], q):
    data = allfiles[:,start:start+q]
    ...

rawDescription: Python/Numpy - Extract a 2-d Sub-array from a 2-d array using variables


code:
df = pd.DataFrame({'a':[0,1],'b':[2,3]})

df1 = pd.DataFrame([4,5]).T

pd.concat([df[:1], df1.rename(columns=dict(zip(df1.columns,df.columns))), df[1:]])

#Out[46]:
#   a  b
#0  0  2
#0  4  5
#1  1  3

rawDescription: Insert Row in Python Pandas DataFrame

description: Insert Row in Python Pandas DataFrame


code:
ax = sns.boxplot(data=x)
box = ax.artists[0]
box. set_facecolor("white")

rawDescription: Boxplot: colors by x value and hues differentiated by pattern


code:
json.dumps(['please','help','me'])
json.loads('["please", "help", "me"]')

rawDescription: Python: Proper way to store list of strings in sqlite3 or mysql


code: [y for x, y in sorted(zip(l, l2))]

rawDescription: Mimic the array swaps from a sort

description: Mimic the array swaps from a sort


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

fig = plt.figure()
fig_norm = plt.figure()
fig.show()
fig_norm.show()
ax_fig = fig.add_subplot(1, 1, 1)
ax_fig_norm = fig_norm.add_subplot(1, 1, 1)
ax_fig.set_title("Figure 1", fontsize='large')
ax_fig_norm.set_title("Figure Normalized", fontsize='large')

plt.ion()

while True:
    x = np.random.rand(100)
    y = np.random.rand(100)
    ax_fig.plot(x, y)
    ax_fig_norm.plot(x*3, y*3)
    fig.canvas.draw()
    fig_norm.canvas.draw()

rawDescription: Draw and refresh two independent windows with pyplot


code:
from xlsxwriter.workbook import Workbook

workbook = Workbook('protection.xlsx')
worksheet = workbook.add_worksheet()

# Create a cell format with protection properties.
unlocked = workbook.add_format({'locked': False})

# Format the columns to make the text clearer.
worksheet.set_column('A:A', 40)

# Turn worksheet protection on.
worksheet.protect()

# Write a locked and unlocked cell.
worksheet.write('A1', 'Cell B1 is locked. It cannot be edited.')
worksheet.write('A2', 'Cell B2 is unlocked. It can be edited.')

worksheet.write_formula('B1', '=1+2')  # Locked by default.
worksheet.write_formula('B2', '=1+2', unlocked)

workbook.close()

rawDescription: Python xlsx cell protection (lock)

description: Python xlsx cell protection (lock)


code:
import decimal
decimal.getcontext().prec = 100
decimal.Decimal(1) / decimal.Decimal(3)

rawDescription: how to display a decimal number to 100 decimal places

description: Display a decimal number to 100 decimal places


code:
import re, collections

def words(text): return re.findall('[a-z]+', text.lower())

def train(features):
    model = collections.defaultdict(lambda: 1)
    for f in features:
        model[f] += 1
    return model

NWORDS = train(words(file('big.txt').read()))

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def edits1(word):
    splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
    deletes    = [a + b[1:] for a, b in splits if b]
    transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
    replaces   = [a + c + b[1:] for a, b in splits for c in alphabet if b]
    inserts    = [a + c + b     for a, b in splits for c in alphabet]
    return set(deletes + transposes + replaces + inserts)

def known_edits2(word):
    return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)

def known(words): return set(w for w in words if w in NWORDS)

def correct(word):
    candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
    return max(candidates, key=NWORDS.get)

rawDescription: Efficient way of resolving unknown words to known words?


code:
import datetime as dt
dates=[]
with open('holiday.txt','r') as f:
    dates=[dt.datetime.strptime(line.strip(),'%m/%d/%y')
           for line in f if line.strip()]

print(dates)

rawDescription: How can I convert input file data into date format?

description: Convert input file data into date format


rawDescription: Stack and Pivot Dataframe in Python

description: Stack and Pivot Dataframe in Python


code:
obj.image = img_path
obj.save()

rawDescription: Django point ImageField to an already existing image


code:
for link in links:
    driver.get(link)
    # check for presence of pictures

rawDescription: How to launch several URIs in selenium without crashing firefox?

description: Launch several URIs in selenium without crashing firefox


code:
from matplotlib import colors
data = array([[1,2,3],[2,3,5], [3,1,2]])
cols = {1:'red',2:'blue',3:'green',5:'purple'}

cvr = colors.ColorConverter()
tmp = sorted(cols.keys())
cols_rgb = [cvr.to_rgb(cols[k]) for k in tmp]
intervals = array(tmp + [tmp[-1]+1]) - 0.5
cmap, norm = colors.from_levels_and_colors(intervals,cols_rgb)
plt.pcolor(data,cmap = cmap, norm = norm)

rawDescription: matplotlib heatmap with discrete values with custom defined colors

description: Matplotlib heatmap with discrete values with custom defined colors


rawDescription: What is the equivalent of "zip()" in Python's numpy?


code:
parser = argparse.ArgumentParser()
parser.add_argument('--foo', action='store_true')

args = parser.parse_args()
if args.foo:
    print('--foo was specified')

rawDescription: How to Check if an Argument Was Called Without an Action?


code:
def onMouseOver(self, event):
        '''
        Method to calculate where the mouse is pointing and
        then set the tooltip dynamically.
        '''

        # Use CalcUnscrolledPosition() to get the mouse position
        # within the
        # entire grid including what's offscreen
        x, y = self.grid_area.CalcUnscrolledPosition(event.GetX(),event.GetY())

        coords = self.grid_area.XYToCell(x, y)
        # you only need these if you need the value in the cell
        row = coords[0]
        col = coords[1]
        if self.grid_area.GetCellValue(row, col):
            if self.grid_area.GetCellValue(row, col) == "ABC":
                event.GetEventObject().SetToolTipString("Code is abc")
            elif self.grid_area.GetCellValue(row, col) == "XYZ":
                event.GetEventObject().SetToolTipString("code is xyz")
            else:
                event.GetEventObject().SetToolTipString("Unknown code")
        event.Skip()

rawDescription: Tooltip message when hovering on cell with mouse in wx.grid wxpython


code:
color_from_url = self.request.get('color')
flavour_from_url = self.request.get('flavour')

rawDescription: Basic Python Script in Google App Engine to get the GET parameters and use it accordingly


code:
from collections import defaultdict
my_word="apple"
d = defaultdict(list)
for a,b in zip(my_word,my_word[1:]):
   d[a].append(b)

rawDescription: Creating a dictionary based on a word

description: Creating a dictionary based on a word


code:
#Import Folder model
from filer.models.foldermodels import Folder

#Create Folder:
folder = Folder(owner=someuser, name="myname")  #owner is required
folder.save()

#Create Subfolder
subfolder = Folder(owner=someuser, name="subfolder", parent=folder)
subfolder.save()

rawDescription: Django-filer: How to create folders and save uploaded images correctly?


code:
from google.appengine.api.datastore_types import Key

user_id="agxkZXZ-emFiZXRhLTJyCgsSBFVzZXIYGAw"
datamodel.Task.all().filter('user', Key(user_id))

rawDescription: How do I apply a filter to a google datastore collection based on a key?

description: Apply a filter to a google datastore collection based on a key


code:
import numpy as np

from lmfit import Model, Parameters

def my_poly(x, **params):
    val= 0.0
    parnames = sorted(params.keys())
    for i, pname in enumerate(parnames):
        val += params[pname]*x**i
    return val

my_model = Model(my_poly)

# Parameter names and starting values
params = Parameters()
params.add('C00', value=-10)
params.add('C01', value=  5)
params.add('C02', value=  1)
params.add('C03', value=  0)
params.add('C04', value=  0)

x = np.linspace(-20, 20, 101)
y = -30.4 + 7.8*x - 0.5*x*x + 0.03 * x**3 + 0.009*x**4
y = y + np.random.normal(size=len(y), scale=0.2)

out = my_model.fit(y, params, x=x)
print(out.fit_report())

rawDescription: Creating a python lmfit Model with arbitrary number of parameters


code: var1, var2, var3 = (a or '---' for a in [var1, var2, var3])

rawDescription: Check if condition matches multiple variables


code:
grouped = df.groupby([df.index.year,df.index.day])
df['sum'] = grouped.apply(lambda x: x.Open + x.Close)

rawDescription: Add new column in pandas dataframe object with column math


code:
# Python - it's so readable, the code basically just writes itself ;-)
#
with open('infile') as infile:
  with open('outfile', 'w') as outfile:
    for line in infile:
      fields = line.split('\t')
      outfile.write(','.join(fields))

rawDescription: How to change the field separator of a file using Python?

description: Change the field separator of a file using Python


rawDescription: python ldap attribute query

description: Python ldap attribute query


code:
def queryset(self, request):
        qs = super(ContentAdmin, self).queryset(request)
        return qs.filter(score__name='Twitter').order_by('-score__score')

rawDescription: Django Admin: Order by value on related Foreign Key


code:
new_student = student(First_Name = request.POST.get('add_first_name'))
new_student.save()

rawDescription: add row to database django

description: Add row to database django


code:
self.can.move(self.ball1, self.nx, self.ny)

new_pos = self.can.coords(self.ball1)
self.can.create_line(self.posx_ball, self.posy_ball, new_pos[0], new_pos[1], fill='red')

self.can.after(10, self.move)

rawDescription: Doing traces behind balls with Tkinter

description: Doing traces behind balls with Tkinter


code:
def skip_check(path):
    return os.path.splitext(path)[1] in extensions

rawDescription: Convert strings in a list to raw string for re.search


code:
class1_objs = [Clas1(arg1, arg2) for _ in range(5)]    # create Class1 objects in a list
class2_obj  = Clas2(arg)

for i, obj in enumerate(class1_objs):     # loop over objects and indexes with enumerate
    class2_obj.runloop(obj, *class1_objs[:i] or ["none"])  # use index to slice the list

rawDescription: Generating separate instances; passing list of instances as *args


code:
import importlib

hello = importlib.import_module("hello_hi.py")

rawDescription: Python--How to make method call specific .py scripts depending on method arguments?


code:
pipeline = [
    {
        "$match": {
            "lon": {"$gte": 75, "$lte": 80},
            "country": "India"
        }
    },
    {
        "$unwind": "$isPartOf"
    },
    {
        "$group": {
            "_id":  "$isPartOf",
            "count": {
                "$sum": 1
            }
        }
    },
    {
        "$project": {
            "_id": 0,
            "Region": "$_id",
            "NumberOfCities": "$count"
        }
    },
    {
        "$sort": {"NumberOfCities": -1}
    },
    { "$limit": 1 }
]

rawDescription: mongodb python , quick pipeline code check

description: Mongodb python , quick pipeline code check


code:
from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = (
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
    )
    year_in_school = models.CharField(max_length=2,
                                      choices=YEAR_IN_SCHOOL_CHOICES,
                                      default=FRESHMAN)

rawDescription: How to apply 'IN' constraint to the fields of django models

description: Apply 'IN' constraint to the fields of django models


code: scope = locals()

rawDescription: Access variables of caller function in Python


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

start_date = '2003-05-01'
y = np.load(r'c:\python27\abnormal.npy')
x = pd.date_range(start=start_date, periods=len(y), freq='D')

plt.plot(x,y,'.')
plt.show()

rawDescription: how to make graph

description: Make graph


code:
system_time = win32api.GetSystemTime()
# do stuff here
import subprocess
filepath="D:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
#p.returncode is 0 if success
# more stuff
win32api.SetSystemTime(*system_time)

rawDescription: Keep windows time in a python clock while changing windows time.


code:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
            paramiko.AutoAddPolicy())

ftp = ssh.open_sftp()
ftp.get('remotefile', 'localfile')

rawDescription: Paramiko SFTPClient - Setting missing host key policy?


code:
from datetime import timedelta

results = MyModel.objects.filter(
                id=pk,
                date__range=(start_time, end_time)
                ).values('my_id'
                ).annotate(max_time=Max('my_date_time'))
for result in results:
    result['max_time'] -= timedelta(minutes=60)

rawDescription: Django ORM Query - How to Subtract Time From Model Field?


rawDescription: How can files be added to a tarfile with Python, without adding the directory hierarchy?


code:
import math
def roundthemnumbers(value):
    x = math.floor(value)
    if (value - x) < .50:
        return x
    else:
        return math.ceil(value)

rawDescription: Pythonic way to "round()" like Javascript "Math.round()"?


code:
import Tkinter as tk

# data for the example
info = (
    ("1.1","1.2","1.3"),
    ("2.1","2.2","2,3"),
    ("3.1","3.2","3.3"),
)

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.status = tk.Label(self, anchor="w")
        self.frame_table = tk.Frame(self, background="black")
        self.frame_table.grid_columnconfigure(1, weight=1)
        self.frame_table.grid_columnconfigure(2, weight=1)
        self.frame_table.grid_columnconfigure(3, weight=1)

        self.status.pack(side="bottom", fill="x")
        self.frame_table.pack(side="top", fill="x", padx=10, pady=10)

        for row_number, row_data in enumerate(info):
            no_1, code, value = row_data
            label = tk.Label(self.frame_table, text="row %d" % row_number, background="gray")
            col1  = tk.Label(self.frame_table, text=no_1)
            col2  = tk.Label(self.frame_table, text=code)
            col3  = tk.Label(self.frame_table, text=value)

            # N.B. 'value' is automatically passed to
            # the command by tkinter; we're adding
            # an extra parameter, 'row'
            command=lambda value, row=row_number: self.ChoiceBox(value, row)
            stringvar = tk.StringVar(self.frame_table)
            stringvar.set("Fixed")
            option_menu = tk.OptionMenu(self.frame_table, stringvar,
                                        "Fixed","List","Min","Max",
                                        command=command)
            label.grid(row=row_number, column=0, sticky="nsew", padx=1, pady=1)
            col1.grid(row=row_number, column=1, sticky="nsew", padx=1, pady=1)
            col2.grid(row=row_number, column=2, sticky="nsew", padx=1, pady=1)
            col3.grid(row=row_number, column=3, sticky="nsew", padx=1, pady=1)
            option_menu.grid(row=row_number, column=6, sticky="nsew",
                             padx=1, pady=1)

    def ChoiceBox(self, value, row_number):
        self.status.config(text="you set row %d to '%s'" % (row_number, value))

app = SampleApp()
app.mainloop()

rawDescription: Determining row number of chosen OptionMenu but possibility to create within same variable - Tkinter


code:
dataDict={}
for line in myFile:
        words = line.strip().split()
        userId = words[0]
        movieId = words[1]
        rating = words[2]
        innerDict = dataDict.setdefault(userId, {})
        innerDict[movieId] = rating

rawDescription: Python: Nested Dictionary duplicate values


rawDescription: How do I count the number of 0s at the end of an integer?

description: Count the number of 0s at the end of an integer


rawDescription: Python 3 - open file from console

description: Python 3 - open file from console


code: [list(x[1]) for x in itertools.groupby([1, 2, 3], lambda x: x == 2) if not x[0]]

rawDescription: split a list by a lambda function in python

description: Split a list by a lambda function in python


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

x = np.array([0.2,0.4])
y = np.array([0.2,1.2])
r = np.array([0.5,0.3])

phi = np.linspace(0.0,2*np.pi,100)

na=np.newaxis

# the first axis of these arrays varies the angle,
# the second varies the circles
x_line = x[na,:]+r[na,:]*np.sin(phi[:,na])
y_line = y[na,:]+r[na,:]*np.cos(phi[:,na])

plt.plot(x_line,y_line,'-')
plt.show()

rawDescription: plot many circles based on x,y,r being vectors in python

description: Plot many circles based on x,y,r being vectors in python


code:
from mytests import testfunc

def test_parameter_view(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ParameterForm(request.POST)
        if form.is_valid():
            testfunc(form.cleaned_data['parameter'])   # <-- Here the actual testing happens
            return HttpResponseRedirect(reverse(test_result)) # Redirect after POST
    else:
        form = ParameterForm()

    return render_to_response('test.html', {
        'form': form,
    })

rawDescription: integrating python scripts with django

description: Integrating python scripts with django


code:
colors = ['k','k','k']
for i in range(3):
    tempcolors = list(colors)
    tempcolors[i] = 'r'
    plt.figure()
    plt.bar(x,y,color=tempcolors)

rawDescription: Color specific bars in matplot lib according to x label


code:
import re

s = 'STARTabcdENDefSTARTghiEND'
a = 'START'
b = 'END'
out = re.findall(a+'(.+?)'+b, s)
# out: ['abcd', 'ghi']

rawDescription: How to get substring in between certain tokens?

description: Get substring in between certain tokens


rawDescription: how to redirect to new page with javascript , after submit html form?

description: Redirect to new page with javascript , after submit html form


code:
from PyQt4 import QtGui,QtCore

class CentralWidget(QtGui.QFrame):

    def __init__(self, *args):
        super(CentralWidget, self).__init__(*args)
        self.setStyleSheet("background-color: rgb(255,0,0); margin:5px; border:1px solid rgb(0, 255, 0); ")

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    mw = QtGui.QMainWindow()
    w = CentralWidget(mw)
    mw.setCentralWidget(w)
    mw.show()
    w.show()
    app.exec_()

rawDescription: How to add border around QWidget?

description: Add border around QWidget


code:
class A:
    x = y

rawDescription: In what ways can the interpreter leave a class definition?


code:
while True:
    func()
    answer = raw_input( "Loop again? " )
    if answer != 'y':
        break

rawDescription: python, basic question on loops

description: Python, basic question on loops


code:
...
text="Hello, world"
default_font = tkFont.nametofont("TkDefaultFont")
width = default_font.measure(text)
height = default_font.metrics("linespace")
...

rawDescription: Tkinter Label: How do I know that the text is too long for it?


code:
import os, re

path = 'C:\\Users\\ME\\Desktop\\TEST'
text_files = [filename for filename in os.listdir(path)]

desired_text1 = re.compile(r'^\d{3}_[a-zA-Z]+\d{3}.jpg')
desired_text2 = re.compile(r'^\d{3}_[a-zA-Z]+_\d{3}.jpg')

for i in range(len(text_files)):
    working_file = path + '\\' + text_files[i]
    fin = open(working_file, 'r')
    match = ''

    for line in fin:
        mo1 = desired_text1.search(line)
        mo2 = desired_text2.search(line)
        if mo1:
            match += mo1.group()[:-7] + '_' + mo1.group()[-7:]+'\n'
        elif mo2:
            match += mo2.group() +'\n'

    fin.close()

    fout = open(working_file, 'w')
    fout.write(match)
    fout.close()

rawDescription: Pattern searching in a file and replacing the found results


code:
for el in tree.iter():
    ws = olWS()
    ws.country = el.text if el.tag == 'custom_var4' else ''
    ws.comment = el.text if el.tag == 'comments' else ''
    ws.save()

rawDescription: Django modelfield to put in data recursively while iterating over xml tags


code:
# Plotting
df.plot(kind='line', subplots=True, grid=True, title="Sample Data (Unit)",
    layout=(4, 3), sharex=True, sharey=False, legend=False,
    style=['r', 'r', 'r', 'g', 'g', 'g', 'b', 'b', 'b', 'r', 'r', 'r'],
    xticks=np.arange(0, len(df), 16))

[ax.legend(loc=1) for ax in plt.gcf().axes]

rawDescription: Plot pandas dataframe with subplots (subplots=True): Place legend and use tight layout


code:
words = words = ["Happy", "Happy", "Happy", "Duck", "Duck"]
words_dict = {}

for w in words:
    if w in words_dict:
        words_dict[w] += 1
    else:
        words_dict[w] = 1

result_num = max(words_dict.values())

print(result_num)
# 3

rawDescription: Python - My frequency function is inefficient


code:
def mix(s, c=' ', n=1):
    return ''.join(s[i:i+n]+c for i in range(0,len(s),n))

rawDescription: how to 'marry' two strings in python?

description: 'marry' two strings in python


code:
def ipRange(start_ip, end_ip):
  start = list(map(int, start_ip.split(".")))
  end = list(map(int, end_ip.split(".")))
  temp = start
  ip_range = []

  ip_range.append(start_ip)
  while temp != end:
    start[3] += 1
    for i in (3, 2, 1):
      if temp[i] == 256:
        temp[i] = 0
        temp[i-1] += 1
    ip_range.append(".".join(map(str, temp)))
  return ip_range

def IPTVSignalTest(ip):
  # do your test here, return true if IPTV signal, false otherwise
  return TRUE

ip_range = ipRange("192.168.1.0", "192.171.3.25")
save_ip = []
for ip in ip_range:
  if IPTVSignalTest(ip):
    save_ip.append(ip)

rawDescription: Python script to verify IPTV streams (UDP)


code:
def connected_tuples(pairs):
    # for every element, we keep a reference to the list it belongs to
    lists_by_element = {}

    def make_new_list_for(x, y):
        lists_by_element[x] = lists_by_element[y] = [x, y]

    def add_element_to_list(lst, el):
        lst.append(el)
        lists_by_element[el] = lst

    def merge_lists(lst1, lst2):
        merged_list = lst1 + lst2
        for el in merged_list:
            lists_by_element[el] = merged_list

    for x, y in pairs:
        xList = lists_by_element.get(x)
        yList = lists_by_element.get(y)

        if not xList and not yList:
            make_new_list_for(x, y)

        if xList and not yList:
            add_element_to_list(xList, y)

        if yList and not xList:
            add_element_to_list(yList, x)

        if xList and yList and xList != yList:
            merge_lists(xList, yList)

    # return the unique lists present in the dictionary
    return set(tuple(l) for l in lists_by_element.values())

rawDescription: Given n tuples representing pairs, return a list with connected tuples


rawDescription: How to implement this python generator

description: Implement this python generator


code:
testdf = pd.DataFrame({"happy": [1, 2, 1, 3], "sad": [4, 5, 6, 7], "cool":[1, 99, 0, -5]})
testgb = testdf.groupby(["happy"]).agg({'sad': lambda x: max(x)})

rawDescription: Pandas Aggregating a GroupBy object using UDF


code:
try:
     # This handles imports when running .py files from inside app directory
     from file_to_import.py import class_instance
except:
     # This handles imports when running nosetests from top-level (above app)
     # directory
     from directory_containing_app_files.file_to_import import class_instance

rawDescription: PYTHON: nosetests import file path with multiple modules/files


rawDescription: Skip specific data lines from a .txt file in order to plot a 2D line with breaks


code: args = parser.parse_args()

rawDescription: Optional Command Line Parameter in Python


code:
def replace(sequence, replacement, lst, expand=False):
    out = list(lst)
    for i, e in enumerate(lst):
        if e == sequence[0]:
            i1 = i
            f = 1
            for e1, e2 in zip(sequence, lst[i:]):
                if e1 != e2:
                    f = 0
                    break
                i1 += 1
            if f == 1:
                del out[i:i1]
                if expand:
                    for x in list(replacement):
                        out.insert(i, x)
                else:
                    out.insert(i, replacement)
    return out

rawDescription: Replace sequence in list with a value in Python


code: pygame.draw.circle(gameDisplay, yellow, (750+lead_z, 200), 75, 0)

rawDescription: Pygame Circle Fill Number of Arguments Passed Error


code:
for year, state, county in foo:
    if (state, county) in bar:
        aFile.write(...)

rawDescription: write to file from nested for loop with try statement

description: Write to file from nested for loop with try statement


code:
ref_by_number = dict(
  (row.number, row)
  for row in db.session.query(reference).filter(reference.parent == 1)
)

rawDescription: How to access SQLalchemy object in jinja template using column key

description: Access SQLalchemy object in jinja template using column key


code:
import numpy as np
a=np.asarray([3,4,np.nan,1,2])
np.isnan(a)
a[np.isnan(a)]
np.where(np.isnan(a))

rawDescription: Finding nans in an array

description: Finding nans in an array


code:
result = []
ms, mb = (dict(a),dict(b)) if len(a)<len(b) else (dict(b),dict(a))
for k in ms:
  if k in mb:
    result.append([k,ms[k]+mb[k]])

rawDescription: python array intersection efficiently

description: Python array intersection efficiently


code:
content = BeautifulSoup(page)
scripts = [tag.extract() for tag in soup.find_all('script')]
for script in scripts:
    old_script = script
    src = script.get('src')
    if '/COMPRESSED/' in src:
        script['async'] = "True"
    page = page.replace(old_script, script)

rawDescription: Django-Compressor Compressed Filename

description: Django-Compressor Compressed Filename


code:
import os
import sys

config_name = 'myapp.cfg'

# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
    application_path = os.path.dirname(sys.executable)
elif __file__:
    application_path = os.path.dirname(__file__)

config_path = os.path.join(application_path, config_name)

rawDescription: Determining application path in a Python EXE generated by pyInstaller


code:
...
y = exons[name]

for index in range(len(y) - 1): # the - 1 is to prevent going out of bounds
    first_max = max(y[index])
    second_min = min(y[index+1])
    ... # do more stuff, I didn't completely follow what you're trying to do

rawDescription: using enumerate to iterate over a dictionary of lists to extract information

description: Using enumerate to iterate over a dictionary of lists to extract information


code:
from distance import distance
x0=float(input("Please input x0: "))
y0=float(input("Please input y0: "))
x1=float(input("Please input x1: "))
y1=float(input("Please input y1: "))
print ("")
print (distance(x0, y0, x1, y1))

rawDescription: importing function from module python 3

description: Importing function from module python 3


code:
class menu(osv.Model):
    _name = "menu"
    _description = "Menu"
    _order = "tipo"
    _rec_name = 'nome'

    # ...

rawDescription: How to change displayed value from many2one field in OpenERP (Odoo)?

description: Change displayed value from many2one field in OpenERP (Odoo)


code: (shipX-mouseX, shipY-mouseY)

rawDescription: How to have an object run directly away from mouse at a constant speed

description: Have an object run directly away from mouse at a constant speed


code:
{
'DESCR': None,
 'data': [],
 'filenames': array(),
 'target': array(),
 'target_names': []
}

rawDescription: load_files in scikit-learn not loading all files in directory

description: Load_files in scikit-learn not loading all files in directory