code:
from tkinter.filename import askopenfile as ask
ofile = ask()  # you might want to pass a beginning directory

rawDescription: How to open a text file with Python GUI?

description: Open a text file with Python GUI


code:
import win32com.client
xlApp = win32com.client.Dispatch('Excel.Application')

xlBook = xlApp.Workbooks.Add()

xlSheet = xlBook.Sheets(1)
xlSheet.Name = "Algoritmos de Busqueda"
xlSheet.Cells(1,1).Value="Secuencial"
xlSheet.Cells(2,1).Value="Binaria"
xlSheet.Cells(1,2).Value="32"
xlSheet.Cells(2,2).Value="32"

chart = xlApp.Charts.Add()
chart.Name= "Grafico "+xlSheet.Name
series = chart.SeriesCollection(1)
series.XValues= xlSheet.Range("A1:A2")
series.Values= xlSheet.Range("B1:B2")
series.Name= "Algoritmos"
chart.Axes()[0].HasMajorGridlines = True

rawDescription: Python - Extra Excel chart series with win32com


code:
def generate_times_opt(rate_function,max_t,delta):
    t = numpy.arange(delta,max_t, delta)
    avg_rate = (rate_function(t) + rate_function(t + delta)) / 2.0
    avg_prob = 1 - numpy.exp(-avg_rate * delta / 1000.0)
    rand_throws = numpy.random.uniform(size=t.shape[0])

    return t[avg_prob >= rand_throws].tolist()

rawDescription: How to sample inhomogeneous Poisson processes in Python faster than this?

description: Sample inhomogeneous Poisson processes in Python faster than this


code:
class C(B, A): # change order of A and B
    def __init__(self):
        pass

rawDescription: How to invoke __repr__ of parent class?

description: Invoke __repr__ of parent class


code:
x_new = (  (x - cx) * cos(θ) + (y - cy) * sin(θ) ) + cx
y_new = ( -(x - cx) * sin(θ) + (y - cy) * cos(θ) ) + cy

rawDescription: Rotate line around center point given two vertices


code: isinstance(o, str)

rawDescription: What's the canonical way to check for type in python?


code: [target.find('name').text for target in top]

rawDescription: Python elementree having hard time extracting data


code: getargspec(pfunc)

rawDescription: Python function vs partial - Scipy doesn't like partials


code:
x = {}

for row in file_map:
   x[row_key] = {} # derive this from something.
   for idx, col in enumerate(row):
       x[row_key][idx] = col

rawDescription: How do you create nested dict in Python?

description: Create nested dict in Python


code:
from datetime import datetime
datetime.strptime("2012/04/08 13:31:00 UTC", "%Y/%m/%d %H:%M:%S %Z")

rawDescription: Converting a string to a datetime

description: Converting a string to a datetime


rawDescription: Set Python27 Google AppEngine default encoding for entire app


code: ['my file name', 'myfilename']

rawDescription: Extracting part of a string with irregular delimiters in python


code:
import json

s = '{"1": "\\"s\\u00f3 pra fude", "None": null, "Note": [], "N\\u00e3o reclama": [], "12.2": null, "666": {}, "merda 2": [1, 2, 3], "merda 1": {}, "T\\u00e9dio da nisso": {"Note": null}, "Fudeu": {"1": null, "2": 1, "3": 2}, "Quero $$$": []}'

d = json.loads(s)
result = dict((k, v) for k, v in d.iteritems() if not v or k == "Note")

rawDescription: How to clear empty keys in a dictionary with subdictionaries

description: Clear empty keys in a dictionary with subdictionaries


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

# fill grid
x = np.linspace(1,10,10)
y = np.linspace(1,10,10)

X, Y = np.meshgrid(x,y)
Z = np.abs(np.cos(X**2 - Y**2) * X**2 * Y)

# plot
f, ax = plt.subplots()
p = plt.pcolormesh(X, Y, Z, norm=LogNorm(), vmin=1e-2, vmax=1e2)
cb = plt.colorbar(p, ax=ax, orientation='horizontal', aspect=10)

cb.ax.minorticks_on()

plt.show()

rawDescription: Minor ticks in matplotlib's colorbar

description: Minor ticks in matplotlib's colorbar


rawDescription: REGEX python find previous string

description: REGEX python find previous string


code:
def main():
    from google.appengine.dist import use_library
    use_library('django', '1.2')

    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

    from django.conf import settings
    views_path = os.path.join(os.path.dirname(__file__), 'app','views')
    settings.TEMPLATE_LOADERS = (('gaemvclib.mvctemplateloader.MvcTemplateLoader', views_path), 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader')

rawDescription: TemplateDoesNotExist on python app-engine django 1.2 while template rendering relative paths


code:
from urllib.request import urlopen
import json

URLs = [
    # Some URLs that return JSON objects
    'http://httpbin.org/ip',
    'http://httpbin.org/user-agent',
    'http://httpbin.org/headers'
]

json_list = []
for url in URLs:
    resp = urlopen(url)
    resp = resp.read().decode(resp.headers.get_content_charset() or 'ascii')
    json_list.append(json.loads(resp))
with open('result.json', 'w') as fp:
    json.dump(json_list, fp, indent=2)

rawDescription: Python 3 - Parse JSON from multiple API requests into a list and output to a file


code: df_dup = df.groupby(axis=1, level=0).apply(lambda x: x.duplicated())

rawDescription: openpyxl Python Iterating Through Large Data List

description: Openpyxl Python Iterating Through Large Data List


code:
from ctypes import cdll, c_size_t, c_uint32
from numpy import uint32
from numpy.ctypeslib import ndpointer

__all__ = ['integer_sort']

# In spreadsort.cpp: void spreadsort(std::uint32_t* begin,  std::size_t len)
lib = cdll.LoadLibrary('./spreadsort.so')
sort = lib.spreadsort
sort.restype = None
sort.argtypes = [ndpointer(c_uint32, flags='C_CONTIGUOUS'), c_size_t]

def integer_sort(arr):
    assert arr.dtype == uint32, 'Expected uint32, got {}'.format(arr.dtype)
    sort(arr, arr.size)

rawDescription: How to sort an array of integers faster than quicksort?

description: Sort an array of integers faster than quicksort


code: import numpy as np

rawDescription: Python: How to perform division according to its representation?


code:
{'children': [{'children': [{'DATA': '123', 'name': 'AUTAUGA COUNTY'},
                            {'DATA': '321', 'name': 'BALDWIN COUNTY'}],
               'name': 'ALABAMA'},
              {'children': [{'DATA': '456', 'name': 'ALEUTIANS EAST BOROU'}],
               'name': 'ALASKA'}],
 'name': 'USA'}

rawDescription: Refactor a list of JSON objects to a nested list


code:
word = input("Input a word: ")

values = {"a":5,"e":4,"i":3,"o":2,"u":1}
print(sum(values.get(ch,0) for ch in word))

rawDescription: Shortening down this specific code

description: Shortening down this specific code


code:
my_arrays = [array1, array2]
my_lists = [my_list1, my_list2]
main1[np.logical_and(*(np.in1d(array, lst) for array, lst in zip(my_arrays, my_lists)))]

rawDescription: Slice numpy array based on x number of other arrays


code:
class Trend(object):

    def __init__(self, user_name):
        self.user_name = user_name

trend = Trend(sys.argv[1])

rawDescription: importing a class from another python file issue

description: Importing a class from another python file issue


rawDescription: Read into a bytearray at an offset?

description: Read into a bytearray at an offset


code:
from rq import Queue, get_current_job
from redis import StrictRedis

conn = StrictRedis()
q = Queue('high', connection=conn)

def first_job():
    return 'result of the first job'

def second_job():
    current_job = get_current_job(conn)
    first_job_id = current_job.dependencies[0].id
    first_job_result = q.fetch_job(first_job_id).result
    assert first_job_result == 'result of the first job'

rawDescription: Passing results to depending on job - python rq


rawDescription: Python : Sort file by arbitrary column, where column contains time values


code: C = numpy.correlate(v1,v1,'full') + numpy.correlate(v2,v2,'full')

rawDescription: Correlating vector data with numpy

description: Correlating vector data with numpy


code:
import unittest
from mock import patch
import machines

@patch('machines.increment', increment_mock)
@patch('machines.decrement', decrement_mock)
class TestMachine(unittest.TestCase):
    def test_mult(self):
        '''The bound method of Calculator is replaced with MockCalculator'''
        machine = machines.Machine(MockCalculator(3))
        self.assertEqual(machine.mult(3), 18)

    def test_incr(self):
        '''increment() is replaced with increment_mock()'''
        machine = machines.Machine(MockCalculator(3))
        self.assertEqual(machine.incr(3), 5)

    def test_decr(self):
        '''decrement() is replaced with decrement_mock()'''
        machine = machines.Machine(MockCalculator(3))
        self.assertEqual(machine.decr(3), 1)

rawDescription: How to mock Python static methods and class methods

description: Mock Python static methods and class methods


code:
from itertools import product
word = "L0B7B0B5"
subs = product("68", repeat=word.count("B"))
list(subs)

rawDescription: Create strings with all possible combinations


rawDescription: Slicing a matrix with Python

description: Slicing a matrix with Python


rawDescription: Building a histogram from MongoDB with Pymongo


code: ['gamma', 'delta']

rawDescription: Python: How to iterate over specific columns in rows in text file


rawDescription: Merge CSV Files in Python with Different file names


rawDescription: Scipy's leastsq with complex numbers

description: Scipy's leastsq with complex numbers


code:
lst = list(range(20))
for start in range(5, len(lst), 10):
    lst[start:start+5] = lst[start+4:start-1:-1]

rawDescription: Python3 Make a list that increments for a certain amount, decrements for a certain amount


rawDescription: Sorting within a Pandas group without changing group position


code:
r = range(5)
r.__next__
ri = iter(r)
ri.__next__

rawDescription: how to check if an iterable allows more than one pass?

description: Check if an iterable allows more than one pass


code: os.unlink('grep.tmp')  # Or os.remove; same thing, different names

rawDescription: strange output when using flags in python

description: Strange output when using flags in python


rawDescription: Interpreting Python code for partial derivatives of multi-variable function


code:
input = open('fishnet.json','r')
input_list = input.readlines()
output = open('updated.json','w')
for line in input_list:
  updated = re.sub(r'"Col_Row": "(.*?) - (.*?)",', repl, line)
  output.write(updated)
output.close()
input.close()

rawDescription: How can I search & replace numbers with numbers+1000

description: Search & replace numbers with numbers+1000


code: i

rawDescription: Can anybody explain me the numpy.indices()?


code:
import numpy as np

def f(r):
    return 0.1 + 1 / (2 * r ** 2) - 2 / (3 * np.sqrt(r ** 3))

r = np.linspace(0.6, 3, 1000)
plot(r, f(r))

rawDescription: python numerically solving an equation with no sign change between the upper and lower bound

description: Python numerically solving an equation with no sign change between the upper and lower bound


code: wrapped = ["<p>{}</p>".format(name) for name in names]

rawDescription: Write pure and functional code in Python using the concept higher-order functions like in JavaScript


code: Matrix_files = [ 'fileA.MAT', 'file1.MAT', 'no pattern to these names.MAT' ]

rawDescription: Load many files into one array - Python

description: Load many files into one array - Python


code:
def votes_agree(member_a, member_b, threshold):
    # Find the union of issues they voted on...
    issues = set(member_a.keys()).union(member_b.keys())
    # See how many of these they voted the same way on (we use a placeholder
    # if one member did not vote on the issue, so that they automatically
    # disagree) and compare the fraction of agreeing votes to the threshold.
    # There is a little hack in here: `True` is 1 in a numeric context, and
    # `False` is zero, so we can add up the boolean results directly.
    return sum(
        member_a.get(issue, None) == member_b.get(issue, None)
        for issue in issues
    ) / float(len(issues)) >= threshold

rawDescription: Create edgelist from a python dictionary


rawDescription: Numpy remove a dimension from np array

description: Numpy remove a dimension from np array


code:
from scipy.spatial.distance import pdist
pdist(V)

rawDescription: Tetrahedron side lengths from vertices (numpy)


code:
def get_parallel_paths(G):
    colpaths = []
    for i in G.nodes_iter():
        for j in G.nodes_iter():
            if i == j:
                continue
            nbp = nobranchpaths(G, i, j)
            if len(nbp) > 1:
                colpaths += [nbp]
    return colpaths

def nobranchpaths(G, u, v):
    paths = []
    for p in nx.all_simple_paths(G, u, v):
        if len(p) == 2 or max(G.degree(i) for i in p[1:-1]) == 2:
            paths += [p]
    return paths

rawDescription: Get list of parallel paths in a directed graph


code:
dfs = [output_1, output_2, ...]
df_length = sum(x.shape[0] for x in dfs)

rawDescription: How to dynamically refer to dataframes in a for loop in Python

description: Dynamically refer to dataframes in a for loop in Python


code:
output = {'output': [
    {'status': status, 'data': diseases}
    for status, diseases in states.iteritems()]}

rawDescription: Merging 2 dicts with common elements in python


code: dict((x.pk, x) for x in Blog.objects.all())

rawDescription: how to get dict of model objects keyed by field

description: Get dict of model objects keyed by field


rawDescription: Repeating elements in list Python

description: Repeating elements in list Python


code:
for gram in range(nGram):
   lst.append(getCollection(gram))

rawDescription: How to create list of collections.Counter?

description: Create list of collections.Counter


code:
# NT provides delete-on-close as a primitive, so we don't need
# the wrapper to do anything special.  We still use it so that
# file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
if _os.name != 'nt':
    # Cache the unlinker so we don't get spurious errors at
    # shutdown when the module-level "os" is None'd out.  Note
    # that this must be referenced as self.unlink, because the
    # name TemporaryFileWrapper may also get None'd out before
    # __del__ is called.
    unlink = _os.unlink

rawDescription: Why does Python's tempfile method unlink() require a filename?


rawDescription: Writing camera matrix into xml/yaml file


code: np.vstack((unq, unq_avg))

rawDescription: average of all rows corresponing to all unique rows

description: Average of all rows corresponing to all unique rows


code:
q = Qux()
q.foo(x=1, y=2, z=3)
vars(q)
q.foo(die='invalid')

q.foo(x=1, y=2, z=3, die='invalid')

rawDescription: Python Multiple Inheritance: Argument passing (**kwargs) and super()


code:
from IPython.core.display import Javascript, display
display(Javascript("""
    $('head').append(
        "<style type='text/css'>tr.odd{background-color: #def}</style>"
    );
"""))

rawDescription: "Zebra Tables" in IPython Notebook?

description: "Zebra Tables" in IPython Notebook


rawDescription: local maximum in lists within list

description: Local maximum in lists within list


code:
while True:
    a_piece = pickle.load(sys.stdin)
    more_data = transform1( a_piece )
    pickle.dump( NewNamedTuple( piece, more_data ) )

rawDescription: Sharing data between processes in Python


code: print(*[randint(10, 110) for _ in range(20)])

rawDescription: Python Random Function without using random module


code:
''.join(chr(c + 96) for c in encrypted)
'jdqnn'

rawDescription: Adding certain numbers together in a string/list then turning then into letters


rawDescription: Python - Convert time to different time zone with am/pm


code: x = np.linspace(-np.pi/4, np.pi/4, npoints)

rawDescription: Plotted arc: anomaly in the plot

description: Plotted arc: anomaly in the plot


code:
type(t)
type(t) is datetime.datetime

rawDescription: about python datetime type

description: About python datetime type


rawDescription: The fastest way to find common elements at the beginning of 2 python lists?


rawDescription: In python, how can I can I code this sense: "when true for all members of the list, do this." [Solved]


code:
from collections import Counter
from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def port_table(ports):
    d = Counter()
    for portseq in ports:
        for subset in powerset(sorted(portseq)):
            if subset:
                d[subset] += 1
    return d

rawDescription: Counting unique intersecting sets from a list


rawDescription: replace multiple occurrences of any special character by one in python

description: Replace multiple occurrences of any special character by one in python


code:
CS.collections[0].set_linewidth(4)           # the dark blue line
CS.collections[2].set_linewidth(5)           # the cyan line, zero level
CS.collections[2].set_linestyle('dashed')
CS.collections[3].set_linewidth(7)           # the red line
CS.collections[3].set_color('red')
CS.collections[3].set_linestyle('dotted')

type(CS.collections[0])
# matplotlib.collections.LineCollection

rawDescription: highlight single contour line

description: Highlight single contour line


code: soup.select('div ul.main li p')[1].text

rawDescription: Python : Extract HTML content

description: Python : Extract HTML content


code:
M1=M.tocsr()
M1.data
M1.indices
M1.indptr
np.nonzero(M.A)

rawDescription: is there something like coo_matrix but for sparse vectors?

description: Is there something like coo_matrix but for sparse vectors


code:
from pandas import DataFrame
df = DataFrame([[1,11,2012],[1,10,2012]], columns=['day','month','year'])
df
df.apply(lambda row: str(row['day'])+'/'+str(row['month'])+'/'+str(row['year']), axis=1)

rawDescription: Combining rows in DataFrame

description: Combining rows in DataFrame


code:
for line in sorted(open('file.txt')):
    print(line, end='')

rawDescription: Display a .txt file in alphabetical order in python


code: test_obj = t[t_type]['obj']()

rawDescription: How to force new instance of SQLAlchemy class

description: Force new instance of SQLAlchemy class


code:
import re, urlparse

find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)')

