code:
excuses = ["Please go away, DND", "Didn't you hear me? DND", "I said DND!"]
[excuse.replace('DND', 'do not disturb') for excuse in excuses]

rawDescription: Swapping "words" in a list of strings in Python


code: global variable

rawDescription: Python: Global variables in threads

description: Python: Global variables in threads


code:
for fi in sys.argv[1:]:
    with open(fi) as markup:
        soup = BeautifulSoup(''.join(unuuencode(markup, ignore_length_errors=True)))
    with open("strip_" + fi, "w") as f:
        f.write(soup.get_text().encode('utf-8'))

rawDescription: Python - delete uuencoding lines

description: Python - delete uuencoding lines


code:
urlpatterns = patterns('',
    (r'^contact/$', ContactWizard.as_view([ContactForm1, ContactForm2])),
)

rawDescription: can you use Form Wizard for Model Forms in django?

description: Use Form Wizard for Model Forms in django


rawDescription: How can I plot implicit functions in python?

description: Plot implicit functions in python


code:
def format_list(l):
    if len(l)==1: return l[0]
    else:
        return '{:<10}|{:>10}'.format(l[0],l[1])

for l in [['abc'],['Dave', '14']]:
    print(format_list(l))

rawDescription: python - Conditional list formatting

description: Python - Conditional list formatting


code:
from collections import Counter
x = Counter(['foo', 'foo', 'bar', 'bar'])
n = 2
x + Counter(dict.fromkeys(x, n))
y = Counter(['foo', 'foo', 'bar', 'bar', 'spam'])
y + Counter(dict.fromkeys(y, n))

rawDescription: How to add N to every value of a Counter? - python

description: Add N to every value of a Counter? - python


code:
import pandas as pd

df= pd.read_csv("file.csv")

rawDescription: Conditional probability density estimation in python


code:
for n in range(3,int(a ** 0.5) + 1):
    if a % n == 0: return False
    if a % n != 0: return True  # This if condition is not needed

rawDescription: Difficulty with python prime number check


code:
x = [False,True,True,False,True,False,True,False,False,False,True,False,True]
nth_item(50, True, x)
nth_item(0, True, x)
nth_item(1, True, x)
nth_item(2, True, x)
nth_item(3, True, x)

rawDescription: Find the index of the n'th item in a list


rawDescription: Starting jython program from python using subprocess module?


code:
for adding in mytuple:
    print("{0:4d}".format(adding[0] + adding[1]))

rawDescription: python add elements in a tuple

description: Python add elements in a tuple


rawDescription: Preparing a list from a dictionary in python


code:
entries = filter(
    lambda d: d['hostName'] == hostName,
    json.loads(data)
)

if not entries:
    raise KeyError('There is no entry with that host name.')

id = entries[0]['id']

rawDescription: Search a complex data structure in Python


code:
'caraeCqCA2LvMf9oLn'
'car7vAHCzaeuT7uAgN'
'carQ6bkckGfmdxMGim'
'car9WlxbcV1uOhXQkj'
'carONwavdLrMdc804g'
'carSwBU0WkNgT7YL1l'
'carCtWClbz9khoMDmU'

rawDescription: Generate randon and uniques ids in django


code:
def start():
   print ("hello")
def litroom():
   start()

if __name__=='__main__':
   # magix trick : name value is the name of the file
   # unless run as the "main" script where it's __main__
   start()

rawDescription: import a single function

description: Import a single function


rawDescription: 2D Array - Select range of columns

description: 2D Array - Select range of columns


code:
params = {"json_records": jsonified_task_records,
                          "user": user.key.urlsafe()}
taskqueue.Task(url='/worker',
                          payload=json.dumps(params)
                          ).add(queue_name='postios')

rawDescription: How to utilise payload instead of params in Taskqueue?

description: Utilise payload instead of params in Taskqueue


rawDescription: assigning points to bins

description: Assigning points to bins


code:
for _ in range(3):
    pool.apply_async(ImageData.shepard_interpolation, args=[ImageData()],
                     callback=results.append)

rawDescription: Can't pickle static method - Multiprocessing - Python


rawDescription: Difference between multiple elements in list with same string . Python 2.7


code:
def addAttrs(attr_names):
  def deco(cls):
    for attr_name in attr_names:
      def getAttr(self, attr_name=attr_name):
        return getattr(self, "_" + attr_name)
      def setAttr(self, value, attr_name=attr_name):
        setattr(self, "_" + attr_name, value)
      prop = property(getAttr, setAttr)
      setattr(cls, attr_name, prop)
      setattr(cls, "_" + attr_name, None) # Default value for that attribute
    return cls
  return deco

@addAttrs(['x', 'y'])
class MyClass(object):
  pass

rawDescription: How can I add properties to a class using a decorator that takes a list of names as argument?

description: Add properties to a class using a decorator that takes a list of names as argument


code:
pattern = re.compile(r"(?<=SecurityGroup:)(.*)")
matches = re.findall(pattern, your_string)

rawDescription: Match everything expect a specific string


code: parse('a:b -> c : d e')

rawDescription: syntactic whitespaces with pyparsing's operatorPrecedence

description: Syntactic whitespaces with pyparsing's operatorPrecedence


code:
def point():
    return (random.randint(MIN, MAX)) + (random.randint(MIN, MAX))

rawDescription: My program runs great but my client wants


code:
'   asdfadsf '.strip()
'\nblablabla\n'.strip()
a = []
a.append('   \n asdf \n    '.strip())
a
words = [' a ', '   b    ', '\nc\n']
words = [word.strip() for word in words]
words

rawDescription: how does strip() method works with append() method?

description: How does strip() method works with append() method


code:
def f():
    1 + 1
    "win"

dis.dis(f)

rawDescription: How to use Python 3.4's enums without significant slowdown?

description: Use Python 3.4's enums without significant slowdown


code:
response = HttpResponse(f.getvalue(), content_type='text/csv')
# etc.

rawDescription: Django/Python: CSV for-in loop overriding first row each time through


code:
parser = MyOptionParser()
parser.add_option(MyOption("-f", "-file", dest="filename",
                 help="write report to FILE", metavar="FILE"))
parser.add_option(MyOption("-q", "-quiet",
                 action="store_false", dest="verbose", default=True,
                 help="don't print status messages to stdout"))

rawDescription: parsing non GNU-standard options using optparse in python

description: Parsing non GNU-standard options using optparse in python


code:
import pandas as pd
df = pd.DataFrame({'col1': [1, 2, 1], 'col2': [6, 3, 6]})
di = {'col1': 1, 'col2': 6}
df['col3'] = pd.DataFrame([df[k]==v for k,v in di.iteritems()]).all()
df

rawDescription: pandas: select all rows matching multiple conditions

description: Pandas: select all rows matching multiple conditions


code: xpos1 = np.array((number_of_iterations, TotalNumberofParticles))

rawDescription: save simulation data in python

description: Save simulation data in python


code:
from pandas.io import sql

def get_sqltype(pytype, flavor):
    sqltype = {'mysql': 'VARCHAR (63)',    # <-- change this value to something sufficient higher
               'sqlite': 'TEXT'}

    if issubclass(pytype, np.floating):
        sqltype['mysql'] = 'FLOAT'
        sqltype['sqlite'] = 'REAL'
    if issubclass(pytype, np.integer):
        sqltype['mysql'] = 'BIGINT'
        sqltype['sqlite'] = 'INTEGER'
    if issubclass(pytype, np.datetime64) or pytype is datetime:
        sqltype['mysql'] = 'DATETIME'
        sqltype['sqlite'] = 'TIMESTAMP'
    if pytype is datetime.date:
        sqltype['mysql'] = 'DATE'
        sqltype['sqlite'] = 'TIMESTAMP'
    if issubclass(pytype, np.bool_):
        sqltype['sqlite'] = 'INTEGER'

    return sqltype[flavor]

sql.get_sqltype = get_sqltype

rawDescription: pandas to_sql truncates my data

description: Pandas to_sql truncates my data


code:
@app.route('/create', methods=['GET', 'POST'])
@login_required
def create_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data, body=form.body.data,
                    topic=form.topic.data)
        db.session.add(post)
        db.session.commit()
        Topic.update_counts()
        flash('Your post has been published.')
        return redirect(url_for('display_post', url=url))
    posts = Post.query.all()
    return render_template('create_post.html', form=form, posts=posts)

rawDescription: WTForms: setting default value from an SQLAlchemy field with relationship


code:
from scipy.sparse.linalg import LinearOperator
A = whatever_dok_matrix_minus_constant_term
def my_matvec(x):
    return A*x + constant_term * x.sum()
op = LinearOperator(A.shape, matvec=my_matvec)

rawDescription: scipy.sparse default value

description: Scipy.sparse default value


code:
from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

rawDescription: Django - A bit lost with forms

description: Django - A bit lost with forms


rawDescription: Comparing nested lists

description: Comparing nested lists


code:
import statistics as stats
avg = stats.mean(nums)
avg
stddv = stats.stdev(nums)
stddv

rawDescription: How to simulate random normal variate Python

description: Simulate random normal variate Python


code:
import pandas as pd
import numpy as np

df = pd.DataFrame(index=range(0,5), data=[range(5*i,5*i+5) for i in range(0,5)])

rawDescription: Selecting a data value from pandas dataframe based on row and column to append to list


code: l.sort(key=lambda d: d.get('age', float('-inf')))

rawDescription: How to reorder a list in Python based on its content

description: Reorder a list in Python based on its content


code:
import logging
logging.basicConfig(
    level=logging.DEBUG,
    format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
    datefmt="%H:%M:%S", stream=sys.stdout)
log.info("HEY")

rawDescription: what is the default python logging formatter

description: What is the default python logging formatter


rawDescription: How do you tell python to get the first 6 numbers from a text file and put them horizontally

description: Tell python to get the first 6 numbers from a text file and put them horizontally


cmd: python3 -u $file

rawDescription: How to set which version of python sublime text uses

description: Set which version of python sublime text uses


rawDescription: Please explain reasoning behind code snippet from argparse module


code:
from sqlalchemy import event, DDL

event.listen(some_table, 'after_create', DDL("CREATE SPATIAL INDEX sp_index ON geom (g)"))

rawDescription: MySQL spatial index with sqlalchemy?

description: MySQL spatial index with sqlalchemy


code: getattr(item, linkGlue)

rawDescription: Printing value of a variable as a object name python


code: yield dict1[item1][2], dict2[item2][6]

rawDescription: Help using *args in tuple matching Python function


rawDescription: Split string by regular expression

description: Split string by regular expression


code:
def grps(a):
    it = iter(a)
    i = next(it)
    start, spk = i[0], i[2]
    for ele in it:
        if spk != ele[2]:
            yield [start, ele[0], spk]
            spk = ele[2]
            start = ele[0]
    yield start, ele[1], spk

print(list(grps(a)))

rawDescription: Mapping diagonal elements recursively and check for condition, Python


code: [x for x in L if x >= 0]

rawDescription: How to remove negative values from a list using lambda functions by python

description: Remove negative values from a list using lambda functions by python


code: db.execute(i, ...)

rawDescription: How to implement session.add on this code:

description: Implement session.add on this code:


code:
elems = browser.find_elements_by_xpath("""//*[@id="body"]/table/tbody/tr[1]/td/table[2]/tbody/tr/td[2]/table/tbody/tr[4]/td[1]""")
print([elm.text for elm in elems])

rawDescription: Selenium get text from a table cell (td) with XPath


rawDescription: removing pairs of elements from numpy arrays that are NaN (or another value) in Python

description: Removing pairs of elements from numpy arrays that are NaN (or another value) in Python


