code: nickname = line.split("\t")[0]

rawDescription: Parsing a simple text file using Python

description: Parsing a simple text file using Python


code:
class MyHandler(BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(200, "ok")
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header("Access-Control-Allow-Headers", "X-Requested-With")

    def do_GET(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Content-type',    'text/html')
        self.end_headers()
        self.wfile.write("Hello world!")
        self.connection.shutdown(1)

rawDescription: Strange JQuery Error "code 501, message Unsupported method OPTIONS"


code:
from os import walk
from os.path import splitext
from os.path import join

foodir = r"C:\path\to\top\dir"
barlist = list()

for root, dirs, files in walk(foodir):
  for f in files:
    if splitext(f)[1].lower() == ".txt":
      barlist.append(join(root, f))

rawDescription: Get path of all .txt files in a folder and subfolders


rawDescription: multidimensional numpy array __eq__

description: Multidimensional numpy array __eq__


code:
class ProductDelegate(QtSql.QSqlRelationalDelegate):
    def createEditor(self, parent, option, index):
        if index.column() == 3:
            editor = QtGui.QDateEdit(parent)
            now = QtCore.QDate.currentDate()
            editor.setDisplayFormat('yyyy-MM-dd')
            editor.setMinimumDate(now)
            editor.setCalendarPopup(True)
            return editor
        return super(ProductDelegate, self).createEditor(parent, option, index)

    def setEditorData(self, editor, index):
        if index.column() == 3:
            data = index.data()
            if not isinstance(data, QtCore.QPyNullVariant):
                 editor.setDate(QtCore.QDate.fromString(data))
        else:
            super(ProductDelegate, self).setEditorData(editor, index)

    def setModelData(self, editor, model, index):
        if index.column() == 3:
            value = editor.date().toString('yyyy-MM-dd')
            model.setData(index, value, QtCore.Qt.EditRole)
        else:
            super(ProductDelegate, self).setModelData(editor, model, index)

rawDescription: pyqt4 dateedit delegate don't want to display time

description: Pyqt4 dateedit delegate don't want to display time


code:
import multiprocessing as mp

def foo(in_file, out_file):
    in_data = ""
    # this is just an example of how to read file
    with open(in_file, "rb") as f:
        for line in f:
            in_data += line
    ...
    out_data = process(in_data)
    ...
    with open(out_file,'wb') as f:
        f.write(out_data)

def main():
    files =[("/infile1", "/outfile1"), ("/infile2", "/outfile2"), ...]
    # you should choose how many processes you wish to instantiate.
    # leaving it blank will assume the number of threads/core available.
    pool = mp.Pool(processes=4)
    pool.starmap_async(foo,files)

rawDescription: How does one execute asynchronous tasks in Python 3.4?

description: Execute asynchronous tasks in Python 3.4


code:
from sklearn.dummy import DummyClassifier
import numpy as np

two_dimensional_values = []
class_labels           = []

for i in xrange(90):
    two_dimensional_values.append( [1,1] )
    class_labels.append(1)

for i in xrange(10):
    two_dimensional_values.append( [0,0] )
    class_labels.append(0)

#now 90% of the training data contains the target property
X = np.array( two_dimensional_values )
y = np.array( class_labels )

#train a dummy classifier to make predictions based on the most_frequent class value
dummy_classifier = DummyClassifier(strategy="most_frequent")
dummy_classifier.fit( X,y )

#this produces 100 predictions that say "1"
for i in two_dimensional_values:
    print( dummy_classifier.predict( [i]) )

#train a dummy classifier to make predictions based on the class values
new_dummy_classifier = DummyClassifier(strategy="stratified")
new_dummy_classifier.fit( X,y )

#this produces roughly 90 guesses that say "1" and roughly 10 guesses that say "0"
for i in two_dimensional_values:
    print( new_dummy_classifier.predict( [i]) )

rawDescription: What is the theorical foundation for scikit-learn dummy classifier?


code:
d1 = {'a': {'b1': 12, 'c21': 41}, 'ff': {'h1': 2, 'b1': 32}}
d2 = {'a': 22, 'b1': 77, 'g8': 10, 'h1': 37}

print({key: {inner_key: inner_value for inner_key, inner_value in value.items() if inner_key in d2}
       for key, value in d1.items()})

rawDescription: Filtering out keys the are not shared between two nested dictionaries


code:
from itertools import product
for y, x in product(range(3), repeat=2):
  do_something()
  for y1, x1 in product(range(3), repeat=2):
    do_something_else()

rawDescription: In python is there an easier way to write 6 nested for loops?


code:
def read_items(f):
  s = f.read(108*1000)
  for o in range(0, len(s), 108):
    yield buffer(s, o, 108)

for data in read_items(f):
   ...

rawDescription: List of structures from unpack binary files fast


code:
with_avg = SomeObject.objects.annotate(avg=Avg('something'))
with_avg_and_has = with_avg.extra(select={'has_something': 'something is NULL'})
sorted_result = with_avg_and_has.order_by('-has_something', '-avg').all()

rawDescription: Django ORM: Ordering w/ aggregate functions — None special treatment


code:
player = soup.find_all('td',{'class':'player-name'})
if len(player) > 2:
    first_player_name = player[1].find('a').get_text()

rawDescription: Cleaning up web parsing

description: Cleaning up web parsing


code:
import re
regex = '\s(\w+)\s(\d+\,)\s(\d+)' # this will match the form "str int, int"

with open('textfile.txt', 'r') as f:
    text = f.read()

all_dates = [' '.join(date) for date in re.findall(regex, text)]

rawDescription: Read text file and count number of words between two words(Two Dates)


code:
import os
pfad = askopenfilename()
name, ext = os.path.splitext(pfad)
backup_name = name + "-original" + ext
if not os.path.isfile(backup_name):
    im_backup = Image.open(pfad)
    im_backup.save(backup_name)

rawDescription: Python PIL save Image in directory no override if the name is same


rawDescription: The initialization of 2-dimensional array in python


code:
import gi
help(gi)

rawDescription: Find / Generate documentation for Gtk, Gdk, GdkPixbuf,


code:
def createStars(x):
    if x == 0:
        return '*'
    else:
        return createStars(x-1) * 2

rawDescription: create recursive power of 2 '*' in python

description: Create recursive power of 2 '*' in python


code:
import tkinter as tk

root = tk.Tk()
c = tk.Canvas(root)
c.pack()
r = c.create_rectangle((50, 50, 100, 100), fill='red')
c.tag_bind(r, '<Button-1>', lambda event: print('works'))
root.mainloop()

rawDescription: Tkinter Button opacity

description: Tkinter Button opacity


rawDescription: Cutting out row and column of an array

description: Cutting out row and column of an array


code:
query = {}

if 'name' in request.args:
    query['name'] = request.args['name']

if 'phone' in request.args:
    query['phone'] = request.args['phone']

if 'email' in request.args:
    query['email'] = request.args['email']

user = User.objects(**query)

rawDescription: Chaining queries in MongoEngine

description: Chaining queries in MongoEngine


code:
import os
fileDir = os.listdir(directory) #I hope that isn't a keyword
print(any(x==fileName for x in fileDir))
#will return True if the file is in the directory

rawDescription: Search for a PDF name in a Folder Python


code:
xpath_jobs_sel = './/div[contains(@class,"listResults")]//a[@class="job-link"]'
for sel in response.xpath(xpath_jobs_sel):
    title = sel.xpath('./@title').extract()

rawDescription: web scraping with scrapy. how to define an xpath wildcard for numbers?

description: Web scraping with scrapy. how to define an xpath wildcard for numbers


code: button = Button(frame1, text = "OK", command = lambda : listOfFiles.append(FileNameOption.get()))

rawDescription: Python Prints List Object [tkinter.StringVar object at 0x01FEAD50], But Not Items in List *Tkinter*


code:
import numpy as np
a = np.array([[False,False,True],
              [False,True,False]])
np.argwhere(a) # equivalent to checking a == True
#array([[0, 2],
#       [1, 1]], dtype=int64)
np.where(a) # equivalent to checking a == True
#(array([0, 1], dtype=int64), array([2, 1], dtype=int64))

rawDescription: Convert mask (boolean) array to list of x,y coordinates


code:
date_str = "2016-03-28T20:23:46+0800"
format = '%Y-%m-%dT%H:%M:%S%z'
new_format = '%Y-%m-%d %H:%M:%S'
datetime.datetime.strptime(date_str, format).strftime(new_format)

rawDescription: How to translate datetime string to sql format?

description: Translate datetime string to sql format


code:
r=requests.post( url
               , data={'sessionId':sessionId, 'source':'Neurotracker'}
               , files={'files[factfile]': (os.path.basename(filename), filecontent, 'application/octet-stream')} )

rawDescription: Send a .csv file using Requests 2.2.1 in Python 2.7.6


code:
def file(self, filename):
    url = "./%d.JPG" % (self.id,)
    return url

class Employee(models.Model):
    id = models.IntegerField(max_length = 6,primary_key=True,verbose_name="Employee ID")
    name = models.CharField(max_length = 100,verbose_name="Name")
    image = models.ImageField(upload_to = file,blank=True,null=True)

rawDescription: Added Image field in django model.py , how ever when uploading it takes default name


rawDescription: Directly providing foreign key value in django


code:
row_sums = a.sum(axis=1)
new_matrix = a / row_sums[:, numpy.newaxis]

rawDescription: How to normalize a 2-dimensional numpy array in python less verbose?

description: Normalize a 2-dimensional numpy array in python less verbose


code: concat_ws(' ', nullif(namt, ''), nullif(namf, ''), nullif(naml, ''), nullif(nams, ''))

rawDescription: combine strings from mysql tables without extra spaces

description: Combine strings from mysql tables without extra spaces


code: re.sub(r'\(a\)', '@', x.strip(), flags=re.IGNORECASE)

rawDescription: Replace '(a)' with '@‘within a python string


rawDescription: How to extract array from the first element of triples in 2d array of triples using numpy

description: Extract array from the first element of triples in 2d array of triples using numpy


code: WebDriverWait(driver, 10).until(lambda driver : driver.title.lower().startswith("cheese!"))

rawDescription: In Python - Selenium2 how to set the time for which a webdriver instance should wait,when loading a page,before giving a timeout exception?


code:
import datetime

mydate = datetime.datetime(2015, 10, 22, 00, 00, 00, 00)
mymondaydate = mydate - datetime.timedelta(days=mydate.weekday())
mytuesdaydate = mymondaydate + datetime.timedelta(days=1)

print(mydate)
print(mymondaydate)
print(mytuesdaydate)

rawDescription: Generating dates to the days of a week in Python?


code:
for root, dirs, files in os.walk(args):
    with file('{}/test.file'.format(root)) as f:
        f.write('test')

    files.append('test')

rawDescription: os walk with changed directory structure

description: Os walk with changed directory structure


code:
from __future__ import print_function

import json

raw_response = '[["Message","User string from here."]]'
data = json.loads(raw_response)

print(data[0][1])

rawDescription: How to print specific json list items?

description: Print specific json list items


code: listMult = [sum(x*y for x, y in zip(tup, somelist)) for tup in tuplelist]

rawDescription: Unpacking an unspecified amount of variables


code:
from lxml.etree import fromstring
data = urllib.urlopen(url) # fetching url with iframe
tree = fromstring(data.read()) # parsing tree to get src attribute
src_url = tree.cssselect("iframe").attrib['src']
data = urllib.urlopen(src_url) # open iframe src url
tree = fromstring(data.read()) # parsing iframe tree

rawDescription: Parse an iframe using lxml

description: Parse an iframe using lxml


code:
if isinstance(variable, int):
   variable = (variable, )

rawDescription: How to unify single values and sequences/tuples?

description: Unify single values and sequences/tuples


code:
import os.path
os.path.join('/my/root/directory', 'in', 'here')

rawDescription: Create file path from variables

description: Create file path from variables


code:
ideas.aggregate([
    {"$match": {'colour':'some_Color_of_ur_choice' }},
    {'$group':{'_id': "$_id",'count':{"$sum": 1 } }}
    ])

rawDescription: pymongo extract objectID from find

description: Pymongo extract objectID from find


code:
import ast
[ast.literal_eval(x) for x in open("test.txt")]

rawDescription: How can I read a text file that contains lists and add those lists to a list?

description: Read a text file that contains lists and add those lists to a list


code:
with open('file1.txt', 'r+'), open('file2.txt') as file1, file2:
    list = file1.readlines()
    list.insert(3, file2.readlines())
    file1.writelines(list)

rawDescription: How to copy and paste 4th line a another file using python

description: Copy and paste 4th line a another file using python


code:
class MyWidget(QtGui.QWidget):
    keyPressed = QtCore.pyqtSignal()

    def keyPressEvent(self, event):
        super(MyWidget, self).keyPressEvent(event)
        self.keyPressed.emit()
...

self.widget.keyPressed.connect(on_key)

rawDescription: PyQt Connect to KeyPressEvent

description: PyQt Connect to KeyPressEvent


code:
a = [(1,'a'), (3,'b'), (2,'c')]
b = [4,6,5]

sort_function = lambda x: x[0][0]
sort_target = list(zip(a,b))
sort_target.sort(key = sort_function)

resorted_a, resorted_b = zip(*sort_target)

print (resorted_a) # prints ((1, 'a'), (2, 'c'), (3, 'b'))
print (resorted_b) # prints (4, 5, 6)

rawDescription: Reordering a list in python according to the changes made in another


code: option = """--pretty-print "http://foo.com" {'bbb'}"""

rawDescription: Python string escape

description: Python string escape


rawDescription: Cross-platform addressing of the config file


code:
import urlparse
import os

def worksheet_ids(feed):
  def _id(entry):
    split = urlparse.urlsplit(entry.id.text)
    return os.path.basename(split.path)
  return dict([
    (entry.title.text, _id(entry))
    for entry in feed.entry
    ])

rawDescription: List worksheets and associated worksheet IDs from Google Spreadsheet API in Python


code:
import pandas
cur = db.cursor()
nf = pandas.io.sql.read_frame("select * from tablename limit 50;", db)

rawDescription: Dealing with data from MySQL using Python


code:
TXT_file = 'TXT.txt'
CSV_file = 'CSV.csv'
OUT_file = 'OUTPUT.csv'

## From the TXT, create a list of domains you do not want to include in output
with open(TXT_file, 'r') as txt:
    domain_to_be_removed_list = []

    ## for each domain in the TXT
    ## remove the return character at the end of line
    ## and add the domain to list domains-to-be-removed list
    for domain in txt:
        domain = domain.rstrip()
        domain_to_be_removed_list.append(domain)

with open(OUT_file, 'w') as outfile:
    with open(CSV_file, 'r') as csv:

        ## for each line in csv
        ## extract the csv domain
        for line in csv:
            csv_domain = line.split(';')[0]

            ## if csv domain is not in domains-to-be-removed list,
            ## then write that to outfile
            if (not csv_domain in domain_to_be_removed_list):
                outfile.write(line)

rawDescription: Remove line from file if containing word from another .txt file in python/bash


code:
m = re.match('a','a')  #example match command
help(m)

rawDescription: Comprehensive reference for python standard library classes / methods


code:
q = (
    session
    .query(A)
    .options(joinedload(A.b).joinedload(B.c))
    .options(joinedload(A.b).joinedload(B.d))
)

rawDescription: SQLAlchemy: eager loading of more than one relationship


code:
from django.forms import Form
from formfieldset.forms import FieldsetMixin

class MyForm(Form, FieldsetMixin):
    fieldsets = (
        (u'', {'fields': ['name', 'company']}),
        (u'Interested in', {'fields': ['foo', 'bar', 'baz']}),
    )

    # rest of the form

rawDescription: Inserting A Heading Into A Django Form

description: Inserting A Heading Into A Django Form


code:
def parse(self, response):
    ...
    item = MyCustomItem()
    ...
    yield Request(urlparse.urljoin(response.url, url),
                  method="HEAD",
                  meta={'item': item},
                  callback=self.my_callback)

def my_callback(self, response):
    item = response.meta['item']
    ...

rawDescription: Can I specify any method as the callback when constructing a Scrapy Request object?

description: Specify any method as the callback when constructing a Scrapy Request object


code:
import datetime
import calendar

year = 2012
month = 6

num_days = calendar.monthrange(year, month)[1]
start_date = datetime.date(year, month, 1)
end_date = datetime.date(year, month, num_days)

results = session.query(Event).filter(
    and_(Event.date >= start_date, Event.date <= end_date)).all()

rawDescription: How to get all objects with a date that fall in a specific month SQLAlchemy

description: Get all objects with a date that fall in a specific month SQLAlchemy


code:
import tkinter as tk

class Example(tk.Frame):
    def __init__(self, root):

        tk.Frame.__init__(self, root)
        for scale in ("red", "green", "blue"):
            widget = tk.Scale(self, from_=0, to=255, orient="horizontal",
                              command=lambda value, name=scale: self.report_change(name, value))
            widget.pack()

    def report_change(self, name, value):
        print("%s changed to %s" % (name, value))

if __name__ == "__main__":
    root=tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: How to pass command to function from Tkinter Scale

description: Pass command to function from Tkinter Scale


code:
# create a new column with only time from your date column
df['time'] = df['date'].apply(lambda x: x.time())

#filter based on the time column
mask = (df['time'] > datetime.time(11,00)) & (df['time'] < datetime.time(11,30))
df = df[mask]

rawDescription: How selected time period in a pandas dataframe?


code:
def post(self):
    """
    Adds a :class:`Persona` resource in Persona resource list.

    :returns: A newly created Persona resource with http 201 response code.

    .. todo::

       Validate all post fields

    """

rawDescription: Sphinx-apidocs not generating TODO documentation from python code


code:
# ~/.config/sublime-text-3/Packages/User/Python3.sublime-build
{
    "cmd": ["/usr/bin/python3.5", "-u", "$file"],
    "selector": "source.python",
    "file_regex": "file \"(...*?)\", line ([0-9]+)"
}

rawDescription: Sublime Text 3 Python 3 print while running


code:
def get_fluentd_logger(name):
    import logging
    from fluent import handler

    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(name)
    logger.level = logging.INFO
    handler = handler.FluentHandler(name, host='localhost', port=24224)
    handler.level = logging.INFO
    logger.addHandler(handler)
    return logger

rawDescription: Python logging - overview of currently installed loggers/handlers


code:
def chunks(l, n):
    """ Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

test_x = pd.DataFrame(test_x)
test_result = pd.DataFrame()
for chunk in chunks(test_x.index, 10000):
    test_data = test_x.ix[chunk]
    test_result = pd.concat([test_result, pd.DataFrame(clf.predict(test_data))])

rawDescription: How to apply a randomforest classifier to all of the dataset, a small section at a time in python

description: Apply a randomforest classifier to all of the dataset, a small section at a time in python


code: the_regex  = re.compile(re.escape(the_value))

rawDescription: Is there a simple way to switch between using and ignoring metacharacters in Python regular expressions?


code:
import subprocess

with open('myfile.txt', 'w') as fout:
    subprocess.check_call('ls', stdout=fout)

rawDescription: Redirection opeartors, < and >, in os.system(cmd)


code:
from collections import Counter
counts = Counter(main_list)

duplicate_list, unique_list = [], []
for entry in main_list:
    if counts[entry] > 1:
        duplicate_list.append(entry)
    else:
        unique_list.append(entry)

rawDescription: How to make another list of the duplicate entries in existing list using python?

description: Make another list of the duplicate entries in existing list using python


code:
from optparse import make_option

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--delete',
            action='store_true',
            dest='delete',
            default=False,
            help='Delete inactive packages'),
        )

    def handle(self, *args, **options):

        if options['delete']:
            selected_packs.objects.filter(activation_date__lt=timeframe).delete()

rawDescription: Automatically delete items from subscriptions database after they have expired?


code:
def get_models_within_25 (self):
    from django.db import connection, transaction
    cursor = connection.cursor()

    cursor.execute("""SELECT id, (
        3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) *
        cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) *
        sin( radians( lat ) ) ) )
        AS distance FROM stores HAVING distance < 25
        ORDER BY distance LIMIT 0 , 20;""")
    ids = [row[0] for row in cursor.fetchall()]

    return MyModel.filter(id__in=ids)

rawDescription: Filter zipcodes by proximity in Django with the Spherical Law of Cosines


code:
for root, subFolders, files in os.walk(rootdir):
    if '.svn' in subFolders:
      subFolders.remove('.svn')

rawDescription: os.walk exclude .svn folders

description: Os.walk exclude .svn folders


code:
import pycurl

name='bob'
pwd='pwd1'
url="https://mywebservice"

curl = pycurl.Curl()
curl.setopt(pycurl.URL, url)
curl.setopt(pycurl.SSL_VERIFYPEER, 0)

curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_NTLM)
curl.setopt(pycurl.USERPWD, "{}:{}".format(name, pwd))

curl.perform()
curl.close()

rawDescription: Get page using NTLM with pyCurl

description: Get page using NTLM with pyCurl


code:
import sys
from PyQt4 import QtGui, QtCore

class CompiledWindow(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle('Reasonably named window')
        names = ['Open Logo Picture', 'Open Setup Picture', 'Open first data file', 'Open second data file', 'Enter text about settings', 'Enter other text about settings', 'Enter third setting', 'Enter fourth setting']
        grid = QtGui.QGridLayout(self)
        self.Logo_button = QtGui.QPushButton(names[0], self)
        self.Logo_button.clicked.connect(self.logo_pic)
        grid.addWidget(self.Logo_button, 0, 0)

    def logo_pic(self):
        self.Logo_picture = unicode(QtGui.QFileDialog.getOpenFileName())
        print(self.Logo_picture)

app = QtGui.QApplication(sys.argv)
cw = CompiledWindow()
cw.show()
sys.exit(app.exec_())

rawDescription: PyQt4 - signals and slots. Trouble connecting button to a method


rawDescription: Reorder Indexes of MultiIndex in a Pandas DataFrame


code:
def zip_dir(zipname, dir_to_zip):
    dir_to_zip_len = len(dir_to_zip.rstrip(os.sep)) + 1
    with zipfile.ZipFile(zipname, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
        for dirname, subdirs, files in os.walk(dir_to_zip):
            for filename in files:
                path = os.path.join(dirname, filename)
                entry = path[dir_to_zip_len:]
                zf.write(path, entry)

rawDescription: Python: Zipping a Folder + File

description: Python: Zipping a Folder + File


code:
from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def my_view(request):
    ...

rawDescription: Speed up often used Django random query

description: Speed up often used Django random query


code:
import contextlib
@contextlib.contextmanager
def dummyctx(x):
    yield x

def get_last_synced_changelist(p4port, client_name, p4=None):
    if p4 is None:
        ctx = P4Connection(p4port)
    else:
        ctx = dummyctx(p4)
    with ctx as p4:
        last_change_list = p4.run_changes("-m1", "@%s" % client_name)
        if last_change_list:
            return last_change_list[0]["change"]
        else:
            return None

rawDescription: Python handling parameters in "with" context


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

n = 1000

fig = plt.figure()
ax = fig.gca(projection='3d')

for k in linspace(0, 5, 5):
    THETA = linspace(0, 2*pi, n)
    R     = ones(THETA.shape)*cos(THETA*k)

    # Convert to Cartesian coordinates
    X = R*cos(THETA)
    Y = R*sin(THETA)

    ax.plot(X, Y, k-2)

plt.show()

rawDescription: Create a stack of polar plots using Matplotlib/Python


code:
import sys
sys.path.append("C:\Program Files (x86)\ActiveState Komodo IDE 8\lib\support\dbgp\pythonlib")  # path to Komodo dbgp library
from dbgp import client
client.brk()

rawDescription: How to Debug GAE using Komodo IDE

description: Debug GAE using Komodo IDE


code:
def loadForm(self):
 ...
 self.setPropList("cmbTypeCompression", "model", ["Item A", "Item B"])

def setPropList(self, objName,  propName, values):
 obj = self.win.findChild(QObject, objName)
 property = QQmlProperty(obj, propName)
 property.write(values)

rawDescription: PyQt 5.5 QML Combobox

description: PyQt 5.5 QML Combobox


code:
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt
import numpy as np
from vectors import *

def pnt2line(pnt, start, end):
    line_vec = vector(start, end)
    pnt_vec = vector(start, pnt)
    line_len = length(line_vec)
    line_unitvec = unit(line_vec)
    pnt_vec_scaled = scale(pnt_vec, 1.0/line_len)
    t = dot(line_unitvec, pnt_vec_scaled)
    if t < 0.0:
        t = 0.0
    elif t > 1.0:
        t = 1.0
    nearest = scale(line_vec, t)
    dist = distance(nearest, pnt_vec)
    nearest = add(nearest, start)
    return (dist, nearest)

def point_in_poly(x,y,poly):

    n = len(poly)
    inside = False

    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside

# Original points, hull and test points
points = np.random.rand(30, 2)   # 30 random points in 2-D
hull = ConvexHull(points)
newpoints = np.random.rand(30, 2)   # 30 random points in 2-D

pt_dist = []
for p_idx in range(30):
    pt = newpoints[p_idx,:]
    dist_list = []
    for v_idx in range(len(hull.vertices)):
        v1 = hull.vertices[v_idx - 1]
        v2 = hull.vertices[v_idx]
        start = points[v1]
        end = points[v2]
        temp = pnt2line(pt, start, end)
        dist_list.append(temp[0])

    #Check point is within polygon
    inside =  point_in_poly(pt[0],pt[1],points[hull.vertices])
    if (inside == True):
        dist_temp = -1. * min(dist_list)
    else:
        dist_temp = min(dist_list)

    pt_dist.append(dist_temp)

# Plot original points, hull and new points
plt.plot(points[:,0], points[:,1], 'ro')
plt.plot(points[hull.vertices,0], points[hull.vertices,1], 'r--', lw=2)
plt.plot(newpoints[:,0], newpoints[:,1], 'go')
for p_idx in range(30):
    pt = newpoints[p_idx,:]
    pt[1] = pt[1] + 0.01
    dist = pt_dist[p_idx]
    distLabel = "%.2f" % dist
    plt.annotate(distLabel,xy=pt)

rawDescription: Distance to convexHull

description: Distance to convexHull


code:
with open('your.csv') as f:
    lines = [line.split(';') for line in f.read().splitlines()[1:]]

lines_grouped = [[l for l in lines if l[2]==x] for x in {l[2] for l in lines}]
for group in lines_grouped:
    with open('Id' + group[0][2] + '.csv', 'w+') as f:
        f.write('\n'.join([','.join(line) for line in group]))

rawDescription: Created csv from csv list based on column values Python


code:
import itertools as it

list(it.chain.from_iterable(it.izip(a,b,c)))

rawDescription: python merge 3 lists into 1 list

description: Python merge 3 lists into 1 list


code:
with open('C:/Users/Family3/Downloads/weather.csv', 'a', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(listsof)

rawDescription: Write to CSV on first empty line

description: Write to CSV on first empty line


code:
import inspect
import weakref
class Value(object):
    def __init__(self, val):
        self.val = val
    def __get__(self, instance, owner):
        return self.val

def get_value_from_proxy(obj, inst):
    if isinstance(obj, Value):
        return obj.__get__(inst, inst.__class__)
    else:
        return obj

class ValueList(list):
    def __init__(self, instance, *args, **kwargs):
        list.__init__(self, *args, **kwargs)
        self.instance = weakref.ref(instance)
    def __getitem__(self, idx):
        return get_value_from_proxy(list.__getitem__(self, idx), self.instance() )

class ValueDict(dict):
    def __init__(self, instance, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self.instance = weakref.ref(instance)
    def __getitem__(self, key):
        return get_value_from_proxy(dict.__getitem__(self, key), self.instance() )

class BaseContainer(object):
    def __init__(self):
        for el in inspect.getmembers(self):
            if isinstance(el[1],list):
                setattr(self, el[0], ValueList(self, el[1]))
            elif isinstance(el[1],dict):
                setattr(self, el[0], ValueDict(self, el[1]))

class Container(BaseContainer):
    x = Value(1)
    y = [ Value(2), Value(3) ]
    z = {"test":Value(4)}

c = Container()
assert c.x == 1
assert c.y[0] == 2
assert c.z["test"] == 4

rawDescription: Writing a thin object proxy by implementing the __get__ descriptor


code:
@wraps(func)
def decorated_view(*args, **kwargs):
    if current_app.login_manager._login_disabled:
        return func(*args, **kwargs)
    elif not current_user.is_authenticated():
        return current_app.login_manager.unauthorized()
    return func(*args, **kwargs)

rawDescription: Flask Login not detecting Anonymous Users


code:
from otherapp.admin import OriginalFooAdmin
from otherapp.models import Foo
from yourapp.models import YourExtension
from django.contrib import admin

admin.site.unregister(Foo)

class ExtensionInline(admin.StackedInline):
    model = YourExtension

class NewFooAdmin(OriginalFooAdmin):
    inlines = OriginalFooAdmin.inlines + [ExtensionInline]
admin.site.register(Foo, NewFooAdmin)

rawDescription: Django add field to existing model app

description: Django add field to existing model app


code:
inFile = ('ana john joe', 'eric daniel veronica')
vowels = 'aeiou'
counts = []
for line in inFile:
    count = 0
    words = line.split()
    for word in words:
        count = 0
        for character in word:
            if character in vowels:
                count+=1
        counts.append(str(count))
print(' '.join(counts))

rawDescription: python vowels counter in each word

description: Python vowels counter in each word


code:
i = frame.index.searchsorted(date)
frame.ix[frame.index[i]]

rawDescription: How to get the closest single row after a specific datetime index using Python Pandas

description: Get the closest single row after a specific datetime index using Python Pandas


code:
tickersymbols = ['ticker1', 'ticker2']

i = 0
while (i <  3):
    lcd.clear()
    stockWentDown=False
    for tickerSymbol in tickersymbols:
        allInfo = ystockquote.get_all(tickerSymbol)
        price = float(allInfo["price"])
        change = float(allInfo["change"])
        lcd.write(tickerSymbol+ "= %+3.2f (%+0.2f)" % (price, change))
        if change < 0:
            stockWentDown=True
    if not stockWentDown: #if the stock went up or stayed the same
        #color it green
        backlight.rgb(0,255,0)
    elif stockWentDown: #if the stock went down
        #color it red
        backlight.rgb(255,0,0)

rawDescription: How can I get an if statement to remember a value as it executes?

description: Get an if statement to remember a value as it executes


code:
from scipy.sparse import lil_matrix

result = lil_matrix((N, N))  # In order to save memory, one may add: dtype=bool, or dtype=numpy.int8

with open('matrix.csv') as input_file:
    for line in input_file:
        x, y = map(int, line.split(',', 1))  # The "1" is only here to speed the splitting up
        result[x, y] = 1

rawDescription: From text file to a market matrix format


code:
import random
import sys

while True: # outer game loop

    print('Welcome to the game.')

    secret_number = random.randrange(1, 5)

    guess = 0
    tries = 0

    while guess != secret_number:
        guess = int(input("Guess a number: "))
        tries = tries + 1

        if guess < secret_number:
            print("Too low!")

        elif guess > secret_number:
            print("Too high!")

        else:
            print("You got it!")
            print("Number of tries: ", tries)

    userInput = input("Enter 'R' to restart or 'X' to exit").capitalize()

    if userInput == "X":
        print('Goodbye.')
        sys.exit(-1) # exits the program

rawDescription: Python program that allows user to restart or exit it


code:
c = conn.cursor(buffered=True)
results = c.execute(query, multi=True)
for cur in results:
    print('cursor:', cur)
    if cur.with_rows:
        print('result:', cur.fetchall())
conn.commit()
conn.close()

rawDescription: mysql.connector, multi=True, sql variable assignment not working

description: Mysql.connector, multi=True, sql variable assignment not working


code:
def map_operator(operator, iterable):
    # closure value of operator is now separate for each generator created
    return (operator(item) for item in iterable)

def main():
    vals = reader()
    for op in operators:
        vals = map_operator(op, vals)
    return vals

rawDescription: Python Generator "chain" in a for loop

description: Python Generator "chain" in a for loop


code:
pythonpath = os.env['PYTHONPATH']
file_relative_path = os.path.join('subdir', 'resourcefile') // e.g. subdir/resourcefile
for dir in pythonpath.split(os.pathsep):
    resource_path = os.path.join(dir, file_relative_path)
    if os.path.exists(resource_path):
        return resource_path

rawDescription: How do I use test resources (like a fixed yaml file) with pytest?

description: Use test resources (like a fixed yaml file) with pytest


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(open('htmlfile'))

for elem in soup.find_all('span', class_='finereader'):
    elem.replace_with(elem.string or '')

print(soup.prettify())

rawDescription: Handle HTML tags using python

description: Handle HTML tags using python


code:
def mousePressEvent(self, event):
    item = self.itemAt(event.scenePos())
    if item and item.inDraggingArea(event.scenePos()):
            QGraphicsScene.mousePressEvent(self,event)

rawDescription: Only move QGraphicsItem when mouse in specific region


rawDescription: Python 3.5 + Selenium Scrap. Is there anyway to select <a><a/> tags?


code:
class UsesIngredientForm(forms.ModelForm):
    class Meta:
        model = UsesIngredient

    def has_changed(self, *args, **kwargs):
        self._get_changed_data(*args, **kwargs)
        # If group is in changed_data, but no other fields are filled in, remove group so
        # the form will not be validated or saved
        if 'group' in self._changed_data and len(self._changed_data) == 1:
            contains_data = False
            for name in ['ingredient', 'amount', 'unit']:
                field = self.fields[name]
                prefixed_name = self.add_prefix(name)
                data_value = field.widget.value_from_datadict(self.data, self.files, prefixed_name)
                if data_value:
                    contains_data = True
                    break
            if not contains_data:
                self._changed_data.remove('group')
        return bool(self._changed_data)

rawDescription: django ignore changed field in formset

description: Django ignore changed field in formset


code:
import pandas as pd
import pylab as plt
import numpy as np

#my made up data
index = pd.DatetimeIndex(['1997-12-30', '1997-12-31', '1998-01-01',
'1998-01-02'])
values = np.array([np.nan, np.nan, 1.402, 1.464])

#we are actually using this array as the x values in our graph, then replacing the labels with dates
x = np.arange(len(index))

#create plot
fig, ax = plt.subplots()
ax.set_xlim([0,len(index)])

#create axes with dates along the x axis
ax.set(xticks=x, xticklabels = index)

#plot values with the corresponding dates
ax.plot_date(x, values)

#show plot
plt.show()

rawDescription: matplotlib: How to plot_date without clipping NaN at the beginning and end

description: Matplotlib: How to plot_date without clipping NaN at the beginning and end


rawDescription: How to get sorted results in MongoKit?

description: Get sorted results in MongoKit


code:
C = A.sub(B.squeeze(), axis=0)
print(C)

rawDescription: Pandas dataframe.sub() method on a Multiindex DataFrame?


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

plt.figure(figsize=(10,10)) #
arr = np.random.random((10000,10000)) # my array
plt.imshow(arr)

plt.savefig('fig.png', dpi=1000)

rawDescription: Why does `imshow` display a 2D (non-RGB) array in color, and how can I export such a color image to a .png file?


code:
import pygraphviz as pgv
G=pgv.AGraph()
G.add_node('a')
G.add_edge('b','c')
G

rawDescription: How to create a DOT file in Python?

description: Create a DOT file in Python


rawDescription: How do I display my 'findall' results on it's own separate line?

description: Display my 'findall' results on it's own separate line


code:
def WeekRequestForm(request):
    form = WeekSelection()
    weekstat = None
    if request.method == "POST":
        form = WeekSelection(request.POST)
        if form.is_valid():
            year = int(form.cleaned_data["q_year"])
            week = int(form.cleaned_data["q_week"])
            currstat_b = [year, week]
            weekstat = WeekRange(*currstat_b)
    return render_to_response('form.html', {'weekstat': weekstat, 'form': form},
        context_instance=RequestContext(request))

rawDescription: request from form to raw database on django

description: Request from form to raw database on django


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

A = np.random.rand(50,50)*50
plt.imshow(A, norm=matplotlib.colors.LogNorm())
formatter = LogFormatter(10, labelOnlyBase=False)
cb = plt.colorbar(ticks=[1,5,10,20,50], format=formatter)
plt.show()

rawDescription: Log labels on colorbar matplotlib

description: Log labels on colorbar matplotlib


code:
if any((foo, bar, baz)):
    do_something(foo, bar, baz)
else:
    raise SomeException

rawDescription: Check if a set of variables have non-false values?


code:
df = DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                        'foo', 'bar', 'foo', 'foo'],
                 'B' : ['one', 'one', 'two', 'three',
                        'two', 'two', 'one', 'three'],
                 'C' : randn(8), 'D' : randn(8)})
grouped = df.groupby('A')
grouped
test = grouped.aggregate(np.sum)
test

rawDescription: Convert DataFrameGroupBy object to DataFrame pandas


rawDescription: Sort a list of dictionary provided an order


code:
import wx

class View(wx.Panel):
    def __init__(self, parent):
        super(View, self).__init__(parent)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.Bind(wx.EVT_SIZE, self.on_size)
        self.Bind(wx.EVT_PAINT, self.on_paint)
    def on_size(self, event):
        event.Skip()
        self.Refresh()
    def on_paint(self, event):
        w, h = self.GetClientSize()
        dc = wx.AutoBufferedPaintDC(self)
        dc.Clear()
        dc.DrawLine(0, 0, w, h)
        dc.SetPen(wx.Pen(wx.BLACK, 5))
        dc.DrawCircle(w / 2, h / 2, 100)

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None)
        self.SetTitle('My Title')
        self.SetClientSize((500, 500))
        self.Center()
        self.view = View(self)

def main():
    app = wx.App(False)
    frame = Frame()
    frame.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: Best Canvas for WxPython

description: Best Canvas for WxPython


code:
length = "\x00\x00\x0c"
struct.unpack('>I', '\x00' + length)

rawDescription: How to get frame size in ID3v2.2 MP3 tags?

description: Get frame size in ID3v2.2 MP3 tags


code: hdf[hdf.index.get_level_values(0).isin(['foo', 'qux']) & (hdf.index.get_level_values(1) == 'two')][['A', 'C']]

rawDescription: subsetting hierarchical data in pandas

description: Subsetting hierarchical data in pandas


code:
import numpy as np
a = np.random.rand(3,3)
a
a.max(axis=1)

rawDescription: How to return the highest value from a multi dimensional array?

description: Return the highest value from a multi dimensional array


code:
arr[i] = 0   # zeroes out row i
arr[:,i] = 0 # zeroes out column i

rawDescription: How to 'zero' out rows & columns in an array

description: 'zero' out rows & columns in an array


code:
from urllib import request
filename = '/Users/kyle/Desktop/html_test.html'

u = request.urlopen('http://www.ebay.com')
with open(filename, 'wb') as f: #notice the 'b' here
    f.write(u.read())

import webbrowser
webbrowser.open_new(filename)

rawDescription: can't open file with browser

description: Can't open file with browser


code:
def item_and_index(my_list):
    for i in range(len(my_list)):
        print(my_list[i], i)

rawDescription: Function that prints each element of a list and its index per line


code:
class TornadoRequestHandler(BaseHandler):

     @gen.coroutine
     def get(self):
          result = yield gen.Task(celery_task.apply_aync)
          self.write(result)
          self.finish()

rawDescription: Making Celery returning a Future

description: Making Celery returning a Future


code:
def getFloats(filepath):
  fd = open(filepath) # open the file
  try:
    content = fd.read().split() # read fully
    def flo(value):  # a function that returns a float for the given str or None
      try: return float(value)
      except ValueError: return None # skip invalid values
    # iterate through content and make items float or None,
    # iterate over the result to choose floats only
    return [x for x in [flo(y) for y in content] if x]
  finally:
    fd.close()

rawDescription: the Eval function in Python

description: The Eval function in Python


code:
list=[] #declare a blank list to use later
x=4

while(1):
    list.append(x) #add x to the list
    x += 1 # a shorthand way to add 1 to x
    if x == 8:break

print(list) #after the loop is finished, print the list

rawDescription: how to create a list after a while loop

description: Create a list after a while loop


code:
import cProfile
cProfile.run('foo()', 'fooprof')

rawDescription: Using cProfile or line_profile on a Python script in /cgi-bin/?


rawDescription: how to set secret or private options in argparse

description: Set secret or private options in argparse


code:
di = {}
for i in a:
  if di.get(i['name']):
    di[i['name']].append((i['one'], i['two']))
  else:
    di[i['name']] = []
    di[i['name']].append((i['one'], i['two']))

rawDescription: How to join a few dicts in one?

description: Join a few dicts in one


code: ret += "SomePage" + pythonic_date.strftime("%B %-d, %Y") + "|"

rawDescription: How to count back days in time in Python?

description: Count back days in time in Python


code:
import re
filteredtext = re.sub('\s+<.*?/>', '', xmltext)

rawDescription: Suds generates empty elements; how to remove them?


code:
from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template("index.html")

@app.route('/pic.html')
def pic():
    return render_template("pic.html")

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

rawDescription: How to open html containing framset using flask framework

description: Open html containing framset using flask framework


code:
name_dict = {} # create empty dictionary

with open (file_name, 'r') as fi: # open file

    for line in fi:               # iterate over the lines

        if line.startswith('>'):  # check for name line marker
            current_name = line.lstrip('>') # store name without angle bracket
            name_dict[current_name] = [] # create dictionary entry with empty list

        else:
            name_dict[current_name].append(line) # not a name line, add to current name's list of lines

rawDescription: Reading Lines Between "Name" Lines into a Dictionary Python


rawDescription: python regex [:alpha:]

description: Python regex [:alpha:]


code:
from itertools import product
my_dict = {'A': [1, 2], 'B': [1, 4]}
keys = list(my_dict)
[dict(zip(keys, p)) for p in product(*my_dict.values())]

rawDescription: Get the product of lists inside a dict while retaining the same keys


code:
places = Place.objects.all()
not_restaurants = [p for p in places if not hasattr(p, 'restaurant')]

rawDescription: Django model inheritance - only want instances of parent class in a query


code:
from setuptools import setup

DATA_FILES = []
OPTIONS = {'argv_emulation': True,
           'packages' : ['lxml'],
           'frameworks' : ['/usr/local/libxml2-2.7.2/lib/libxml2.2.7.2.dylib']
          }

setup(app=MyApp.py,
      data_files=DATA_FILES,
      options={'py2app' : OPTIONS},
      setup_requires=['py2app'])

rawDescription: Problem using py2app with the lxml package


code:
from PySide import QtCore, QtGui
# modify the import if needed
# from PyQt5 import QtCore, QtGui
# from PyQt4 import QtCore, QtGui

from ui import Ui_MainWindow

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    """Main Window.
    """
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        #  your code here

rawDescription: python how to amend file after importing

description: Python how to amend file after importing


code:
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
ax = sns.heatmap(flights, annot=True, fmt="d")

for label in ax.get_yticklabels():
    if label.get_text() == "February":
        label.set_size(13)
        label.set_weight("bold")
        label.set_color("red")

rawDescription: Seaborn Heat Map: Customize A Label

description: Seaborn Heat Map: Customize A Label


rawDescription: How to set TTL index for collection in MongoKit?

description: Set TTL index for collection in MongoKit


code:
from types import FunctionType

class C:
    def __init__(self):
        for name,f in C.__dict__.iteritems():
            if type(f) == FunctionType and hasattr(f, 'setup'):
                  self.instance_method()

    def instance_method(self):
      print('Method called')

    def decorator(f):
        setattr(f, 'setup', True)
        return f

    @decorator
    def function(self):
      pass

c = C()
c.function()
c.function()

rawDescription: Calling Python instance methods in function decorators


code:
pics = [None, None, None, None]   #  This will be the list that will hold a reference to each of your PhotoImages.

def randp(*args):
    w = ['wb.gif', 'wc.gif', 'wd.gif', 'we.gif']
    random.shuffle(w)
    am = 1

    for k, i in enumerate(w):    # Enumerate provides an index for the pics list.
        pic = PhotoImage(file=i)
        pics[k] = pic      # Keep a reference to the PhotoImage in the list, so your PhotoImage does not get garbage-collected.
        ttk.Label(mainframe, image=pic).grid(column=am, row=0, sticky=(W, E))
        am+=1

rawDescription: Displaying pics in Labels with a for Statement using tkinter, can it be done?


code:
import numpy as np

def sample_signal(n_samples, corr, mu=0, sigma=1):
    assert 0 < corr < 1, "Auto-correlation must be between 0 and 1"

    # Find out the offset `c` and the std of the white noise `sigma_e`
    # that produce a signal with the desired mean and variance.
    # See https://en.wikipedia.org/wiki/Autoregressive_model#Example:_An_AR.281.29_process
    c = mu * (1 - corr)
    sigma_e = np.sqrt((sigma ** 2) * (1 - corr ** 2))

    # Sample the auto-regressive process.
    signal = [c + np.random.normal(0, sigma_e)]
    for _ in range(1, n_samples):
        signal.append(c + corr * signal[-1] + np.random.normal(0, sigma_e))

    return np.array(signal)

def compute_corr_lag_1(signal):
    return np.corrcoef(signal[:-1], signal[1:])[0][1]

# Examples.
print(compute_corr_lag_1(sample_signal(5000, 0.5)))
print(np.mean(sample_signal(5000, 0.5, mu=2)))
print(np.std(sample_signal(5000, 0.5, sigma=3)))

rawDescription: Python - generate array of specific autocorrelation


code:
l = []
for m in Message.objects.filter(dst=p).order_by('-date_last_modif'):
    for c in m.conversations.all():
        if c not in l:
            l.append(c.pk)
conversations_read = [c for c in Conversation.objects.filter(pk__in=l)]

rawDescription: Django: how to make an "order by" filter based on a foreign key


code:
from eve import Eve

def on_fetched_resource(resource, response):
    del(response['_links'])
    del(response['_meta'])

    # would result in an empty JSON document
    # del(response['_items'])

app = Eve()
app.on_fetched_resource += on_fetched_resource

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

rawDescription: Request `_items` only using python-eve API to a MongoDB


rawDescription: How can I access the value of 'imageCaption' field of a ATNewsItem object?

description: Access the value of 'imageCaption' field of a ATNewsItem object


code: print('Number of Elephants less than %s: %s' % (floatB, len(myList)))

rawDescription: Is there a better way to write str(len(myList))?


code:
import csv
with open('desired-filename-here.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=' ',
                           quotechar='|', quoting=csv.QUOTE_MINIMAL)
    row_info = [productName.get_text(), productDesc.get_text(),
                productPrice.get_text()]
    csvwriter.writerow(row_info)

rawDescription: Write output in csv format in python

description: Write output in csv format in python


code:
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        self.label = QLabel("Test", self)
        self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setStyleSheet("QLabel {background-color: red;}")

        self.button = QPushButton("Test", self)

        self.layout = QGridLayout()
        self.layout.addWidget(self.label, 0, 0)
        self.layout.addWidget(self.button, 0, 1)

        self.setLayout(self.layout)
        self.show()

app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())

rawDescription: PyQt5: Center align a label

description: PyQt5: Center align a label


code:
from tkinter import *
import random
root = Tk()

class Recta:

    def __init__(self, height=60, width=80):
        self.height = height
        self.width = width
        self.create_buttons()
        self.canvas = Canvas(root)
        self.canvas.pack()

    def create_buttons(self):
        self.frame = Frame(root, bg='grey', width=400, height=40)
        self.frame.pack(fill='x')

        self.button1 = Button(self.frame, text='Add Rect', command=self.randomRects)
        self.button1.pack(side='left', padx=10)
        self.button2 = Button(self.frame, text='Remove Rect', command=self.randomRects)
        self.button2.pack(side='left')

    def randomRects(self):
        w = random.randrange(300)
        h = random.randrange(200)
        self.canvas.create_rectangle(0, 0, w, h, fill='green')

tes = Recta()
root.mainloop()

rawDescription: Make buttons work on canvas (tkinter)

description: Make buttons work on canvas (tkinter)


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

data1 = np.random.random_sample((2, 10000))
data2 = np.random.random_sample((2, 100000))
plt.plot(data1[0], data1[1], 'o',markersize=10, markeredgewidth=1)
plt.plot(data1[0], data1[1]+1, 'o',markersize=10, markeredgewidth=0)
plt.plot(data2[0], data2[1]+2, 'o',markersize=1, markeredgewidth=0)

plt.xlim((-0.5,1.5))
plt.ylim((-0.5,3.5))
plt.show()

rawDescription: making the color in the plot continuous(if possible, by identifying and outlining boundaries)

description: Making the color in the plot continuous(if possible, by identifying and outlining boundaries)


code: filter(lambda i: i < limit, a)

rawDescription: Verbose list comprehension in Python

description: Verbose list comprehension in Python


code:
from urllib import urlopen

from bs4 import BeautifulSoup
baseURL = 'http://www.gbgb.org.uk/resultsMeeting.aspx?id=135488'
html = urlopen(baseURL)
bsObj = BeautifulSoup(html, 'lxml')
nameList = bsObj.findAll("div", {"class": "resultsBlock"})
for i in nameList:
    # just the trap info, the rest is similar
    nameList2 = i.findAll("li", {"class": "trap"})
    for j in nameList2:
        print(j.get_text())

rawDescription: Beautiful soup looping through Urls and displaying data


code:
import xml.etree.ElementTree as ET
root = ET.ElementTree(file="nwind_medium.xml")

orders = root.findall("./orders")
quantityTotal = 0
for order in orders:
    orderdetails = order.findall("./orderdetails")
    for detail in orderdetails:
        productName = detail.findall("./products/productname")
        quantityNew = detail.findall("./quantity")
        if productName[0].text == "chang" or productName[0].text == "chai" or productName[0].text == "Tofus":
            _quantity = 3
        else:
            _quantity = float(quantityNew[0].text)
        quantityTotal += _quantity
numberQuantity = len(orders)

rawDescription: python changing the value while doing average

description: Python changing the value while doing average


code: order_by(Page.rank==0, Page.rank)

rawDescription: Sorting zeros last with Flask / SQLAlchemy


rawDescription: Numpy, python: automatically expand dimensions of arrays when broadcasting


code:
import re

m = re.search(r"(NM_\d+)\s+range", name2)
if m:
   print(m.group(1))

rawDescription: Partitioning a string in Python

description: Partitioning a string in Python


code:
j = df.columns.get_level_values(1).isin(['Net', 'Upper', 'Zsore'])
df.loc[:,j]

rawDescription: python pandas - build subset based on column names

description: Python pandas - build subset based on column names


code:
def main():
    from idlelib.Percolator import Percolator
    root = Tk()
    root.wm_protocol("WM_DELETE_WINDOW", root.quit)
    text = Text(background="white")
    text.pack(expand=1, fill="both")
    text.focus_set()
    p = Percolator(text)
    d = ColorDelegator()
    p.insertfilter(d)
    root.mainloop()

rawDescription: How does one use ColorDelegator in from Python IDLE?

description: Use ColorDelegator in from Python IDLE


rawDescription: Pandas Groupby Range of Values

description: Pandas Groupby Range of Values


code:
import GameLogic

...

GameLogic.globalDict['Key'] = value

...

value = GameLogic.globalDict['Key']

rawDescription: How to create global variables?

description: Create global variables


code:
soup = BeautifulSoup(page)
anchors = soup.findAll('a')
for anchor in anchors:
  anchor.replaceWithChildren()

rawDescription: Remove all <a> tags

description: Remove all <a> tags


rawDescription: Matplotlib - change colour based on series/subarray/slice


code:
X=[1,3,4,5]
Y=[3,4,1,3]
L=['A', 'B', 'C', 'D']
f=plt.figure(figsize=(10,16), dpi=100)
gs1 = gridspec.GridSpec(4,1)
gs1.update(left = 0.15, right = .3375 , wspace=0.02)
gs2 = gridspec.GridSpec(4,1)
gs2.update(left = 0.3875, right = .575, wspace=.25)
sp1 = [plt.subplot(gs1[i,0]) for i in range(4)]
sp2 = [plt.subplot(gs2[i,0]) for i in range(4)]
for sp in [sp1, sp2]:
    for ax in sp:
        ax.bar(range(len(L)), X, 0.35, color='r')
        ax.bar(np.arange(len(L))+0.35, Y, 0.35)
        ax.spines['right'].set_visible(False)
        ax.yaxis.set_ticks_position('left')
        ax.spines['top'].set_visible(False)
        ax.xaxis.set_ticks_position('bottom')
        if sp==sp1:
            ax.axis(list(ax.get_xlim())+list(ax.get_ylim())) #set the axis view limit
            ll=ax.plot((0,10), (0,0), '-r') #Let's plot it in red to show it better
            ll[0].set_clip_on(False) #Allow the line to extend beyond the axis view
plt.savefig('temp.png')

rawDescription: matplotlib, add common horizontal lines at the x axis across multiple subplots

description: Matplotlib, add common horizontal lines at the x axis across multiple subplots


code:
s = StringIO.StringIO('Hello, world!')
sys.stdin = s ; r = raw_input('What you say?\n') ; sys.stdin = sys.__stdin__
r

rawDescription: How to use a string as stdin

description: Use a string as stdin


code: cor1, cor2 = [int(x) for x in raw_input("enter x y: ").split()]

rawDescription: input a graph's edges

description: Input a graph's edges


code:
import pickle

dictpairs  = {'bkkooorw' : ['bookwork', 'workbook']}
#store your dict
with open(fileName, 'wb') as handle:
  pickle.dump(dictpairs  , handle)
#load your dict
with open(fileName, 'rb') as handle:
 dictpairs = pickle.load(handle)

rawDescription: Run code once to create a new file, and use the content in that file remotely? Python


code:
Tot=input("Enter Income:")
NetInc=Tot
NetXpense=0
c = 0
while (c==0):
    Xpense=input("Enter your expenses:")
    NetXpense+=int(Xpense)
    if (int(Xpense)==0):
        c=1
NetInc = int(Tot)-NetXpense
print("Expenditure:",NetXpense)
print("Net Income:",NetInc)

rawDescription: Python Loops-Adding

description: Python Loops-Adding


code:
class Person(models.Model):
    name = models.CharField(max_length=45)
    surname = models.CharField(max_length=45)
    objects = PersonManager()

    class Meta:
        abstract = True

rawDescription: Subclassing django model doesn't carry the Manager


code:
import numpy as np
from PIL import Image

def normalize(arr):
    """
    Linear normalization
    http://en.wikipedia.org/wiki/Normalization_%28image_processing%29
    """
    arr = arr.astype('float')
    # Do not touch the alpha channel
    for i in range(3):
        minval = arr[...,i].min()
        maxval = arr[...,i].max()
        if minval != maxval:
            arr[...,i] -= minval
            arr[...,i] *= (255.0/(maxval-minval))
    return arr

def demo_normalize():
    img = Image.open(FILENAME).convert('RGBA')
    arr = np.array(img)
    new_img = Image.fromarray(normalize(arr).astype('uint8'),'RGBA')
    new_img.save('/tmp/normalized.png')

rawDescription: Intensity normalization of image using Python+PIL - Speed issues


code:
while letterCount > 0:
    temp1 = "word"
    letter = input("Guess a letter in the word or attempt to guess the whole word: ")
    if (len(letter) > 1):
        print ("this is the test word: word, this is letter:" + letter)
        if letter == "word":
            print ("You win!!!")
            letterCount = 0
    else:
        x = temp1.find(letter)
        while x != -1:
            x = temp1.find(letter)
            temp1 = temp1[:(x + 1)].replace(letter, '0') + temp1[(x + 1):]
            guess = guess[:(x + 1)].replace('-', letter) + guess[(x + 1):]
        print (("Your guess is now: " + guess))
    letterCount = letterCount - 1
    x = 0

rawDescription: What's wrong with this string equality comparison? (Python)


code:
def my_roundup(x):
  return math.ceil(x*100)/100.

roundUp = my_roundup

rawDescription: Extracting text using regex in Python

description: Extracting text using regex in Python


code:
args = {'days':1}
datetime.timedelta(**args)

rawDescription: Replace function arguments name by local variables in Python


rawDescription: Python Requests Recreate Post Request with Cookies


code:
for dirpath, dirnames, filenames in os.walk(my_directory):
    # Remove regular files, ignore directories
    for filename in filenames:
        os.unlink(os.path.join(dirpath, filename))

rawDescription: shutil.rmtree to remove files only?

description: Shutil.rmtree to remove files only


code:
while True:
    doContinue = input('Would you like to start Y/N ?')
    if doContinue.lower() == 'y' or doContinue.lower() == 'yes':
        break

rawDescription: Looping an if statement?

description: Looping an if statement


code:
for coll in covariance1.collections:
    coll.remove()

rawDescription: Matplotlib: how to remove just one contour element from axis with other plotted elements?


code:
STOP = None

def _execute(self):
    while 1:
        nextCommand = self._commandQueue.get()[1]
        if nextCommand is STOP:
           break
        self._commandExecutor.execute(nextCommand)
        self._commandQueue.task_done()

def wait_for_stop_signal(self):
    self._closeEvent.wait()
    self._commandQueue.put((-1, STOP))

rawDescription: Python waiting for a queue and an event

description: Python waiting for a queue and an event


code:
from collections import defaultdict
import re

# Nested defaultdict for data structure
def make_map():
    def make_map_dict():
        return defaultdict(dict)
    return defaultdict(make_map_dict)

# Read in the data
with open('/path/to/your/txt_file.txt', 'r') as f:
    txt_data = [map(str.strip, x.split('\n')) for x in map(str.strip, f.read().split('\n\n')) if x]

with open('/path/to/your/csv_file.csv', 'r') as f:
    header = f.readline()
    csv_data = [map(str.strip, x.split(',')) for x in map(str.strip, f.read().split('\n')) if x]

# Generate a mapping dictionaries
txt_map = defaultdict(make_map)
csv_map = defaultdict(make_map)

# Regex matches
name_re = re.compile(r'^(\d+) +(\w+(?: \w+)*) +(\d+/\d+)$')
data_re = re.compile(r'^(Data(?:\d+)?) +(\$\d+(?:\.\d{2})?)$')

# Make txt mapping
for datapoint in txt_data:
    names = [name_re.match(x).group(2) for x in datapoint[2:] if name_re.match(x)]
    data = {data_re.match(x).group(1): data_re.match(x).group(2) for x in datapoint[2:] if data_re.match(x)}
    for name in names:
        txt_map[datapoint[1]][datapoint[0]][name] = data

# Make csv mapping
for datapoint in csv_data:
    csv_map[datapoint[0]][datapoint[1]][datapoint[8]] = [datapoint[9]]

# Merge maps
final_map = defaultdict(make_map)
for x in txt_map:
    for y in txt_map[x]:
        for z in txt_map[x][y]:
            if csv_map[x][y][z] is not None:
                final_map[x][y][z] = csv_map[x][y][z] + [txt_map[x][y][z]]

# You now have final_map to do with what you will

rawDescription: Three way cross matching csv and pulling/printing data in python


code:
from collections import defaultdict
from itertools import chain
c1 = [
  ('orange', 10),
  ('apple', 20)
]
c2 = [
  ('orange', 15),
  ('apple', 30)
]
merged = defaultdict(list)
for item in chain(c1, c2):
    merged[item[0]].append(item[1])

merged

rawDescription: How to merge two or more Counters into a single dictionary?

description: Merge two or more Counters into a single dictionary


code:
t2 = Thread(target=printLo)
t = Thread(target=printYo)

rawDescription: My understanding of threading

description: My understanding of threading


code:
get_input = web.input(_method='get')
post_input = web.input(_method='post')

rawDescription: web.py: how to get POST parameter and GET parameter?

description: Web.py: how to get POST parameter and GET parameter


code: f = lambda x:'' if x is None else x

rawDescription: Python lambda returning None instead of empty string


code:
class GeocodeResult(object):
    """class to handle Reverse Geocode Result"""

    ...

    Result = namedtuple(
        'Result',
        'address score location attributes',
    )

    @property
    def results(self):
        results = []
        for result in self.address + self.candidates + self.locations:
            results.append(self.Result(...))  # pass in the four relevant attributes
        return result

    ...

rawDescription: Dynamic class creation with type and __slots__?


code:
class SendDocuments(webapp2.RequestHandler):
    def post(self):
        document_key = self.request.get("document_key")
        document_key = Key(str(document_key))
        the_document = DocumentsModel.all().filter("__key__ =", document_key).get()
        file_data = blobstore.BlobInfo.get(str(the_document.blobstore_key))
        payload = {}
        payload['user_id'] = '1234123412341234'
        payload['test_file'] = MultipartParam('the_file', filename="something",
                                      filetype=file_data.content_type,
                                      fileobj=file_data.open())

rawDescription: How can I retrieve a file object from the blobstore within a handler?

description: Retrieve a file object from the blobstore within a handler


code:
import os
import MySQLdb as mdb
import csv

def read_file():
    file_path = "/home/local/user/Main/Module-1.0.4/file_processing/part-00000.txt"
    with open('part-00000','r') as infile:
        file_open= csv.reader(infile, delimiter='\t')
        cache = []
        for line in file_open:
            cache.append(line)
            if len(cache) > 500:
                yield cache
                cache = []
        yield cache

conn = mdb.connect(user='root', passwd='redhat', db='Xml_Data', host='localhost', charset="utf8")
cursor = conn.cursor()
query = "insert into PerformaceReport (campaignID, keywordID, keyword, avgPosition) VALUES (%s,%s,%s,%s)"
for rows in read_file():
    try:
        cursor.executemany(query, rows)
    except mdb.Error:
        conn.rollback()
    else:
        conn.commit()

rawDescription: How to process a 1GB text file with python

description: Process a 1GB text file with python


code:
import pygame, sys

screen = pygame.display.set_mode((1024, 640))

running = True

#let's create a surface to hold our ellipse:
surface = pygame.Surface((320, 240))

red = (180, 50, 50)
size = (0, 0, 300, 200)

#drawing an ellipse onto the
ellipse = pygame.draw.ellipse(surface, red, size)

#new surface variable for clarity (could use our existing though)
#we use the pygame.transform module to rotate the original surface by 45°
surface2 = pygame.transform.rotate(surface, 45)

while running:
    screen.fill((255, 250, 200))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    screen.blit(surface2, (100, 100))
    pygame.display.update()

rawDescription: drawing a diagonal ellipse with pygame

description: Drawing a diagonal ellipse with pygame


code:
with open ("my.ini", "r") as myfile:
    my_config = myfile.read()

lines = my_config.splitlines(True)
replacements = {"path_jamjs": {"changeUsername": "Te"},
                "path_php": {"changeUsername": "TeS"}}

for path, reps in replacements.items():
    for i, line in enumerate(lines):
        if line.startswith(path + ':'):
            for key, value in reps.items():
                line = line.replace('[' + key + ']', value)
            lines[i] = line

result = ''.join(lines)

rawDescription: how to apply a specific regex to a specific line

description: Apply a specific regex to a specific line


code:
import collections
ct = collections.Counter("1234567890123475431234")
ct['3'] == 4
ct.most_common() # gives a list of tuples, ordered by times of occurrence

rawDescription: How to insert value to specific cell in array in Python?

description: Insert value to specific cell in array in Python


code:
class A(object):
    parent = None

class B(object):
    def __init__(self, child):
        self.child = child
        child.parent = self

rawDescription: Python: accessing attributes and methods of one class in another


code:
class Room(db.Model):
    users = db.StringListProperty()

def join(userId):
    def _transaction():
        room = Room.get_by_key_name('room_1')
        if room is None:
            room = Room(key_name = 'room_1', users = [])
        room.users.append(userId)
        room.put()
        return room.users
    return db.run_in_transaction(_transaction)

rawDescription: Read -> change -> save. Thread safe

description: Read -> change -> save. Thread safe


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

x = [1,2,3,4,5]
y = [3,4,2,3,4]
c = [1,2,4,0.5,5]

cmap = mpl.colors.ListedColormap(['blue','red','magenta', 'green', 'gray'])
c_norm = mpl.colors.BoundaryNorm(boundaries=[0,1,2,3,4,5], ncolors=5)
plt.scatter(x, y, c=c, s=200, cmap=cmap, norm=c_norm)
plt.colorbar()
plt.show()

rawDescription: How to change scatter plot color according to certain rule

description: Change scatter plot color according to certain rule


code:
v.bind()
GL.glEnableClientState(GL.GL_VERTEX_ARRAY)
GL.glVertexPointerf(v)
for v in self.vbos:
    GL.glDrawArrays(GL.GL_LINE_STRIP, vbo_offset_goes_here, v.data.shape[0])
GL.glDisableClientState(GL.GL_VERTEX_ARRAY)
v.unbind()

rawDescription: VBO Equivalent of Display List with multiple primitives?


code: FullName = LastName + (", " + FirstName if FirstName else "")

rawDescription: Join string and None/string using optional delimiter


code:
def TextBoxUpdate(event):
    ...
FriendListComboBox.bind("<<ComboboxSelected>>", TextBoxUpdate)

rawDescription: How to make a ttk.Combobox callback

description: Make a ttk.Combobox callback


code:
def maxmin():
    minimum = None
    maximum = None
    num = None

    while True:
        num = input('Please enter a number, or -10 to stop: ')
        if num == -10:
            break

        if (minimum) is None or (num < minimum):
            minimum = num
        if (maximum) is None or (num > maximum):
            maximum = num
    print ("Maximum: ", maximum)
    print ("Minimum: ", minimum)

maxmin()

rawDescription: Maximum, minimum and total numbers

description: Maximum, minimum and total numbers


code:
trie = {"a": {"b": {"e": {},
                    "f": {},
                    "g": {"l": {},
                          "m": {},
                          "n": {}}},
              "c": {"h": {},
                    "i": {}},
              "d": {"j": {},
                    "k": {}}}}

target = 'achqr'
sub_trie = trie
longest_sequence = []
for c in target:
    sub_trie = sub_trie.get(c)
    if sub_trie is None:  # the letter being looked for doesn't exist after this sequence
        break
    longest_sequence.append(c)  # track the sequence since the trie is not reverse linked
print(longest_sequence)

rawDescription: How to search for a word in a tree represented as a dictionary of dictionaries in python?

description: Search for a word in a tree represented as a dictionary of dictionaries in python


code:
class values(FromClause):
    named_with_column = True

    def __init__(self, columns, *args, **kw):
        self._column_args = columns
        self.list = args
        self.alias_name = self.name = kw.pop('alias_name', None)

    def _populate_column_collection(self):
        # self._columns.update((col.name, col) for col in self._column_args)
        for c in self._column_args:
            c._make_proxy(self, c.name)

@compiles(values)
def compile_values(clause, compiler, asfrom=False, **kw):
    def decide(value, column):
        add_type_hint = False
        if isinstance(value, array) and not value.clauses:  # for empty array literals
            add_type_hint = True

        if isinstance(value, ClauseElement):
            intermediate = compiler.process(value)
            if add_type_hint:
                intermediate += '::' + str(column.type)
            return intermediate

        elif value is None:
            return compiler.render_literal_value(
                value,
                NULLTYPE
            ) + '::' + str(column.type)
        else:
            return compiler.process(
                bindparam(
                    None,
                    value=compiler.render_literal_value(
                        value,
                        column.type
                    ).strip("'")
                )
            ) + '::' + str(column.type)

    columns = clause.columns
    v = "VALUES %s" % ", ".join(
        "(%s)" % ", ".join(
            decide(elem, column)
            for elem, column in zip(tup, columns))
        for tup in clause.list
    )
    if asfrom:
        if clause.alias_name:
            v = "(%s) AS %s (%s)" % (v, clause.alias_name, (", ".join(c.name for c in clause.columns)))
        else:
            v = "(%s)" % v
    return v

rawDescription: How to make use of bindparam() in a custom Compiled expression?

description: Make use of bindparam() in a custom Compiled expression


code:
from os.path import join, dirname
from tkFileDialog import askopenfilename

infilename= askopenfilename()
outfilename = join(dirname(infilename), 'timeouts.txt')
with open(infilename, 'r') as f_in, open(outfilename, 'a') as f_out:
    fout.writelines(line for line in f_in if "INF: Camera timeout" in line)

rawDescription: Saving f.write file to same directory as the askopenfilename was found


code:
class saisirsoum(osv.osv):

    _name='saisir.soum'

    _sql_constraints = [
    ('NumOffre', 'unique(NumOffre)', 'NumOffre already exists'),
    ]

    _columns = {
    'NumOffre' : fields.char('N° Offre'), # to be defined as key !!
    'organisme_s' : fields.char('Organisme'),
    'des_offre' : fields.char('Designation'),
    'order_line' :fields.one2many('saisir.soumission.ligne','order_id','soumission_id'),
    'observation_d' : fields.text('Observation'),
    }

    def create(self, cr, uid, vals, context=None): # when the record is about to created
        NumOffre = vals.get('NumOffre') #get NumOffre from the form
        if NumOffre:
            pass # you can do something with it e.g searching

        return super(saisirsoum, self).create(cr, uid, vals, context=context) # finally call the create method from the super class and create the record after you're done

rawDescription: Use a field as key and it must be unique for each record to use it to browse the table (Openerp)


rawDescription: How to convert variable into integer in python? like in php (int)

description: Convert variable into integer in python? like in php (int)


code:
with open('100temp.txt') as in_file, open('new_100temp.txt', 'w') as out_file:
    for line1, line2, line3, line4 in grouper(in_file, 4):
         # modify 4 lines
         out_file.writelines([line1, line2, line3, line4])

rawDescription: processing speed - editing large 2GB text file python

description: Processing speed - editing large 2GB text file python


code:
from itertools import groupby
from operator import itemgetter

[f(list(g)) for k, g in groupby(data, key=itemgetter(0))]

rawDescription: Python accessing slices of a list in order


code:
def holdable(widget):
    class Filter(QObject):
        clicked = pyqtSignal(QWidget)
        def eventFilter(self, obj, event):
            if obj == widget:
                if event.type() == QEvent.MouseButtonPress:
                    if obj.rect().contains(event.pos()):
                        obj.heldDown = datetime.datetime.now()
                        #return True
                elif event.type() == QEvent.MouseButtonRelease:
                    if obj.rect().contains(event.pos()):
                        if(obj.heldDown):
                            diff = datetime.datetime.now() - obj.heldDown
                            obj.heldDown = None
                            if(diff.total_seconds() > 1):
                                self.clicked.emit(obj)
                                return True
            return False
    filter = Filter(widget)
    widget.installEventFilter(filter)
    return filter.clicked

rawDescription: QT Event filter for holding mouse button down


code:
import csv
with open('Data/ShowroomData.csv', 'rt') as Data:
    SR = csv.DictReader(Data, delimiter=' ', quotechar='|')
    for row in SR:
        # if you were to print just `row`, you would get a dictionary
        # like {'SiteName': 'foo', 'BGPAS': 'bar'}
        print (row['SiteName'], row['BGPAS'])

rawDescription: Reading csv and importing into datatable (Python)


code:
import mymodule

@mymodule.myClass
class myOtherClass:
    pass

rawDescription: Using Python decorators when the class def is in another file?


rawDescription: why isnt the mqtt client subscriber displaying topic?

description: Why isnt the mqtt client subscriber displaying topic


rawDescription: How can i Convert 110_181 to 11.0.181

description: Convert 110_181 to 11.0.181


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

class main_frame(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.initUI()

    def initUI(self):

        # A push buttnon
        btn_get = QPushButton("Get Time", self)
        btn_get.move(100, 250)

        #
        time = QTime()
        # Find what is the local/system time
        curent_t = time.currentTime()
        # Convert it to a str
        # The output shoud be HH:MM:SS  , eg 10:45:28
        curent_t_str = curent_t.toString()

        # Create a timeEdit widget
        time_widget = QTimeEdit(time, self)
        time_widget.setTime(curent_t)

        def get_time():
            print(curent_t_str)

        btn_get.clicked.connect(get_time)

        ### At the end of the day you got curent_t_str variable
        ### which you can use it in your code down the road
        ### so I belive that`s helpful for your needs
        ### implement this may vary, depending your needs ...

        # Set a costom size for the mainWindow
        self.setFixedSize(300, 300)

def main():

    app = QApplication(sys.argv)
    myapp = main_frame()
    myapp.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: How to get a value of QTimeEdit,QCheckBox and QDateTimeEdit into a variable. (Python)

description: Get a value of QTimeEdit,QCheckBox and QDateTimeEdit into a variable. (Python)


code:
import csv
import re
import sys

csvdictreader = csv.DictReader(sys.stdin, delimiter=',')
csvdictwriter = csv.DictWriter(sys.stdout, fieldnames=csvdictreader.fieldnames, delimiter=',')
csvdictwriter.writeheader()
targets = [name for name in csvdictreader.fieldnames if name.startswith('HLA-')]

for rowfields in csvdictreader:
    keep = True
    for field in targets:
        value = rowfields[field]
        if re.match(r'^DQB1\*\d\d$', value): # gene resolution too low?
            keep = False
            break # quit processing target fields
        else: # reduce gene resolution if too high
              # by only keeping first two alles if three are present
            rowfields[field] = re.sub(r'^DQB1\*(\d\d):(\d\d):(\d\d)$',
                                      r'DQB1*\1:\2', value)
    if keep:
        csvdictwriter.writerow(rowfields)

rawDescription: Filtering a CSV file in python

description: Filtering a CSV file in python


code:
from collections import Counter, defaultdict

def suffix_counts(wordlist):
    output = defaultdict(int)
    counts =  Counter(
        word[-suffix_size:]
        for word in wordlist
        if len(word) >= suffix_size
    )
    output.update(counts)
    return output

afrikaans_suffixes = suffix_counts(afrikaans_list)
english_suffixes = suffix_counts(english_list)
common_english_suffixes = [
    suffix
    for suffix, count in english_suffixes.iteritems()
    if (float(count) / (count + afrikaans_suffixes[suffix])) > thresh
]  # All suffixes which are found in English thresh percent of the time

rawDescription: Python - Find suffixes that commonly occur in one list, but not in another


code:
a = QtCore.QByteArray(data)
b = QtCore.QBuffer(a)
b.open(QtCore.QIODevice.ReadOnly)
m = QtGui.QMovie(b, 'GIF')

rawDescription: load gif into QMovie object from data (no file)

description: Load gif into QMovie object from data (no file)


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

import web
import threading

from time import sleep

class MyWebserver(threading.Thread):
    def run(self):
        urls = ('/', 'MyWebserver')
        app = web.application(urls, globals())
        app.run()

if __name__ == '__main__':
    t = MyWebserver()
    t.daemon = True
    t.start()
    while True:
        sleep(100)

rawDescription: Can't exit Asynchronous Web.py Web Server


code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(patches.Wedge(center=(0,0), r=0.9, theta1=90, theta2=120, facecolor="red", label="Test"))
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.legend()  # <--- here
fig1.savefig('wedge1.png', dpi=90, bbox_inches='tight')
plt.show()

rawDescription: Wedges with label parameter, but none label in result


code:
from collections import OrderedDict
import itertools
o = OrderedDict([('xmllist', 123), ('A', 124), ('B', 125), ('C', 126), ('D', 127)])
OrderedDict((key1, o[key2]) for key1, key2 in zip(itertools.islice(o, 1, None), o))

rawDescription: Interchange values and keys in OrderedDict Python


code:
@app.route('/api/orders', methods=['GET'])
def getAllOrders():
    session = Session()
    allOrders = session.query(Order).all()
    return json.dumps(allOrders, cls=new_alchemy_encoder(False, ['orderItems', 'product']), check_circular=False, ensure_ascii=False) #ensure_ascii=False -- for rigth out cyrlic;

rawDescription: Sqlalchemy returns different results of the SELECT command (query.all)


code:
from struct import pack
from math import sin, pi
import time

def au_file(name, freq, freq1, dur, vol):
    fout = open(name, 'wb')
    # header needs size, encoding=2, sampling_rate=8000, channel=1
    fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1))
    factor = 2 * pi * freq/8000
    factor1 = 2 * pi * freq1/8000
    # write data
    for seg in range(8 * dur):
        # sine wave calculations
        sin_seg = sin(seg * factor) + sin(seg * factor1)
        fout.write(pack('b', vol * 64 * sin_seg))
    fout.close()

t = time.strftime("%S", time.localtime())
ti = time.strftime("%M", time.localtime())
tis = float(t)
tis = tis * 100
tim = float(ti)
tim = tim * 100

if __name__ == '__main__':
    au_file(name='timeSound2.au', freq=tim, freq1=tis, dur=1000, vol=1.0)

    import os
    os.startfile('timeSound2.au')

rawDescription: Using python to play two sine tones at once


code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set_style("white") #for aesthetic purpose only

# fake data
df = pd.DataFrame({'A': np.random.choice(['foo', 'bar'], 100),
                   'B': np.random.choice(['one', 'two', 'three'], 100),
                   'C': np.random.choice(['I1', 'I2', 'I3', 'I4'], 100),
                   'D': np.random.randint(-10,11,100),
                   'E': np.random.randn(100)})

p = pd.pivot_table(df, index=['A','B'], columns='C', values='D')
e = pd.pivot_table(df, index=['A','B'], columns='C', values='E')

ax = p.plot(kind='barh', xerr=e, width=0.85)

for r in ax.patches:
    if r.get_x() < 0: # it it's a negative bar
        ax.text(0.25, # set label on the opposite side
                r.get_y() + r.get_height()/5., # y
                "{:" ">7.1f}%".format(r.get_x()*100), # text
                bbox={"facecolor":"red",
                      "alpha":0.5,
                      "pad":1},
                fontsize=10, family="monospace", zorder=10)
    else:
        ax.text(-1.5, # set label on the opposite side
                r.get_y() + r.get_height()/5., # y
                "{:" ">6.1f}%".format(r.get_width()*100),
                bbox={"facecolor":"green",
                      "alpha":0.5,
                      "pad":1},
                fontsize=10, family="monospace", zorder=10)
plt.tight_layout()

rawDescription: Pandas Bar plot, how to annotate grouped horizontal bar charts


code:
import csv

with open('input.csv') as fin, open('output.csv', 'wb') as fout:
    csvin = csv.reader(fin)
    csvout = csv.writer(fout)
    for row in csvin:
        for colno, col in enumerate(row):
            if col.strip() == '.':
                row[colno] = ''
        csvout.writerow(row)

rawDescription: Python: How do I delete periods occurring alone in a CSV file?


code:
import ast
col = "[u'$929.95']"
col2 = ast.literal_eval(col)
type(col)
type(col2)
col2[0]
str(col2[0])

rawDescription: Python: unable to convert unicode to string


code:
import inspect

def isdebugging():
  for frame in inspect.stack():
    if frame[1].endswith("pydevd.py"):
      return True
  return False

rawDescription: How to detect that Python code is being executed through the debugger?

description: Detect that Python code is being executed through the debugger


code:
pattern = [[j*i for j in range(1,i+1)] for i in range(1,8)]
print ("\n".join(" ".join(map(str, line)) for line in pattern))

rawDescription: Nested list comprehension, python, pattern printing


code:
class NormalDistribution(SingleContinuousDistribution):
    _argnames = ('mean', 'std')

    @staticmethod
    def check(mean, std):
        _value_check(std > 0, "Standard deviation must be positive")

    def pdf(self, x):
        return exp(-(x - self.mean)**2 / (2*self.std**2)) / (sqrt(2*pi)*self.std)

    def sample(self):
        return random.normalvariate(self.mean, self.std)

def Normal(name, mean, std):
    return rv(name, NormalDistribution, (mean, std))

rawDescription: How to create a Rician random variable?

description: Create a Rician random variable


code:
run_instances()
start_instances()
stop_instances()
terminate_instances()

rawDescription: boto3 changing AWS ec2 instance state

description: Boto3 changing AWS ec2 instance state


code:
_list1_ = sorted(_list1_)
_list2_ = sorted(_list2_)

rawDescription: Sort an integer list in Python

description: Sort an integer list in Python


code:
def makeA(d, default=0):
    """Converts a dictionary to a list. Pads with a default element

    Examples:

    >>> makeA({0: 1, 2: 1, 4: 2, 6: 1, 9: 1})
    [1, 0, 1, 0, 2, 0, 1, 0, 0, 1]

    >>> makeA({3: 'kos'},'')
    ['', '', '', 'kos']

    """
    maxElem = max(d)
    return [d.get(x, default) for x in range(maxElem+1)]

rawDescription: Dictionary to Sparse Vector Python

description: Dictionary to Sparse Vector Python


rawDescription: Mayavi, python axes INDICATOR

description: Mayavi, python axes INDICATOR


code:
import bs4

text = """

             Link Text
             Link2 Text