def fix_urls(document, base_url):
    ret = []
    last_end = 0
    for match in find_re.finditer(document):
        url = match.group(1)
        if url[0] in "\"'":
            url = url.strip(url[0])
        parsed = urlparse.urlparse(url)
        if parsed.scheme == parsed.netloc == '': #relative to domain
            url = urlparse.urljoin(base_url, url)
            ret.append(document[last_end:match.start(1)])
            ret.append('"%s"' % (url,))
            last_end = match.end(1)
    ret.append(document[last_end:])
    return ''.join(ret)

rawDescription: How to find a relative URL and translate it to an absolute URL in Python

description: Find a relative URL and translate it to an absolute URL in Python


code:
p1=re.compile(r'\b[a-z]+_coding\b')
p2=re.compile(r'\bexon\b')
li=[p.search(line) for p in [p1, p2]]
li
all(e for e in li)

rawDescription: use regular expression in python to find two strings in line

description: Use regular expression in python to find two strings in line


code: id_find = input('Enter the unique student ID: ')

rawDescription: Referring to a dictionary using an input


code:
im = np.array(Image.open('Mean.png').convert('L'), dtype=float)

# normalize the input, in place
im -= inputMin
im /= inputMax

# Convert the 0-1 range into a value in the right range.
im *= outputMax - outputMin
im += outputMin

rawDescription: Convert all array elements to a range in Python


code: sumdict["Streak"] = "Wins", lambda x: (x > 5).sum()

rawDescription: Summarizing Dataframes with ambiguous columns with apply function


code:
b <= objtime # Finished before (or on) the objective time
b > objtime  # Finished after the objective time

rawDescription: How would I format inputted minutes/seconds into datetime.now() format?


code:
while True:
    store = shelve.open('store',writeback = True)
    Item = input('Enter an item: ').capitalize() #I prefer str(raw_input('Question '))
    if not Item or Item == 'Break':
        break
    store['item_quantity'][Item] = int(input(('Enter the number of {0} available in the store: ').format(Item)))
    store['item_rate'][Item] = float(input(('Enter the rate of {0}: ').format(Item)))
    store.sync()
    store.close()

rawDescription: How to *append* a text to a database file opened with shelve?


rawDescription: Disable the underlying window when a popup is created in Python TKinter


code: import os

rawDescription: How to create files to and open files from a sub directory in Python?

description: Create files to and open files from a sub directory in Python


code:
import struct
x=(65,222,102,102)
struct.unpack('>L',bytes(x))[0]

rawDescription: Little bit complicated hex to decimal

description: Little bit complicated hex to decimal


code:
def add_many_handlers(logger, handler_list):
    for handler in handler_list:
        logger.addHandler(handler)

rawDescription: Is there an easy way to add handlers to the logger object?


code:
def all_dicts(a_dict):
    yield a_dict
    for key in a_dict:
        if isinstance(a_dict[key], dict):
            yield from all_dicts(a_dict[key])

rawDescription: Find deeper in dictionary or list

description: Find deeper in dictionary or list


code:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)

rawDescription: python import path: packages with the same name in different folders

description: Python import path: packages with the same name in different folders


code:
class Mythread(threading.Thread):
    def __init__(self, params):
        threading.Thread.__init__(self)
        self.h = i
        self.params = params
    def run(self):
        time.sleep(1)
        # do expensive work, your time taking script

rawDescription: Flask: Execute time taking python script and direct the user to another page


code:
from datetime import date, timedelta
def prev_weekday(adate):
    adate -= timedelta(days=1)
    while adate.weekday() > 4: # Mon-Fri are 0-4
        adate -= timedelta(days=1)
    return adate

rawDescription: Previous weekday in Python

description: Previous weekday in Python


rawDescription: Apply similar function to multilevel pandas dataframe


fields: a b c d

fields: e f g h

rawDescription: GAE load data into datastore without using CSV


rawDescription: how to groupby a DataFrame by index

description: Groupby a DataFrame by index


code:
def functionthatisuseless(n):
    n + 7

print(functionthatisuseless(8))        # should output None

rawDescription: What does return do? Nothing is ever returned


code:
cards_count = Card.query()
for value in q:
  q = q.filter(tags_value==value)
cards_count = q.count()

rawDescription: How does it make query ndb.AND condition more smart


code:
a = np.arange(10, dtype='float')
b = a.copy()
a /= 2.0
a
b = b / 2.0
b

rawDescription: In python the result of a /= 2.0 and a = a / 2.0 are not the same


rawDescription: Displaying a list of items vertically in a table instead of horizonally


code:
def myFunction3(x):
    outcomes = [1, 2, 3, 4]
    probs = [0.5, 0.75, 0.9, 1.0]
    result = [
        next(o for o, p in zip(outcomes, probs) if num <= p)
        for num in x
    ]
    return result

rawDescription: List Comprehension Control Flow

description: List Comprehension Control Flow


code:
from django.contrib.auth.models import User

class PagerDutyPolicy(models.Model):
    # the model automatically gets an id field
    policy_name = models.CharField(max_length=200)

class PagerDuty(models.Model):
    # I'm assuming you wanted these to be related to users who can log in..
    user = models.ForeignKey(User)
    mobile = models.CharField(max_length=200)
    policy = models.ForeignKey(PagerDutyPolicy)

rawDescription: django object get two fields into a list from a model

description: Django object get two fields into a list from a model


code: old = x0.copy()

rawDescription: Using a stored value of a variable in a for loop


code:
def bd_from_ac(a, c):
    b,d = neighbor_min(a, c)
    return a*b, d