code:
timeit.timeit("list_replace_test(s2, chars)", setup="from __main__ import list_replace_test, s2, chars")
timeit.timeit("string_replace_test(s, chars)", setup="from __main__ import string_replace_test, s, chars")
timeit.timeit("str_translate(s, map)", setup="from __main__ import str_translate, s, map")

rawDescription: Why is list element replacement slower than string element replacement in python?


code:
CLB, HNRG, LPI, MTDR, MVO, NRGY, PSE, PVR, RRC, WES
ACMP, ATLS, ATW, BP, BWP, COG, DGAS, DNR, EPB, EPL
EXLP, NOV, OIS, PNRG, SEP, APL, ARP, CVX, DMLP, DRQ
DWSN, EC, ECA, FTI, GLOG, IMO, LINE, NFX, OILT, PNG
QRE, RGP, RRMS, SDRL, SNP, TLP, VNR, XOM, XTXI, AHGP

rawDescription: How to create a new list or new line after a certain number of iterations

description: Create a new list or new line after a certain number of iterations


code:
def count_digits(n):
    if n == 0:
        return 1
    count = 0
    while n > 0:
        n = n // 10
        count += 1
    return count

rawDescription: Counting digits of number with no string operations


rawDescription: How to use discontinuous index to form a new list in python?

description: Use discontinuous index to form a new list in python


rawDescription: Parsing and reformatting CSV/text data using Python


code:
def convert_to_dict(line, header):
    d = {}
    for cell in header:
        d[cell] = ''

    row = line.strip().split(';')
    for cell in row:
        if cell:
            key, value = cell.split('=')
            d[key] = value

    return d

rawDescription: Parse Specific Text File to CSV Format with Headers


code:
class TypeHandler(object):
    def __init__(self, type_dict):
        self.types = type_dict

    def __call__(self, name):
        def wrapper(f):
            self.types[name] = f
            return f
        return wrapper

class MyClass(object):
    types = {}
    thandle = TypeHandler(types)

    @thandle('a')
    def foo_a(self, a):
        pass

rawDescription: Class level decorator

description: Class level decorator


code: t = list(product(*(range(i+1) for i in maxvalues)))

rawDescription: Python: finding all tuples with constrained elements that add up to a constant


code:
a = np.array([2, 3, 14, 15, 54])
res = np.abs(a[:, np.newaxis] - a) < 10  # Note: perhaps you want <= 10.
np.fill_diagonal(res, False)
res.any(0)

rawDescription: how to filter groupby object in pandas based on difference of values within the group?

description: Filter groupby object in pandas based on difference of values within the group


rawDescription: regular expression pattern about word boundary in python

description: Regular expression pattern about word boundary in python


code:
newdata = [tuple(header)]
newdata.extend(data)

rawDescription: join new tuple to first list of tuples in Python

description: Join new tuple to first list of tuples in Python


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

with sqlite3.connect(":memory:") as con:
    cur = con.cursor()
    cur.execute("CREATE TABLE DATEN(Source TEXT, Target TEXT, Weight REAL)")
    cur.execute("INSERT INTO DATEN VALUES('X33', 'X20', 0.014)")
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X20', 0.024)")
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X20', 0.167)")
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X32', 0.015)")
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X33', 0.003)")
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X33', 0.035)")

    G = nx.Graph()
    cur.execute('SELECT Source, Target, Weight FROM DATEN')
    G.add_weighted_edges_from(cur)

nx.draw(G)
plt.show()

rawDescription: graph from weighted edge list from a database

description: Graph from weighted edge list from a database


code:
d = {}
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
    # I don't actually know how you're calculating values
    # and it kind of doesn't matter
    value = calculate(letter)
    if value in (inf, nan):
        continue
    d[letter] = value

rawDescription: remove values from a python dict

description: Remove values from a python dict


code: my_output = my_output + ' ' + word

rawDescription: Grab a keyword and the text between keywords in Python


code:
class CloseButton(gtk.Button):
    def __init__(self, widget):
        gtk.Button.__init__(self)
        self.widget_ref = widget#Pass the widget reference to this button
        #Initialize the button here...
        self.connect( 'destroy', self.on_destroy )
    def on_destroy( self, widget ):
        self.widget_ref = None#Destroy the reference to the widget

rawDescription: pygtk notebook page close memory leak

description: Pygtk notebook page close memory leak


code:
import sqlite3,time

db = sqlite3.connect("my_database.sql") #you can put whatever ... created if not exist
conn = db.cursor()

conn.execute("CREATE TABLE IF NOT EXISTS Activities (timestamp int, name text);")

def AddActivity(activityName):
    conn.execute("INSERT INTO Activities (timestamp,name) VALUES (?,?)",(time.time(),activityName))
    db.commit()

def GetAllActivitiesOnDate(month,day,year):
    start_time = time.mktime((year,month,day,0,0,0,0,0,0))
    end_time = time.mktime((year,month,day,23,59,0,0,0,0)) #use 1 for last  argument if you live somewhere with dst
    conn.execute("SELECT * FROM Activities WHERE timestamp > ? AND timestamp < ?",(start_time,end_time))
    return conn.fetchall()

rawDescription: A good way to store date-based data using python?


code: df.pivot_table('data', 'week_time', 'week').rename(columns=lambda x: 'Week ' + str(x)).plot()

rawDescription: Plotting Weekly Tick Data From A Year Time Series


code: options='P-S-D'  #order by price, 5 items per page, descending order

rawDescription: Django - Paginating in Template using multiple GET parameters


rawDescription: what is the most efficient way to turn a list in python

description: What is the most efficient way to turn a list in python


rawDescription: Best way to add a "+" and "-"?

description: Add a "+" and "-"


code:
from subprocess import Popen
Popen("run the commands", shell=True, cwd="/directory/path/here")

rawDescription: pushd through os.system

description: Pushd through os.system


code: replace_in_config('_stripped', 'gco:')

rawDescription: How to parse the xml to find the text value of the following node in python?

description: Parse the xml to find the text value of the following node in python


code:
False
True
False

rawDescription: Python object that monitors changes in objects


code:
EXTENSIONS = {
    'your_package.extensions.StatusMailer': 80
}

rawDescription: Emailing items and logs with Scrapy

description: Emailing items and logs with Scrapy


rawDescription: Elements of the original list changes when a deep copy of changes


code:
from collections import defaultdict
names=defaultdict(lambda :defaultdict(list))

with open('f.txt') as f:
   lines = [l.split() for l in f.readlines() if l.strip()]
   for l in lines:
       names[l[0]][l[1]].append(float(l[2]))

rawDescription: accessing lists values of dictionary

description: Accessing lists values of dictionary


code: overlapped = set(com for com,was_overlapped in combos.items() if was_overlapped)

rawDescription: Checking two time intervals are overlapping or not


rawDescription: Python find list of surrounding neighbours of a node in 2D array


code: (df.index.to_series() / 5).astype(int)

rawDescription: Pandas' equivalent of resample for integer index


code: p = pool.apply_async(_do_chunk_wrapper, (k_start, k_end, xi, yi))

rawDescription: Minimize overhead in Python multiprocessing.Pool with numpy/scipy


code: dict((i,d[i]) for i in d if i!='c')

rawDescription: Remove key from dictionary in Python returning new dictionary


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

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure()
for n in range(len(x)):
    plt.cla()
    plt.plot(x[:n], y[:n], color='k')
    plt.axis([0, 10, 0, 1])
    plt.savefig('Frame%03d.png' %n)

rawDescription: Animating "growing" line plot in Python/Matplotlib


code: data

rawDescription: Create CSR matrix from x_index, y_index, value


code:
s = "This must not b3 delet3d, but the number at the end yes 134411"
s = re.sub(" \d+", " ", s)
s

rawDescription: Delete digits in Python (Regex)

description: Delete digits in Python (Regex)


code:
while True:
    agent = random.choice(agents)
    if agent.state == 0:
        break

rawDescription: Selecting random elements in a list conditional on attribute


code: all_props_templist = [prop_list[j][i] for j in range(13)]

rawDescription: Python - Subtract 2 lists from each other that are in a dictionary


code:
colprint(sorted([(name, version[0].summary or '')
             for (name, version) in versions.iteritems()]))

rawDescription: lisp-style style `let` syntax in Python list-comprehensions

description: Lisp-style style `let` syntax in Python list-comprehensions


code:
from .meta_base import PluginBase
class SubModS(PluginBase):
    def __init__(self):
        super(SubModS, self).__init__()

rawDescription: least burdensome technique for package submodule to see all classes of importer

description: Least burdensome technique for package submodule to see all classes of importer


code:
def make_counter(n):
    def inc():
        n = n + 1
        return n
    return inc

rawDescription: lambda in python

description: Lambda in python


code:
urlpatterns = router.urls

urlpatterns = urlpatterns + [
    url(r'get_user_details/', get_user_details),
]

rawDescription: Send data from django views to angularjs controller


code:
sortedBookList = sorted(
    bookList,
    key=lambda elem: (sortByName(elem),
                      sortByFirstLanguage(elem, firstLanguage),
                      sortByLanguages(elem, possibleLanguages)))

rawDescription: How to pass additional arguments to custom python sorting function

description: Pass additional arguments to custom python sorting function


code:
import numpy as np
import pandas as pd

ser = pd.Series([19411.0, 19325.0, 19325.0, 19443.0, 19778.0])
ser = pd.to_timedelta(ser, unit='D') + pd.Timestamp('1960-1-1')

rawDescription: convert numeric sas date to datetime in Pandas

description: Convert numeric sas date to datetime in Pandas


code:
def parse(input):
  index = 0
  stack = [];

  def top():
    if len(stack) > 0:
      return stack[len(stack)-1]
    else:
      return None

  while index < len(input):
    if input[index] in ['0', '1']:
      pass
    elif input[index] is '(':
      stack.append('(')
    elif input[index] is 'U' and top() == '(':
      stack.append('U')
    elif input[index] is ')' and top() == 'U':
      stack.pop()
      stack.pop()
    else:
      raise MySyntaxError("Unexpected char '" + input[index] + "'", index)
    index += 1

  if len(stack):
    raise MySyntaxError("unterminated input", index)

rawDescription: Add parenthesis to statement

description: Add parenthesis to statement


code:
def contains(self, value):
    """
    contains(IntRange self, int value) -> bool

    Parameters
    ----------
    value: int

    """
    return _foo.IntRange_contains(self, value)

rawDescription: swig C++->Python 2.X conversion and method's arguments

description: Swig C++->Python 2.X conversion and method's arguments


foo

x: y

rawDescription: Python - how to avoid exec for batching?

description: Python - how to avoid exec for batching


code:
character_equally_often = {i: counter1[i] == counter2[i] for i in counter1}
print(character_equally_often)
# {'i': False, 'u': False, 'f': False, 'g': False, 'o': True,
#  's': False, 'd': False, 'n': False, 't': False, 'h': True,
#  'v': False, 'b': False, 'e': False, 'y': False, 'a': True}

rawDescription: How to compare the value of the key in Dict 1 is "==" or"!=" value of the same key in Dict2,if exists

description: Compare the value of the key in Dict 1 is "==" or"!=" value of the same key in Dict2,if exists


rawDescription: List of tuples from (a, all b) to (b, all a)


code:
np.bincount(np.searchsorted(np.cumsum(b), np.random.random(100)),
            minlength=b.size).reshape(b.shape)

rawDescription: Discretization of probability array in Python


rawDescription: Python regex for Java annotations

description: Python regex for Java annotations


code:
import random
import time
from IPython.display import Image, display, clear_output
from ipywidgets import widgets