"""

soup = bs4.BeautifulSoup(text)

listitems = soup.select("table > tbody > tr > td > table > tbody > tr > td > div > ol > li")
tags = [tag for tag in listitems[0] if isinstance(tag,bs4.element.Tag)]
for tag in tags:
    print(tag)

# OUTPUT
# Link Text
# Link2 Text

rawDescription: How can I print these html tags as text with lxml?

description: Print these html tags as text with lxml


code:
from scipy.stats import uniform
import numpy as np

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

pdf = uniform.pdf(x) # Create a uniform pdf over the range [0,1].

print(pdf)
# [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]

rawDescription: Call scipy.stats probability distributions like normal python functions


code:
class WNode(object):

    def __init__(self,w):
        self._w=w
        self._content=[]

    def find(self, x):
        if self._w == x:
            return self
        else:
            y = None
            for i in self._content:
                y = i.find(x)
                if y:
                    break
            return y
        return None

if __name__ == '__main__':
    r = WNode(1)
    r._content = [WNode(2), WNode(3), WNode(4)]
    for i in xrange(1, 6):
        print('find({}) = {}'.format(i, r.find(i)))

rawDescription: find and return a node from a tree in Python

description: Find and return a node from a tree in Python


code:
from google.appengine.ext import testbed
from google.appengine.api.blobstore import file_blob_storage

testbed.Testbed()
testbed._blob_storage = file_blob_storage.FileBlobStorage('/tmp/', 'testing')
testbed.init_blobstore_stub()
testbed.init_files_stub()

rawDescription: Unit testing GAE Blobstore (with nose)

description: Unit testing GAE Blobstore (with nose)


code:
text = '1211211121'
text.split('2')
max(text.split('2'), key=len)

rawDescription: Python Finding Longest String of Digits Without a Particular Number


code:
nstorms_good = []
for i in range(len(lowerBound)):
  if min37[i] >= lowerBound[i] and min37[i] < upperBound[i]:
    ...
  else:
    nstorms_good.append( i )

# process
for nstorm in nstorms_good:
    ...

rawDescription: Defining variables and arrays using the else statement - Python


rawDescription: Split list in special chunks

description: Split list in special chunks


code:
import visvis as vv
vv.use('wx')

import numpy as np
from matplotlib.image import imread
from matplotlib.cbook import get_sample_data

imgdata = imread(get_sample_data('lena.png'))

nr, nc = imgdata.shape[:2]
x,y = np.mgrid[:nr, :nc]
z = np.ones((nr, nc))

for ii in xrange(5):
    vv.functions.surf(x, y, z*ii*100, imgdata, aa=3)

rawDescription: Displaying true-colour 2D RGB textures in a 3D plot?


code:
with contextlib.ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

rawDescription: Open a list of files using with/as context manager


code:
import simplejson as json
myfruits = {'fruit':4, 'color':11}
json.dumps(myfruits)

rawDescription: How do I turn a dictionary into a JSON object using simplejson, in Python?

description: Turn a dictionary into a JSON object using simplejson, in Python


code:
import numpy as np
# ....
a = [[1,2,3],[4,5,6],[7,8,9]]
a = np.array(a).astype(np.float32)
padding = 2
noDataValue = -999.0
pixels = np.pad(a, (padding,padding), mode='constant', constant_values=(noDataValue))

rawDescription: padding numpy array/matrix with string

description: Padding numpy array/matrix with string


rawDescription: Numpy return array of index

description: Numpy return array of index


code:
from datetime import datetime
datetime.strptime('24/Aug/2014:17:57:26 +0200', '%d/%b/%Y:%H:%M:%S %z')

rawDescription: Python timezone '%z' directive for datetime.strptime() not available


code:
def parse(user_input):
    words = user_input.split()
    command = words[0]        # first word is the command
    parameters = words[1:]    # the rest are parameters for the command
    if command == 'spawn':
        spawn(*parameters)
    elif command == 'foo':
        foo(*parameters)
    # etc.
    else:
        print('Command not recognised')

def spawn(type_, number):
    print('spawning', type_, number)

parse('spawn mob 000001')

rawDescription: How to make a in game command console with pygame

description: Make a in game command console with pygame


code:
def allOnes2d(L):
    return all(allOnes(a) for a in L)

rawDescription: How do I check if all items in a 2D list are all the same?

description: Check if all items in a 2D list are all the same


code:
def search_package_in_avd(device):
    command = device.shell("pm list packages -3")
    splitedline=re.split(':|\r|\n',command)
    if not splitedline:
        return ""
    else:
        return splitedline

rawDescription: Python, MonkeyRunner. How to find a package name inside all list packages?


code:
import re

s = "bad bad keyword1 GOOD DATA " \
    "keyword2 bad bad bad bad " \
    "keyword1 MORE GOOD DATA " \
    "keyword2 bad bad"

for i in re.findall('keyword1(.*?)keyword2', s, re.DOTALL):
    print(i)

rawDescription: Python re.findall from file

description: Python re.findall from file


code:
averages = {}
counts = {}
for name, value in zip(names, result_values):
    if name in averages:
        averages[name] += value
        counts[name] += 1
    else:
        averages[name] = value
        counts[name] = 1
for name in averages:
    averages[name] = averages[name]/float(counts[name])

rawDescription: Average the duplicated values from two paired lists in Python


code:
class   Application(Frame):
    def __init__(self,  master=None):
        Frame.__init__(self, master)
        self.grid(sticky=N+S+E+W)
        self.mainframe()

    def mainframe(self):
        self.data = Listbox(self, bg='red')
        self.scrollbar = Scrollbar(self.data, orient=VERTICAL)
        self.data.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.data.yview)

        for i in range(1000):
            self.data.insert(END, str(i))

    self.run = Button(self, text="run")
    self.stop = Button(self, text="stop")

    self.data.grid(row=0, column=0, rowspan=4,
                   columnspan=2, sticky=N+E+S+W)
    self.data.columnconfigure(0, weight=1)

    self.run.grid(row=4,column=0,sticky=EW)
    self.stop.grid(row=4,column=1,sticky=EW)

    self.scrollbar.grid(column=2, sticky=N+S)

a = Application()
a.mainframe()
a.mainloop()

rawDescription: scrollable listbox within a grid using tkinter

description: Scrollable listbox within a grid using tkinter


code:
import numpy as np
bins_x, bins_y = 1., 1.
x = np.array([1,1,2,2,3,3,3])
y = np.array([1,1,2,2,3,3,3])
w = np.array([1,2,3,4,5,6,7], 'float')

# You can get a bin number for each point like this
x = (x // bins_x).astype('int')
y = (y // bins_y).astype('int')
shape = [x.max()+1, y.max()+1]
bin = np.ravel_multi_index([x, y], shape)

# You could get the mean by doing something like:
mean = np.bincount(bin, w) / np.bincount(bin)

# Median is a bit harder
order = bin.argsort()
bin = bin[order]
w = w[order]
edges = (bin[1:] != bin[:-1]).nonzero()[0] + 1
med_index = (np.r_[0, edges] + np.r_[edges, len(w)]) // 2
median = w[med_index]

# But that's not quite right, so maybe
median2 = [np.median(i) for i in np.split(w, edges)]

rawDescription: Quantile/Median/2D binning in Python

description: Quantile/Median/2D binning in Python


rawDescription: RegEx for string of groups delimited by " and ,


code:
import re
somestring='in this/ string / i have many. interesting.occurrences of {different chars} that need     to .be removed  '
rx = re.compile('\W+')
res = rx.sub(' ', somestring).strip()
res

rawDescription: python: cleaning up a string

description: Python: cleaning up a string


code:
dispatch = {
    "a": MyClassA,
    "b": MyClassB,
}

instance = dispatch[which_one]() # Notice the second pair of parens here!

rawDescription: create objects on runtime in python

description: Create objects on runtime in python


code:
import lxml.etree as le
root = le.fromstring('''<text>test

All you need to know about British birds.

</text>''')
for elem in root.xpath("//text"):
    elem.text = '1111'
    del elem[:]  # <----------
le.tostring(root)

rawDescription: lxml get full ext of element

description: Lxml get full ext of element


code:
sheet.row(4).height_mismatch = True
sheet.row(4).height = 256*20

rawDescription: Python XLWT can not specify row height

description: Python XLWT can not specify row height


code: re.sub(r"Item", "success", "ITEM",  flags=re.IGNORECASE)

rawDescription: Case-insensitive replacement in Python using regex not working


code:
from django import forms
from django.forms.widgets import Widget
from django.utils.safestring import mark_safe

class Html5Email(Widget):

    def render(self, name, value, attrs=None):
        return mark_safe(u'<input name="custom-email" type="email" />')

class YourForm(forms.Form):
    html5_email = forms.CharField(widget=Html5Email())

rawDescription: Add property to one of the form fields in django


rawDescription: Optimizing writing equations for odeint

description: Optimizing writing equations for odeint


code:
NoSQLStore = {}

class NoSQL(object):
    """ fake """
    def query(self, key):
        return '%s\n' % NoSQLStore.get(key, 'no such key')
    def put(self, key, value):
        NoSQLStore[key] = value

def with_database(fn):
    """ Decorator for functions, that need database access.
        NoSQL object will be stored under ``g.db``.
    """
    def connect_and_close(*args, **kwargs):
        g.db = NoSQL()
        __result = fn(*args, **kwargs)
        # a real database should be somehow ``closed()`` here
        return __result
    return connect_and_close

class StoreAPI(MethodView):

    @with_database
    def get(self):
        return g.db.query(request.args.get('key'))

    @with_database
    def post(self):
        key, value = str(random.randint(0, 1000)), str(random.randint(0, 1000))
        g.db.put(key, value)
        return 'set %s => %s\n' % (key, value)

rawDescription: In flask, how can I execute a before_filter on a particular pluggable view?


code:
import shutil

zip_file_path = shutil.make_archive(zip_file_build_path, 'zip', root_dir = dist_dir);

rawDescription: Zipping a Mac app bundle with Python

description: Zipping a Mac app bundle with Python


code:
user_dict = dict((d[0], [d[1], d[2]]) for d in
                 user_data.values_list('id', 'name', 'reporting_time'))

rawDescription: How to transform the output of .values() function in django?

description: Transform the output of .values() function in django


code:
class PVData(object):
    def __init__(self):
        self.date = yesterday()
        self._initialize()

    def change_date(self, date):
        if self.date != self.date:
            self.date = date
            self._initialize()

    def _initialize(self):
        self.data = load_data(self.date)

        #time, temp, sun
        self.time = []
        self.temperature = []
        self.sunlight = []
        self.powerlist = [] ####LIST OF ALL POWER TUPLES FOR DAY
        for minute in self.data:
            self.time.append(minute[0])
            self.temperature.append(minute[1])
            self.sunlight.append(minute[2])
            self.powerlist.append(minute[3])
        ##power

        self.placelist = []
        for i in ARRAYS:
            self.placelist.append(i)

        ##Combine lists to dictionary with loop
        self.dictionary = {}
        self.dictionary = dict(zip(self.placelist, self.powerlist))

rawDescription: How to renew a variable in another function within a class?

description: Renew a variable in another function within a class


code:
for dataset in data:
    subprocess.call("cat part-r-* > combined_output",shell=True,cwd=dataset+'.matrix')

rawDescription: execute bash commands sequentially inside for loop in Python

description: Execute bash commands sequentially inside for loop in Python


code:
import random
thelist = ['a', 'b', 'c', 'd']
random.shuffle(thelist)
thelist

rawDescription: Does anyone know a way to scramble the elements in a list?