rawDescription: Numpy: fast calculations considering items' neighbors and their position inside the array


code:
from mylogger import sms_counter
print('sms count is {}'.format(sms_counter.inc()))

rawDescription: What is the scope of a variable in logging?


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--row-to-query', type=str, help='row to query')
namespace = parser.parse_args()

row_name = namespace.row_to_query
...

rawDescription: Set Input Variable at the Start of a Python Script


code:
import string
type(string)
type("someValues")
help(dir)

rawDescription: Difference between dir(string) and dir(someString) in Python?


code: csv_file = open(file, mode="r")

rawDescription: Modify csv files with Python

description: Modify csv files with Python


code:
from nonedict import NoneDict as nd
foo = nd()

rawDescription: Classes Inside Modules

description: Classes Inside Modules


code: self.msg.content_subtype = "iso-8859-1"

rawDescription: Django EmailMultiAlternatives and HTML e-mail display in Outlook 2003 on Win2003


code:
class OutLog:
    def __init__(self, edit, out=None, color=None):
        """(edit, out=None, color=None) -> can write stdout, stderr to a
        QTextEdit.
        edit = QTextEdit
        out = alternate stream ( can be the original sys.stdout )
        color = alternate color (i.e. color stderr a different color)
        """
        self.edit = edit
        self.out = None
        self.color = color

    def write(self, m):
        if self.color:
            tc = self.edit.textColor()
            self.edit.setTextColor(self.color)

        self.edit.moveCursor(QtGui.QTextCursor.End)
        self.edit.insertPlainText( m )

        if self.color:
            self.edit.setTextColor(tc)

        if self.out:
            self.out.write(m)

rawDescription: PySide and python logging

description: PySide and python logging


code: df['spread'] = df.ask-df.bid

rawDescription: Aggregating over timestamps in pandas

description: Aggregating over timestamps in pandas


rawDescription: What is the fastest way to slice a scipy.sparse matrix?


code: keys = ["Client", "Name", "Phone", "Address", "Email"]

rawDescription: Python List to List of Dictionaries

description: Python List to List of Dictionaries


code:
class Gift(Base):
    # ...
    category = relationship(
        Category,
        uselist=False,
        secondary=SubCategory.__table__,
        primaryjoin=sub_category_id == SubCategory.id,
        secondaryjoin=SubCategory.category_id == Category.id,
        viewonly=True,
        backref="gifts",
    )

rawDescription: How to access child of child from parent in sqlalchemy?

description: Access child of child from parent in sqlalchemy


code:
import matplotlib.pyplot as plt

fig = plt.figure() # Creates a new figure
fig.suptitle('Temperature', fontsize=50) # Add the text/suptitle to figure

ax = fig.add_subplot(111) # add a subplot to the new figure, 111 means "1x1 grid, first subplot"
fig.subplots_adjust(top=0.80) # adjust the placing of subplot, adjust top, bottom, left and right spacing
ax.set_title('Humidity',fontsize= 30) # title of plot

ax.set_xlabel('xlabel',fontsize = 20) #xlabel
ax.set_ylabel('ylabel', fontsize = 20)#ylabel

x = [0,1,2,5,6,7,4,4,7,8]
y = [2,4,6,4,6,7,5,4,5,7]

ax.plot(x,y,'-o') #plotting the data with marker '-o'
ax.axis([0, 10, 0, 10]) #specifying plot axes lengths
plt.show()

rawDescription: How to increase plt.title font size (python)

description: Increase plt.title font size (python)


code:
from collections import defaultdict
import itertools

d = defaultdict(list)
for i,j in itertools.chain.from_iterable(datas2):
    if not isinstance(j, str):
        d[i].append(j)

rawDescription: Arbitrary Amount of Tuple Unpacking With Common Date


code:
all_values = []

with open('scores.txt', newline='') as infile:
    for line in infile:
        all_values.extend(line.strip().split(','))

rawDescription: How to append from file into list in Python?

description: Append from file into list in Python


code: slist = infile.readlines()

rawDescription: blank file while copying a file in python

description: Blank file while copying a file in python


code:
class Person(object):
    firstname=None
    lastname=None

rawDescription: How can I create a user defined data structure in python

description: Create a user defined data structure in python


code:
@register.simple_tag(takes_context=True)
def menu_main_active(context, urlnames):
    if context['request'].resolver_match.url_name in urlnames.split():
        return ' active'
    else:
        return ''

rawDescription: Test if string matches django url with params


rawDescription: Convert date to string with limited precision


rawDescription: How to do this join query in Django

description: Do this join query in Django


code:
list_of_values = [55, 33, 22]
bytes_of_values = bytes(list_of_values)
bytes_of_values
bytes_of_values == '\x37\x21\x16'

rawDescription: Python3 How to make a bytes object from a list of integers


code:
sql = "SELECT ... WHERE User=?"
params = [user]
if a_is_specified:
    sql += " AND ColA=?"
    params += [a]
...
cursor.execute(sql, params)

rawDescription: Optional parameters in a SQLite SELECT statement


code:
print(totals[totals.argsort()])
# Africa/Casablanca        1
# Africa/Johannesburg      1
# Africa/Lusaka            1
# Africa/Ceuta             2
# Africa/Cairo             3
# America/Anchorage        5
# tz                     521

rawDescription: Weird Data manipulation in Pandas

description: Weird Data manipulation in Pandas


code:
class Base(object):

    def load(self):
        print('do logic A')
        self.new_logic() # call new logic from child class, if exist.
        print('do logic B')

    def new_logic(self):
        # overwrite this one in child class
        pass

class Child(Base):

    def new_logic(self):
        print('do logic C')

c = Child()
c.load()

rawDescription: Extending the behavior of an inherited function in Python


rawDescription: Pyqt QMdiSubWindow resize with variable number of widgets


code:
def transform(self, node, results):
    if 'obj2' in results:
        print("found 2", results['obj1'], results['obj2'])
    else:
        print("found 1", results['obj1'])
    return node

rawDescription: pattern to match 1-or-2-arg function call for lib2to3

description: Pattern to match 1-or-2-arg function call for lib2to3


code:
def add_page_to_index(index, url, content):
    words = content.split()
    map(lambda word: add_to_index(index, word, url), words)

rawDescription: python mapping a function

description: Python mapping a function


code: os.execv('/bin/echo', ['echo', 'foo', 'bar'])

rawDescription: First parameter of os.exec*

description: First parameter of os.exec*


rawDescription: How to remove large numbers of dictionary entries in python

description: Remove large numbers of dictionary entries in python


code:
from collections import namedtuple

Link = namedtuple('Link', ['title', 'url'], verbose=True)

def Save(request):
    ...
    for i in reversed(nba):
        links.append(Link(title=i.text, url=i["href"])) # list of urls
        ...

rawDescription: I got title and url. How to make link?

description: I got title and url. How to make link


code: tree(dg)

rawDescription: Tree interval representation in python

description: Tree interval representation in python


code: plt.setp(ax, xlabel='Xlabel', ylabel='Ylabel', xticks=range(0, 100, 20))

rawDescription: How do I 'correct' this matplotlib plotting routine?


code:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)

rawDescription: Python to PHP valuables

description: Python to PHP valuables


code:
import importlib
fabfile = importlib.import_module('my-repo-name.fab.fabfile', None)
X = fabfile.X

rawDescription: python module resides in a repository whose name contains dash characters

description: Python module resides in a repository whose name contains dash characters


code:
import time

while True:
    now = time.time()            # get the time
    do_something()               # do your stuff
    elapsed = time.time() - now  # how long was it running?
    time.sleep(1.-elapsed)       # sleep accordingly so the full iteration takes 1 second

rawDescription: How do I ensure that a Python while-loop takes a particular amount of time to run?

description: Ensure that a Python while-loop takes a particular amount of time to run


code: usercount_per_day = {d: len(user_ids) for d, user_ids in users_in_day.iteritems()}

rawDescription: Group dictionary by key and find max value


code: pairs = re.split("\+-*\+-*\+\n?",likes_and_dislikes)[2:-1] #Drop the header and the tail

rawDescription: Parsing a pretty printed table into Python objects


code:
class A(object):
    v = []               # Class attribute, shared across all instances!

rawDescription: Terrifying initial values - mutable types share same reference?


code:
dnsses = openCON(query)
for dns in dnsses:
    printHeader(*dns[0:3])
    printDNS(*dns[3:])

rawDescription: Python Array Function

description: Python Array Function


code:
to_del = df[df['Type'].isin(type_val)].index.tolist()
df= df.drop(to_del, axis)

rawDescription: Delete multiple Pandas DataFrame row where column value is this or that


code:
import json

from bs4 import BeautifulSoup
import requests

URL = "<some processing file .asmx>"
response = requests.post(URL)
data = json.loads(response.content)

div = BeautifulSoup(data['d'])

rawDescription: Scraping a website that uses AJAX Post to populate the data


code:
class SomeLibraryClass(object):
  def __init__(self, x):
      self.x = x

  def foo(self, y):
     print('Hello', self.x, y)

def my_foo(self, y):
    print ('Good buy', self.x, y)

SomeLibraryClass.foo = my_foo

rawDescription: How do I modify class method without touching source code in python?

description: Modify class method without touching source code in python


code:
class MyUser(models.Model):
    user = models.OneToOneField(User)
    takingReqSets = models.ManyToManyField(RequirementSet, blank=True)
    takingCourses = models.ManyToManyField(Course, through='TakingCourse', blank=True, null=True)
    school = models.ForeignKey(School)

class TakingCourse(models.Model):
    my_user = models.ForeignKey(MyUser)
    course = models.ForeignKey(Course)
    term = models.ForeignKey(Term)

    class Meta:
         unique_together = ('my_user', 'course')

rawDescription: Django models: Use multiple values as a key?


code:
for player in session.query(PlayerModel).filter(PlayerModel.nation.like(nation)):
    result.append({'username':player.username, 'alliance': player.aliance.name if player.aliance is not None else ''})

rawDescription: Left join when there is no primary key (glue 2 given queries to one if possible)


code:
import numpy as np
L = [np.array([1, 2]), np.array([3, 4]), np.array([5, 6])]
X = [a[0] for a in L]
Y = [a[1] for a in L]
X
Y

rawDescription: Grab all the x values from stacked array? Python


code:
from sympy.polys.domains import ZZ, QQ, RR, FF, EX

x, y, z, t = symbols('x y z t')
ZZ['theta']

rawDescription: Representing rings of algebraic integers


code:
import re

hostname = re.sub(r'\.[a-z.]+$', '', domain)

rawDescription: python split a string when a keyword comes after a pattern

description: Python split a string when a keyword comes after a pattern


code:
import re
re.split('\.gds|\.cdl', your_string)

rawDescription: parameter passing to split function from if condition

description: Parameter passing to split function from if condition


code:
with open("example.csv") as file1, open("list.csv") as file2, open("output.csv", "wb+") as file3:
    writer = csv.writer(file3)
    key_words = [word.strip() for word in file2.readlines()]
    for row in file1:
        row = row.strip()
        for key in (key for key in key_words if key in row):
            writer.writerow([key, row])

rawDescription: Similarities between two csv files

description: Similarities between two csv files


code:
#!python3.3
print("World")

rawDescription: How to invoke a specific Python version WITHIN a script.py -- Windows

description: Invoke a specific Python version WITHIN a script.py -- Windows


code: eqs.sort_index() - 1

rawDescription: Pandas : determine mapping from unique rows to original dataframe