x = ['tree.jpg','house.jpg','car.jpg','door.jpg','train.jpg','moon.jpg']

def redraw():
    choices = random.sample(x, 4)
    correct = random.choice(choices)

    display(Image(correct))
    time.sleep(3)

    button1 = widgets.Button(description = choices[0])
    button2 = widgets.Button(description = choices[1])
    button3 = widgets.Button(description = choices[2])
    button4 = widgets.Button(description = choices[3])

    container = widgets.HBox(children=[button1,button2,button3,button4])
    display(container)

    def on_button1_clicked(b):
        # [insert code to record choice]
        container.close()
        clear_output()
        redraw()

    def on_button2_clicked(b):
        # [insert code to record choice]
        container.close()
        clear_output()
        redraw()

    def on_button3_clicked(b):
        # [insert code to record choice]
        container.close()
        clear_output()
        redraw()

    def on_button4_clicked(b):
        # [insert code to record choice]
        container.close()
        clear_output()
        redraw()

    button1.on_click(on_button1_clicked)
    button2.on_click(on_button2_clicked)
    button3.on_click(on_button3_clicked)
    button4.on_click(on_button4_clicked)

redraw() # initializes the first choice

rawDescription: Using ipywidget for multiple choice test


code:
import subprocess
import re
import requests

urls = ['http://192.168.1.10/testSource.sh']

for url in urls:
    response = requests.get(url).content
    values = dict.fromkeys(['foo', 'bar', 'var3'])
    proc = subprocess.Popen(['bash', '0<'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
    proc.stdin.write(response)
    proc.stdin.flush()
    output, err = proc.communicate(input='set')
    for key in values:
        match = re.search('%s=(.*)$' % key, output, re.MULTILINE)
        if match:
            values[key] = match.group(1)
            print('%s=%s' % (key,values[key]))

rawDescription: Read variables from shell/bash script into python


code:
x = (1,2,3)
assert x[0] == 1 #yup, works.
x.remove(0) #AttributeError: 'tuple' object has no attribute 'remove'

rawDescription: Removing tuple from list

description: Removing tuple from list


code:
import random
random.shuffle(lst)

rawDescription: Pick a random variable then have it become unavailable to be chosen again in Python?


code:
def my_switch(x):
    my_dict = {
            '1': 'my name is ali',
            '2': 'my name is hamza',
        }
    if x in my_dict.keys():
        return my_dict[x]
    else:
        return "invalid input"

rawDescription: Simple C code in python --- switch statement


code:
class stopper(object):
    def __init__(self, func):
        self.func = func
        self.finished = False

    def __call__(self, *args, **kwargs):
        for x in self.func(*args, **kwargs):
            if x == 6:
                self.finished = True
                raise StopIteration
            yield x
        else:
            self.finished = True

rawDescription: What do you call an iterator with two different "done" states?


code:
import numpy as np
import pandas as pd
df = pd.read_csv('data', parse_dates=[0], sep=',\s*')

def big_df(df):
    df = df.copy()
    for i in range(7):
        dates = df['Date'] + pd.Timedelta(df.iloc[-1]['Date']-df.iloc[0]['Date']) + pd.Timedelta('1 minute')
        df2 = pd.DataFrame({'Date': dates, 'A': df['A']})
        df = pd.concat([df, df2])
    df = df.reset_index(drop=True)
    return df

def using_apply():
    start_dates = df['Date'] - pd.Timedelta(minutes=5)
    df['start_index'] = df['Date'].values.searchsorted(start_dates, side='right')
    df['end_index'] = np.arange(len(df))

    def sum_window(row):
        return df['A'].iloc[row['start_index']:row['end_index']+1].sum()

    df['rolling_sum'] = df.apply(sum_window, axis=1)
    return df[['Date', 'rolling_sum']]

def using_asfreq():
    result = (pd.rolling_sum(
        df.set_index(['Date']).asfreq('1T').fillna(0),
        window=5, min_periods=1).reindex(df['Date']))
    return result

rawDescription: pandas rolling sum of last five minutes

description: Pandas rolling sum of last five minutes


rawDescription: Slice list to ordered chunks

description: Slice list to ordered chunks


rawDescription: How to convert this data structure in python

description: Convert this data structure in python


code: [[x, number / x] for x in range(1, limit + 1) if number % x == 0]

rawDescription: Adding two data items in a list comprehension simultaneously, after a mathematical operation


rawDescription: parsing a python string with floats and ints

description: Parsing a python string with floats and ints


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

frame = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "fm2")))
driver.switch_to.frame(frame)

driver.switch_to.frame("contentFrame")

rawDescription: Selenium Webdriver give NoSuchFrameException


code: {'Company': ['Crowdbooster', 'Captricity'], 'Year': ['Nov 2010', 'Feb 2011'], 'Followers': ['299', '513'], 'Location': ['Palo Alto   Native Advertising', 'Oakland   Data Integration'], 'Summary': ['Adsense for native content', 'Democratizing Data Access.']}

rawDescription: Making columns with data in other column in Pandas


code:
with open('a.txt') as a:
    with open('b.txt') as b:
        do_many_amazing_things(a, b)

rawDescription: Multiple context `with` statement in Python 2.6


code: doc.appendChild( elem )

rawDescription: Copy and Write XML Node in Python

description: Copy and Write XML Node in Python


code:
import win32print
PRINTER_DEFAULTS = {"DesiredAccess":win32print.PRINTER_ALL_ACCESS}
pHandle = win32print.OpenPrinter('RICOH-LOCAL', PRINTER_DEFAULTS)
properties = win32print.GetPrinter(pHandle, 2) #get the properties
pDevModeObj = properties["pDevMode"] #get the devmode
automaticTray = 7
tray_one = 1
tray_two = 3
tray_three = 2
printer_tray = []
pDevModeObj.DefaultSource = tray_three #set the tray
properties["pDevMode"]=pDevModeObj #write the devmode back to properties
win32print.SetPrinter(pHandle,2,properties,0) #save the properties to the printer

rawDescription: Switching Printer Trays

description: Switching Printer Trays


code:
a2, b2 = a.copy(), b.copy()
removeCommonElements(a2, b2)

rawDescription: Removing common elements in two lists

description: Removing common elements in two lists


code:
import sys
from functools import partial
from PyQt4 import QtCore, QtGui

class Tree(QtGui.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super(Tree, self).__init__()
        for each in ['Item_1','Item_2','Item_3','Item_4','Item_5']:
            item=QtGui.QTreeWidgetItem([each])
            self.addTopLevelItem(item)
            comboBox = QtGui.QComboBox()
            lineEdit = QtGui.QLineEdit()
            self.setItemWidget(item, 1, comboBox)
            self.setItemWidget(item, 2, lineEdit)
            comboBox.mousePressEvent = partial(self.mousePressEventChild, currentQTreeWidgetItem = item, child = comboBox)
            lineEdit.mousePressEvent = partial(self.mousePressEventChild, currentQTreeWidgetItem = item, child = lineEdit)
        self.setColumnCount(5)
        self.resize(360,240)
        self.show()

    def mousePressEventChild (self, QMouseEvent, currentQTreeWidgetItem = None, child = None):
        if isinstance(currentQTreeWidgetItem, QtGui.QTreeWidgetItem):
            self.setCurrentItem(currentQTreeWidgetItem)
        super(child.__class__, child).mousePressEvent(QMouseEvent)

app = QtGui.QApplication([])
tree=Tree()
sys.exit(app.exec_())

rawDescription: How to select QTreeWidgetItem by clicking its item-widget

description: Select QTreeWidgetItem by clicking its item-widget


code:
from collections import defaultdict

operators = defaultdict(list)
for line in open('data').readlines():
    pre, begin, end, _, operator_name = line.split(None,4)
    operators[pre].append((int(begin),int(end),operator_name))

rawDescription: How to properly pass text file to search the data there?

description: Properly pass text file to search the data there


code:
import numpy as np
import pylab as pl

# normalize this
color_param = np.array([9.0, 2.0, 21.0])
color_param = (color_param - color_param.min())/(color_param.max() - color_param.min())

data = [(-118, -118), (34.07, 34.16),
        (-117.99, -118.15), (34.07, 34.16),
        (-118, -117.98), (34.16, 34.07)]

startD = data[::2]
stopD  = data[1::2]

for start, stop, col in zip( startD, stopD,  color_param):
    pl.plot( start, stop, color = pl.cm.jet(col) )

pl.show()

rawDescription: Plotting multiple segments with colors based on some variable with matplotlib


code: max(x, key=sum)

rawDescription: How to find the list in a list of lists whose sum of elements is the greatest?

description: Find the list in a list of lists whose sum of elements is the greatest


code: rd = requests.get(url, headers={"Cookie": "JSESSIONID=%s" % r.cookies['JSESSIONID']})

rawDescription: JIRA REST API and kerberos authentication


code:
bedtools_exe_path = 'D:/BEDTools/bin/bedtools.exe'
gene_bed_file = 'output/gene.csv'
snp_bed_file = 'output/snps.csv'
output_file = 'output/intersect_gene_snp.bed'

rawDescription: Python - subprocess.call using cygwin instead of cmd on windows


code:
parser.parse('Sunday, 16/09/2012')
parser.parse('01/12/2012')
parser.parse('January 12, 2012')

rawDescription: Temporal Expression recognition in Python


code:
def my_extend(self, other_list, index):
    self[index:index] = other_list

rawDescription: list extend() to index, inserting list elements not only to the end

description: List extend() to index, inserting list elements not only to the end


code: project_points(x, y, z, *calc_plane_bis(x, y, z))

rawDescription: orthogonal projection with numpy

description: Orthogonal projection with numpy


code:
df.loc[:, ['Value1', 'Value2', 'Value3']].apply(pd.notnull)
df.loc[:, ['Value1', 'Value2', 'Value3']].apply(pd.notnull).all(1)

rawDescription: Skipping rows in a csv file using Python Pandas


rawDescription: Rounding numpy float array read from img with python, values returned not rounded


code: "statt 29,95 â‚¬ nur "

rawDescription: How to select a string of variable length but with fixed beginning and ending?

description: Select a string of variable length but with fixed beginning and ending


code:
pylab.close('all')
pylab.ion()

m = Basemap(width=12000000, height=8000000, resolution='l', projection='stere',
            lat_ts=50, lat_0=50, lon_0=-107.)
m.drawcoastlines()
m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(numpy.arange(-80.,81.,20.))
m.drawmeridians(numpy.arange(-180.,181.,20.))
m.drawmapboundary(fill_color='aqua')
# draw ellipses
ax = pylab.gca()
for y in numpy.linspace(m.ymax/20, 19*m.ymax/20, 9):
    for x in numpy.linspace(m.xmax/20, 19*m.xmax/20, 12):
        lon, lat = m(x, y, inverse=True)
        poly = m.ellipse(lon, lat, 3, 1.5, 100, facecolor='green', zorder=10,
            alpha=0.5)
pylab.title("Ellipses on stereographic projection")

rawDescription: Drawing ellipses on matplotlib basemap projections


code:
for tr in subpage.cssselect('tr.nob-border'):
    previous = tr.xpath('count(./preceding-sibling::tr)+1')
    next = tr.xpath('count(./following-sibling::tr[contains(@class, "nob-border")][1]/preceding-sibling::tr)+1')
    tr_in_between = tr.xpath('./following-sibling::tr[position() < $next]', next=next-previous)

rawDescription: Selecting siblings from html with Python lxml(html) library


code:
def load_inst(self):
    module = self.readline()[:-1]
    name = self.readline()[:-1]
    klass = self.find_class(module, name)
    # Now module is imported and ready to be used:
    self._instantiate(klass, self.marker())
dispatch[INST] = load_inst

rawDescription: How to control what gets imported when you unpickle python object?

description: Control what gets imported when you unpickle python object


code:
def prng(x, a, c, m):
    while True:
        x = (a * x + c) % m
        yield x

rawDescription: How Can I: Generate 40/64 Bit WEP Key In Python?


code: ( df > df.stack().quantile(.25) ) & ( df < df.stack().quantile(.75) )

rawDescription: Excluding data from a pandas dataframe based on percentiles


code:
from datetime import datetime

converted = datetime.strptime(original, '%d/%b/%Y').strftime('%Y/%m/%d')

rawDescription: Converting 23/Oct/2014 to 2014/10/23 in Python


rawDescription: How to get the index with the key in Python dictionary?

description: Get the index with the key in Python dictionary


code:
rule_defs = { 'and': lambda r: (lambda d ,r1: print(d))}
rule_defs['and'](1)(2,3)

rawDescription: Getting a return value from Lambda python


code: df = pd.concat(dataList.values(), axis=1, keys=dataList.keys()).interpolate('time').loc[max(dataList.values(), key=len).index]

rawDescription: Resampling and merging data frame with python


code:
import subprocess

p = subprocess.Popen("gzip -c > zipped.gz", shell=True, stdin=subprocess.PIPE)
p.stdin.write("Some data")

# Write more data here...

p.communicate() # Finish writing data and wait for subprocess to finish

rawDescription: Python equivalent of piping file output to gzip in Perl using a pipe


code: some_name = BooleanColumn(yesno=',')

rawDescription: django-tables2 edit yesno parameter for all BooleanColumn

description: Django-tables2 edit yesno parameter for all BooleanColumn


code: id, val, val2, rsn = reader

rawDescription: Python CSV reader print out specific field


code:
class Sentence(object):
    pass

sentence = Sentence()
sentence.the_string = "This is a sentence."

rawDescription: Storing a string into a property

description: Storing a string into a property


code:
class City(models.Model):
    name = models.CharField(max_length=20)

class Office(models.Model):
    room = models.CharField(max_length=3)
    phone = models.CharField(max_length=8)
    city = models.ForeignKey(City)

rawDescription: What to do with model general attributes in django models?


code:
aThread = myThread(myGui,myOtherStuff)
aThread.start()

rawDescription: Help adding threading for GUI progress

description: Help adding threading for GUI progress


code: cur.execute("SELECT * FROM list WHERE InstitutionName=?", (Variable,))

rawDescription: Searching SQLite Database with Python Variables


code: Table = namedtuple('Table', ['up', 'down', 'left', 'right'])

rawDescription: Copying a list in python

description: Copying a list in python


code:
from collections import defaultdict
import csv

with open("in.csv") as f:
    r = csv.reader(f)
    next(r) # skip header
    # fruite will be keys, values will be dicts
    # with brands as keys  and running totals for rev as values
    d = defaultdict(lambda: defaultdict(int))
    for fruit, brand, rev in r:
        d[fruit][brand] += float(rev)

rawDescription: How to identify "keys" of a tuple/list of 3-item tuples?

description: Identify "keys" of a tuple/list of 3-item tuples


code:
df_scr_crd_d.loc[df_scr_crd_d.Subject == 'MATH', 'SCR_STRT'].tolist()
df_scr_crd_d.loc[df_scr_crd_d.Subject == 'MATH', 'POINTS'].tolist()

rawDescription: python pandas converting dataframe(s) to lists

description: Python pandas converting dataframe(s) to lists


code:
c.property_set.all()
# => [Property <MyProperty>, Property <OtherProperty>, ...]

rawDescription: What is the best solution for multi tenancy in Django?


code:
import example
spam = example.Spam(42)
spam = example.Spam([42])

rawDescription: Boost Python iterable convertible masking non-iterable constructor


code:
class PersonForm(forms.ModelForm):
    favorite_color = DenormalizedChoiceField(choices=Person.COLORS)
    class Meta:
        model = Person
        fields = '__all__'

rawDescription: Importing Denormalized data into django models via modelforms


code:
from PyQt4 import QtGui
import sys

class MyMainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):

        super(MyMainWindow, self).__init__(parent)
        self.form_widget = FormWidget(self)
        self.setCentralWidget(self.form_widget)