code:
from datetime import datetime

# ...
lines = f_open.readlines()

# split string and ignore unwanted elements
for line in lines:
    _, year, julian, time, *values = line.split(",")

# format date, convert julian day-of-year to 'day-month'
    date = datetime.strptime(year+julian, "%Y%j").strftime("%Y-%d-%m")
    time = datetime.strptime(time.rjust(4, "0"), "%H%M").strftime("%H:%M:%S")
    timestamp = "%s %s" % (date, time)

    with open(targetName, 'a') as target:
        for i, value in enumerate(values[:10], 1):
            target.write(",".join((timestamp, str(i), value)))
            target.write("\n")

rawDescription: Python parsing for MySQL import

description: Python parsing for MySQL import


code:
result2 = np.einsum('...mm->...m', arr)
assert np.allclose(result, result2)

rawDescription: Numpy einsum broadcasting

description: Numpy einsum broadcasting


rawDescription: How to test response contains a particular key and value

description: Test response contains a particular key and value


code:
"1001".isdigit()
"jsidofj882".isdigit()

rawDescription: Delete rows from csv containing non-numeric content at a specific column


rawDescription: Using LXML to print out individual strings from file


rawDescription: Remove elements from several lists simultaneously


rawDescription: Getting values OF a set in Python

description: Getting values OF a set in Python


code:
import os

files = run('ls -ltr /opt/nds')
files1 = run('ls -ltr /opt/web')
with open(section + "_tmp"+".txt", "w") as fo:
    fo.write(files)
    fo.write(os.linesep)
    fo.write(files1)

rawDescription: How do i write a new line or \n into a file

description: Write a new line or \n into a file


code: [apply_function(item) for item in list_of_lists]

rawDescription: How to apply a function to each sublist of a list in python?

description: Apply a function to each sublist of a list in python


code:
from collections import defaultdict

d = defaultdict(lambda: 0)

for i in xrange(100):
    d[i % 10] += 1

rawDescription: Check if a given key already exists in a dictionary


code:
mysubset = ["d","f"]
mask = df.columns.isin(mysubset)
pd.concat([df.loc[:,mask], df.loc[:,~mask]], axis=1)

rawDescription: How to change the column order in a pandas dataframe when there are too many columns?

description: Change the column order in a pandas dataframe when there are too many columns


code:
class RoundingDict(dict):
    def _round(self, key):
        return int(key * 20) / 20.0

    def __contains__(self, key):
        return super(RoundingDict, self).__contains__(self._round(key))

    def __getitem__(self, key):
        return super(RoundingDict, self).__getitem__(self._round(key))

    def __setitem__(self, key, value):
        super(RoundingDict, self).__setitem__(self._round(key), value)

    def __delitem__(self, key):
        super(RoundingDict, self).__delitem__(self._round(key))

    def get(self, key, default=None):
        return super(RoundingDict, self).get(self._round(key), default)

    def pop(self, key, default=None):
        return super(RoundingDict, self).pop(self._round(key), default)

    def update(self, iterable):
        try:
            super(RoundingDict, self).update({
                self._round(k): v for k, v in iterable.iteritems()})
        except AttributeError:
            super(RoundingDict, self).update((
                (self._round(k), v) for k, v in iterable))

rawDescription: How to make a dictionary, in which multiple values access one value(Python)

description: Make a dictionary, in which multiple values access one value(Python)


code:
from numpy import copy

newArray = copy(theArray)
for k, v in d.iteritems(): newArray[theArray==k] = v

rawDescription: Fast replacement of values in a numpy array


code:
from collections import Iterable
a = 1
isinstance(a, Iterable) # returns False
a = [1,2,3]
isinstance(a, Iterable) # returns True

rawDescription: How to handle edge case when iterating over cartesian product of sets in Python?

description: Handle edge case when iterating over cartesian product of sets in Python


code:
def fill_item(item, value):
  item.setExpanded(True)
  if type(value) is dict:
    for key, val in sorted(value.iteritems()):
      child = QTreeWidgetItem()
      child.setText(0, unicode(key))
      item.addChild(child)
      fill_item(child, val)
  elif type(value) is list:
    for val in value:
      child = QTreeWidgetItem()
      item.addChild(child)
      if type(val) is dict:
        child.setText(0, '[dict]')
        fill_item(child, val)
      elif type(val) is list:
        child.setText(0, '[list]')
        fill_item(child, val)
      else:
        child.setText(0, unicode(val))
      child.setExpanded(True)
  else:
    child = QTreeWidgetItem()
    child.setText(0, unicode(value))
    item.addChild(child)

def fill_widget(widget, value):
  widget.clear()
  fill_item(widget.invisibleRootItem(), value)

rawDescription: QTreeWidget to Mirror python Dictionary

description: QTreeWidget to Mirror python Dictionary


code: text =  input.read()

rawDescription: Remove special characters from csv file using python


code: odo(iris.species.distinct(), pd.Series)

rawDescription: python blaze postgresql can't print "distinct" iris species

description: Python blaze postgresql can't print "distinct" iris species


rawDescription: How to update list in python from user entered value in last item

description: Update list in python from user entered value in last item


code:
def combs(idx,array,current=[]):
    for item in array[idx]:
        current_copy = current[:]
        current_copy.append(item)
        if idx + 1 < len(array):
            for i in combs(idx+1,array,current_copy):
                yield i
        else:
            yield current_copy

rawDescription: Python Recursive Generator

description: Python Recursive Generator


rawDescription: How can I make a for-loop pyramid more concise in Python?

description: Make a for-loop pyramid more concise in Python


rawDescription: pandas datetimeindex between_time function(how to get a not_between_time)

description: Pandas datetimeindex between_time function(how to get a not_between_time)


code:
import requests
from bs4 import BeautifulSoup

url = "http://csgo.99damage.de/de/edb/players"
response = requests.get(url, headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"})

soup = BeautifulSoup(response.content, "html.parser")
for player in soup.select('#content a[href*="player/"]'):
    rank, name = player.find_all("span")[:2]
    print(rank.get_text(strip=True), name.get_text(strip=True))

rawDescription: Get text between tags BeautifulSoup4

description: Get text between tags BeautifulSoup4


code:
coords = []
for a in atom_indices:
    for k in range(3):
        coords.append(3*a+k)

rawDescription: Create larger list from an existing list using a list comprehension or map()


code:
organism = Organism()
new_organism = organism.reproduce()

rawDescription: Create new class instance from class method


code:
for i in range(1, len(df)):
    if df.ix[i, 'INDEX'] == 'AZB':
        df.ix[i, 'INDEX'] = df.ix[i-1, 'INDEX']

rawDescription: conditional replacement with pandas

description: Conditional replacement with pandas


code: your_index.search('composed_field:"%s"' % query)  # Look ma', no OR

rawDescription: Is it more performant to do an OR on multiple fields, or combine those field values into a single fieldname


rawDescription: How to create a new column with a tuple (or a list)?

description: Create a new column with a tuple (or a list)


code:
numpy.sqrt(-1+0j)
numpy.arctanh(24+0j)

rawDescription: numpy.arctanh(x) for x >= 1 returns NaN but I want complex

description: Numpy.arctanh(x) for x >= 1 returns NaN but I want complex


code:
class _AliveNodes(dict):
    ...

rawDescription: PyTables dealing with data with size many times larger than size of memory


code:
import ast
dictString = "{'a': 1, 'b': 2, 'c': 3}";
dictFinal = ast.literal_eval(dictString)
print (dictFinal)

rawDescription: How can I extract a dict form from a string?

description: Extract a dict form from a string


code: binary_obj = xmlrpclib.Binary( open('foo.pdf').read() )

rawDescription: How to base64 encode a PDF file in Python

description: Base64 encode a PDF file in Python


rawDescription: pands groupby last n

description: Pands groupby last n


rawDescription: Python - Split List into a Dictionary

description: Python - Split List into a Dictionary


code: rect_sizes.append(pygame.Rect(position_x + x, position_y + y, position_x, position_y))

rawDescription: How do I check to see if a mouse click is within a rectangle for each rectangle in this pygame program?

description: Check to see if a mouse click is within a rectangle for each rectangle in this pygame program


code:
from collections import Counter
tp = {1:Counter({u'x':1, u'b':1, u'H':3}),2:Counter({u'j':1, u'm':4, u'e':2})}
dict((k, dict(v)) for k, v in tp.iteritems())

rawDescription: Removing 'Counter' from Dictionary python


code:
new_dictionary = {}
count = 0
for line in lines:
    count += 1
    new_dictionary['sequence_{}'.format(count)] = line

rawDescription: Assigning a string from a .txt file into a variable


code:
def onOkay():
    global myName #make myName a global so it's accessible in other functions
    name = entry.get() #print shouldn't be a variable name. Also, .get() returns a string, so str() is redundant
    myName = Label(root, text='Your name is '+name+'.')
    myName.pack(side=BOTTOM,padx=15,pady=10) #put this on a new line so myName is a valid variable

rawDescription: How do I get rid of a label in TkInter?

description: Get rid of a label in TkInter


code:
W = pysal.queen_from_shapefile("/path/to/shapefile.shp")
out = pysal.open("output.gal", 'w')
out.write(W)
out.close()

rawDescription: Saving full QUEEN neighbor array to CSV in Pysal (Census Block Groups)


code:
from glob import iglob
from itertools import islice

for file in islice(iglob('path/file.*'), 0, None, 90):
    ...

rawDescription: loop over files in python?

description: Loop over files in python


code:
def Any(*cls):
    class Any(metaclass=abc.ABCMeta):
        def __eq__(self, other):
            return isinstance(other, cls)
    for c in cls:
        Any.register(c)
    return Any()

rawDescription: Assert that a method was called with one argument out of several


code:
a = [1, 2, 3]
b = a
del a[:]      # equivalent to   del a[0:len(a)]
print(a)
print(b)
a is b

rawDescription: Clearing Python lists

description: Clearing Python lists


code: commandStage = commandStage + 1

rawDescription: Python Application Breaks From While Loop


rawDescription: Python List with ranges

description: Python List with ranges


code: if str(READ,"ascii") == os.linesep: READ = "C:\\temp"

rawDescription: Python 3.2.2 READ from console

description: Python 3.2.2 READ from console


rawDescription: Python 3 - Regular Expression - Match string with one character less


rawDescription: Sending Hex data

description: Sending Hex data


code: pd.DataFrame(A, columns=data.columns)

rawDescription: Randomizing/Shuffling rows in a dataframe in pandas


code:
def func1(some_function):
    some_function()

rawDescription: calling a function passed as an argument without parentheses

description: Calling a function passed as an argument without parentheses


code:
class Profile(models.Model):
    USER_TYPE_CHOICES = (
        ('s', 'Student'),
        ('t', 'Teacher' ),
    )
    user = models.OneToOneField(User)
    type_user = models.CharField(max_length=20, default='s',choices=USER_TYPE_CHOICES)

    #     ...    ...     ...
    #      Your fields here

rawDescription: How do I define multiple user types in Django using the existing User model?

description: Define multiple user types in Django using the existing User model


rawDescription: SQLAlchemy through Paramiko SSH

description: SQLAlchemy through Paramiko SSH


code:
def make_heuristic(G):
    def heuristic(a, b):
        a_attr, b_attr = [G.node[n][key] for n in (a, b)]
        ...
    return heuristic

nx.astar_path(G,start,end,make_heuristic(G))

rawDescription: Use attributes in heuristic

description: Use attributes in heuristic


code:
s.add(1)
s

rawDescription: What is the correct way to implement a set that checks type in the add method in python 2.7?


code:
temp.next = temp.next.next
return self

rawDescription: Deleting a specific node from a linked list - python


code:
import numpy
x = [10, 20, 30]
numpy.mean(x)

rawDescription: Arithmetic Mean Number of a List - Python


code:
from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference('plugins.hide_infobar_for_missing_plugin', True)

driver = webdriver.Firefox(firefox_profile=profile)

rawDescription: Selenium: How to click on the install plugins button?


rawDescription: Is it possible to add a weight/probability to a node in graph theory(using networkx)


code: token = channel.create_channel(keyid)

rawDescription: Using GAE Channel's from a TaskQueue

description: Using GAE Channel's from a TaskQueue


rawDescription: Python: Index an array using the colon operator in an arbitrary dimension


rawDescription: Dynamically calculated zero padding in format string in python


code:
import pandas as pd
df = pd.read_csv('date.csv', parse_dates=['Col3(time)'])

rawDescription: Convert a column into time in pandas dataframe


code:
from pylab import *
A = rand(5,5)
figure(1)
imshow(A, interpolation='nearest')
grid(True)

left = 4.5
right = 9.5
bottom = 4.5
top = -0.5
extent = [left, right, bottom, top]

figure(2)
imshow(A, interpolation='nearest', extent=extent)
grid(True)

show()

rawDescription: relabel x-axis in matplotlib heatmap

description: Relabel x-axis in matplotlib heatmap


code:
lineEdits = {}
for i in range(5):
    myLineEdit = QtGui.QLineEdit("myLineEdit")
    lineEdits[i] = myLineEdit

lineEdits[3].setText("My new text")

rawDescription: PyQt: Creating QT Widgets Programmatically


code:
def filter_small(item):
    item.Bar = item.Bar.lower()

def filter_medium(item):
    item.Bar = item.Bar.title()

def filter_large(item):
    item.Bar = item.Bar.upper()

rawDescription: Using IronRuby or IronPython to modify a list of C# objects


code:
import re
def hasNumbers(inputString):
    return bool(re.search(r'\d', inputString))

hasNumbers("I own 1 dog")
hasNumbers("I own no dog")

rawDescription: check if a string contains a number

description: Check if a string contains a number


rawDescription: Checking file extension

description: Checking file extension


rawDescription: Get minimum value of masked array

description: Get minimum value of masked array


code:
lst = ['hey','what',0,False,None,14]
print(sum(x is not None for x in lst))

rawDescription: How to count the number of occurences of `None` in a list?

description: Count the number of occurences of `None` in a list


code: line = data.rstrip("\n")

rawDescription: Having trouble sorting the data from a file


code:
from base64 import b64encode

headers = {
    'Authorization': 'Basic ' + b64encode("{0}:{1}".format(username, password))
}

rv = self.app.get('api/v1.0/{0}'.format(ios_sync_timestamp), headers=headers)

rawDescription: How to send username:password to unittest's app.get() request?

description: Send username:password to unittest's app.get() request


rawDescription: File name encoding in Python 2.7

description: File name encoding in Python 2.7


rawDescription: numpy non-integer grid

description: Numpy non-integer grid


rawDescription: Recursive algorithm for generating a acyclic directed graph


code:
import Tkinter as tk
root = tk.Tk()
frames = []
for i in range(3):
    f = tk.Frame(root)
    f.grid(row=i, column=0, columnspan=i+1, sticky=tk.E)
    frames.append(f)

#Now, you can add buffer spaces (frames) into the grid at
# `row=0,column=0`, `row=0,column=1` and `row=1,column=1` if you need it.

root.mainloop()

rawDescription: Quick Tkinter Formatting Issue

description: Quick Tkinter Formatting Issue


rawDescription: How to remove library modules or specific functions from pycallgraph

description: Remove library modules or specific functions from pycallgraph


code: swapon /var/swap.img

rawDescription: Django-cities exits with "killed"

description: Django-cities exits with "killed"


rawDescription: Remove brackets from argv string

description: Remove brackets from argv string


rawDescription: numpy matrix rank incorrect result

description: Numpy matrix rank incorrect result


code:
def onClick(event):
    global pause
    pause ^= True
fig.canvas.mpl_connect('button_press_event', onClick)

rawDescription: stop / start / pause in python matplotlib animation

description: Stop / start / pause in python matplotlib animation


code: (df.value - df.value.min()) / (df.value.max() - df.value.min())

rawDescription: python pandas - how to apply a normalise function to a dataframe column

description: Python pandas - how to apply a normalise function to a dataframe column


code:
from pattern.en import wordnet

list_of_words = [u"bird", u"smart", u"cool", u"happy"]
list_of_words_synonyms = []
list_of_words_hypnonyms = []

for word in list_of_words:
    sts = wordnet.synsets(word)
    if len(sts):
        st = sts[0]
        list_of_words_synonyms.extend(st.synonyms)
        list_of_words_hypnonyms.extend(hs.senses[0] for hs in st.hyponyms())

list_of_words = list_of_words + list_of_words_synonyms + list_of_words_hypnonyms
print(list_of_words)

rawDescription: Synset function to include synonym in a list


code:
end_len = len(h.hex_digest())
all_text = open("file_with_hash").read()
text, expected_hmac = all_text[:end_len], all_text[end_len:]
h = HMAC.new(secret_key)
h.update(text)
if h.hexdigest() != expected_hmac:
    raise "Somebody messed with your file!"

rawDescription: Calculate and add hash to a file in python


rawDescription: Condensing Multiple List Comprehensions

description: Condensing Multiple List Comprehensions


code:
import xml.etree.ElementTree as ET
html = ET.XML('<title>Hi</title>')
html.head = html.find('head')
html.head.append(ET.XML('<link type="text/css" href="main.css" rel="stylesheet" />'))
html.head.title = html.head.find('title')
html.head.title.text

rawDescription: What's the most Pythonic XHTML/HTML parser/generator/template module that supports DOM like access?


code:
from collections import defaultdict
a = defaultdict(list)

rawDescription: How to append to Python list without having to initialize the list?

description: Append to Python list without having to initialize the list


code:
from tempfile import NamedTemporaryFile

with open('file.txt','r') as f, NamedTemporaryFile(dir=".",delete=False) as  temp:
    for line in f:
        if "phrase" in line:
            for i in range(38):
                next(f)
        else:
            temp.write(line)

import shutil
shutil.move(temp.name,"file.txt")

rawDescription: Not Recognizing Loop Variable in Python

description: Not Recognizing Loop Variable in Python


code: customer = models.ForeignKey('Customer', db_constraint=False)

rawDescription: Django ForeignKey which does not require referential integrity?


code:
d=[(k, s) for k, v in mydict.items() for s in v.split()]
df = pd.DataFrame(d, columns=['key_val','splitted_words'])

rawDescription: How to efficiently convert the entries of a dictionary into a dataframe

description: Efficiently convert the entries of a dictionary into a dataframe


code:
def get_queryset(self, request):
    qs = self.model._default_manager.get_queryset()
    newquery = qs.query+' ORDER BY idx(array'+order.__str__()+', status)'
    return self.model._default_manager.raw(newquery)

rawDescription: Sort a Django queryset based on the values in the choice field


code: from exampleModule import *

rawDescription: Using Python Functions in Terminal

description: Using Python Functions in Terminal


rawDescription: I need help ordering nested loops by integers and displaying them


code: float(timedelta.days) + float(timedelta.seconds) / float(86400)

rawDescription: How to put timedelta in django model?

description: Put timedelta in django model


code:
def check_asteroid_collision( self, asteroid, size ) :
    # Create a vector based on the distance between the two points
    distx   = self.rect.centerx - asteroid[0];
    disty   = self.rect.centery - asteroid[1];
    # Get magnitude (sqrt of x^2 + y^2)
    distmag = ((distx * distx) + (disty * disty)) ** 0.5;

    # Get the closest point on the circle:
    # Circle center + normalized vector * radius
    clsx    = asteroid[0] + distx / distmag * size;
    clsy    = asteroid[1] + disty / distmag * size;

    # Check if it's within our rect
    if self.rect.collidepoint( clsx, clsy ) :
        # We're colliding!! Do whatever
        print( "Oh no!" );

rawDescription: Sprite collide with object function?

description: Sprite collide with object function


code:
from __future__ import print_function

import re
import operator
import collections
import pprint as pp

importance = {
    'CRITICAL': 0,
    'ERROR': 100,
    'INFO': 200,
    'DEBUG': 300
}

with open('log.log', 'r') as f:
    data = f.read().splitlines()

parsed = collections.OrderedDict()

for line in data:
    cols = re.split(r'\s+\-\s+', line)
    parsed[line] = importance[cols[0]]

for k,v in sorted(parsed.items(), key=operator.itemgetter(1)):
    print(k)

rawDescription: Sort strings by splitted words

description: Sort strings by splitted words


code:
import csv

def data_pull():
    results = {}

    with open("C:\sample.csv", 'rb') as datafile:
        reader = csv.reader(datafile)
        for row in reader:
            results[row[0]] = row[1:]

    return results

rawDescription: .csv data into a dictionary in Python: Duplicate values


rawDescription: Appending data to a scapy packet

description: Appending data to a scapy packet


rawDescription: Functional programming in Python: returning none instead of correct value


code:
def music_object_list(request, object_type, starts_with=None):
     if object_type == 'artists':
         return artist_list(request, starts_with=starts_with)
     elif object_type == 'albums':
         return album_list(request, starts_with=starts_with)
     ...

rawDescription: Django: Named URLs / Same Template, Different Named URL


rawDescription: How to print a conditional's literal expression in Python

description: Print a conditional's literal expression in Python


code:
def get_dictionary_word_list():
    # with context manager assures us the
    # file will be closed when leaving the scope

    with open('dictionary.txt') as f:
        # create a  dictionary object to return
        result = dict()
        for line in f.read().splitlines():
            # split the line to a key - value.
            k, v = line.split()
            # add the key - value to the dictionary object
            result[k]  = v
        return result

rawDescription: How to return a list of words from a text file in python

description: Return a list of words from a text file in python


rawDescription: Getting completely wrong fit from python scipy.optimize.curve_fit


code:
def setEditorData(self, editor, index):
    value = index.model().data(index, Qt.UserRole)
    editor.setCurrentIndex(int(value))

def setModelData(self, editor, model, index):
    model.setData(index, editor.currentIndex(), Qt.UserRole)

rawDescription: How to restore the index of a QComboBox delegate in a QTableView?

description: Restore the index of a QComboBox delegate in a QTableView


code:
bpy.ops.object.select_all(action = 'DESELECT')
object.select = True

rawDescription: How to apply a modifier in Python, creating a new mesh?

description: Apply a modifier in Python, creating a new mesh


code:
import sys
import time
for i in ['-', '/', '|', '\\'] * 10:
    sys.stdout.write('\rSome text [{0}]'.format(i))
    sys.stdout.flush()
    time.sleep(1)

rawDescription: How to create dynamic text?

description: Create dynamic text


rawDescription: sorted on basis of two keys, descending order sort for first and ascending for second

description: Sorted on basis of two keys, descending order sort for first and ascending for second


code:
from django.contrib.auth.admin import UserAdmin
UserAdmin.add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'password1', 'password2', 'first_name', 'last_name')}
        ),
    )

rawDescription: django: Add user popup. Missing fields (first_name, last_name)

description: Django: Add user popup. Missing fields (first_name, last_name)