class FormWidget(QtGui.QWidget):

    def __init__(self, parent):
        super(FormWidget, self).__init__(parent)
        self.layout = QtGui.QVBoxLayout(self)

        self.button = QtGui.QPushButton("Button!")
        self.layout.addWidget(self.button)

if __name__ == "__main__":
    app = QtGui.QApplication([])
    foo = MyMainWindow()
    foo.show()
    sys.exit(app.exec_())

rawDescription: Running python files

description: Running python files


rawDescription: How to make a partition structure

description: Make a partition structure


code: interp.call("myproc", d)

rawDescription: Pass Python variables to `Tkinter.Tcl().eval()`


rawDescription: Matlab / Octave bwdist() in Python or C

description: Matlab / Octave bwdist() in Python or C


rawDescription: Simple question: In numpy how do you make a multidimensional array of arrays?


code:
df_from_g = pd.DataFrame(g.get_adjacency(attribute='weight').data,
                         columns=g.vs['label'], index=g.vs['label'])
(df_from_g == a).all().all()  # --> True

rawDescription: igraph Graph from numpy or pandas adjacency matrix

description: Igraph Graph from numpy or pandas adjacency matrix


rawDescription: How to find all the indices of all the elements in a 2d matrix using Python?

description: Find all the indices of all the elements in a 2d matrix using Python


code:
class A:

    def __init__(self):
        self.data = np.array([])

    def update(self, row):
        self.data = np.append(self.data, row)

    def finalize(self):
        return np.reshape(self.data, newshape=(self.data.shape[0]/5, 5))

rawDescription: Fastest way to grow a numpy numeric array


code:
x = plt.linspace(0, 10, 100)
y = 1e6 + plt.sin(x)

ax = plt.subplot(111)
ax.plot(x, y)
ax.set_yticklabels(["{:.6e}".format(t) for t in ax.get_yticks()])
plt.subplots_adjust(left=0.2)
plt.show()

rawDescription: How to get a graph axis into standard form

description: Get a graph axis into standard form


code: USE_TZ = True

rawDescription: How do I get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4?

description: Get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4


code: import HTMLParser

rawDescription: HTML parser in Python

description: HTML parser in Python


code:
import sys

def traceit(frame, event, arg):
    if event == "call":
        co = frame.f_code
        func_name = co.co_name
        print("event:", event,"of function",func_name)
    return traceit

def main():
    print ("In main")
    for i in range(5):
        print (i, i*3)
    print ("Done.")

sys.settrace(traceit)
main()

rawDescription: How can I trace the functions call stack in a Python script?

description: Trace the functions call stack in a Python script


code:
import ctypes

rustLib = "libtest.dylib"

def testRust():
    lib = ctypes.cdll.LoadLibrary(rustLib)
    list_to_send = ['blah', 'blah', 'blah', 'blah']
    c_array = (ctypes.c_char_p * len(list_to_send))(*list_to_send)
    lib.get_strings(c_array, len(list_to_send))

if __name__=="__main__":
    testRust()

rawDescription: Passing a list of strings from Python to Rust


code:
bool_indices = numpy.all(rolling_window(a, 3) == [8, 4, 0], axis=1)
numpy.mgrid[0:len(bool_indices)][bool_indices]

rawDescription: Python/NumPy first occurrence of subarray


code:
def get_template_names(self):
    if self.request.mobile:
        return 'mobile/gallery.html'
    return 'normal/gallery.html'

rawDescription: Django Class model access self

description: Django Class model access self


code:
def _finditem(obj, key):
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = _finditem(v, key)
            if item is not None:
                return item

_finditem(j,'revisions')[0]['*']

rawDescription: Getting Page Content via Json

description: Getting Page Content via Json


code:
from app.models import History
History.insert_history(field1, field2, field3)

rawDescription: Django - Function inside a model. How to call it from a view?


code:
names = ["name1", "name2"]
ids = ["id1", "id2"]
dtypes = ["type1", "type2"]
zip(names,ids,dtypes)

rawDescription: Run 3 variables at once in a python for loop.


code: {u'color': u'orange', u'data': u'none', u'size': u'big'}

rawDescription: Dictionary of tags in declarative SQLAlchemy?


code:
class Pool(object):
    Process = Process

    def __init__(self, processes=None, initializer=None, initargs=(),
                 maxtasksperchild=None):
        self._setup_queues()
        self._taskqueue = Queue.Queue()
        self._cache = {}
        ... # stuff we don't care about
        self._worker_handler = threading.Thread(
            target=Pool._handle_workers,
            args=(self, )
            )
        self._worker_handler.daemon = True
        self._worker_handler._state = RUN
        self._worker_handler.start()

        self._task_handler = threading.Thread(
            target=Pool._handle_tasks,
            args=(self._taskqueue, self._quick_put, self._outqueue,
                  self._pool, self._cache)
            )
        self._task_handler.daemon = True
        self._task_handler._state = RUN
        self._task_handler.start()

        self._result_handler = threading.Thread(
            target=Pool._handle_results,
            args=(self._outqueue, self._quick_get, self._cache)
            )
        self._result_handler.daemon = True
        self._result_handler._state = RUN
        self._result_handler.start()

rawDescription: Who runs the callback when using apply_async method of a multiprocessing pool?


code:
from itertools import product
count_squares([[1,1],[1,1]])
def count_squares(A):
    width, height = len(A[0]), len(A)
    indices = product(range(width - 1), range(height - 1))
    is_square = lambda x, y: all(A[a][b] == 1 for a, b in product((x, x + 1), (y, y + 1)))
    return sum(1 for x, y in indices if is_square(x, y))

count_squares([[1,1],[1,1]])
count_squares([[1, 1, 0, 1] , [1, 1, 1, 1], [1, 1, 1, 0], [0, 1, 1, 1]])

rawDescription: counting 2*2 squares in n*n binary matrix

description: Counting 2*2 squares in n*n binary matrix


code:
with open("C:/codefile.cpp", "r+") as codefile:
    # find the line
    line = ""
    while line != marker:
        line = codefile.readline()
    # write the new method
    codefile.write(method)
    # erase everything after it from the file
    codefile.truncate()

rawDescription: Get to specific line in file, then start writing after that line


code:
def update(request):
    success = False

    try:
        product = Mattress.objects.get(id=id)
        success = True
    except Mattress.DoesNotExist:
        pass

    if success:
        return render_to_response("success.html")
    else:
        return render_to_response('failure.html')

rawDescription: Are booleans mutable in python?

description: Are booleans mutable in python


code: (last_key, tot_cnt, v_id) = (None, 0, None)

rawDescription: How to get the Reducer to emit according to key type

description: Get the Reducer to emit according to key type


code:
with open(file, "rb") as f:
    byte = f.read(20) # read the first 20 bytes? *Yes*

rawDescription: Extract first 20 bytes in a binary header


code:
import re, json
broken = r'"JSON string with escaped quote: \' and various other broken escapes: \a \& \$ and a newline!\n"'
json.loads(broken)
json.loads(re.sub(r'(?<!\\)\\(?!["\\/bfnrt]|u[0-9a-fA-F]{4})', r'', broken))

rawDescription: Dealing with mis-escaped characters in JSON


code: widgetItem = wx.Button(parent, -1, "...", style=wx.BU_EXACTFIT)

rawDescription: wxPython : How do I shrink the size of Button to the width of the label text?