code:
keys = 'brand', 'speed', 'model'

ll = [dict(zip(keys, combo)) for combo in product(brand, speed, model)]

rawDescription: Cartesian product giving a dictionary

description: Cartesian product giving a dictionary


code: find_key = find(row[3], '/home/ro/Desktop/search/IDBUF')

rawDescription: How to find the path of files in a directory from a column of a CSV (PYTHON)

description: Find the path of files in a directory from a column of a CSV (PYTHON)


code:
for item in beta['data']:
    if item['username'] == xy: # here check the username from your input
        print(item['id'])

rawDescription: Finding the exact match of many usernames stored in a variable while looping


code:
import datalayer
datalayerInstance = get_datalayerinstance();

rawDescription: Python creating single instance in whole module


code:
filemenu.add_command(label='Item-a', command=lambda : gui('a'))
filemenu.add_command(label='Item-b', command=lambda : gui('b'))

rawDescription: Python tkinter menu + variable

description: Python tkinter menu + variable


code:
from collections import defaultdict

total = defaultdict(set)

for d in dicts:
    for key, value in d.items():
        total[key].add(value)

rawDescription: Find specific dictionary element without looping


code:
a = Symbol('a') # create an object with name 'a' for variable a to point to
b = a + 1; b    # create another object that refers to what 'a' refers to
a = 4; a        # a now points to the literal integer 4, not Symbol('a')
b               # but b is still pointing at Symbol('a')

rawDescription: Sympy "global" substitution

description: Sympy "global" substitution


code:
def relate_identities(self, is_processed):
    #http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
    #http://www.sitepoint.com/hierarchical-data-database-2/
    #http://www.pure-performance.com/2009/03/managing-hierarchical-data-in-sql/
    #http://www.sqlalchemy.org/trac/browser/examples/nested_sets/nested_sets.py
    identify = Identity()
    session = Session()
    entries = []
    related = []
    tbl = IdentityRelated
    not_processed = False
    log_counter = 0
    id_counter = 0
    while True:
        #Get the initial record
        identity = session.query(tbl).filter(tbl.is_processed == is_processed).order_by(tbl.id).first()
        entries.append({identity:'not_processed'})
        related.append(identity)
        if len(entries) == 0: break
        #for key, value in entries[0].items():
            #print("ID:%s; ref_no:%s" %(key.id, key.ref_no))
        while True:
            for entry in entries:
                if not_processed == True: break
                for key, value in entry.items():
                    if value == 'not_processed':
                        not_processed = True
                        break

            if not_processed == False:
                break
            else:
                not_processed = False

            for entry in entries:
                for key, value in entry.items():
                    if value == 'not_processed':
                        #Get objects which have the same identity_id as current object
                        duplicates = session.query(tbl).filter(tbl.identity_id == key.id).\
                                                            order_by(tbl.id).all()
                        if len(duplicates) != 0:
                            for duplicate in duplicates:
                                if not duplicate in related:
                                    related.append(duplicate)
                                    entries.append({duplicate:'not_processed'})

                        for entry in entries:
                            for key, value in entry.items():
                                if value == 'not_processed':
                                    #Get objects that have the same reference numbers as all entries that we have fetched so far
                                    ref_nos = session.query(tbl).filter(tbl.ref_no == key.ref_no).order_by(tbl.id).all()
                                    for ref_no in ref_nos:
                                        if not ref_no in related:
                                            related.append(ref_no)
                                            entries.append({ref_no:'not_processed'})
                                    #Remove current entry from entries
                                    entries.remove(entry)
                                    #Add the entry but change the status
                                    entries.append({key:'processed'})

        #Generate a new RelationCode
        while True:
            ref_no = get_reference_no(REFERENCE_NO.idrelation)
            params = {'key':'relation','relation':ref_no}
            if identify.get_identity(session, **params) == None:
                break
        #Add each relatedID to the DB and set the Nested Set Value
        #Set is_processed as True to ensure we don't run it again
        relation_counter = 0
        for entry in entries:
            for key, value in entry.items():
                key.ref_no = ref_no
                key.lft = relation_counter + 1
                key.rgt = ((len(related) * 2) - relation_counter)
                key.is_processed = True
                relation_counter += 1

        #Reset values
        log_counter += 1
        id_counter += 1
        related = []
        entries = []

        #Commit the session
        session.commit()

rawDescription: How do I relate data without one single master or starting point

description: Relate data without one single master or starting point


code:
import networkx as nx
g = nx.Graph()
g.add_edge(1,2)
g.add_edge(2,3)
g.edges()

rawDescription: How do I get nodes from the specific edge in the networkx?

description: Get nodes from the specific edge in the networkx


code:
cmd = subprocess.Popen(['ls'], stdout=subprocess.PIPE)
for line in cmd.stdout:
    do_stuff(line)

rawDescription: is there a limit to command.getstatusoutput() buffer in python

description: Is there a limit to command.getstatusoutput() buffer in python


code:
class Tk_app(Frame):
    def __init__(self, root):
        Frame.__init__(root);
        self.grid();
        self.createElements()
        self.nameElements()

rawDescription: Python tkinter, making a quiz with randomly generated questions that reset after each submit


code:
def test():
    yield 1
    return 2
gen = Generator(test())
for i in gen:
   print(i)
print(gen.value)

rawDescription: Best way to receive the 'return' value from a python generator

description: Receive the 'return' value from a python generator


code:
import itertools
for combo in itertools.permutations(["an", "de", "si", "ta"], 4):
    print(''.join(combo))

rawDescription: Add permutation outcomes into a string and break line between them


code:
from ctypes import *
from ctypes.wintypes import *

PROCESS_ALL_ACCESS = 0x1F0FFF

def read_process_memory(pid, address, offsets, size_of_data):
    # Open the process and get the handle.
    process_handle = windll.kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid)
    size_of_data = 4 # Size of your data
    data = ""
    read_buff = create_string_buffer(size_of_data)
    count = c_ulong(0)
    current_address = address
    offsets.append(None) # We want a final loop where we actually get the data out, this lets us do that in one go.
    for offset in offsets:
        if not windll.kernel32.ReadProcessMemory(process_handle, current_address, cast(read_buff, LPVOID), size_of_data, byref(count)):
            return -1 # Error, so we're quitting.
        else:
            val = read_buff.value
            result = int.from_bytes(val, byteorder='little')
            # Here that None comes into play.
            if(offset != None):
                current_address = result+offset
            else:
                windll.kernel32.CloseHandle(process_handle)
                return result

rawDescription: How do I look up the value of a multi-level pointer inside a process in Python?

description: Look up the value of a multi-level pointer inside a process in Python


code:
MAX_SIZE = 10 * 1024 * 1024 # 10MB
BUF_SIZE = 8192

# code assumes that MAX_SIZE >= BUF_SIZE

data_blocks = []
byte_count = 0

buf = f.read(BUF_SIZE)
while buf:
    byte_count += len(buf)

    if byte_count > MAX_SIZE:
        # if you want to just truncate at (approximately) MAX_SIZE bytes:
        break
        # or, if you want to abort the call
        raise bottle.HTTPError(413, 'Request entity too large (max: {} bytes)'.format(MAX_SIZE))

    data_blocks.append(buf)
    buf = f.read(BUF_SIZE)

data = ''.join(data_blocks)

rawDescription: Python bottle - How to upload media files without DOSing the server


code:
{
    u'Age Range': u'9 - 12 years',
    u'Amazon Best Sellers Rank': u'#1,440 in Books (',
    u'Average Customer Review': u'',
    u'Grade Level': u'4 - 7',
    u'ISBN-10': u'0439136369',
    u'ISBN-13': u'978-0439136365',
    u'Language': u'English',
    u'Lexile Measure': u'880L',
    u'Mass Market Paperback': u'448 pages',
    u'Product Dimensions': u'1.2 x 5.2 x 7.8 inches',
    u'Publisher': u'Scholastic Paperbacks (September 11, 2001)',
    u'Series': u'Harry Potter (Book 3)',
    u'Shipping Weight': u'11.2 ounces ('
}

rawDescription: how to scrape product details on amazon webpage using beautifulsoup

description: Scrape product details on amazon webpage using beautifulsoup


code: validate_input("What is the condition of the phone?", {"new", "used"})

rawDescription: How to redo an input if user enters invalid answer

description: Redo an input if user enters invalid answer


code:
import re
l = ['asdas2', 'asdas1', 'asds3ssd']
sorted(l, key=lambda x: int(re.sub('\D', '', x)))

rawDescription: sort string by number inside

description: Sort string by number inside


code:
filetypes = [('.gz', gzip.GzipFile, (IOError, MaybeSomeGzipExceptions)),
             ('.x', xCompressLib.xCompressFile, (IOError, MaybeSomeXCompressExceptions))]

class UnknownCompressionFormat(Exception):
    pass

def open_compressed(fn):
    for ext, cls, exs in filetypes:
        try:
            return cls(fn + ext)
        except exs:
            pass
    raise UnknownCompressionFormat

try:
    with open_compressed(fn) as f:
        result = process(f)
except UnknownCompressionFormat:
    result = "some default value"

rawDescription: Several `with`s in `try`s

description: Several `with`s in `try`s


code: all([True, False])

rawDescription: Split Pandas Dataframe into separate pieces based on column values


code:
TokenKind.KEYWORD
TokenKind.IDENTIFIER
TokenKind.PUNCTUATION
TokenKind.KEYWORD
TokenKind.IDENTIFIER
TokenKind.PUNCTUATION
TokenKind.PUNCTUATION
TokenKind.KEYWORD
TokenKind.PUNCTUATION
TokenKind.IDENTIFIER
TokenKind.PUNCTUATION
TokenKind.LITERAL
TokenKind.PUNCTUATION
TokenKind.PUNCTUATION
TokenKind.IDENTIFIER
TokenKind.PUNCTUATION
TokenKind.IDENTIFIER
TokenKind.PUNCTUATION
TokenKind.IDENTIFIER
TokenKind.PUNCTUATION
TokenKind.LITERAL
TokenKind.PUNCTUATION
TokenKind.PUNCTUATION
TokenKind.LITERAL
TokenKind.PUNCTUATION
TokenKind.PUNCTUATION

rawDescription: Using libclang to parse in C++ in Python


code:
# change_defaults.py

from functools import wraps

class Default(object):
    def __init__(self, name):
        super(Default, self).__init__()

        self.name = name

def set_defaults(defaults):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            # Backup original function defaults.
            original_defaults = f.func_defaults

            # Replace every `Default("...")` argument with its current value.
            function_defaults = []
            for default_value in f.func_defaults:
                if isinstance(default_value, Default):
                    function_defaults.append(defaults[default_value.name])
                else:
                    function_defaults.append(default_value)

            # Set the new function defaults.
            f.func_defaults = tuple(function_defaults)

            return_value = f(*args, **kwargs)

            # Restore original defaults (required to keep this trick working.)
            f.func_defaults = original_defaults

            return return_value

        return wrapper

    return decorator

rawDescription: Python 2.7: Defining default parameters based on globals?


code: imap(func, self._walk(starting_node))

rawDescription: Building a generator from a recursive algorithm


code: self.data = kwargs

rawDescription: Declaring variable w/o knowing the name

description: Declaring variable w/o knowing the name


code:
from itertools import groupby
with open("in.txt") as f:
    for k, sec in groupby(f,key=lambda x: bool(x.strip())):
        if k:
            print(list(sec))

rawDescription: print first paragraph in python

description: Print first paragraph in python