description: WxPython : How do I shrink the size of Button to the width of the label text


code:
try:
    att_name = float(att.name)
    ret = "Integer" if att_name.is_integer() else "Float"
except ValueError:
    ret = "String"

rawDescription: Using regex on Charfield in Django

description: Using regex on Charfield in Django


code:
class MonkeyTester(unittest.TestCase):
    def test_myfunc(self):
        without_timestamp = my_func()
        del without_timestamp["monkey_creation"]
        self.assertEqual(without_timestamp, {'monkey_head_count': 3})

rawDescription: Dictionaries with volatile values in Python unit tests?


code:
import pandas as pd
df = pd.DataFrame({'A':'foo foo foo bar bar bar'.split(),
                   'B':[0.1, 0.5, 1.0]*2})

df['C'] = df.groupby(['A'])['B'].transform(
                     lambda x: pd.qcut(x, 3, labels=range(1,4)))
print(df)

rawDescription: Pandas groupby and qcut

description: Pandas groupby and qcut


code: labeled_array, num_features = scipy.ndimage.measurements.label(inverted)

rawDescription: Calculate the area of two separate geometries in Python


code:
[map(None, *sublist) for sublist in List] # Python 2
[list(itertools.zip_longest(*sublist)) for sublist in List] # Python 3

rawDescription: Python reorder lists inside lists

description: Python reorder lists inside lists


code:
max_value = 10**n
with open("outfile","wb") as variant:
    for number in xrange(max_value):
        variant.write("{0:09d}\n".format(number))

rawDescription: Python itertool variations, memory maximum reached


code:
if isTheWorldRound:
    return Bar
return [Bar, Foo]

rawDescription: Adding lines to a function

description: Adding lines to a function


rawDescription: Python how create sublists based by date?


code:
import collections
dictionary = collections.defaultdict(list)
dictionary['key1'].append('value1')
dictionary['key2'].append('value2')
dictionary['key1'].append('value3')
print(dictionary['key1'])

rawDescription: How do I search for multiple identical keys in a dictionary? (Python3)

description: Search for multiple identical keys in a dictionary? (Python3)


code:
primes529 = (2, 3, 5, 7, 11, 13, 17, 19, 23)

def composite529(x):
    return any(x % i == 0 for i in primes529)

[x for x in range(1, 1000) if composite529(x)]

rawDescription: Best way to make many logical comparisons in the if clause of a list comprehension in Python?

description: Make many logical comparisons in the if clause of a list comprehension in Python


code:
fix_pys(
    '/Users/me/my_folder',
    r'type\((\w+)\)\s*==\s*(\w+)',
    # r'' -> raw string
    # \( and \) is a necessary escape, because braces means groups in regexes
    # \w+ means more than word character (word characters are: a-z A-Z 0-9 and _)
    # \s* means 0 or more spaces
    r'isinstance(\1, \2)'
    # \1 refers to the content of the first group
    # \2 refers to the content of the second group
)

rawDescription: creating your own python code fixer (not debugger, although it could be used for that)

description: Creating your own python code fixer (not debugger, although it could be used for that)


rawDescription: boolean indexing that can produce a view to a large pandas dataframe?

description: Boolean indexing that can produce a view to a large pandas dataframe


code:
def is_interesting(tt):
    return tt['target_type'] == 670 and tt.get('script') in ('abc','syz','mno')

rawDescription: Better approach to do this

description: Better approach to do this


code:
np.random.seed(3)
np.random.rand()
np.random.randint(10**3, 10**4)

rawDescription: How to use random.RandomState

description: Use random.RandomState


code:
class SView(ListView):

    def get_context_data(self, **kwargs):
        ...
        bills = Bill.objects.all()
        for bill in bills:
            bill.total_amount = bill.sold_amount * bill.item.price

        context['bills'] = bills
        ...

rawDescription: Combined value from multiple models

description: Combined value from multiple models


code:
class Container:
    def __init__(self, name, date, foo, bar):
        self.name = name
        self.date = date
        self.foo = foo
        self.bar = bar

mycontainer = Container(name, date, foo, bar)

rawDescription: When and why should I use a namedtuple instead of a dictionary?


code: render("index.html", title='A title', subject='A subject')

rawDescription: Is there any way to pass all variables in the current scope to Mako as a context?


code:
def future6(A):
    # list of tuples (index into A, value in A)
    # invariant: indexes and values in sorted order
    known = []
    result = []
    for idx in xrange(len(A) - 1, -1, -1):
        value = A[idx]
        # since known is sorted a binary search could be applied here
        # I haven't bothered

        # anything lower then the current value
        # cannot possibly be used again, since this value will be first index instead
        # of those
        while known and known[-1][1] < value:
            known.pop()

        if known:
            # all values in known are > current value
            # they reverse sorted by index
            # the value with the lowest index is first
            result.append(known[-1][0])
        else:
            # no values exist this high, report -1
            result.append(-1)
        # add to end of the list to maintain invariant
        known.append( (idx, value) )

    # let numpy worry about reversing the array
    return np.array(result)[::-1]

rawDescription: Numpy vectorization algorithms to find first future element greater than current element


code:
def rename(coefs):
    # just a simple sketch for the polynomial representation.
    coefs_and_exps = reversed(list(enumerate(coefs)))
    str_repr = ' + '.join('{} * x**{}'.format(coef, i) for i, coef in coefs_and_exps)

    def decorator(func):
        func.__name__ = func.__qualname__ = str_repr
        return func

    return decorator

rawDescription: Which information is returned when I type the name of a function in the Python interpreter?


code:
grouper = indexer.copy()
grouper[indexer<20] = 0
grouper[indexer>20] = 1
grouper[(indexer<20) & (indexer.cumsum()>50)] = 2
grouper

rawDescription: Pandas group by time windows

description: Pandas group by time windows


code: filter(lambda word: all(f not in word for f in filters), wordlist)

rawDescription: Two Lists of strings: remove strings from list A that contain any string from list B?


code: somere.sub(lambda m: replacements[m.group()], text)

rawDescription: Can you pass a dictionary when replacing strings in Python?

description: Pass a dictionary when replacing strings in Python


code:
layout = go.Layout(
    barmode='group',
    annotations=annotations,
    xaxis=dict(nticks=13),
)

rawDescription: Adding annotations to a bar graph in Plotly


code: tk.Button(..., command=lambda route=prog.theroute: runprog(route))

rawDescription: Python tkinter button callback unexpected behaviour


code: vectors[i] = A

rawDescription: Trying to find all combinations of a 2-state vector (in python)


code:
import sys
st_run_time_1 = int(sys.argv[1]) * 60 # <---

print ("Station 1 : %s" % st_run_time_1)

rawDescription: Want to multiply, not repeat variable

description: Want to multiply, not repeat variable


code:
my_build_directory = '.'

echo_cmd = Command('always.echo', [],  "echo %s" % (Dir('.').abspath))
Alias('echo', echo_cmd)

rawDescription: Determining Build Directory from SConscript


code:
def merge_dicts(list_of_dicts):
    lookup = {}
    results = []
    for d in list_of_dicts:
        key = (d['type'], d['obj_id'])
        try: # it's easier to ask forgiveness than permission
            lookup[key]['actor'].append(d['actor'])
        except KeyError:
            val = {'type': d['type'],
                   'obj_id': d['obj_id'],
                   'actor': [d['actor']], # note, extra [] around value to make it a list
                   'extra_fields': d['extra_fields']}
            lookup[key] = val
            results.append(val)

    return results

rawDescription: Grouping data in a list of of dicts

description: Grouping data in a list of of dicts


rawDescription: good practice for string.partition in python

description: Good practice for string.partition in python


rawDescription: TypeError : 'NoneType' object not callable when using split in Python with BeautifulSoup


code:
def lemma(file):
    return list(file)

rawDescription: get a list in a function in python

description: Get a list in a function in python


rawDescription: Regular expression to find last group in python


code: myString = re.sub(r'\s*\(\w+\)\s*$', '', myString)

rawDescription: Strip a string if it contains a parnethesis


code: {{ user|hash:item }}

rawDescription: Django Templates and variable attributes


code:
import numpy as np
import pandas as pd

def speed(grp):
    dist = np.sqrt(grp['Latitude'].diff()**2 + grp['Longitude'].diff()**2)
    time = grp['Datetime'].diff() / np.timedelta64(1, 's')
    result = dist/time
    return result

df = pd.read_table('data', sep=';', parse_dates=[3])
grouped = df.groupby(['User_ID'], group_keys=False)
spd = grouped.apply(speed)
mask = spd > 1e-6
print(df.loc[mask])

rawDescription: pandas - apply time and space functions to groupby

description: Pandas - apply time and space functions to groupby


code:
import itertools

memostirling1 = {(0, 0): 1}
def stirling1(n, k):
    ans = memostirling1.get((n, k))
    if ans is None:
        if not 1 <= k <= n: return 0
        ans = (n - 1) * stirling1(n - 1, k) + stirling1(n - 1, k - 1)
        memostirling1[(n, k)] = ans
    return ans

def cyclecount(prefix):
    c = 0
    visited = [False] * len(prefix)
    for (i, j) in enumerate(prefix):
        while j < len(prefix) and not visited[j]:
            visited[j] = True
            if j == i:
                c += 1
                break
            j = prefix[j]
    return c

def extcount(n, dset, prefix):
    c = cyclecount(prefix)
    return sum(stirling1(n - len(prefix), n - d - c) for d in dset)

def unrank(n, dset, rnk):
    assert rnk >= 0
    choices = set(range(n))
    prefix = []
    while choices:
        for i in sorted(choices):
            prefix.append(i)
            count = extcount(n, dset, prefix)
            if rnk < count:
                choices.remove(i)
                break
            del prefix[-1]
            rnk -= count
        else:
            assert False
    return tuple(prefix)

def rank(n, dset, perm):
    assert n == len(perm)
    rnk = 0
    prefix = []
    choices = set(range(n))
    for j in perm:
        choices.remove(j)
        for i in sorted(choices):
            if i < j:
                prefix.append(i)
                rnk += extcount(n, dset, prefix)
                del prefix[-1]
        prefix.append(j)
    return rnk

def degree(perm):
    return len(perm) - cyclecount(perm)

def test(n, dset):
    for (rnk, perm) in enumerate(perm for perm in itertools.permutations(range(n)) if degree(perm) in dset):
        assert unrank(n, dset, rnk) == perm
        assert rank(n, dset, perm) == rnk

test(7, {2, 3, 5})

rawDescription: Get permutation with specified degree by index number


code:
ElementTree.parse("r.xml").getroot().findall('{http://example.com/z}row')
# => [<Element {http://example.com/z}row at 551ee0>, <Element {http://example.com/z}row at 551c60>, <Element {http://example.com/z}row at 551f08>, <Element {http://example.com/z}row at 551be8>, <Element {http://example.com/z}row at 551eb8>, <Element {http://example.com/z}row at 551f30>]

rawDescription: Getting rows from XML using XPath and Python


code: setitems(d, ('a', 'b', 'd'), mytuple)

rawDescription: Update values for multiple keys in python


code:
pos = {}
for key, value in graph.node.items():
    height = value['time']    # Time value as defined when adding the node `key`
    pos[key] = (50, -height)

rawDescription: Draw graph with time label on the nodes

description: Draw graph with time label on the nodes


code:
def window(length, size=2, start=0):
    while start + size <= length:
        yield slice(start, start + size)
        start += 1

rawDescription: How to compute rolling rank correlation using Pandas

description: Compute rolling rank correlation using Pandas


code:
sublists = [[d.get('type') for d in cell] for cell in df.misc]
cols = list(set([item for sublist in sublists for item in sublist]))
for c in cols:
    df[c] = 0

rawDescription: remove dictionary from list in pandas colum

description: Remove dictionary from list in pandas colum


code: "Hello %s" % ', '.join(map(str, my_args))

rawDescription: python - How to format variable number of arguments into a string?

description: Python - How to format variable number of arguments into a string


rawDescription: Convert Python strings into floats explicitly using the comma or the point as separators


code: game_surf.blit(screen, the_position)

rawDescription: Pygame, is there a way to make "screen layers"?


code:
idx, col = np.where(df.values)
n = df.values[idx, col]
idx2 = df.index.values[idx.repeat(n)]
col2 = df.columns.values[col.repeat(n)]
df2 = pd.DataFrame({"id":idx2, "type":col2})

rawDescription: Generating Rows from Values in Several Columns


code:
res = df.groupby(['category', 'sensitivity_level']).max()
x = res[res.val <= 30]

x
x.reset_index('category').sort_index(ascending=False).groupby(level='sensitivity_level').first()

rawDescription: Assign values to the groups of a groupby in pandas


code:
data = urllib2.urlopen(apacheLog)
for line in data:
    with open('C:\LogCopy.txt','a') as f: # probably need a double backslash
        f.write(line)

rawDescription: Parse Apache log with Python 2.7

description: Parse Apache log with Python 2.7


code:
from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Print list of strings to file with newline inserted after n items


code:
import requests
import csv

url = "http://stats.nba.com/stats/leaguedashplayerstats?DateFrom=&DateTo=&GameScope=&GameSegment=&LastNGames=15&LeagueID=00&Location=&MeasureType=Advanced&Month=0&OpponentTeamID=0&Outcome=&PaceAdjust=N&PerMode=Totals&Period=0&PlayerExperience=&PlayerPosition=&PlusMinus=N&Rank=N&Season=2015-16&SeasonSegment=&SeasonType=Regular+Season&StarterBench=&VsConference=&VsDivision="

data = requests.get(url)
entries = data.json()

with open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(entries['resultSets'][0]['headers'])
    csv_output.writerows(entries['resultSets'][0]['rowSet'])

rawDescription: Import CSV NBA Stats in Excel

description: Import CSV NBA Stats in Excel


code:
cam = Camera(0)
cam1 = Camera(1)
while True:
    i1 = cam.getImage()
    i2 = cam1.getImage()
    i1.sideBySide(i2).show()

rawDescription: Use simplecv to display videos in multiple windows


code:
class MyForm(forms.Form):
    to_select = forms.MultipleChoiceField(widget=forms.CheckboxInput, choices=[])

rawDescription: django form with select fields

description: Django form with select fields


code:
class A(object):
    def __init__( self, connections, sum ):
        self.connections = connections
        self.sum = sum

    def passToConnections( self, index ):
        self.connections[ index ].receive( self.sum )

    def receive( self, input ):
       self.sum += input

rawDescription: How to implement pointers in Python? (or any similar solution else)

description: Implement pointers in Python? (or any similar solution else)


code:
precomputed_flat = np.column_stack((svf.flatten(), shf.flatten()))
measured_flat = np.column_stack((VVmeasured.flatten(), HHmeasured.flatten()))
deltas = precomputed_flat - measured_flat[:, None, :]

rawDescription: more efficient way to calculate distance in numpy?

description: More efficient way to calculate distance in numpy


code:
import os
import time
import webapp2
import jinja2
import json
from google.appengine.api import taskqueue

template_dir = os.path.join(os.path.dirname(__file__), 'templates')
JINJA_ENV = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)

myresults = []
myProgressValue = 0 #range[ 0, 100 ]

class MainHandler(webapp2.RequestHandler):
    def get(self):
        template_values = {'myresults': myresults, 'progressScriptActive':False}
        counter_template = JINJA_ENV.get_template('counter.html')
        self.response.out.write(counter_template.render(template_values))

    def post(self):
        key = self.request.get('key')
        # Add the task to the default queue.
        taskqueue.add(url='/worker', params={'key': key})

        template_values = {'myresults': myresults, 'progressScriptActive':True}
        counter_template = JINJA_ENV.get_template('counter.html')
        self.response.out.write(counter_template.render(template_values))

class TaskWorker(webapp2.RequestHandler):
    def post(self):
        global myresults
        global myProgressValue

        key = self.request.get('key')
        for x in xrange(1, 11):
            time.sleep(1)
            res = x*int(key)
            myresults.append(str(res))
            myProgressValue = myProgressValue + 10

class ProgressWorker(webapp2.RequestHandler):
    def get(self):
        global myProgressValue

        json_result = json.dumps( myProgressValue )
        self.response.headers['Content-Type'] = 'application/json; charset=UTF-8'
        self.response.out.write(json_result)

application = webapp2.WSGIApplication(
    [
        ('/', MainHandler),
        ('/worker', TaskWorker),
        ('/progress', ProgressWorker)
    ], debug=True)

rawDescription: How to show progress for a running google app engine task queue task?

description: Show progress for a running google app engine task queue task


code:
def cyclic_letters(start='a'):
    i = string.lowercase.index(start)
    letts = string.lowercase[i:] + string.lowercase[:i]
    return itertools.cycle(letts)

rawDescription: How to create a letter progression for a variable in a loop in Python?

description: Create a letter progression for a variable in a loop in Python


code:
class myWidget(QtGui.QWidget):
    def __init__( self, parent=None):
        super(myWidget, self ).__init__( parent )
        self.button=QtGui.QPushButton("add entry")
        self.button.clicked.connect(self.on_click)

    def on_click(self):
        self.session.add_an_entry()

rawDescription: One button click fires signal multiple times instead of once


code: df

rawDescription: using python's stats.kendalltau function

description: Using python's stats.kendalltau function


code:
#inside your RideViewSet
def create(self, request, *args, **kwargs):
    request.data['driver'] = self.request.user.userprofile
    return super(RideViewSet, self).create(request, *args, **kwargs)

rawDescription: django - Many To Many relationship issue

description: Django - Many To Many relationship issue


code:
@app.before_request
def before():
    # todo with request
    # e.g. print request.headers
    pass

rawDescription: Debugging a request/response in Python flask


rawDescription: How to remove character from tuples in list?

description: Remove character from tuples in list


code:
res = []
for hour in range(11):
    for quarter in (0, 15, 30, 45):
        res.append(('{}:{:02}'.format(hour, quarter), '{:02}:{:02}'.format(hour, quarter)))

rawDescription: python range creation best practice

description: Python range creation best practice


code:
def decorate(f):
    def wrapper(*args, **kw):
        return f(*args, **kw) * 2
    return wrapper

rawDescription: Python __getattribute__ and wrapper of method


rawDescription: Restrict Dashboard Users Django-Oscar (Sandbox Gateway App)


code:
class A: m = lambda: None
A.m

rawDescription: Why is a method not identical to itself?

description: Why is a method not identical to itself


code:
import easygui
#Childs Litercay Game
#Charlotte Lowe 03/09/2015

def play(choices, answer, Score):
    """Check spelling."""
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices=choices)
    if PlayerAnswer == choices[answer]:
        Score += 1
        easygui.msgbox ("You're right! Your score is " + str(Score))
    else:
        easygui.msgbox ("Sorry Incorrect! Your score is " + str(Score))
    return Score
#    print(Score) #To check if programme is calculating score properly

tests = (
        (["Awesome","Awsome","Awesom"], 0),
        (["Becuse","Becus","Because"], 2),
        (["Morning","Moring","Morening"], 0),
        (["Beleave","Believe","Belive"], 1),
        (["Jewelry","Jewlery","Jewley"], 0),
        # Fill in the rest.....
    )

congrats = {
        10:"you got them all right ",
        9:"one away",
        8:"so close",
        7:"nearly there",
        6:"amlost made it",
        5:"half way there",
        4:"a little more pratice",
        3:"pratice makes perfect",
        2:"try again",
        1:"better luck next time",
        0:"better luck next time",
}

# Hello and instructions
playOn = easygui.buttonbox ("Hey there, are you ready to test your spelling?", choices = ["Yes"])
PlayerName = easygui.enterbox ("Before we begin, what's your name?")
easygui.msgbox ("Hi " + PlayerName +"! Here are the rules of the game.")
easygui.msgbox ("There will be 3 words you can choose from, 2 will be incorrect and 1 will be right.")
easygui.msgbox ("All you have to do is select the correctly spelt word.")
easygui.msgbox ("For every right word you pick you will earn a point! There are 10 questions in this quiz")
easygui.msgbox ("Let's begin!")

while True:
    Score = 0
    for choices, answer in tests:
        Score = play(choices, answer, Score)
        print(Score) #To check if programme is calculating score properly
    easygui.msgbox (congrats[Score] +" " + PlayerName+ "!")

    playOn = easygui.buttonbox ("Do you want to play again?", choices = ["Yes", "No"])
    if playOn == "No":
      easygui.msgbox ("Bye for now. Hope you'll play the game again soon!")
      break

rawDescription: Python program not looping/restarting

description: Python program not looping/restarting


code: import csv

rawDescription: Matching elements in a file to a nested dictionary python


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({'Days': [1, 4, 5, 9, 1, 4, 5, 9],
                   'IS_TRUE': [1, 1, 0, 1, 1, 1, 0, 1],
                   'person_num': [1, 1, 1, 1, 2, 2, 2, 2]})

def window(group):
    diff = np.subtract.outer(group.Days, group.Days)
    group['IS_TRUE_7day_WINDOW'] = np.dot((diff > 0) & (diff <= 7),
                                          group['IS_TRUE'])
    return group

f.groupby('person_num').apply(window)

rawDescription: Python Dataframe rolling_sum with numbers not date


code:
with open(file_name, 'a') as f:
    df.to_csv(f, header=False)

rawDescription: pandas DataFrame output end of csv

description: Pandas DataFrame output end of csv


code:
def rearrange_list(*my_lists):
    return [list(t) for t in zip(*my_lists)]

rawDescription: How do I take a list of lists and rearrange them in python

description: Take a list of lists and rearrange them in python


code:
...
def model():
    ...
    SS_a = [0]
    for _ in range(30):
        SS_a.append( SS_a[-1]+ speedfactor*(... - SS_a[-1])*Dt )
    ...
    plot(SS_a)
    show()

rawDescription: Accessing a value from an np.array from a while loop


rawDescription: Regex match till the first number occurs in a string in python


rawDescription: Match a term ending with digit

description: Match a term ending with digit


code:
label2field = {
    field_val['label']: field_key
    for field_key, field_val in myDict.items()
    if isinstance(field_val, dict)
}

rawDescription: python find a dictionary in a dictionary

description: Python find a dictionary in a dictionary


code:
class Entry(object):
    """
    Data structure used in Dijkstra's and Prim's algorithms.
    """

    def __init__(self):
        """
        (Algorithms.Entry) -> None
        Constructor.
        """
        self.known = False
        self.distance = sys.maxint
        self.predecessor = sys.maxint

rawDescription: Python - Dijkstra's Algorithm

description: Python - Dijkstra's Algorithm


code: s.enter(5, 0, addCount, (counter,))

rawDescription: What does action mean for scheduled events in python?


code:
Index1,Sample1,Sample2,Sample3
AAAA+XXXX,37,49,61
BBBB+YYYY,70,46,81
CCCC+ZZZZ,78,55,42

rawDescription: Python - merging data in two tables

description: Python - merging data in two tables


code:
class status_file(object):

   def __init__(self, str_statusfile):
       self.myConfig = ConfigParser.RawConfigParser()
       self.myConfig.optionxform = str
       ...