code:
for path in lst:
    if path.endswith('/'):
        dir_list.append(path)
    else:
        file_list.append(path)

rawDescription: What is best to distinguish between file and dir path in a string


rawDescription: Random's randint won't work in a for-loop


code: reduce(np.dot, T, np.eye(2))

rawDescription: Multiplying matrices that are stored in an array in Python


code:
data = {}
def store(stor, username, password):
    stor[username] = password

def create():
    for i in range(2):
        user = input("Username: ")
        pas = input("Password: ")
        while user in data:
            print("Try Again")
            user = input("Username: ")
            pas = input("Password: ")
        store(data,user, pas)
        print (data)

create()

rawDescription: how can i get my function to go through the dictionary and check if the key exists when user inputs

description: Get my function to go through the dictionary and check if the key exists when user inputs


code:
solditem_changed = Signal()
@receiver(solditem_changed)
def update_invoice(sender, **kwargs):
    if hasattr(sender, 'solditem_set'):
        total = 0
        for item in sender.solditem_set.all():
            total += item.item.price * item.qty
        sender.amount = total
        sender.save()
    else:
        sender.amount = 0
        sender.save()

rawDescription: Post save process using ManyToMany with intermediary model in admin


code: pennLC_data['pennLC'] # guessing here, it might be a different name

rawDescription: rpy2 (version 2.3.10) - importing data from R package into python

description: Rpy2 (version 2.3.10) - importing data from R package into python


code: group[:-1] > group[-1]

rawDescription: Comparing single dataframe value to previous 10 in same column


rawDescription: How to selectively import only lines of words with genfromtxt into Python?

description: Selectively import only lines of words with genfromtxt into Python


code:
from collections import defaultdict
consolidated = defaultdict(set)
for verb, adverb in pairs:
    consolidated[verb].add(adverb)

rawDescription: How to extract the verbs and all corresponding adverbs from a text?

description: Extract the verbs and all corresponding adverbs from a text


code:
from enum import Enum

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return 'Point(%r, %r)' % (self.x, self.y)

class Corner(Enum):
    BottomLeft = Point(0, 0)
    TopLeft = Point(0, 100)
    TopRight = Point(100, 100)
    BottmRight = Point(100, 0)

rawDescription: Python enums with complex types

description: Python enums with complex types


code: reduce(outer_merge, tmp).fillna(0)

rawDescription: How to pass keyword arguments in reduce over Pandas merge function

description: Pass keyword arguments in reduce over Pandas merge function


code:
{'awesome': 'positive',
 'bad': 'negative',
 'best': 'positive',
 'better': 'positive',
 'down': 'negative',
 'dreadful': 'negative',
 'fantastic': 'positive',
 'good': 'positive',
 'happy': 'positive',
 'horrible': 'negative',
 'sad': 'negative',
 'terrible': 'negative',
 'up': 'positive',
 'wonderful': 'positive',
 'worse': 'negative',
 'worst': 'negative'}

rawDescription: Data structure to implement reverse functionality of a dictionary


code:
for item in range(n):
    if ((s1[item])**2 + (s2[item])**2) < 1:
        ii = ii + 1

rawDescription: How to increase the performance for estimating `Pi`in Python

description: Increase the performance for estimating `Pi`in Python


code:
def argsort(xs):
    return sorted(range(len(xs)), key=xs.__getitem__)
argsort(argsort('hello'))
argsort(argsort('cadeb'))

rawDescription: How to create a list of small values out of large values

description: Create a list of small values out of large values


rawDescription: python pandas: Simplest way to perform group by and extract count of unique entities?

description: Python pandas: Simplest way to perform group by and extract count of unique entities


rawDescription: Count all +1's in the file python

description: Count all +1's in the file python


code:
some_list = [1,2,3]
b = some_list
del b   # destroys the list?
b
some_list   # list is still there!
c = some_list
del some_list
c        # list is still there!
del c

rawDescription: Is overriding __del__() the best choice here?


code:
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
                       url(r'^', include('homepage.urls')),
                       url(r'^admin/', include(admin.site.urls)),
                       url(r'^', include('simpleapp.urls')),
)

rawDescription: staticfile is not working on other page, but index

description: Staticfile is not working on other page, but index


code:
def groups(l, keys, i, n):
    tk = takewhile(lambda x: x != i, l)
    return filter(lambda x: len(x) == n, (dict(zip(keys, chain(islice(tk, n - 1),(i,))))
                                          for i in tk))

rawDescription: Loop through list until value is found then breaking?


code:
import sys
from subprocess import Popen, PIPE, STDOUT
from producer import LineProducer, MultiThreadedLineProducer, MultiProcessedLineProducer

#using normal yield
for line in LineProducer().run():
    sys.stdout.write(line + '\n')

#using yield with multi threading
for line in MultiThreadedLineProducer().run():
    sys.stdout.write(line + '\n')

#using yield with mult processing
for line in MultiProcessedLineProducer().run():
    sys.stdout.write(line + '\n')

#using normal yield in child process
for line in Popen(['python', 'producer.py'], bufsize = 0, shell = False, stdout = PIPE, stderr = STDOUT).stdout:
    sys.stdout.write(line)

rawDescription: python pass long running process to another script

description: Python pass long running process to another script


code:
def replace_with(data):
    def replacer(match):
        return next(data)
    return replacer

rawDescription: regex replace from a list

description: Regex replace from a list


code:
a_tuple = (1, 2, 3)
a_tuple.__hash__ is None
hash(a_tuple)

rawDescription: A list as a key for PySpark's reduceByKey


code: qtylist[x.finished_case.name] = x.qty

rawDescription: Page Refresh Disrupts Sort Order. Server Restart Restores It


code:
import datetime
d = parse_duration('P1M')
d.todatetime(start=datetime.datetime.today())

rawDescription: How to convert string date interval to number of days or seconds (ISO_8601)?

description: Convert string date interval to number of days or seconds (ISO_8601)


code:
import string

for char in string.ascii_uppercase:
    if char not in processed:
        print("{0} is empty...".format(char))
    else:
        print("{0}: min={1}, max={2}".format(char,
                                             min(processed[char]),
                                             max(processed[char])))

rawDescription: How to Search data from a list of Key-Value pair that it is in list or not


code:
import re

pat = '(atg).+?(?:TAA|TGA|TAG)'
reg = re.compile(pat,re.IGNORECASE)

def find_ORF_seq(fdna,messages=None,s =0,reg=reg):
    ORF_sequences = []
    while True:
        ma = reg.search(fdna[s:])
        if ma:
            if ma.group(1)=='ATG':
                break
            else:
                ORF_sequences.append(ma.group().upper())
                s = s + ma.start() + 1
        else:
            break
    return ORF_sequences

rawDescription: Limiting re.findall() to record values before a certain number. Python


code:
def calcaluate_winner(d):
    max_value = max(d.values())
    winners = [key for key in d if d[key] == max_value]
    if len(winners) == 1:
        return winners[0]
    else:
        return 'TIE', winners

rawDescription: Python max on potential same values

description: Python max on potential same values


code:
def Pearson(r, n=len(dat)):
    r = max(min(r, 1.0), -1.0)
    df = n - 2
    if abs(r) == 1.0:
        prob = 0.0
    else:
        t_squared = r**2 * (df / ((1.0 - r) * (1.0 + r)))
        prob = betai(0.5*df, 0.5, df/(df+t_squared))

    return (r,prob)

rawDescription: Python pandas function applied to all pairwise combinations of rows


rawDescription: How to delete from an arbitrarilly deeply nested dictionary

description: Delete from an arbitrarilly deeply nested dictionary


code: Z.data *= Y[Z.row] # you can use np.take which is faster then indexing.

rawDescription: Multiplying elements in a sparse array with rows in matrix


code: median()

rawDescription: Finding median in Spark Streaming

description: Finding median in Spark Streaming


code:
class Pracownik:
    total = 0.0

    def __init__(self, imie, wynagrodzenie_brutto):
        self.imie=imie
        self.wynagrodzenie_brutto=wynagrodzenie_brutto

    def wynagrodzenie_netto(self):
        skladki_pracownik=round(0.1371*self.wynagrodzenie_brutto,2)
        zdrowotne=round((self.wynagrodzenie_brutto-skladki_pracownik)*0.09,2)
        zdrowotne_odliczenie=round((self.wynagrodzenie_brutto-skladki_pracownik)*0.0775,2)
        kup=111.25
        zaliczka_podstawa=round(self.wynagrodzenie_brutto-kup-skladki_pracownik,2)
        zaliczka_pobrana=round((zaliczka_podstawa*0.18)-zdrowotne_odliczenie-46.33,0)
        netto=round(self.wynagrodzenie_brutto-skladki_pracownik-zdrowotne-zaliczka_pobrana,2)
        return netto

    def skladki_pracodawcy(self):
        skladki_pracodawca=round(self.wynagrodzenie_brutto*0.2074,2)
        return skladki_pracodawca

    def koszty_calkowite(self):
        calosc=round(self.wynagrodzenie_brutto+self.skladki_pracodawcy(),2)
        Pracownik.total += calosc
        return calosc

    def __str__(self):
        return self.imie + ' ' + str(self.wynagrodzenie_netto()) + ' ' + str(self.skladki_pracodawcy()) + ' ' + str(self.koszty_calkowite())

x = int(input('Enter nr: '))

for i in range(x):
    s = input('Enter name and salary: ')
    param_list = s.split(' ')
    pracownik = Pracownik(param_list[0], int(param_list[1]))
    print(pracownik)
print(Pracownik.total)

rawDescription: Defining and summing object in Python

description: Defining and summing object in Python


code:
# filter on x[1][5] and x[2]
e = [r for r in d if r.Pair1[1]==x and r.Scalar0==23]
e

rawDescription: python matching on structures

description: Python matching on structures


code:
def _print_board(game_state):
    # headers
    for i in range(len(game_state[0]) + 1):
        if i == 0:
            # column for row numbers
            print("   ", end="")
        else:
            # column headers
            print("{0:2d} ".format(i), end="")
    print()
    for i, row in enumerate(game_state, 1):
        # row number
        print("{0:2d} ".format(i), end="")
        for col in row:
            # row data
            if col == NONE:
                print(" {0} ".format("."), end="")
            else:
                print(" {0} ".format(col), end="")
        print()

rawDescription: How do I print a grid from a list of lists with numbered rows and columns

description: Print a grid from a list of lists with numbered rows and columns


code:
import re
txt = """<bookstore>
    <book category="COOKING">
        <title lang="english">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>300.00</price>
    </book>
    <book category="CHILDREN">
        <title lang="english">Harry Potter</title>
        <author>J K. Rowling </author>
        <year>2005</year>
        <price>625.00</price>
    </book>
</bookstore>"""
exp = re.compile(r'<.*?>')
text_only = exp.sub('',txt).strip()
text_only

rawDescription: extract text from xml documents in python

description: Extract text from xml documents in python


code: [[(int(a), int(b), 2) for a, b in pairs] for pairs in l]

rawDescription: Iterate over Python list, preserving structure of embedded lists


code:
import functools

def replacement(table, match):
    try:
        return table[match.group(1)]
    except:
        return match.group(0)

table = dict(...)
result = pattern.sub(functools.partial(replacement, table), text)

rawDescription: python regex for string replacement

description: Python regex for string replacement


code:
# module1.py
import Tkinter as tk
class Module1(tk.Frame):
    def __init__(self, *args, **kwargs):
        label = tk.Label(self, text="I am module 1")
        label.pack(side="top", fill="both", expand=True)