rawDescription: python RawConfigParser

description: Python RawConfigParser


rawDescription: all subsets of a set append Nonetype Error

description: All subsets of a set append Nonetype Error


code: raw_input = ("?")

rawDescription: "TypeError: 'str' object is not callable" with raw_input


code:
unzip = lambda l: [list(li) for li in zip(*l)]
array2d[ix_(unzip(nonzeroValidCoordinates))]

rawDescription: Efficient vector selection in numpy

description: Efficient vector selection in numpy


code:
s = "The wolf ate the chicken and ate the rooster"
re.sub(r'wolf.*?chicken|\bate\b', lambda m: "drank" if m.group()=="ate" else m.group(), s)

rawDescription: Python Regex - replace a string not located between two specific words


code:
for i, el in enumerate(child):
    child[i] = value_map[el]

rawDescription: Efficient way of re-numbering elements in an array


rawDescription: How to eliminate email formatting in received email?

description: Eliminate email formatting in received email


rawDescription: Introducing new variables using a given string


code:
s = subprocess.check_output('ipconfig') # calls ipconfig and sends output to s
for line in s.splitlines():
    if re.search("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", str(line)):
        # if line contains an IP address...
        print(line)

rawDescription: What Regex to use in this example

description: What Regex to use in this example


code: dfg.pivot_table(["incoming", "level"], "month", "goods")

rawDescription: Filling gaps for cumulative sum with Pandas


code:
from pyramid.threadlocal import get_current_registry
from pyramid.httpexceptions import HTTPFound

#Define some awesome student views here
@view_config(name='student')
def student(request):
    return HTTPFound('Foo!')

if get_current_registry().settings['teacher_enabled']:

    #Some awesome student and teacher views here
    @view_config(name='student_and_teacher')
    def student_and_teacher(request):
        return HTTPFound('Bar!')

rawDescription: Pyramid: modifying site content based on settings


code:
import lxml.etree
root = lxml.etree.fromstring('''<root><foo>bar</foo>baz</root>''')
root[0]
root[0].tail

rawDescription: Extracting text after tag in Python's ElementTree


rawDescription: Preserving line breaks when parsing with Scrapy in Python


code:
sam; USA; 23
john; England; 41
napoleon; France; 19
tanaka; Japan; 16
ming; China; 55

rawDescription: Can i integrate multiple lists in python?

description: Integrate multiple lists in python


code:
from pprint import pprint
pprint([[item] for c_list in lists for item in c_list])

rawDescription: Split lists within list

description: Split lists within list


rawDescription: Fermat Factorisation with Python

description: Fermat Factorisation with Python


code:
# -*- coding: utf-8 -*-
import wx
import sys
from wx.lib.pubsub import pub

class PanelOne(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour("blue")
        font = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        button1 = wx.Button(self, -1, label='Button1')
        button2 = wx.Button(self, -1, label='Button2')
        button1.SetFont(font)
        button2.SetFont(font)

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(button1, 1, wx.EXPAND)
        vbox.Add(button2, 1, wx.EXPAND)
        self.SetSizer(vbox)

class PanelTwo(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        textctrl = wx.TextCtrl(self, -1, pos=(200,120), style=wx.TE_PROCESS_ENTER|wx.CENTER)
        textctrl.Bind(wx.EVT_KEY_DOWN, self.OnEnter)

    def OnEnter(self, event):
        keycode = event.GetKeyCode()
        pub.sendMessage("CHANGE_TEXT",value="")
        if keycode == wx.WXK_RETURN or keycode == wx.WXK_NUMPAD_ENTER:
            """Here, I want to Print some message in PanelThree textctrl """
            pub.sendMessage("CHANGE_TEXT", value = "Enter Pressed")
        event.Skip()

class PanelThree(wx.Panel):
    """"""

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

        self.text = wx.TextCtrl(self, -1,
                            style = wx.TE_MULTILINE|wx.TE_READONLY|
                            wx.HSCROLL)
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.text, 1, wx.EXPAND)
        self.SetSizer(vbox)
        pub.subscribe(self.PrintMessage, "CHANGE_TEXT")

    def PrintMessage(self, value):
        self.text.SetValue(value)

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

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

        topSplitter = wx.SplitterWindow(self, size=(800,600))
        vSplitter = wx.SplitterWindow(topSplitter)

        self.panelOne = PanelOne(vSplitter)
        self.panelTwo = PanelTwo(vSplitter)
        self.panelThree = PanelThree(topSplitter)

        vSplitter.SplitVertically(self.panelOne, self.panelTwo)
        vSplitter.SetSashGravity(0.3)

        topSplitter.SplitHorizontally(vSplitter, self.panelThree)
        topSplitter.SetSashGravity(0.5)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(topSplitter, 1, wx.EXPAND)

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title='my program',
                          size=(800,600))
        panel = MainPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

rawDescription: wxpython How to change the values of widgets in other panel

description: Wxpython How to change the values of widgets in other panel


rawDescription: Invalid syntax in path when changing directory


rawDescription: Matrix multiplication in numpy

description: Matrix multiplication in numpy


code:
interval = someinterval
callbacks = [some, callbacks]
f = Foo(interval, callbacks)
f.start()
try:
    while True:
        time.sleep(0.1)
except KeyboardInterrupt:
    f.kill()
    raise

rawDescription: Interrupting a thread in Python with a KeyboardException in the main thread


code:
('SirGoose', 12) < ('Barbarian', 160)
('SirGoose', 12) < ('SirGoose', 160)

rawDescription: Python: Sort a list of objects based on their attributes


rawDescription: Python - Removing an element in list

description: Python - Removing an element in list


code: c.query("Select SourceName, Message from Win32_NTLogEvent where EventType =1 AND Logfile = \"Application\" AND TimeWritten<=\"20110421013749.000000-000\" ")

rawDescription: WMI Query Date Filter

description: WMI Query Date Filter


code:
class A(object):
    class B(object):
        pass

rawDescription: Scope of classes inside of functions and classes inside of a class in python


code:
df1 = s1.reset_index()
s1.reset_index()
df2 = s2.reset_index()
df1.merge(df2)

rawDescription: Combining two series in pandas along their index


code:
@static_init
class Foo:
    _PARAM = None

    def test(self):
        print(Foo._PARAM)

f = Foo()  #Exception: Foo.static_init() should be called.

rawDescription: Best way to make class variables initialization mandatory

description: Make class variables initialization mandatory


code:
s = strings(i for i in range(400))
s
s.a391

rawDescription: Any way to bypass namedtuple 255 arguments limitation?


code:
def dispatch(self, arg):
    bound = self.dispatch_map[arg].__get__(self, type(self))
    bound()

rawDescription: Dispatch a class method

description: Dispatch a class method


code:
import requests
from bs4 import BeautifulSoup
from urlparse import urljoin

def make_soup(url):
    thepage = requests.get(url)
    soupdata = BeautifulSoup(thepage.text, "html.parser")
    return soupdata

soup = make_soup("https://uwaterloo.ca")
i = 1
for img in soup.select('img[src]'):
    temp = img["src"]
    alt = img["alt"]
    if not alt:
        alt = i
        i += 1
    if temp.startswith("/"):
        temp = urljoin("https://uwaterloo.ca", temp)
    with open("{}{}.jpeg".format(alt, i), 'wb') as f:
        f.write(requests.get(temp).content)

rawDescription: following webscraping in python tutorial they use urllib im using requests help translating instructions

description: Following webscraping in python tutorial they use urllib im using requests help translating instructions


code: ListB += ['New_Field_Name']

rawDescription: Python Append to a list returns none

description: Python Append to a list returns none


code: return lambda t, y, dt: ( ... )

rawDescription: Understanding Python lambdas

description: Understanding Python lambdas


code: url(r'^$', views.index, name='index'),

rawDescription: Url pattern matching is confusing in django


rawDescription: Python regex find and replace inplace

description: Python regex find and replace inplace


code: result = [[x] * sequence.count(x) for x in set(sequence)]

rawDescription: Splitting a list into each unique element


rawDescription: Remove Outliers from dataset

description: Remove Outliers from dataset


code:
import model
c = model.client()
s = model.staff()
o = model.order()

rawDescription: python MySQL module class file name

description: Python MySQL module class file name


rawDescription: selecting elements from list according to their labels in the other list

description: Selecting elements from list according to their labels in the other list


code:
Bob
James
Harry

rawDescription: Tkinter option menu

description: Tkinter option menu


code:
import re

fn1='one.txt'
fn2='two.txt'
fn3='one-two.txt'

with open(fn1, 'w') as f1, open(fn2, 'w') as f2, open(fn3, 'w') as f3:
    for t in re.findall(r'(Cluster \d+)(.*?)(?=Cluster|$)', txt, re.S):
        one=t[1].count('one')
        two=t[1].count('two')
        out= '{} {} {}\n'.format(t[0], one, two)
        if one and two:
            f3.write(out)
        elif one:
            f1.write(out)
        elif two:
            f2.write(out)

rawDescription: Count duplicate records between two pattern


rawDescription: Storing large amount of boolean data in python


code:
import numpy as np
x = np.array([['a.','cd'],['ef','g.']])
x[np.char.find(x, '.') > -1]

rawDescription: finding element of numpy array that satisfies condition

description: Finding element of numpy array that satisfies condition


code: all('abc' in d for d in (d1, d2, d3, d4))

rawDescription: check to see if key exist in 2 dictionary in same line

description: Check to see if key exist in 2 dictionary in same line


rawDescription: Filter item from a dict and process a subset


code:
for row in rv:
    the_id = row['id']
    name = row['name']

rawDescription: How to store two different values returned from query into list data types to be used later(plpy python)

description: Store two different values returned from query into list data types to be used later(plpy python)


code:
record = {}

caller = inspect.getframeinfo(inspect.currentframe().f_back)[2]
record[caller] = record.get(caller, 0) + 1

rawDescription: Profiling in Python: Who called the function?


code:
from tkinter import filedialog
from tkinter.filedialog import asksaveasfilename

rawDescription: How to save text form a textbox (String and Int) in python 3.x tkinter

description: Save text form a textbox (String and Int) in python 3.x tkinter


code: df2 = pd.concat([df["id"], df["value"]*2], axis=1)

rawDescription: Python Pandas. Creating DataFrame with Series does not preserve dtype


code:
action = Action1.object.get(id=1)
event = action.get_event

rawDescription: Generic one-to-one relation in Django

description: Generic one-to-one relation in Django


code:
list_string = [ "aaa", "bb", "cc", "dd", "ee"]
str_len = 6
[[''.join(list_string[:i]), ''.join(list_string[i:])] for i in xrange(len(list_string)) if all(1 <= len(s) <= str_len for s in [''.join(list_string[:i]), ''.join(list_string[i:])])]

rawDescription: Python: List comprehension to create a list strings of n-size maximum from list of strings of random size


code: int_list[i], int_list[i+1] = int_list[i+1], int_list[i]

rawDescription: Sorting algorithm doesn't work

description: Sorting algorithm doesn't work


code:
def intersect(dicts):
    common_keys = reduce(set.intersection, map(set, dicts))
    num = float(len(dicts))
    return {k: sum(d[k] for d in dicts)/num for k in common_keys}

rawDescription: Intersect dictionaries with keys averaged


code:
class SomethingForm(forms.modelForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        self.fields['user'].initial = self.user.id
        super(SomethingForm, self).__init__(*args, **kwargs)

rawDescription: Django default value for form

description: Django default value for form


code: df_later = df.iloc[idx:].copy()

rawDescription: possible speed up of pandas apply

description: Possible speed up of pandas apply


code:
t=Timer("%s(%d)"%(func.__name__, cnt), "from __main__ import %s"%(func.__name__, ))
tms = t.repeat(repeat=5, number=1)

rawDescription: How to do profiling for this?

description: Do profiling for this


code:
if __name__ == '__main__':
    with open('input.txt') as istr:
        for test in parse_file(istr):
            print(test)

rawDescription: Python: Most optimal way to read file line by line


code:
Code
import urllib2

class BottomPipeResult :

    AGENT_ID   = "Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"
    BOTTOMPIPE_URL = "http://boilerpipe-web.appspot.com/extract?url={0}&extractor=LargestContentExtractor&output=text"
    _myBPPage = ""

    # scrape and get results from bottompipe
    def scrapeResult(self, theURL, user_agent=AGENT_ID) :
        request = urllib2.Request(self.BOTTOMPIPE_URL.format(theURL))
        if user_agent:
            request.add_header("User-Agent", user_agent)
            pagefile = urllib2.urlopen(request)
            realurl = pagefile.geturl()
            f = pagefile
            self._myBPPAge = f.read()
        return(self._myBPPAge)

bpr = BottomPipeResult()
myLinkResult = 'http://result.com'

f = open('out.html', 'a')
f.write(bpr.scrapeResult(myLinkResult))
f.close()

rawDescription: Python: How to keep breaks reading from a txt file when printing to html


code:
from allauth.account.adapter import DefaultAccountAdapter

class YourAccountAdapter(DefaultAccountAdapter):

    def clean_username(self, username, shallow=False):
        # -----------------------
        # do our validation first
        # -----------------------

        # character exists with username?
        if (YourModel.objects.filter(loginname__iexact=str(username))):

            # let's poke this a bit
            char = YourModel.objects.get(loginname__iexact=str(username))

            # is it a protected character name?
            if char.protected:
                raise ValidationError("Name belongs to protected character, please contact site admin to claim")
            else:
                raise ValidationError("Character with name exists, cannot use as a login name")

        # -----------------------------------------
        # if that went okay, call and return parent
        # -----------------------------------------
        return super(YourAccountAdapter, self).clean_username(username, shallow)

rawDescription: Django All-Auth - Validate against linked object on account creation?


rawDescription: Python split string in moving window

description: Python split string in moving window


code:
x = dict(_id=0, sub=dict(a=1, b=2))
x.update(x.pop('sub'))
x

rawDescription: Chained Method Calls in Python with dict


code:
ld = [{'language': 'de', 'suggestion': 'fressen', 'comment': 'for animals'},
{'language': 'de', 'suggestion': 'essen', 'comment': ''},
{'language': 'fr', 'suggestion': 'manger', 'comment': ''},
{'language': 'fr', 'suggestion': 'bouffer', 'comment': 'slang'}]

langs = {i['language'] for i in ld}

d = []

for lang in langs:
    d.append({"language": lang})
    for key in ld[0].keys() - ["language"]:
        d[-1][key] = [i[key] for i in ld if i["language"] == lang]

print(d)

rawDescription: Transform dictionaries to a list of dictionaries according to their values


code:
def reverse_binary_search(a, x, lo=0, hi=None):
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)/2
        if x > a[mid][4]:
            hi = mid
        else:
            lo = mid+1
    return lo

my_list = [[3,0.99,1], [2,0.98,54], [10,.85,4], [1,0.7,10], [12,0.69,31], [12,0.65,43], [1.56,0]]
threshold = [0.97, 0.90, 0.83, 0.6]

index_list = []
last_index = 0
for t in threshold:
    last_index = reverse_binary_search(my_list, t, last_index) # next time start search from last_index
    index_list.append(last_index)

rawDescription: Python: index of fist element smaller than threshold in reverse sorted list


code:
objects = sc.parallelize([
    {"name": "foo", "x": 1}, {"name": "foo", "y": 3},
    {"name": "bar", "z": 4}
]).map(lambda x: Foobar(**x))

rawDescription: How to return a dictionary in parallel processing in spark?

description: Return a dictionary in parallel processing in spark


code:
import re
with open('jokes.txt', 'r+') as original_file:
    modfile = original_file.read()
    midfile = re.sub(r"\d+\. |(?<!^)\n", "", modfile, flags=re.MULTILINE)
    original_file.seek(0)
    original_file.truncate()
    original_file.write(modfile)

rawDescription: How to modify a text file using Python

description: Modify a text file using Python


code:
import scipy.stats

class rvc(scipy.stats.rv_continuous):
    def __init__(self, freqs):
        super().__init__(a=0,b=359.9999)
        self.WindDir = [0.,45.,90.,135.,180.,225.,270.,315.,360.]
        self.Freqs = freqs

    def _cdf(self, x):
        return [self.do_cdf(i) for i in x]

    def do_cdf(self, x):
        if x < 0: return 0.0
        if x >= 360: return 1.0
        v = 0.0
        for i in range(9):
            if x >= self.WindDir[i]:
                v += self.Freqs[i]
            else:
                v += (self.Freqs[i]-self.Freqs[i-1])*(x-self.WindDir[i-1])/45.
                break
        return v

rv = rvc([0.01,0.01, 0.01, 0.01, 0.01, 0.01, 0.92, 0.01, 0.01])
print(rv.rvs(size=100))

rawDescription: Create a continuous distribution in python


code:
def show_table(table):
    return ''.join(['| {} |\n'.format(' | '.join(row)) for row in table])

rawDescription: function def show_table create a and return a formatted string representing the 2D table

description: Function def show_table create a and return a formatted string representing the 2D table


code: mask = theano.sparse.neq(A_sparse, theano.sparse.sp_zeros_like(A_sparse))

rawDescription: Theano: Operate on nonzero elements of sparse matrix


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

def maxwellian_transform_image(image):

    from skimage.transform import PiecewiseAffineTransform, warp

    rows, cols = image.shape[0], image.shape[1]

    src_cols = np.linspace(0, cols, 20)
    src_rows = np.linspace(0, rows, 10)
    src_rows, src_cols = np.meshgrid(src_rows, src_cols)
    src = np.dstack([src_cols.flat, src_rows.flat])[0]

    # add maxwellian to row coordinates
    x = np.linspace(0, 3., src.shape[0])
    dst_rows = src[:, 1] + (np.sqrt(2/np.pi)*x**2 * np.exp(-x**2/2)) * 50
    dst_cols = src[:, 0]
    dst_rows *= 1.5
    dst_rows -= 1.0 * 50
    dst = np.vstack([dst_cols, dst_rows]).T

    tform = PiecewiseAffineTransform()
    tform.estimate(src, dst)

    out_rows = image.shape[0] - 1.5 * 50
    out_cols = cols
    out = warp(image, tform, output_shape=(out_rows, out_cols))

    return out

#Create the new figure
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

#Plot page from a book
im = plt.imread("./book_page.jpg")
implot = ax.imshow(im, origin='lower')

# Plot and save graph as image, will need some manipulation of location
temp, at = plt.subplots()
margin = im.shape[0]*0.1
x = np.linspace(margin,im.shape[0]/2.,40)
y = im.shape[1]/3. + 0.1*im.shape[1]*np.sin(12.*np.pi*x/im.shape[0])
at.plot(x,y,'-ro',alpha=0.5)
temp.savefig("lineplot.png",transparent=True)

#Read in plot as an image and apply transform
plot = plt.imread("./lineplot.png")
out = maxwellian_transform_image(plot)
ax.imshow(out, extent=[0,im.shape[1],0,im.shape[0]])

plt.show()

rawDescription: matplotlib: jpg image special effect/transformation as if its on a page of an open book

description: Matplotlib: jpg image special effect/transformation as if its on a page of an open book


rawDescription: Math operations from string

description: Math operations from string


code:
def pension ():
    income = int(input("What is your annual income?"))
    pension_contribution = int(input("What is your monthly pension contribution?"))
    if pension_contribution > ((income//12) * .075):
        print ("Your pension contribution is too high. Monthly pension contributions may not exceed 7.5% of your gross monthly income")

    else:
        print("Your annual pension contribution is R", pension_contribution * 12)

pension() #still have to call function

rawDescription: Use user input within as input in a function Python


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

    def __str__(self):
        return '-'.join([str(thing) for thing in self.things.all()])

rawDescription: Django many-to-many return list of releated objects


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

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA

data = np.ones((25, 111))

specFig = plt.figure()
specAx = host_subplot(111, axes_class=AA.Axes)

specAx.set_xlim([0, data.shape[1]])
specAx.imshow(data, origin="lower")

#Add parasite axis
newax = specAx.get_grid_helper().new_fixed_axis
specAx.axis["top"] = newax(loc="top", axes=specAx)

plt.show()

rawDescription: Matplotlib - Keep aspect ratio when using multiple axes


code:
sorted_list = sorted(my_list)
return sorted_list == range(sorted_list[0],sorted_list[-1]+1)

rawDescription: Python: find out whether a list of integers is coherent


code: x = next(s for s in leest if re.search("th.*e", s))

rawDescription: More line-efficient way to use re.search to match string in a list?


rawDescription: numpy 2d array operation, keeping certain positions

description: Numpy 2d array operation, keeping certain positions


code: df[df.Category == 'Facebook'].groupby(['Category', 'Date']).Date.count()

rawDescription: Counting frequency of occurrence by month-year using python panda


code: [[float(element[1])] for element in arrResult]

rawDescription: Python sqlite => reportlab data what is difference between [1,2,3] and [[1],[2],[3]]


code:
class MainHandler(webapp2.RequestHandler):
  @decorator.oauth_required
  def get(self):
    http = decorator.http()

    self.response.write(http.request('https://www.google.com/m8/feeds/contacts/default/full')[1])
    self.response.write(http.request('https://www.googleapis.com/calendar/v3/users/me/calendarList')[1])

rawDescription: Unifying OAuth handling between gdata and newer Google APIs


code:
import collections
class module_class(object):
    def __init__(self, submods={}):
        self.name = "name"
        self.submods = collections.OrderedDict(submods)

rawDescription: Check if dictionary exist within dictionary and if so change it


code:
from PIL import Image, ImageOps, ImageDraw

size = (128, 128)
mask = Image.new('L', size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + size, fill=255)
im = Image.open('image.jpg')
output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.putalpha(mask)
output.save('output.png')

rawDescription: How do I generate circular thumbnails with PIL?

description: Generate circular thumbnails with PIL


code:
#!/usr/bin/env python
import os
import time

os.environ['TZ'] = 'right/UTC' # TAI scale with 1970-01-01 00:00:10 (TAI) epoch
time.tzset() # Unix

from datetime import datetime, timedelta

gps_timestamp = 1092121243.0 # input
gps_epoch_as_gps = datetime(1980, 1, 6)
# by definition
gps_time_as_gps = gps_epoch_as_gps + timedelta(seconds=gps_timestamp)
gps_time_as_tai = gps_time_as_gps + timedelta(seconds=19) # constant offset
tai_epoch_as_tai = datetime(1970, 1, 1, 0, 0, 10)
# by definition
tai_timestamp = (gps_time_as_tai - tai_epoch_as_tai).total_seconds()
print(datetime.utcfromtimestamp(tai_timestamp)) # "right" timezone is in effect!

rawDescription: How to get current date and time from GPS unsegment time in python

description: Get current date and time from GPS unsegment time in python


rawDescription: Python: Unicode output to csv using unicodecsv


code:
source = self.open(member, pwd=pwd)
target = file(targetpath, "wb")
shutil.copyfileobj(source, target)
source.close()
target.close()

rawDescription: Extract ZipFile using Python, display Progress Percentage?