# this code will not run if this module is imported
if __name__ == "__main__":
    root = tk.Tk()
    m1 = Module1(root)
    m1.pack(side="top", fill="both", expand=True)

rawDescription: When importing modules written with tkinter and ttk, stuff doesn't work


code:
import urllib
from bs4 import BeautifulSoup

def get_artist_link(artist):
    base = 'http://www.allmusic.com/search/all/'
    # encode spaces
    query = artist.replace(' ', '%20')
    url = base + query
    page = urllib.urlopen(url)
    soup = BeautifulSoup(page.read())
    artists = soup.find_all("li", class_ = "artist")
    for artist in artists:
        print(artist.a.attrs['href'])

if __name__ == '__main__':
    get_artist_link('the beatles')
    get_artist_link('arcade fire')

rawDescription: Google Search Results/ Beginner Python

description: Google Search Results/ Beginner Python


code:
gender=json_dict.get('gender')
if gender=='male':
        gender= unicode('M')
elif gender=='female':
        gender=unicode('F')
else:
     gender = None # is the default case. no need to write that.

rawDescription: Alternative to multiple try/except statements to check if a field exists


code: list(enumerate(['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']))

rawDescription: Python: building new list from existing by dropping every n-th element


code: splitlist = [prices.split(',') for prices in yourlist]

rawDescription: What is the most efficient method to assign an X and Y header for a list of the following nature?


code: 'this isar ando msen tenc e'

rawDescription: How do I insert a space after a certain amount of characters in a string using python?

description: Insert a space after a certain amount of characters in a string using python


code:
urlpatterns = patterns('',
                       url(r'first_expression', index, name='first'),
                       url(r'second_expression', index, name='second'),
                       )

rawDescription: Django - Reusing views in different templates


code:
import sys
save_stdout = sys.stdout
sys.stdout = open('trash', 'w')
foo()
sys.stdout = save_stdout

rawDescription: Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call


rawDescription: Python: how to get number of days from fixed past date to now


code:
for row in rows:
    if row.th: continue

rawDescription: python beautifulsoup4 parsing google finance data

description: Python beautifulsoup4 parsing google finance data


code:
import collections
import itertools as IT
import pandas as pd

data = ['word1, word2, word3',
        'word2, word3',
        'word4, word3, word1',
        'word2, word4']

result = collections.Counter()
for item in data:
    for pair in IT.combinations(item.split(', '), 2):
        result[tuple(sorted(pair))] += 1

df = pd.DataFrame([pair+(freq,) for pair, freq in result.items()], columns=['source', 'target', 'freqency'])
print(df)

rawDescription: If I have a list of character strings which are words separated by commas, how do I convert that into a DataFrame with word pairings and frequencies?


code:
def nearest_workday(dt):
    """
    If holiday falls on Saturday, use day before (Friday) instead;
    if holiday falls on Sunday, use day thereafter (Monday) instead.
    """
    if dt.weekday() == 5:
        return dt - timedelta(1)
    elif dt.weekday() == 6:
        return dt + timedelta(1)
    return dt

def after_nearest_workday(dt):
    """
    returns next workday after nearest workday
    needed for Boxing day or multiple holidays in a series
    """
    return next_workday(nearest_workday(dt))

rawDescription: Pandas Time Series Holiday Rule Offset

description: Pandas Time Series Holiday Rule Offset


code: re.split(r'JUNE|JULY', 'ABCJUNE123')

rawDescription: Splitting members of series using regular expressions with strings


code: import liball as foo, libalb as bar, liball

rawDescription: fake python modules via symlinks: on windows?

description: Fake python modules via symlinks: on windows


code:
import tkinter as tk

# --- functions ---

def text_change():
    global text

    text += 1

    if text > 4:
        text = 1

    print("changed to:", text)

    #btn['text'] = text
    btn.config(text=text)

def text_print():
    print("current:", text)

# --- main ---

text = 0

root = tk.Tk()

btn = tk.Button(text="1,2,3 or 4", command=text_change, width=10, height=3)
btn.grid(row=1, column=1)

btn2 = tk.Button(text="SHOW", command=text_print, width=10, height=3)
btn2.grid(row=2, column=1)

root.mainloop()

rawDescription: python button change text after click

description: Python button change text after click


code:
def _subfunc1(x):
    """A preceding underscore signals to the reader that it's an internal function."""
    return x + 1

def _subfunc2(x):
    return x * 2

def my_function(x):
    """Yours will be cooler."""
    return _subfunc1(x) * _subfunc2(x)

rawDescription: choosing between a class or function in edge programming case

description: Choosing between a class or function in edge programming case


code:
class Parent(object):
  counter = 0
  def __init__(self):
    type(self).counter += 1

class C1(Parent): pass

class C2(Parent): pass

C1().counter
C1().counter
C1().counter
C2().counter
C2().counter
C2().counter

rawDescription: Parent changing child's attribute

description: Parent changing child's attribute


code:
for k, v in sorted(frequency.items(), key=lambda x: x[1], reverse=True):
    print(k, v)

rawDescription: python word counter w/ sorted frequency

description: Python word counter w/ sorted frequency


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

#Data:
x = np.linspace(0,2*np.pi,100)
f = np.sin(x) + .02*(np.random.rand(100)-.5)

#Normalization:
dx = x[1] - x[0] # use np.diff(x) if x is not uniform
dxdx = dx**2

#First derivatives:
df = np.diff(f) / dx
cf = np.convolve(f, [1,-1]) / dx
gf = ndimage.gaussian_filter1d(f, sigma=1, order=1, mode='wrap') / dx

#Second derivatives:
ddf = np.diff(f, 2) / dxdx
ccf = np.convolve(f, [1, -2, 1]) / dxdx
ggf = ndimage.gaussian_filter1d(f, sigma=1, order=2, mode='wrap') / dxdx

#Plotting:
plt.figure()
plt.plot(x, f, 'k', lw=2, label='original')
plt.plot(x[:-1], df, 'r.', label='np.diff, 1')
plt.plot(x, cf[:-1], 'r--', label='np.convolve, [1,-1]')
plt.plot(x, gf, 'r', label='gaussian, 1')
plt.plot(x[:-2], ddf, 'g.', label='np.diff, 2')
plt.plot(x, ccf[:-2], 'g--', label='np.convolve, [1,-2,1]')
plt.plot(x, ggf, 'g', label='gaussian, 2')

rawDescription: Python finite difference functions?

description: Python finite difference functions


code:
matrices = vectors = None

def init(_matrices, _vectors):
    global matrices, vectors
    matrices = _matrices
    vectors = _vectors

def f(type_, input_vector):
    return np.dot(matrices[type_], input_vector) + vectors[type_]

def main():
    # <declare matrices, vectors, input_vectors here>
    p = multiprocessing.Pool(initializer=init,
                             initargs=(matrices, vectors))
    results = {}
    for type_ in ['type1', 'type2']:
        func = partial(f, type_)
        results[type_] = p.map(func, input_vectors)

if __name__ == "__main__":
    main()

rawDescription: Global variables in python's multiprocessing.Pool class


code:
df = pd.DataFrame({'A': [0, np.nan, 2, 3, np.nan, 5], 'B': [1, 0, 1, np.nan, np.nan, 1]})
df2 = pd.DataFrame({'C': [0, np.nan, 2, 3, 4, 5], 'D': [1, 0, 1, 1, 0, 0]})
df
df2
d = {'A': df2.C, 'B': df2.D}  # pass this values in fillna
df
df.fillna(value=d)

rawDescription: Using pandas fillna() on multiple columns


code:
# Import both wx main module and the xrc module
import wx
import wx.xrc as xrc

class MyDialog(wx.Dialog):
    """
    This is our dialog. XRC will create it's widgets and all we need to do is
    handle the events.
    """
    def __init__(self, parent, res):

        pre = wx.PreDialog()
        self.PostCreate(pre)

        res.LoadOnDialog(self, None, "MyDialog")

        #Binding events

        self.Bind(wx.EVT_BUTTON, self.on_ok, xrc.XRCCTRL(self, "okButton"))
        self.Bind(wx.EVT_BUTTON, self.on_cancel, xrc.XRCCTRL(self, "cancelButton"))

    def on_ok(self, event):
        """Show a message box informing us we pressed the OK button"""
        msgDlg = wx.MessageDialog(self, "OK pressed", style=wx.OK)
        msgDlg.ShowModal()
        msgDlg.Destroy()
        self.Destroy()

    def on_cancel(self, event):
        """Show a message box informing us we pressed the Cancel button"""
        msgDlg = wx.MessageDialog(self, "Cancel pressed", style=wx.OK)
        msgDlg.ShowModal()
        msgDlg.Destroy()
        self.Destroy()

# Create the simplest wxApp object
app = wx.PySimpleApp()

# Load the XRC resources
res = xrc.XmlResource("example.xrc")

# Show and run the dialog
dlg = MyDialog(None, res)
dlg.ShowModal()

rawDescription: Using XRC to create custom Dialog boxes

description: Using XRC to create custom Dialog boxes


code:
import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

import numpy as np
import copy

def get_demo_image():
    from matplotlib.cbook import get_sample_data
    import numpy as np
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3,4,-4,3)

fig, ax = plt.subplots(figsize=[5,4])

# prepare the demo image
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30+ny, 30:30+nx] = Z

# extent = [-3, 4, -4, 3]
im = ax.imshow(Z2, extent=extent, interpolation="nearest",
          origin="lower")

#Without copy, image is shown in insert only
imcopy = copy.copy(im)
axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
axins.add_artist(imcopy)

# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)

plt.xticks(visible=False)
plt.yticks(visible=False)

# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

plt.draw()
plt.show()

rawDescription: Zoomed inset in matplotlib without re-plotting data


code:
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                ha='center', va='bottom')

rawDescription: How can I display text over columns in a bar chart in matplotlib?

description: Display text over columns in a bar chart in matplotlib


code:
import __builtin__
__builtin__.foo = 1
import a

rawDescription: Python: How to make a cross-module variable?


code:
heya = hello()
heya['a', 'b'] = [1, 2]
heya.a
heya.b

rawDescription: modify setattr to mass-assign multiple attributes to different values

description: Modify setattr to mass-assign multiple attributes to different values


code:
b = subprocess.Popen(['/path/to/ovs-vsctl', 'add-br', BR_EX],
                     stdin=None, stderr=None)

rawDescription: how to give raw_input to subprocess

description: Give raw_input to subprocess


code:
class klass(object):
    pass

def fmaker(i):
    def f(self):
        print(i)
    return f

for i in [1,2]:
    setattr(klass, 'f' + str(i), fmaker(i))

rawDescription: MetaPython: Adding Methods to a Class

description: MetaPython: Adding Methods to a Class


rawDescription: Efficient iteration over 3D array?

description: Efficient iteration over 3D array


code:
['line1', 'split at the dot']
['line2', 'split at the colon']
['line3', 'a colon preceded. by a dot']
['line4-neither a colon nor a dot']

rawDescription: Split by the delimiter that comes first, Python


code: print( ", ".join(all_scores) )

rawDescription: Looping test scores in file input/output


code: data = list(csv.reader(open(filename), delimiter=';'))

rawDescription: How can i split text data to a list?

description: Split text data to a list


code:
C = []
for A, B in zip(A_L, B_L):
    C.append([x + '*' if ((x + '*') in B) else x for x in A])

rawDescription: python lists: merge and replace

description: Python lists: merge and replace


rawDescription: Python Sympy Arbitrary Approximation to Arbitrary Sympy Expression?