code:
def explode_first(self):
    if self.bomb:
        if self.isDisarmed:
            self.parent.after(125, self.explode_fourth)   # If bomb is disarmed, skip to the last step, where the bomb is deleted.
        else:                                             # Otherwise, carry on with bomb explosion
            self.b1 -= 5
            self.b2 -= 5
            self.b3 += 5
            self.b4 += 5
            self.canvas.delete(self.bomb)
            self.bomb = self.canvas.create_oval(self.b1,
                                            self.b2,
                                            self.b3,
                                            self.b4,
                                            fill = "orange")
            self.parent.after(125, self.explode_second)

rawDescription: Canceling events after the .after() method has been called on them?


code:
import os
...
os.execl(sys.executable, "python", 'main.py')

rawDescription: Run python script from another python script but not as an child process


code:
WH = W.dot(H)
W = W * W_coeff

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


code: merged = text.splitlines()

rawDescription: How to join second line to end of first line in python?

description: Join second line to end of first line in python


code: {{ value|stringformat:"02d" }}

rawDescription: Django template filter for numbers

description: Django template filter for numbers


code:
expansions = {
        'colors':['red', 'blue', 'green'],
        'fruits':['apple', 'orange', 'banana'],
        'locations':['indoors', 'outdoors'],
        'indoors':['bathroom', 'bedroom', 'kitchen'],
        'green':['forest', 'light', 'dark']
    }

terms = ["colors", "locations"] # fruits omitted, to reduce the number of lines

for p in prod(terms, expansions):
    print(p)

rawDescription: generating conditional product of lists in python (combinatorics)

description: Generating conditional product of lists in python (combinatorics)


code:
int.__mul__
operator.mul

rawDescription: int.__mul__ , executes 2X slower than operator.mul

description: Int.__mul__ , executes 2X slower than operator.mul


code:
...
counts = []
for position in zip(seq1, seq2, seq3): # sets at same position
    counts.append(lettercount(position))
    for pair in combinations(position, 2): # pairs within set
        ...

rawDescription: frequency of letters in column python

description: Frequency of letters in column python


code: len([(1,) + a for a in combinations(range(2, 101), 2)])

rawDescription: Finding Optimal Change for Lowest Coin Total


code:
[
    {"content": "Using a web cam with your computer to video communicate with your loved ones has never been made easier and it's free (providing you have an Internet connection).  With the click of a few buttons, you are sharing your live video and audio with the person you are communicating with. It's that simple.  When you are seeing and hearing your grand kids live across the country or halfway around the world, web camming is the next best thing to being there!", "link": "http://buffalo.craigslist.org/cps/4784390462.html", "title": "Web Cam With Your Computer With Family And Friends"},
    {"content": "Looking to supplement or increase your earnings?", "link": "http://buffalo.craigslist.org/cps/4782757517.html", "title": "1k in 30 Day's"},
    {"content": "Like us on Facebook: https://www.facebook.com/pages/NFB-Systems/514380315268768", "link": "http://buffalo.craigslist.org/cps/4813039886.html", "title": "NFB SYSTEMS COMPUTER SERVICES + WEB DESIGNING"},
    {"content": "Like us on Facebook: https://www.facebook.com/pages/NFB-Systems/514380315268768", "link": "http://buffalo.craigslist.org/cps/4810219714.html", "title": "NFB Systems Computer Repair + Web Designing"},
    {"content": "I can work with you personally and we design your site together (no outsourcing or anything like that!) I'll even train you how to use your brand new site. (Wordpress is really easy to use once it is setup!)", "link": "http://buffalo.craigslist.org/cps/4792628034.html", "title": "I Make First-Class Wordpress Sites with Training"},
    ...
]

rawDescription: Scrapy JSON export issues

description: Scrapy JSON export issues


code:
from importlib import import_module

myplugins = []
for plugin in ['myplugin1', 'myplugin2']:
    myplugins.append(import_module('plugins.' + plugin))
    myplugins[-1].init()

##or using __import__:

myplugins = []
for plugin in ['myplugin1', 'myplugin2']:
    myplugins.append(getattr(__import__('plugins.' + plugin), plugin))
    myplugins[-1].init()

rawDescription: Telling __import__ where to look - am I stuck with sys.path?


code:
class MyClass:
    @property
    def last_transaction(self):
        # an expensive and complicated DB query here
        pass

rawDescription: How to mock a readonly property with mock?

description: Mock a readonly property with mock


code: row[1] = REV(flip(row[n-1]))

rawDescription: Numbers in a Matrix

description: Numbers in a Matrix


code:
for values in zip(*items.values()):
    item = dict(zip(items.keys(), values))
    print(item)

rawDescription: Turning list into dict

description: Turning list into dict


rawDescription: What is the Matlab equivalent to Python's `not in`?


code: BeautifulSoup(html)

rawDescription: how to introduce fault tolerance into beautiful soup

description: Introduce fault tolerance into beautiful soup


code:
import csv

# changed sample data key `Test` in order to have this key equal in all responses
# which would make more sense technically
data = [{u'Test': u'Result1', u'_id': '987600234565ade', u'bugseverity': u'major'},
{u'Test': u'Result2', u'_id': '987600234465ade', u'bugseverity': u'minor'},
{u'Test': u'Result3', u'_id': '9876002399999de', u'bugseverity': u'minor'}]

# define the column names
fieldnames = ['Test', '_id', 'bugseverity']

with open('dict.csv', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    for d in data:
        for key, value in d.items():
           writer.writerow(d)

rawDescription: Using Python need to print in csv format


code:
from timeout import timeout

# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
    ...

# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
    ...

# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
    ...

rawDescription: Timeout function if it takes too long to finish


code: [[(3*i + j, abs(i-j) + min(i,j)) for j in range(3)] for i in range(3)]

rawDescription: Creating a shifted matrix

description: Creating a shifted matrix


code: y_axis += [int(i) / summ]

rawDescription: Divide list elements by list sum and place back into list


code: sent = """The/AT grand/JJ jury/NN commented/VBD on/IN a/AT number/NN of/IN other/AP topics/NNS ,/, AMONG/IN them/PPO the/AT Atlanta/NP and/CC Fulton/NP-tl County/NN-tl purchasing/VBG departments/NNS which/WDT it/PPS said/VBD ``/`` ARE/BER well/QL operated/VBN and/CC follow/VB generally/RB accepted/VBN practices/NNS which/WDT inure/VB to/IN the/AT best/JJT interest/NN of/IN both/ABX governments/NNS ''/'' ./."""

rawDescription: exracting chunks in python using nltk

description: Exracting chunks in python using nltk


rawDescription: Weighted Bimodal Bipartite Graph Projection conserving original weights


code:
from scrapy.http import Response
import requests
from requests_ntlm import HttpNtlmAuth

class NTLM_Middleware(object):

    def process_request(self, request, spider):
        url = request.url
        pwd = getattr(spider, 'http_pass', '')
        usr = getattr(spider, 'http_user', '')
        s = requests.session()
        response = s.get(url,auth=HttpNtlmAuth(usr,pwd))
        return Response(url,response.status_code,{}, response.content)

rawDescription: NTLM authentication with Scrapy for web scraping


code:
# For some reason it needs to be closed before copying it to the table
csv_file.close()
cursor.copy_expert("COPY products(name, description) from stdin with delimiter as ',' csv QUOTE '\"' ESCAPE '\"' NULL 'null' ",open(file_name))
conn.commit()
# Clearing the file
open(file_name, 'w').close()

rawDescription: Python PostgreSQL using copy_from to COPY list of objects to table


rawDescription: Multiply Series by distributing across MultiIndex levels


code:
#!/usr/bin/env python
from itertools import chain

dict1 = {'key_1': 10, 'key_2': 14, 'key_m': 321}
dict2 = {'key_1': 15, 'key_2': 12, 'key_m':2, 'key_n':34}

result = [[key] + [dict.get(key, "")
           for dict in (dict1, dict2)]
          for key in set(chain(dict1, dict2))]
result.sort()

print(result)

rawDescription: merging arrays in python

description: Merging arrays in python


code:
def my_view(request):
    get_args = request.GET #dict of arguments from a get request (like your example)
    post_args = request.POST #dict of arguments from a post request
    all_args = requst.REQUEST #dict of arguments regardless of request type.

rawDescription: How can i grab all url patrameters in django

description: Grab all url patrameters in django


code:
def filepath(filename, foldername=None, envar='MYAPPDIR'):
  dirpath = os.path.expanduser(os.environ.get(envar, "~/myFolder"))
  if foldername:
    dirpath = os.path.join(dirpath, foldername)

  try:
    os.makedirs(dirpath)
  except OSError as e:
    if e.errno != errno.EEXIST:
      raise
  return os.path.join(dirpath, filename)

rawDescription: Python Creating Unwanted Folder in Directory


code:
plt.scatter(x, y, c=t, cmap=cm.cmap_name_r)
# or
plt.scatter(x, y, c=t, cmap="cmap_name_r")

rawDescription: Scatter plot and Color mapping in Python


code: S = {k:[ R[j][k] for j in range(len(R)) ] for k in R[0].keys()}

rawDescription: Python: Mean of several dictionaries with the same keys


code:
import itertools
x = iter([ xrange(0,5), xrange(5,10)])
a = itertools.chain.from_iterable(x)
list(a)

rawDescription: If a python iterator returns iterable objects, how can I chain those objects into one big iterator?


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

nbins = 20
minbin = 0.
maxbin = 1.

data = np.random.normal(size=10000)
bins = np.linspace(minbin,maxbin,20)

cmap = plt.cm.spectral
norm = mpl.colors.Normalize(vmin=data.min(), vmax=data.max())
colors = cmap(bins)

hist, bin_edges = np.histogram(data, bins)

fig = plt.figure()
ax = fig.add_axes([0.05, 0.2, 0.9, 0.7])
ax1 = fig.add_axes([0.05, 0.05, 0.9, 0.1])

cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap,
                                norm=norm,
                                orientation='horizontal')

ax.bar(bin_edges[:-1], hist, width=0.051, color=colors, alpha=0.8)
ax.set_xlim((0., 1.))
plt.show()

rawDescription: How to add colorbar to a histogram?

description: Add colorbar to a histogram


code:
import sys
for line in sys.stdin:
    print(line)

rawDescription: Turn off buffering

description: Turn off buffering


code:
from billiard import Process, forking_enable

def cam(cam_id):
    import cv2 #doesn't matter if you import here or in cam()
    vc = cv2.VideoCapture(cam_id) #modify 0/1 to toggle between USB and internal camera
    while True:
        junk,image = vc.read()
        cv2.imshow("test",image)
        k = cv2.waitKey(33)
        if k==27:    # Esc key to stop
            break

def start():

    forking_enable(0) # Is all you need!
    camProcess = Process(target=cam, args=(0,))
    camProcess.start()

if __name__ == '__main__':
    start()
    cam(1)

rawDescription: OpenCV crash on OS X when reading USB cam in separate process


code:
class GetItem(object):
    def __init__(self, data):
        self.data = data

    def __getitem__(self, x):
        return self.data[x]

rawDescription: Python: the mechanism behind list comprehension


code:
new = []
for i in range(length):
    print(str(i)[-1], end = "")
    new += str(i)[-1]
return new

rawDescription: return a single digit in strings (python 3)

description: Return a single digit in strings (python 3)


code:
#!/usr/bin/python2
import codecs
with codecs.open('y.py', 'w', 'utf8') as outputFile:
    outputFile.write(u'#!/usr/bin/python2\n')
    outputFile.write(u'#coding:utf8\n')
    outputFile.write(u'\n')
    outputFile.write(u'# ' + u'Syst\xe9m' + u'\n')
    outputFile.write(u'print \'Hello, World!\'\n')

rawDescription: Cannot execute auto-generated Python script encoded in UTF8-sig


code:
newimage = np.where(np.in1d(oldimage, vct).reshape(oldimage.shape), 0, oldimage)
newimage

rawDescription: NumPy - Image (matrix) thresholding using an intensity value matrix.


code:
###############################################################################
# Nippey #### 29.10.2012 #### mod_rewrite #####################################
###############################################################################
# This modification to bottly.py allows the application of rewrite rules to
# requests _before_ they are processed by the routing system

class UrlRewriteException(BottleException):
    """ This is a base class for all rewrite related exceptions """

class UrlRewrite():
    """ This class processes every URL before is is passed to the routing system
    In case one of the included rewrite rules matches the URL, the URL will be modified.
    New rules can be added via the .addRule(str, str, bool) method.
    For each requested URL, the method apply will be called with the environ variable as parameter.
    """

    def __init__(self):
        """ Initiates the rules variable """
        print("UrlRewrite init.")
        self.rules = []

    def addRule(self, match, replace, final=False):
        """ Add a new rule.
        match:   Regular expression to search for. Can be a string or a compiled regular expression
        replace: Replacement string. May use backreferences.
        final:   If a rule with <final=True> matches the URL, the evaluation will be stopped afterwards
        """
        print("UrlRewrite addRule.")
        if type(match) is not str and type(replace) is not str:
            raise UrlRewriteException
        pattern = re.compile(match)
        self.rules.append({'pattern':pattern, 'repl':replace, 'final':bool(final)})

    def apply(self, environ):
        """ Test a URL for a match of one of the saved rules and rewrite it if required
        environ: Environmental variable created by bottle on each request. Contains the PATH_INFO
                 information, modification will happen with the reference to this variable.
        returns: Returns true if a rewrite has been executed. Not used by the main program (yet)
                 Original path will still be available as PATH_INFO_ORIGINAL in the environ variable
        """
        print("UrlRewrite apply.")
        rewritten = False
        url = environ['PATH_INFO']
        for rule in self.rules:             #Try to alppy each of the rules
            (url, noSubs) = rule['pattern'].subn(rule['repl'], url)
            if noSubs > 0:
                rewritten = True
                if rule['final']:
                    break
        if rewritten:
            environ['PATH_INFO_ORIGINAL'] = environ['PATH_INFO']
            environ['PATH_INFO'] = url
            return True
        return False

    """ EXAMPLES:

    #Backreferences may be used by the replacement string
    from bottle import url_rewrite
    url_rewrite.addRule("^/he(l*)o", r"/by\1e", False)
    #Input:  "/hello/test_hello"
    #Output: "/bye/test_hello"

    #All matching occurences will be replaced
    from bottle import url_rewrite
    url_rewrite.addRule("hello", "bye", False)
    #Input:  "/hello/test_hello"
    #Output: "/bye/test_bye"

    #Rules will be applied in successive order
    from bottle import url_rewrite
    url_rewrite.addRule("hello", "hi", False)
    url_rewrite.addRule("hi", "bye", False)
    #Input:  "/hello/test_hello"
    #Output: "/bye/test_bye"

    #Rules won't be re-applied from the start if one rule matches
    from bottle import url_rewrite
    url_rewrite.addRule("hi", "bye", False)
    url_rewrite.addRule("hello", "hi", False)
    #Input:  "/hello/test_hello"
    #Output: "/hi/test_hi"

    #After applying a rule with <final> set to True, the evaluation will be finished
    from bottle import url_rewrite
    url_rewrite.addRule("hello", "hi", True)
    url_rewrite.addRule("hi", "bye", False)
    #Input:  "/hello/test_hello"
    #Output: "/hi/test_hi"
    """
# END class UrlRewrite

url_rewrite = UrlRewrite()
# END ## mod_rewrite ## Nippey

rawDescription: Python: mod_rewrite-like function for bottle.py


code: recoded

rawDescription: How to decode string to use with Google Language Detection API?

description: Decode string to use with Google Language Detection API


code: df[(df['item'] == 'record') & (df['storage'].isin(['laptop', 'desktop']))]

rawDescription: Pandas selecting data with specific conditions


code:
#Read page data as a string
pageData = sock.read()
#set p as regular expression
p = re.compile('(?<=line1=)(.*)(?=;)')
#find all instances of regular expression in pageData
parsed = p.findall(pageData)
#load as JSON instead of using evaluate to prevent risky execution of unknown code
newParsed = json.loads(parsed[0])

rawDescription: How can I parse Javascript variables using python?

description: Parse Javascript variables using python


code:
dfm = pd.melt(df, id_vars="Tenor", var_name="Date", value_name="Rate")
dfm = dfm.sort("Tenor").reset_index(drop=True)
dfm["Date"] = pd.to_datetime(dfm["Date"], format="%YM%mD%d")
dfm = dfm[["Date", "Tenor", "Rate"]]

rawDescription: Re-shaping Dataframe so that Column Headers are made into Rows


code:
#coding: utf8
import re
s = """“作為”(act) ，用於罪行或民事過失時，包括一連串作為、任何違法的不作為和一連串違法的不作為；
    “行政上訴委員會”(Administrative Appeals Board) 指根據《行政上訴委員會條例》(第442章)設立的行政上訴委員會；(由1994年第6號第32條增補)
    “成人”、“成年人”(adult)* 指年滿18歲的人；  (由1990年第32號第6條修訂)
    “飛機”、“航空器”(aircraft) 指任何可憑空氣的反作用而在大氣中獲得支承力的機器；
    “外籍人士”(alien) 指並非中國公民的人；  (由1998年第26號第4條增補)
    “修訂”(amend) 包括廢除、增補或更改，亦指同時進行，或以同一條例或文書進行上述全部或其中任何事項；  (由1993年第89號第3條修訂)
    “可逮捕的罪行”(arrestable offence) 指由法律規限固定刑罰的罪行，或根據、憑藉法例對犯者可處超過12個月監禁的罪行，亦指犯任何這類罪行的企圖；  (由1971年第30號第2條增補)
    “《基本法》”(Basic Law) 指《中華人民共和國香港特別行政區基本法》；  (由1998年第26號第4條增補)
    “行政長官”(Chief Executive) 指─"""
for zh1, zh2, en in re.findall(r"“([^”]*)”(?:、“([^”]*)”)?\((.*?)\)",s):
    print(ascii((zh1, zh2, en)))

rawDescription: Python : match string inside double quotes and bracket


code:
class Test(object):
    __slots__ = ("prop",)

t = Test()

rawDescription: Built-in function to read __slots__

description: Built-in function to read __slots__


code:
def is_prime(a):
    for i in xrange(2, int(1 + a ** 0.5)):
        if a % i == 0:
            return False
    return True

rawDescription: finding the lowest collatz sequence that gives more that 65 primes

description: Finding the lowest collatz sequence that gives more that 65 primes


code:
def _resolve_value(self, name):
    value = super(ModelMetadataBase, self)._resolve_value(name)
    try:
        return _resolve(value, self._content_object)
    except AttributeError:
        return value

def _resolve(value, model_instance=None, context=None):
    """ Resolves any template references in the given value. """

    if isinstance(value, basestring) and "{" in value:
        if context is None:
            context = Context()
        if model_instance is not None:
            context[model_instance.__class__.__name__.lower()] = model_instance
    t = Template(value)
    value = t.render(context)
return value

rawDescription: Django SEO app, integrating external data like 'Best {{ product }} of the year'


code:
def checker(data):
    opened, result = 0, []
    for idx, char in enumerate(data):
        if opened == 0 and char != "(":
            result.append([idx, char])
        if char == "(":
            opened += 1
        elif char == ")":
            opened -= 1
    return result

assert checker('(A.(B|A)).A') == [[9, '.'], [10, 'A']]
assert checker('(A.(B|A))')   == []

rawDescription: Determine whether a character is not in a set of paranthesis at an index?


code:
import threading
import time

def infiniteloop1():
    while True:
        print('Loop 1')
        time.sleep(1)

def infiniteloop2():
    while True:
        print('Loop 2')
        time.sleep(1)

thread1 = threading.Thread(target=infiniteloop1)
thread1.start()

thread2 = threading.Thread(target=infiniteloop2)
thread2.start()

rawDescription: Can two infinite loops be ran at once?

description: Can two infinite loops be ran at once


rawDescription: Python - How can I change bytes in a file


code:
from datetime import datetime
from pytz import timezone
import pytz
_utc = pytz.utc

dte = "2002-08-22T07:00:00Z"
utc = datetime.strptime(dte, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=_utc)
for tz in pytz.all_timezones:
    tz = timezone(tz)
    print(tz)
    print(utc.astimezone(tz))

rawDescription: Translating timestamp to Human Readable format


rawDescription: Single variable category scatter plot pandas


rawDescription: Python: What's a fast way to read and split a file?


code:
for i in range(1, number_classes + 1):
    p = input("What is the name of class " + i)

rawDescription: How can I increase number in input statement in python?

description: Increase number in input statement in python


code:
if trickyOperationSucceeds():
    return True,"Success!"
return False,"The tricky thing failed!"

rawDescription: Rubyist in Pythonland: what is a real world example of a tuple?


code:
keys=[(t[1], t[2]) for t in genes]
keys

rawDescription: Bisecting lists containing multi-value entries? Advice on approaching this task


rawDescription: Get complete source code from a website generated on clicking a button


code:
with open('/path/to/some/file/you/want/to/read') as file_1, open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

rawDescription: What does it means to not exceeding 80 characters in a line in Python?


code:
from ican.haz import apple
from ican.haz.grape import Grape

a = apple.Apple()
g = Grape()

rawDescription: Python modules vs classes

description: Python modules vs classes


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

a = range(1,10)
b = range(4,13)
ind = np.arange(len(a))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(ind+0.25, b, 0.45, color='#deb0b0', align='center')

ax2 = ax.twinx()
ax2.bar(ind, a, 0.65, color='#b0c4de', align='center')

plt.xticks(ind, a)
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")

plt.tight_layout()
plt.show()

rawDescription: Two bar charts in matplotlib overlapping the wrong way


code:
import wx

class StaticWrapText(wx.PyControl):
   def __init__(self, parent, id=wx.ID_ANY, label='', pos=wx.DefaultPosition,
                size=wx.DefaultSize, style=wx.NO_BORDER,
                validator=wx.DefaultValidator, name='StaticWrapText'):
      wx.PyControl.__init__(self, parent, id, pos, size, style, validator, name)
      self.statictext = wx.StaticText(self, wx.ID_ANY, label, style=style)
      self.wraplabel = label
      #self.wrap()
   def wrap(self):
      self.Freeze()
      self.statictext.SetLabel(self.wraplabel)
      self.statictext.Wrap(self.GetSize().width)
      self.Thaw()
   def DoGetBestSize(self):
      self.wrap()
      #print self.statictext.GetSize()
      self.SetSize(self.statictext.GetSize())
      return self.GetSize()

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

        # Add a panel so it looks the correct on all platforms
        panel = wx.Panel(self, wx.ID_ANY)

        text = "I'm subclasses the statictext because I want it to act exactly like a static text, but correctly wordwrap as needed. I've found several examples of it on the web, but none that worked how I wanted. The wordwrap makes it look much nicer when the user may decide to re-size the window, so I would definitely like to have it be wordwrapped. I know about the wx.lib.wordwrap, but chose to use the built in Wrap function of the statictext control instead. It basically does the same thing from what I understand."
        #txt = wx.StaticText(panel, label=text)
        txt = StaticWrapText(panel, label=text)
        wxbutton = wx.Button(panel, label='Button', size=wx.Size(120,50))
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(txt,      0, wx.EXPAND, 5)
        sizer.Add(wxbutton, 1, wx.EXPAND, 5)
        panel.SetSizer(sizer)

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

rawDescription: wxPython problems with Wrapping StaticText

description: WxPython problems with Wrapping StaticText


code:
strip_n_chars("   foo", 2, " ")
strip_n_chars(" bar", 2, " ")

rawDescription: How to strip() out a maximum of two white spaces from the front of a string

description: Strip() out a maximum of two white spaces from the front of a string


code:
args = parser.parse_args()
content%args.__dict__

rawDescription: Generating pdf-latex with python script

description: Generating pdf-latex with python script


rawDescription: Generate adjacent pair permutations where each side of the pair can only be used once


code:
# remove uUWSGI's default logging configuration, this can be removed in
# more recent versions of uWSGI
root = logging.getLogger()
map(root.removeHandler, root.handlers[:])
map(root.removeFilter, root.filters[:])

logger = logging.getLogger(__name__)
logging.basicConfig(
    level=logging.INFO,
    format='%(levelname)-8s %(asctime)-15s %(process)4d:%(threadName)-11s %(name)s %(message)s'
)

rawDescription: Python logger not picking up the configure time format.


code:
import sys
import pygame
from pygame.locals import *

pygame.init()

screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("pygame test")
pygame.mouse.set_visible(True)

done = False
while not done:
  for event in pygame.event.get():
    if (event.type == KEYUP) or (event.type == KEYDOWN):
      print(event)
    if (event.key == K_ESCAPE):
      done = True

rawDescription: pygame error: TypeError: must be 2-item sequence

description: Pygame error: TypeError: must be 2-item sequence


rawDescription: Open a text file using notepad as a help file in python?


rawDescription: How to use a bundling/packetizing generator in Python?

description: Use a bundling/packetizing generator in Python


code:
s = "EVENT(X_HELLO) ... EVENT(X_HOW_ARE_YOU_DOING_TODAY)... EVENT(this one shouldn't appear because it doesn't start with X)"
re.findall(r"EVENT\(X(.*?)\)", s)

rawDescription: Getting strings in between two keywords from a file in python


code:
dframe = pd.read_clipboard() # your sample data
dframe['intercept'] = 1
X = dframe[['intercept', 'date_delta']]
y = dframe['monthly_data_smoothed8']

smresults = sm.OLS(y, X).fit()

dframe['pred'] = smresults.predict()

rawDescription: Pandas/Statsmodel OLS predicting future values


code:
import util.file_reader

util.file_reader.main("C:/file_address")

rawDescription: Equivalent of Ipython run command in normal python


code: instance = find_instance(lambda x: x.value == 1, [a, b])

rawDescription: Get class instance where a certain property has a certain value


code: scores.append("%s:%s" % (name, score))

rawDescription: How to store a name and score into a list?

description: Store a name and score into a list


rawDescription: Getting last item this line using python


code:
class Process:
    urgency = None

    def __init__(self, process_id, state, priority):
        self.process_id = process_id
        self.state = state
        self.priority = priority

    def operation_that_adds_class_variables(self):
        if self.priority > 5:
            self.urgency = 'HIGH'
        else:
            self.urgency = 'LOW'

    @property
    def memory_values(self):
        res = (self.process_id, self.state, self.priority)
        if self.urgency is not None:
            return res + (self.urgency,)
        return res

rawDescription: unpacking class variables as a list

description: Unpacking class variables as a list


code:
with open(r"data.csv") as r, open(r"data1.csv", "w") as w:
    rdr = csv.reader(r, quotechar='"', delimiter='|')
    for _, a, b in rdr:
        for x, y in product(a.split(), b.split()):
            w.write("{},{}\n".format(x, y))

rawDescription: Finding word co-occurrences

description: Finding word co-occurrences


code:
dates = [dct['time'] for dct in a]
reduce(datetime.datetime.__add__, dates)

rawDescription: Python list Comprehension inside dictionaries


rawDescription: python: how can I achieve a cartesian product of all the lists in a list?

description: Python: how can I achieve a cartesian product of all the lists in a list


code:
import numpy

# Polynomial Regression
def polyfit(x, y, degree):
    results = {}

    coeffs = numpy.polyfit(x, y, degree)

     # Polynomial Coefficients
    results['polynomial'] = coeffs.tolist()

    # r-squared
    p = numpy.poly1d(coeffs)
    # fit values, and mean
    yhat = p(x)                         # or [p(z) for z in x]
    ybar = numpy.sum(y)/len(y)          # or sum(y)/len(y)
    ssreg = numpy.sum((yhat-ybar)**2)   # or sum([ (yihat - ybar)**2 for yihat in yhat])
    sstot = numpy.sum((y - ybar)**2)    # or sum([ (yi - ybar)**2 for yi in y])
    results['determination'] = ssreg / sstot

    return results

rawDescription: How do I calculate r-squared using Python and Numpy?

description: Calculate r-squared using Python and Numpy


rawDescription: How to pickle individual steps in sklearn's Pipeline?

description: Pickle individual steps in sklearn's Pipeline


code:
class Country(models.Model):
    continent = models.CharField()
    name = models.CharField(unique=True)

class City(models.Model):
    name = models.CharField(unique=True)
    country = models.ForeignKey(Country)
    founded_date = models.DateField()

class Event(models.Model):
    name = models.CharField(unique=True)
    city = models.ForeignKey(City)
    start = models.DateField()
    end = models.DateField()

rawDescription: Storing logic inside database

description: Storing logic inside database


code: from numpy import dot

rawDescription: sum function in python

description: Sum function in python


code: Q = np.prod(1/(1-np.exp(-h*freq[:, None]/kb/T)), axis=0)

rawDescription: python for loop for creating a 2D array form 2 1D array

description: Python for loop for creating a 2D array form 2 1D array


rawDescription: Is it possible to append Series to rows of DataFrame without making a list first?


code:
import re
s = "AATTAATCTATATATTGAAATGGGGCCCCAATTTTCCCAAATC ...."
[(m.start(), m.end()) for m in re.finditer('AAT.*?(?:ATG|TTT|ATC)', s)]

rawDescription: How to: From one string to another in a long list of strings


code:
mat = np.random.randn(4,3)
mat.shape
mat
mat.shape = 2,6
mat.shape
mat

rawDescription: Storing these vectors but which data structure to use in Python


code:
class Foo(object):
    def __init__(self, x):
        self.x = x
        self.count = 0
    def __hash__(self):
        return hash((self.x, ))
    def __iadd__(self, n):
        self.count += n
        return self
    def __eq__(self, other):
        return self.x == other.x

x = {Foo(1)}
i = next(iter(x))
i+=1
x.add(i)
print(x)

rawDescription: Reinserting set element creates holes

description: Reinserting set element creates holes


rawDescription: Changing background colour of wx.MDIParentFrame


code:
import pandas as pd
df = pd.DataFrame({'A': [0, 4, 0, 4, 4, 6], 'B': [5, 10, 10, 5, 5, 10]})
result = df.loc[df['B'] == 5].groupby('A').size()
result = result.reindex(df['A'].unique())

rawDescription: Conditional counting within groups

description: Conditional counting within groups


code:
alldirs = []
for root, dirs, files in os.walk('root path'):
    for dir in dirs:
        alldirs.append(os.path.join(root, dir))

# the following two lines make sure that leaf directories are renamed first
alldirs.sort()
alldirs.reverse()

for dir in alldirs:
    if ...:
        os.rename(...)

rawDescription: recursive script to rename folders ending with a space or period

description: Recursive script to rename folders ending with a space or period


code:
df
df.pivot_table(index='id', columns='key', values='val', aggfunc='sum', fill_value=np.nan)

rawDescription: Dealing with missing data in an one column text file


code:
#!/usr/bin/env python

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

text = MonkeyRunner.help("html");

f = open('help.html', 'w')
f.write(text);
f.close();

rawDescription: Where is the help.py for Android's monkeyrunner


code:
cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('mytable',))
cur.fetchone()[0]

rawDescription: Checking if a postgresql table exists under python (and probably Psycopg2)


code:
soup = BeautifulSoup(page, 'lxml')  # requires 'lxml' to be installed

table = soup.find("center").find("table")
for row in table.find_all("tr")[3:]:
    cells = [cell.get_text(strip=True) for cell in row.find_all("td")]
    print(cells)

rawDescription: Scrape data from reduced table

description: Scrape data from reduced table


code:
equipment = {
              'Longsword': 15,
              'Axe':       17
            }

rawDescription: Text Based Python RPG - Storing Weapons

description: Text Based Python RPG - Storing Weapons


code:
dirs = []
files = []
for name in os.listdir(home_path):
    path = os.path.join(home_path, name)
    if os.isdir(path):
        dirs.append(name)
    else:
        files.append(name)

rawDescription: clean way to os.walk once python

description: Clean way to os.walk once python


rawDescription: Difference between numpy.array shape (R, 1) and (R,)


code:
from markdown import blockprocessors as bp
class NoProcessing(bp.BlockProcessor):
    def test(self, parent, block):
        return False   # never invoke this processor

bp.CodeBlockProcessor = NoProcessing

rawDescription: Reducing capabilities of markdown in python


code:
field_names = list(field_names)
field_names.sort()

rawDescription: Sorting model fields in set

description: Sorting model fields in set


code:
def f2(coord,args):
    x,y,r = args
    # notice that we're returning a vector of dimension 3
    return ((coord[0]-x)**2) + ((coord[1] - y)**2) - (r**2)

rawDescription: How to perform non-linear optimization with scipy/numpy or sympy?

description: Perform non-linear optimization with scipy/numpy or sympy


code:
def vectorized(prob_matrix, items):
    s = prob_matrix.cumsum(axis=0)
    r = np.random.rand(prob_matrix.shape[1])
    k = (s < r).sum(axis=0)
    return items[k]

rawDescription: Fast random weighted selection across all rows of a stochastic matrix


code: my_text = my_button.cget('text')

rawDescription: Get the text of a button widget

description: Get the text of a button widget


code:
def fee(tup):
   return sum(map(lambda x,y:(x-y)**2,tup,tup[1:]+(tup[0],)))

rawDescription: Map a function's argument, which is a lambda, to a tuple?


rawDescription: compare two python strings that contain numbers

description: Compare two python strings that contain numbers


code:
if self.year:
    if self.year == date.year:
        return True
    else:
        return False
return False # Actually return self.year, but usually a boolean is intended in this sort of situation

rawDescription: Logical operator "and" in python

description: Logical operator "and" in python


code:
(Column(name='col1', type_code=23, display_size=None, internal_size=4, precision=None, scale=None, null_ok=None),
 Column(name='col2', type_code=23, display_size=None, internal_size=4, precision=None, scale=None, null_ok=None),
 Column(name='colblah', type_code=705, display_size=None, internal_size=-2, precision=None, scale=None, null_ok=None))

rawDescription: How to get column attributes from a query using PostgreSQL?

description: Get column attributes from a query using PostgreSQL


code:
print([cls.__name__ for cls in vars()['Foo'].__subclasses__()])
# ['Bar', 'Baz']

rawDescription: How can I find all subclasses of a given class in Python?

description: Find all subclasses of a given class in Python


code:
def __getClass__():

    class AClass:

        # constructor

        def __init__(self):
            pass

    return AClass

# allow to 'import *'  from this file as a module

__all__ = ['__getClass__']

rawDescription: Python: how to create a class name on the fly


rawDescription: Get random sample from list while maintaining ordering of items?


code:
import os
cmd = 'lsusb'
os.system(cmd)

rawDescription: What is the easiest way to get an usb-drive unique id with python on linux?


code:
app-arch/bzip2
app-arch/lz4
app-arch/xz-utils
dev-lang/python
dev-libs/expat
dev-libs/glib
dev-libs/icu
dev-libs/libffi
dev-libs/libpcre
dev-libs/libxml2
dev-libs/openssl
dev-python/h5py
dev-python/matplotlib
dev-python/mpi4py
dev-python/numpy
dev-python/pillow
dev-python/PyQt5
dev-python/sip
dev-qt/qtcore
dev-qt/qtdbus
dev-qt/qtgui
dev-qt/qtsvg
dev-qt/qtwidgets
media-gfx/graphite2
media-libs/fontconfig
media-libs/freetype
media-libs/harfbuzz
media-libs/jpeg
media-libs/libpng
media-libs/openjpeg
media-libs/tiff
sci-libs/blas-reference
sci-libs/cblas-reference
sci-libs/hdf5
sci-libs/lapack-reference
sci-libs/szip
sys-apps/attr
sys-apps/dbus
sys-apps/hwloc
sys-apps/systemd
sys-apps/util-linux
sys-cluster/openmpi
sys-devel/gcc
sys-libs/glibc
sys-libs/libcap
sys-libs/zlib
sys-process/numactl
x11-drivers/nvidia-drivers
x11-libs/libICE
x11-libs/libpciaccess
x11-libs/libSM
x11-libs/libX11
x11-libs/libXau
x11-libs/libxcb
x11-libs/libXcursor
x11-libs/libXdmcp
x11-libs/libXext
x11-libs/libXfixes
x11-libs/libXi
x11-libs/libxkbcommon
x11-libs/libXrender
x11-libs/xcb-util
x11-libs/xcb-util-image
x11-libs/xcb-util-keysyms
x11-libs/xcb-util-renderutil
x11-libs/xcb-util-wm

rawDescription: Retrieve list of external C/Fortran dependencies for Python libraries within a virtualenv


code:
def onMessage(self, socket, message):
    if not self.users:
        socket.send("Nobody is online, please use REGISTER command" \
                    " in order to register into the server")
    else:
        socket.send("ONLINE " + ' ' .join(self.users.keys()))

rawDescription: Python: Checking if a 'Dictionary' is empty doesn't seem to work


code: rm = pd.rolling_mean(df2.unstack().T, 7)

rawDescription: computing rolling averages by integer days in pandas

description: Computing rolling averages by integer days in pandas


code:
def get_lines(files):
    for f in files:
        for line in f:
            #preprocess line
            yield line

rawDescription: Where to use yield in Python best?

description: Where to use yield in Python best


code: [(np.bincount(i)>0).sum() for i in data]

rawDescription: vectorize numpy unique for subarrays

description: Vectorize numpy unique for subarrays


code: value = line.rstrip('\n').split(",")

rawDescription: Python reading \n on the end of a line

description: Python reading \n on the end of a line


code:
from Tkinter import *
from ttk import *

class TkGui(object):
    def __init__(self):
        self.root = root = Tk()
        self.root.withdraw()
        selector = FolderSelection(self.root, ('foo', 'bar'))
        self.root.deiconify()
        print(selector.result)

class ChildWindow(object): #Base class
    def __init__(self, parent, title):
        top = self.top = Toplevel(parent)
        self.parent = parent
        top.title(title)
        f = Frame(top)
        self.create_controls(f)
        f.pack(fill=BOTH, expand=Y)

    def create_controls(self, container):
        pass

    def make_modal(self, on_cancel):
        #self.top.transient(self.parent)
        #self.top.wait_visibility() # Python will hang here...
        #self.top.grab_set()
        self.top.focus_set()
        self.top.protocol("WM_DELETE_WINDOW", on_cancel)
        self.top.wait_window(self.top) # ...or here, if wait_visibility is removed

class FolderSelection(ChildWindow):
    def __init__(self, parent, folders):
        self.parent = parent
        self.listvar = Variable(parent)
        self.folderlist = None
        super(FolderSelection, self).__init__(parent, 'Select folder')
        self.result = ''
        self.listvar.set(folders)
        self.make_modal(self.cancel)

    def create_controls(self, container):
        f = Frame(container)
        Label(
            f, text='Please select the folder '
            'you would like to use.').grid(column=0, row=0)
        self.folderlist = Listbox(
            f, listvariable=self.listvar, activestyle='dotbox')
        self.folderlist.grid(column=0, row=1, sticky="nsew")
        Button(
            f, text='OK', command=self.ok
            ).grid(column=0, row=2, sticky="s")
        self.folderlist.bind("<Double-1>", lambda e: self.ok())
        f.pack(fill=BOTH, expand=Y)

    def ok(self):
        if len(self.folderlist.curselection()) != 0:
            self.result = self.folderlist.get(self.folderlist.curselection()[0])
            self.top.protocol('WM_DELETE_WINDOW', None)
            self.top.destroy()

    def cancel(self):
        self.top.destroy()

TkGui()
mainloop()

rawDescription: Hiding Tkinter root window while showing modal window


code:
Yvalues = [1, 2, 3, 4, 5]
file_out = open('file.csv','wb')
mywriter=csv.writer(file_out, delimiter = '\n')
mywriter.writerow(Yvalues)
file_out.close()

rawDescription: Python and appending items to text and excel file


code:
class SparseMatrix:
    def __init__(self, rows: int, cols: int, *entries):
        self.rows = rows
        self.cols = cols
        self.matrix = dict()
        for entry in entries:
            self.matrix[(entry[0], entry[1])] = entry[2]

    def row(self, row_num: int):
        return [self.matrix.get((row_num, i), 0) for i in range(self.cols)]

rawDescription: Returning 0 for a value that doesn't exist


code:
with open('myfile.fasta', 'rU') as fp:
   ...

rawDescription: Python - How to recognize EOL in FASTA file


code:
#Standard
LuminanceA = (0.2126*R) + (0.7152*G) + (0.0722*B)
#Percieved A
LuminanceB = (0.299*R + 0.587*G + 0.114*B)
#Perceived B, slower to calculate
LuminanceC = sqrt( 0.241*R^2 + 0.691*G^2 + 0.068*B^2 )

rawDescription: python -- measuring pixel brightness

description: Python -- measuring pixel brightness


code:
...
AUTH_PROFILE_MODULE = 'accounts.UserProfile'
...

rawDescription: get user profile in django

description: Get user profile in django


code: key_whose_count_is_10 = next(k for k, v in d.items() if v==10)

rawDescription: Python Counter: print key whose count is x


code: sourceout.write (str(readfile) + "\r\n")

rawDescription: Python - glob.glob doesn't find *.txt in specified filepath within Unix OS


rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


rawDescription: Capture contents in regular expression

description: Capture contents in regular expression


rawDescription: Remove Rows Based on User-Input Conditions (Pandas,Python 3)


code:
for ignored in range(int(input())):
    print(input())

rawDescription: exec in Python 3

description: Exec in Python 3


code: data_a[i+1+shift:i+1+shift] = [float(nan)] * int(num_fills)

rawDescription: How to improve my performance in filling gaps in time series and data lists with Python

description: Improve my performance in filling gaps in time series and data lists with Python


code:
newoutput = []
for item in linelist:
   if len(item) == 1:
       newoutput[-1][-1] += item[0]
   else:
       newoutput.append(item)

rawDescription: Concatenating Broken Strings Across Lists - Python


code:
from PyQt4 import QtGui
import sys

filenames = []

class TestGui(QtGui.QWidget):
    """ A Fast test gui show how to create buttons in a ScrollArea"""
    def __init__(self):
        super(TestGui, self).__init__()
        self.lay = QtGui.QHBoxLayout()
        self.sA = QtGui.QScrollArea()
        self.sA_lay = QtGui.QVBoxLayout()
        self.sA.setLayout(self.sA_lay)
        self.closeGui = QtGui.QPushButton("Close")
        self.add_file_button = QtGui.QPushButton("Add File")
        self.lay.addWidget(self.closeGui)
        self.lay.addWidget(self.add_file_button)
        self.lay.addWidget(self.sA)
        self.setLayout(self.lay)
        self.connect_()
        self.show()

    def connect_(self):
        self.add_file_button.clicked.connect(self.__add_file_to_list)
        self.closeGui.clicked.connect(self.close)
        return

    def __add_file_to_list(self):
        fname = QtGui.QFileDialog.getOpenFileName()
        global filenames
        filenames.append(fname)
        button = QtGui.QPushButton(fname)
        self.sA_lay.addWidget(button)
        return

if __name__ == '__main__':
     app = QtGui.QApplication(sys.argv)
     tg = TestGui()
     sys.exit(app.exec_())

rawDescription: How to create a button for each element in a list and put it in a scroll-area?

description: Create a button for each element in a list and put it in a scroll-area


code:
class A(object):
    x = 0

@copyattributes(A)
class B(object):
    y = 0

rawDescription: Python decorator to add class-level variables


rawDescription: Django search multiple filters

description: Django search multiple filters


code:
# use this to create the first level logger
def createTreeLogger(name, level=logging.DEBUG):
    logger = logging.getLogger(name)
    logger.setLevel(level)
    ch = logging.StreamHandler()
    ch.setLevel(level)
    ch.setFormatter(TreeFormatter())
    logger.addHandler(ch)
    return logger

if __name__ == '__main__':

    logger_a = createTreeLogger("a") # first level: use createLogger
    # then create your loggers as always
    logger_a_b = logging.getLogger("a.b")
    logger_a_b_c = logging.getLogger("a.b.c")

    logger_a.debug("One")

    logger_a_b.warning("two")
    logger_a_b.warning("three")

    logger_a_b_c.critical("Four")

    logger_a_b.warning("Five")
    logger_a.warning("Six")

rawDescription: Format log messages as a tree

description: Format log messages as a tree


rawDescription: Python: how to extract the content of a column in a table


code: my_queue = queue.Queue() # or multiprocessing.Queue()

rawDescription: check a list constantly and do something if list has items

description: Check a list constantly and do something if list has items


code:
s = list(1000 * string)
timeit.timeit('f(s)', 'from __main__ import s, inplace_add_concatenation as f', number=1000)
timeit.timeit('f(s)', 'from __main__ import s, str_join_concatenation as f', number=1000)

rawDescription: python list comprehension vs +=

description: Python list comprehension vs +=


rawDescription: Python3: Creating a string with an unescaped backslash


code:
class MyClass(object):
    @classmethod
    def as_view(cls):
        '''method intended to be called on the class, not an instance'''
        return cls(instantiation, args)

rawDescription: How to present a class as a function?

description: Present a class as a function


code:
import scipy.linalg
A = scipy.linalg.block_diag(*A_list)
B = B_list.reshape(-1)
solution = np.linalg.solve(A,B)
solution.reshape(-1,2)

rawDescription: How to map np.linalg.solve to an array of matrice and keep speed?

description: Map np.linalg.solve to an array of matrice and keep speed


rawDescription: How should I organise my functions with pyparsing?


code:
import yaml

class A(yaml.YAMLObject):
    yaml_tag = u'!A'

    def __init__(self):
        self.a = None
        self.b = [1, 2, 3]

    def __repr__(self):
        return yaml.dump(self)

    @classmethod
    def to_yaml(cls, dumper, data):
        cleaned_data = dict((k, v) for (k, v) in data.__dict__.items() if v is not None)
        return dumper.represent_mapping(cls.yaml_tag, cleaned_data)

rawDescription: How can I suppress 'None' output from yaml.dump, in Python?

description: Suppress 'None' output from yaml.dump, in Python


code:
from math import copysign
joyx = copysign(100, joyx) if abs(joyx) > 50 else 0

rawDescription: Is there a Pythonic way of handling this sort of range mapping


code:
import json

class FakeDict(dict):
    def __init__(self, items):
        self['something'] = 'something'
        self._items = items
    def items(self):
        return self._items

print(json.dumps(FakeDict([('a', 1), ('a', 2)])))

rawDescription: Adding duplicate keys to JSON with python


code: from endless_pagination.templatetags.endless import paginate

rawDescription: How to do result post-processing before rendering with django endless-pagination?

description: Do result post-processing before rendering with django endless-pagination


code:
from string import Formatter
num_terms = sum(1 for x in Formatter().parse("{0} {1} {2}"))

rawDescription: Iterate a format string over a list

description: Iterate a format string over a list


code:
def ngrams(tokens, MIN_N, MAX_N):
    n_tokens = len(tokens)
    for i in xrange(n_tokens):
        for j in xrange(i+MIN_N, min(n_tokens, i+MAX_N)+1):
            yield tokens[i:j]

rawDescription: Fast n-gram calculation

description: Fast n-gram calculation


code:
df = df.sort_values(['id', 'speed'])
df.groupby('id').apply(lambda x: x.Volume.iloc[x.speed.searchsorted(x.speed.max()*.5)])

rawDescription: Pandas chaining operators to identify value where record is closest to a number


code: row = 1

rawDescription: Converting for loops to while loops in python


code:
class Child(Parent):
    def __del__(self):
        print('In Child.__del__')
    foo = super_simple_decorator(Parent.foo)

rawDescription: Python classes with decorated methods and __del__ defined do not get garbage collected: how do I uncouple the decorated method?


code:
from fractions import Fraction
ilist1 = [-1, 1, 2, 3]
ilist2 = [-3, 3, 6, 9]
{str(Fraction(x, y)) for x in ilist1 for y in ilist2}
{str(Fraction(x, y)) for x, y in zip(ilist1, ilist2)}

rawDescription: How to make a character in a list appear only once?

description: Make a character in a list appear only once


code:
addresses = ['www.example.com/a/b/c/d', 'www.example.com/a/b/e/f', 'www.example.com/a/c/d/f']
elts = [addr.split('/')[1:] for addr in addresses]
tree = {}
for elt in elts:
    add_nodes(tree, elt)

tree

rawDescription: Pathname to a tree structure

description: Pathname to a tree structure


code: res_list.sort(key=lambda x: (float(x[1]), -float(x[2])))

rawDescription: Numeric sort on two columns but in different order using Python


code: np.intersect1d(a, np.intersect1d(b, c))

rawDescription: how to get items that belongs to all numpy arrays?

description: Get items that belongs to all numpy arrays


rawDescription: Create new list with copied and averaged items from old list


code:
('A', 'A', 'A', '(slang) (Tw) to steal')
('AA制', 'AA制', 'A A zhi4', 'to split the bill/to go Dutch')
('AB制', 'AB制', 'A B zhi4', 'to split the bill (where the male counterpart foots the larger portion of the sum)/(theater) a system where two actors take turns in acting the main role, with one actor replacing the other if either is unavailable')
('A咖', 'A咖', 'A ka1', 'class "A"/top grade')
('A圈兒', 'A圈儿', 'A quan1 r5', 'at symbol, @')
('A片', 'A片', 'A pian4', 'adult movie/pornography')

rawDescription: How to capture all regex groups in one regex?

description: Capture all regex groups in one regex


code:
def comparepeople(p1, p2):
    o1 = p1.lastname, p1.firstname, p1.dob
    o2 = p2.lastname, p2.firstname, p2.dob
    return cmp(o1,o2)

rawDescription: Pythonic Comparison Functions

description: Pythonic Comparison Functions


code:
def __call__(self, *args):
    if args not in self.memo:
        self.memo[args] = self.func(*args)
    return self.memo[args]

rawDescription: Permutation of phone numbers starting at button x, ending at button y, and z numbers long


code: d2.year - d1.year

rawDescription: Difference between 2 dates in years

description: Difference between 2 dates in years


rawDescription: How to compare two percentages in python?

description: Compare two percentages in python


code:
for i in xrange(0, N, batch_size):
    result = f(d[i, i + batch_size]) # This slice still works if i+batch_size > N
    ...

rawDescription: A decorator function for batching computations for large data in Python


rawDescription: Using dictionary values to calculate sum of weighted values without explicitly defined weights


code:
def example(box):
    box.delete(0, END)
    get = box.get()
    ...

for box in box1, box2, box3, box4:
    example(box)

rawDescription: How to repeat a function with change some variables inside of the function? PYTHON 3.4

description: Repeat a function with change some variables inside of the function? PYTHON 3.4


rawDescription: How to change QListWidget size interactively

description: Change QListWidget size interactively


code:
from scipy.ndimage.interpolation import geometric_transform
a=imread("sorNB.png")
h,l=a.shape
def mapping(lc):
    l,c=lc
    dec=(dl*(l-h))/h
    return l,c+dec
figure(1)
dl=50;c=geometric_transform(a,mapping,(h,l+dl),order=5,mode='nearest')
imshow (concatenate((a,zeros((225,50)),c),axis=-1),cmap=cm.gray)

rawDescription: Skewing an array in Python

description: Skewing an array in Python


code:
import json
data = json.load(open('my_file.json', 'r'))

rawDescription: Import JSON data into Python

description: Import JSON data into Python


code:
def sumNumbers(n):
    return sum(range(n+1))

rawDescription: How can I Improve this Code, using While Loop?

description: Improve this Code, using While Loop


code:
def punc(x):
    predicate = lambda y:y not in ''.join(c for c in string.punctuation if c not in ',/')
    out = filter(predicate,x)
    return out

rawDescription: Remove selected punctuation from list of sentences


code:
def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestMyUnit, 'test'))
    return suite

rawDescription: Python unittesting: run tests in another module


code:
expr = 'x*x + 2*x + 1'
expr_obj = compile(expr, '', 'eval')
x = 1
y = eval(expr)

rawDescription: Parsing code used in loop only once

description: Parsing code used in loop only once


code: from a_finder import A

rawDescription: Python, doing conditional imports the right way


code:
pprint(getNeighbour(board, 0, 0, 1))
pprint(getNeighbour(board, 2, 2, 1))

rawDescription: Iterator for each item in a 2D Python list and its immediate m by n neighbourhood


code:
rooms = list(db.rooms.find()[:1000])
print(rooms)

rawDescription: Find() a specified amount of records in mongo/python


code:
for k, v in d.items():
    col.find_one_and_update({k: {"$exists": True}}, {"$push": {k: {"$each": v}}})

rawDescription: Using $each with $push on all fields in python


code:
import datetime

def validate(date_text):
    try:
        datetime.datetime.strptime(date_text, '%Y-%m-%d')
    except ValueError:
        raise ValueError("Incorrect data format, should be YYYY-MM-DD")

rawDescription: How do i check if input is a date

description: Check if input is a date


code: [sum(x) for x in zip(ListA, ListB)]

rawDescription: Python - Merge two lists with a simultaneous concatenation


code:
import re
re.split(r'(\d+)', line)

rawDescription: Split a string using an integer as a delimeter


rawDescription: Numpy indexing multidimensional arrays with array and slice


code: abs(x-x.mean()) > x.std()

rawDescription: Numpy way to determine the value(s) in an array which is causing a high variance


code: df = pd.read_csv('data', sep=r'\s{2,}')

rawDescription: Pandas: read_csv indicating 'space-delimited'


code:
from pyspark.sql.functions import explode, col

transformed = (tokenized
    .drop("sentence")
    .select(col("sentence_id"), explode(col("words")).alias("word")))

rawDescription: "normalize" dataframe of sentences into larger dataframe of words


code:
def my_view(request):
    ...
    object = MyModel.objects.get(...)
    return redirect(object)

rawDescription: Django - template not loading, perpetual 302 message


rawDescription: Separating strings (list elements) with many spliters without loosing spliter from list


code:
timeit
def test():
    """Stupid test function"""
    lst = []
    for i in range(100):
        lst.append(i)

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test()", setup="from __main__ import test"))

rawDescription: Is there any simple way to benchmark python script?


code:
import base64
raw_data = base64.b64decode(data)
image = GdkPixbuf.Pixbuf.new_from_data(raw_data)
image_show_2.set_from_pixbuf(image)

rawDescription: Load image from base64 encoded image in Gtk3+


code:
from matplotlib import pyplot

fig, axes = pyplot.subplots(nrows=2, ncols=2)
fig.subplots_adjust(hspace=0.5)

print(fig.subplotpars.hspace, fig.subplotpars.wspace, sep='; ')

rawDescription: Matplotlib: Getting subplot position values (hspace, wspace, ..)


code: #print 'foo'   -->  logging.debug('foo')

rawDescription: Convert commented out print statements to logging calls - Python


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

N = 50
x_start, x_end = -2.0, 2.0
y_start, y_end = -1.0, 1.0

x = np.linspace(x_start, x_end, N)
y = np.linspace(y_start, y_end, N)

x0, y0, radius = 0.0, 0.0, 0.4

x, y = np.meshgrid(x, y)
r = np.sqrt((x - x0)**2 + (y - y0)**2)

outside = r > radius

fig, ax = plt.subplots()
ax.set(xlabel='X', ylabel='Y', aspect=1.0)

ax.scatter(x[outside], y[outside])

plt.show()

rawDescription: How to delete a set of meshgrid points inside a circle?

description: Delete a set of meshgrid points inside a circle


rawDescription: I want to rank document and store them in a list in python


code: from datetime import datetime

rawDescription: How to get current time in Python

description: Get current time in Python


code: 'beer' in lines

rawDescription: Searching for substrings in file.readlines() in python


code:
class Player(object):
    def __init__(self, nm, am, wp, ht, tp, ide):
        self.name = nm
        self.ammo = am
        self.weapon = wp
        self.health = ht
        self.type = tp
        self.id = ide

class Enemy(object):
    def __init__(self, nm, am, wp, ht, tp, ide):
        self.name = nm
        self.ammo = am
        self.weapon = wp
        self.health = ht
        self.type = tp
        self.id = ide

    def __str__(self):
        values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "I am a: " + self.type + "\n" + "ID #: " + str(self.id)
        return values

    def __str__(self):
        values1 = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "I am a: " + self.type + "\n" + "ID #: " + str(self.id)
        return values1

rawDescription: Creating methods with the same attributes


code:
cool_obj = cool.objects.get(ref_id=ref_id)
obj = cool.objects.filter(friend=cool_obj)
count = cool_obj.referral.all().count()

rawDescription: implementing a counter that counts requests with django

description: Implementing a counter that counts requests with django


code:
types = ['Small', 'Medium','Large']
while True:
    print('Types: '+ types)
    choice = raw_input('Choose a type. ').capitalize()
    if choice in types:
        break

rawDescription: Best way to select from a list

description: Select from a list


rawDescription: Combining two sorted lists in Python

description: Combining two sorted lists in Python


code:
ids = (link['id'] for link in
        BeautifulSoup(content, parseOnlyThese=SoupStrainer('input'))
         if link.has_key('id'))

rawDescription: Storing a List into Python Sqlite3

description: Storing a List into Python Sqlite3


code: dict((key, value) for key, value in ((x, func(y)) for x, y in l) if isinstance(value, int))

rawDescription: Is comprehension possible here?

description: Is comprehension possible here


code:
[item for items in zip(l1, l2) for item in items]
# [1,9,2,8,3,7,4,6]

rawDescription: python: Merge two 1D lists into one 1D list

description: Python: Merge two 1D lists into one 1D list


code:
import itertools
c = itertools.cycle([1, 2, 3])
next(c), next(c), next(c), next(c)
# 1, 2, 3, 1, ...

rawDescription: Sending values to zipped generators

description: Sending values to zipped generators


rawDescription: python parallel Popen

description: Python parallel Popen


code:
accept_intersect=[]
seen = {}

for item in totallist:

    # Track if a subitem has been seen
    seen_flag = False

    for sub_item in item:

        # If it has been seen before
        # stop looking in this list
        if sub_item in seen:
            seen_flag = True
            break

        # Add seen item
        seen[sub_item] = True

    # If a subitem was seen, skip and continue
    # with the next loop.
    if seen_flag == True:
        continue

    # Only append if no items were seen before.
    accept_intersect.append(item)

#totallist = [['19'], ['19', '22']]
#accept_intersect -> [['19']]

#totallist = [['19'], ['19', '22'], ['43'], ['44', '45'], ['65', '19']]
#accept_intersect -> [['19'], ['43'], ['44', '45']]

rawDescription: How to find list which items are not in output list and add list to output list?

description: Find list which items are not in output list and add list to output list


code: sims

rawDescription: Matching array elements to dictionary keys in Python


code:
event = pygame.event.poll()
# use event

rawDescription: Should I use pygame.event.get() or pygame.event.poll()?


code:
def coarse(dt, granularity):
    residue = dt.minute % granularity
    if residue:
        residue = granularity-residue
    dt = dt + datetime.timedelta(minutes=residue, seconds=-dt.second,
                    microseconds=-dt.microsecond)
    t = dt.time()
    return t

rawDescription: Averaging along DataFrame columns with some missing rows


code:
with open("Class {} data.txt".format(classNo),"a+",) as src:
    lines = src.readlines() # all lines are stored here
    for ind,line in enumerate(lines):
        if surname.lower() in line:
            print("yes")
            # score should be written on same line as the surname is in the txt fileS
            lines[ind] = "{} {}\n".format(line.rstrip(), score) # add first or new scores
        else:
            print("nope")
    with open("Class {} data.txt".format(classNo),"w",) as src: # reopen and write updated lines
        src.writelines(lines)

rawDescription: Searching for string in text file and writing on the same line as this string


code:
chunks = pd.read_csv(data, chunksize = 100)
df = pd.concat(chunks, ignore_index=True)

rawDescription: Python pandas to get specified rows from a CSV file


rawDescription: Python converting latin1 to UTF8

description: Python converting latin1 to UTF8


rawDescription: What is the scope of a defaulted parameter in Python?


code: float(repr(a_float)) == a_float

rawDescription: Converting a Python Float to a String without losing precision


code: 'A string with   some    space,\ttabs and \n\n newlines'.split(' ')

rawDescription: optimizing python code for performance

description: Optimizing python code for performance


code:
class foo(object):
    pass

rawDescription: how to determine if a variable is a valid class or type in python?

description: Determine if a variable is a valid class or type in python


code:
import numpy as np
import pylab as pl

pl.ioff()

rand_field = np.random.rand(10,10)

fig = pl.figure()
cm = pl.pcolormesh(rand_field, vmin=0, vmax=1)
pl.colorbar()

x_press = None
y_press = None

def onpress(event):
    global x_press, y_press
    x_press = int(event.xdata) if (event.xdata != None) else None
    y_press = int(event.ydata) if (event.ydata != None) else None

def onrelease(event):
    global x_press, y_press
    x_release = int(event.xdata) if (event.xdata != None) else None
    y_release = int(event.ydata) if (event.ydata != None) else None

    if (x_press != None and y_press != None and x_release != None and y_release != None):
        (xs, xe) = (x_press, x_release+1) if (x_press <= x_release) else (x_release, x_press+1)
        (ys, ye) = (y_press, y_release+1) if (y_press <= y_release) else (y_release, y_press+1)
        print("Slice [{0}:{1},{2}:{3}] will be set to zero".format(xs, xe, ys, ye))
        rand_field[ys:ye, xs:xe] = 0.
        cm.set_array(rand_field.ravel())
        event.canvas.draw()

    x_press = None
    y_press = None

cid_press   = fig.canvas.mpl_connect('button_press_event'  , onpress  )
cid_release = fig.canvas.mpl_connect('button_release_event', onrelease)

pl.show()

rawDescription: Interaction with python's matplotlib figure: assign value to selected features


code:
def splitkeepsep(s, sep):
    return reduce(lambda acc, elem: acc[:-1] + [acc[-1] + elem] if elem == sep else acc + [elem], re.split("(%s)" % re.escape(sep), s), [])

rawDescription: Django - Keep line breaks when importing CSV file


code: set(s for s in sets if not any(other < s for other in sets))

rawDescription: Algorithm to filter a set of all phrases containing in other phrase


code:
result=""
f=open('file.txt','r')
lines=f.readlines()
f.close()
for s in lines:
   L=s.split(" ")
   for x in L:
      i=x.find("|")
      if i!=-1:
         result+=x[:i]+" "
      else:
         result+=x.strip("\n")+" "
   result=result[:-1]+"\n"

rawDescription: Denormalize tab-delimited text file

description: Denormalize tab-delimited text file


code: any('C' in item for item in seto)

rawDescription: How can I tell if a string pattern exists within any element of a set in Python?

description: Tell if a string pattern exists within any element of a set in Python


code:
var1 = "Arbaham"
var2 = "My name is: %s"
print(var2 % var1)
var1 = "Abraham"
print(var2 % var1)

rawDescription: "Updating" a string with a format operator


code:
plt.figure()
for i, symbol in enumerate(symbols):
    y2 = y + 4*i
    plt.plot(x, y2, 'g')
    marker = "$%s$" % symbol
    plt.plot(x, y2, 'k', marker=marker, markersize=30)

rawDescription: matplotlib custom markers

description: Matplotlib custom markers


code:
try:
    x = int( self.c2_low.get() )
except ValueError:
    NotImplemented   #handle invalid input

rawDescription: Automatic filling of Tkinter.entry boxes by a separate function


code: xarr, yarr = array[0, :], array[1, :]

rawDescription: removing entries from a numpy array

description: Removing entries from a numpy array


code: balls = [ x for x in balls if x.times_bounced <= N ]

rawDescription: How to remove specific object from a list, if I can't use the variable it is attached to, to find its index?

description: Remove specific object from a list, if I can't use the variable it is attached to, to find its index


code:
mock_poll = Mock(side_effect=[None, 'data'])
mock_poll()
mock_poll()

rawDescription: python mock side_effect or return_value dependent on call_count

description: Python mock side_effect or return_value dependent on call_count


rawDescription: how regex in Python3 deal with diacritics?

description: How regex in Python3 deal with diacritics


rawDescription: Python Binary Divide by 2 method

description: Python Binary Divide by 2 method


rawDescription: Grouping Pandas DataFrame by date

description: Grouping Pandas DataFrame by date


code:
# n = 101 (in binary
# this can also be represented as 1*(2^2) + 0*(2^1) + 1*(2^0)
# alternatively, since there are three digits in this binary number
# 1*(2^(n-1)) + 0*(2^(n-2)) + 1*(2^(n-3))

rawDescription: binary to decimal using recursion,python

description: Binary to decimal using recursion,python


code:
_im_done = object()

class producer(threading.Thread):
    def run(self):
        '''feed the consumer until you are done'''
        queue.put(_im_done)

class consumer(threading.Thread):
    def run(self):
        while True:
            queue_ret = queue.get()
            if queue_ret is _im_done:
                break
            '''normal execution'''

rawDescription: Need help on producer and consumer thread in python


code:
from pandas import read_csv
from collections import defaultdict

data = defaultdict(lambda : defaultdict(list))

df = read_csv('datafile', sep='\t')
for a, b, c in df.values:
    data[a][b].append(c)

#from pprint import pprint
#pprint(data.items())

# output the total number of passes for each "A" in which all runs of "B" passed.
result_counts = {a: sum(1 for b in data[a] if all(c=='Passed' for c in data[a][b])) for a in data}
print('Counts: {}'.format(result_counts))

# output for each "A" a list of all passed "B"s.
result_passed = {a: list(b for b in data[a] if all(c=='Passed' for c in data[a][b])) for a in data}
print('Passed: {}'.format(result_passed))

rawDescription: Python - iterate text file and create dictionary of dictionary


code: #!/usr/bin/env python

rawDescription: Setting path directories for running files using command, python filename.py


rawDescription: Regular expression: Match string between two slashes if the string itself contains escaped slashes


code:
data=defaultdict(list)
with open('file1.csv') as infile:
    reader=csv.reader(infile)
    for row in reader:
        try:
            data[row[0]].append(row[1])
        except IndexError:
            pass
    print(data)

rawDescription: python3 csv with duplicate keys + python defaultdict

description: Python3 csv with duplicate keys + python defaultdict


code:
rdd = sc.parallelize([('k1', ['v1', 'v2']), ('k2', ['v3','v4','v5'])])
rdd.flatMap(lambda kv: ((kv[0], v) for v in kv[1])).map(lambda kv: (kv[1], func(kv))).collect()

rawDescription: Spark: how to generate several elements in map (python)?


code:
df
query = ' and '.join(['{0}=={1}'.format(x[0], x[1]) for x in parameter])
query
df.query(query)

rawDescription: Filter data iteratively in Python data frame


code: data = {k:v for k,v in { k:list(filter(lambda i: i['check'] == '1' ,v)) for k, v in data.items()}.items() if len(v)}

rawDescription: Filtering defaultdict on the base of value


code: list(map(list, Tuple))

rawDescription: convert a 2d tuple into a list

description: Convert a 2d tuple into a list


code:
# -*- coding: utf-8
...
img_urls = form_soup.findAll('a', title=u'查看大图')

rawDescription: how to get tags when attribute is chinese in beautifulsoup

description: Get tags when attribute is chinese in beautifulsoup


code:
file = 'test.txt'
path, file_name = os.path.split(file)
if not path: path = '.'

rawDescription: most efficient way to substring path and file out of a string

description: Most efficient way to substring path and file out of a string


code:
class transactionsForm(Form):
    loan_id = QuerySelectField('trans_id', validators=[Required()], get_label='name')

rawDescription: Pass a variable to a Flask WTForm

description: Pass a variable to a Flask WTForm


code:
#define your database structure
from google.appengine.ext import db

class PdfStorage(db.Model):
   timeAdded = db.DateTimeProperty(auto_now_add=True)
   pdfContent = db.BlobProperty()

rawDescription: How to save generated PDF with Reportlab to Datastore in App Engine Python

description: Save generated PDF with Reportlab to Datastore in App Engine Python


code: assert not my_var.called, 'method should not have been called'

rawDescription: Assert a function/method was not called using Mock


code:
traversal = np.linspace(0.0, 1.0,
                        num=max(alpha_beta_dist/float(precision), 2))

rawDescription: linspace that would always include the final point?

description: Linspace that would always include the final point


code:
big = np.vstack((lstname1,lstname2)).T
smaller = big[:2]
smaller[:,1]=33
smaller
big

rawDescription: clearing elements of numpy array

description: Clearing elements of numpy array


code: hdul = pyfits.open(filename, mode='update')

rawDescription: change keyword value in the header of a FITS file

description: Change keyword value in the header of a FITS file


code:
names = list(iter(partial(raw_input, 'Name: '), ''))
names

rawDescription: How to do variable assignment inside a while(expression) loop in Python?

description: Do variable assignment inside a while(expression) loop in Python


code:
id_triangle = lambda a, b, c: {0: 'scalene', 1: 'isoceles', 3: 'equilateral'}\
                              [(a == b) + (a == c) + (b == c)]

rawDescription: I'm making a triangle class finder and I'm stuck


rawDescription: Execute a function randomly

description: Execute a function randomly


code: dict((str(k), v) for k, v in c.iteritems())

rawDescription: Python: Convert this list into dictionary


code: hand

rawDescription: going through a dictionary and printing its values in sequence

description: Going through a dictionary and printing its values in sequence


rawDescription: What is the best practice to add tuples to a set?


code: group_position(df['Z'], df['A'])

rawDescription: Multiindex from array in Pandas with non unique data


rawDescription: Python's argparse choices constrained printing


code:
M = dd.max(0)
m = dd.min(0)

x = np.arange(m[0], M[0] + 1)
y = np.arange(m[1], M[1] + 1)
[X, Y] = np.meshgrid(x, y)

Z = np.zeros_like(X)

for num in range(0,size(dd, 0)):
    Z[dd[num, 0], dd[num, 1]] = dd[num, 2]

rawDescription: Matplotlib: Specific color with imshow

description: Matplotlib: Specific color with imshow


code: df

rawDescription: Why doesn't this function "take" after I iterrows over a pandas DataFrame?


code: axes[0, 0].legend(df.index, bbox_to_anchor=(0, 0.5))

rawDescription: Conditional removal of labels in Matplotlib pie chart


code:
import csv
import os

inputFileName = "temp.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_modified.csv"

with open(inputFileName, 'rb') as inFile, open(outputFileName, 'wb') as outfile:
    r = csv.reader(inFile)
    w = csv.writer(outfile)

    next(r, None)  # skip the first row from the reader, the old header
    # write new header
    w.writerow(['Item Number', 'Item Description', 'List Price', 'QTY Available'])

    # copy the rest
    for row in r:
        w.writerow(row)

rawDescription: Python Edit CSV headers

description: Python Edit CSV headers


code:
def consecCheck(s):
    return any(c1 == c2 for c1, c2 in zip(s, s[1:]))
consecCheck("apple")
consecCheck("candyman")

rawDescription: check 2 consecutive occurrences of the same letter

description: Check 2 consecutive occurrences of the same letter


code:
a=['aaaaa']
b=['aaaaa', 'bbbbb', 'ccccc']
c=['aaaaa']
d=['ppppp', 'aaaaa']
e=['aaaaa', 'uuuuu']
f=[]
list_of_lists = [a,b,c,d,e,f]
set.intersection(*(set(s) for s in list_of_lists if s))

rawDescription: Find common denominator for list entries Python


code:
from functools import partial

def func_1(gamma, x):
    return x + gamma

def thing_1(alpha, beta):
    gamma = alpha+beta
    def func_2(x):
        return x*gamma
    return Funcs(partial(func_1, gamma), func_2)

rawDescription: Python: Equivalent of Inheritance with Closures


rawDescription: How to hstack several sparse matrices (feature matrices)?

description: Hstack several sparse matrices (feature matrices)


code: from tkinter.ttk import Combobox

rawDescription: Implement a dynamic dropdown menu based on on the number of lines of text file


code:
def f(lst):
    return [x+1 for x in lst] + [len(lst)]
reduce(lambda lst, i: lst + [f(lst[i])], range(5), [[1]])

rawDescription: Python applying dynamic list comprehension (list append)


code:
df = df.swaplevel(0, 1, axis=1)
df = df.reindex(columns='Bet365 Bwin Betfair'.split(), level=0)
df.columns = ['{}_{}'.format(bet, hw)  for bet, hw  in df.columns]
pd.options.display.width = 100
print(df)

rawDescription: Transform rows in columns in Pandas

description: Transform rows in columns in Pandas


code:
def fileIsImportant(change):

    if "[skipbuild]" in change.comments:
        return False

    # There could be more logic here to test other things...

rawDescription: How can I arbitrarily tell Buildbot to not schedule a build for a given change?

description: Arbitrarily tell Buildbot to not schedule a build for a given change


code:
class Foo(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __repr__(self): # this will help us recognize our objs after we've sorted
        return "<name: {name}, age: {age}>".format(name=self.name, age=self.age)
f = Foo('Bar', 3)
g = Foo('Baz', 4)
def byAge(foo): return foo.age
sorted([f, g], key=byAge)

rawDescription: Discuss the "sorted" function in Python

description: Discuss the "sorted" function in Python


code:
import math
import curses
stdscr = curses.initscr()

radius = 10
for part in range(0, 100):
    angle = (part / 100) * math.pi * 2
    x = math.cos(angle) * radius + radius
    y = math.sin(angle) * radius + radius
    stdscr.addch(int(y * .7), int(x), 'o')

stdscr.getch()

rawDescription: How could I design none square symbol in ncurses?


code:
from m import SomeClass
SomeClass.__module__
import sys
sys.modules[SomeClass.__module__]
sys.modules[SomeClass.__module__].__all__
sys.modules[SomeClass.__module__].A_CONSTANT

rawDescription: Accessing the __all__ list of the parent module of a class instance


rawDescription: Pandas: Group Timeseries into parts of a day


code:
class CAB(A, B):
    '''uses A's __init__'''

class CBA(B, A):
    '''uses B's __init__'''

use1 = CAB()
use2 = CBA()

rawDescription: conditional class inheritance in python

description: Conditional class inheritance in python


code:
import threading
import time

class myBot(JabberBot, threading.Thread):
  def __init__( self, jid, password, res = none):
    threading.Thread.__init__(self)

  def run(self):
    while True:
      self.autoNotify()
      time.sleep(5) # wait 4 seconds

  def autoNotify(self):
    self.send('someuser@jabber.example.com','cooool message text!')

rawDescription: Execute Function Every X Seconds On Class Init


code: g.data_version = my_dict['dataVersion'] if my_dict else None # or 0 or '' depending on what data_version should be.

rawDescription: Python: Inline if statement else do nothing


code:
def recurseadd(test):
    if test:
        return [test[False] + True] + recurseadd(test[True:])
    else:
        return test

rawDescription: Increase each list element in all possible ways


code:
[item.text for item in soup.find_all("p", {"itemprop": "description"})]
[u' DESCRIPTION HERE ']

rawDescription: Using regex in Python to extract description of an app from Apple store html


code:
def byte_array(n):
    for i in range(2**(8*n)):
        yield [i>>j&1 for j in range(8*n-1, -1, -1)]

rawDescription: Python : efficient bytearray incrementation


code:
chained = itertools.chain.from_iterable(sixbit)
list(itertools.izip(*[chained]*8))

rawDescription: iterating over list of string and combining string values Python

description: Iterating over list of string and combining string values Python


code: df = df[(df['Phone'].str.startswith('+1')) & (df['Phone'].str.len() == 13)]

rawDescription: Delete rows not containing a value in pandas


rawDescription: How to create this tabular data structure with numpy?

description: Create this tabular data structure with numpy


code:
methods = {
    '+': lambda a, b: a + b,
    # ...
}

rawDescription: Is there any idiomatic way to add methods to object in Python?


code:
number_to_send = (sequence_number << 4) + fragment_number
bytes_to_send = struct.pack("!H", number_to_send)

rawDescription: Spliting a 16 bits value to 12+4 python struct


code:
widgets = {'combo_first_item': my_comboBox,
           'combo_second_item': my_lineEdit,
           'combo_third_item': my_spinBox}

rawDescription: How to toggle enabled state of widgets based on QcomboBox index

description: Toggle enabled state of widgets based on QcomboBox index


code:
def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = next(it)
    yield total
    for element in it:
        total = func(total, element)
        yield total

rawDescription: Equivalent of Haskell scanl in python

description: Equivalent of Haskell scanl in python


code:
with open(source) as f:
   data = []
   for row in f:
       data.extend(map(float,row.split()))

rawDescription: coordinates (str) to list

description: Coordinates (str) to list


code:
from collections import defaultdict
adic = defaultdict(int)
for i in alist:
    adic[i] += 1
return adic

rawDescription: Count occurence in a list with time complexity of O(nlogn)


code:
import pandas as pd

n = 5
output = pd.DataFrame({'pos': range(1, n + 1),
                      'bidder': [''] * n},
                      columns=['pos', 'bidder'])
bids = {'alice': 3, 'bob': 3}
used_pos = []
for bidder, pos in bids.items():
    if pos in used_pos:
        output.ix[pos, 'bidder'] = "<- %s" % bidder
        output.ix[pos, 'pos'] = ''
    else:
        output.ix[pos - 1, 'bidder'] = "<- %s" % bidder
        used_pos.append(pos)
print(output)

rawDescription: Pretty printing newlines inside a string in a Pandas DataFrame


code:
ax = pylab.subplot(111)
thetas = np.linspace(0,6*np.pi,1000)
i = np.arange(len(thetas))
xdata = (1. + (3.-1.)*i/len(thetas))*np.cos(thetas)
ydata = (1. + (3.-1.)*i/len(thetas))*np.sin(thetas)
ax.plot(xdata, ydata, color = 'b')
pylab.xlabel('x')
pylab.ylabel('y')
for x, y in zip(xdata,ydata)[::25]:
    rtext(ax.lines[0], x, y,
          '$\\alpha = \\alpha_0$', fontsize = 14, color = 'r',
          horizontalalignment='center', verticalalignment='center')

rawDescription: Matplotlib, adding text with more than one line. Adding text that can follow the curve


code: setattr(A, 'x', x)

rawDescription: Creating a variable inside of a for loop


rawDescription: Best way to iterate through a numpy array returning the columns as 2d arrays

description: Iterate through a numpy array returning the columns as 2d arrays


rawDescription: python sort with adjacent difference

description: Python sort with adjacent difference


code:
country_id = 56451
country_url = "http://www.blocgame.com/stats.php?id=" + str(country_id)
country_source = urllib.request.urlopen(country_url)

country_page = BeautifulSoup(country_source)
country_text = country_page.text
rawAirforce = country_text.split("Airforce:")[1]
navyArray = rawAirforce.split("Navy:")
airforce = navyArray[0].strip()
navy = navyArray[1].split("Chemical Weapons:")[0].strip()
print("Airforce: " + airforce + " Navy: " + navy)

rawDescription: How do I ignore the first(or certain) lines when parsing a string/file in python?

description: Ignore the first(or certain) lines when parsing a string/file in python


rawDescription: split command question

description: Split command question


code:
import pyqtgraph as pg
import pyqtgraph.multiprocess as mp
proc = mp.QtProcess() # start second process for plotting
rpg = proc._import('pyqtgraph')
plt = rpg.plot() # create a PlotWidget in remote process

# Unlike the last example, we can use a wile-loop here because the Qt
# event loop is running in another process.
while True:
    data = getNewData()
    if data is not None:
        plt.plot(data, clear=True, _callSync='off')

rawDescription: Integrating two event handling programs in Python


code: p.sub(r'gray \1', s)

rawDescription: How to use python regex to replace using captured group?

description: Use python regex to replace using captured group


code:
def transform(self):
    self.count += 1.1
    self.angle += (self.count*25) % 360
    self.copyImage = pygame.transform.rotate(self.imagePuff, self.angle)
    self.newTrans = pygame.transform.scale(self.copyImage, (400,400))
    self.image =  self.newTrans

rawDescription: How to animate scale and rotate in pygame using rotozoom

description: Animate scale and rotate in pygame using rotozoom


code:
for key, c in count.most_common():
    print("{}: {}".format(key, c))

rawDescription: Display 'Counter' results on seperate line (Python)


code:
x = [2, 4, 7, 12, 3]
sum_of_all_numbers= sum(x)

rawDescription: How do I add together integers in a list in python?

description: Add together integers in a list in python


code:
emptyDict = {}
with open("test.txt", 'r') as infile:
    for line in infile:
        tokens = line.strip().split('=')
        fruit = tokens[0]
        number = tokens[1]
        emptyDict[fruit] = float(number)

rawDescription: Python program to store values in an external file


rawDescription: Efficiently Searching Nested Lists

description: Efficiently Searching Nested Lists


code:
import locale

locales=('en_AU.utf8', 'en_BW.utf8', 'en_CA.utf8',
    'en_DK.utf8', 'en_GB.utf8', 'en_HK.utf8', 'en_IE.utf8', 'en_IN', 'en_NG',
    'en_PH.utf8', 'en_US.utf8', 'en_ZA.utf8',
    'en_ZW.utf8', 'ja_JP.utf8')
for l in locales:
    locale.setlocale(locale.LC_ALL, l)
    conv=locale.localeconv()
    print('{ics} ==> {s}'.format(ics=conv['int_curr_symbol'],
                                 s=conv['currency_symbol']))

rawDescription: Python - Convert currency code to its sign


code:
from geographiclib.geodesic import Geodesic

number_points = 10

gd = Geodesic.WGS84.Inverse(35, 0, 35, 90)
line = Geodesic.WGS84.Line(gd['lat1'], gd['lon1'], gd['azi1'])

for i in range(number_points + 1):
    point = line.Position(gd['s12'] / number_points * i)
    print((point['lat2'], point['lon2']))

rawDescription: Get n points on a line

description: Get n points on a line


code: any( b == a[i:]+a[:i] for i in range(len(a)))

description: Clean way to accomplish -- if x in [(0, 1, 2), (2, 0, 1), (1, 2, 0)]:


code:
d = defaultdict(dict)
input = '-1,0,1;1,-1,4;1,4,-1'
lst = map(lambda x: map(lambda y: int(y), x.split(',')), input.split(';'))
for i,j in enumerate(lst):
    for k,l in enumerate(j):
            d[i][k] = l
d

rawDescription: converting a list to dictionary of dictionary in Python

description: Converting a list to dictionary of dictionary in Python


code: re.findall(r"\b[A-Z]+(?: [A-Z]+)*\b", "ABCD AAA Lkjl JJJJJJ")

rawDescription: Continuous capital run strings in sentence in one line preferably using reduce or map function in python


code:
class MyClass(object):
    def __init__(self, value=0):
        self.value = value
    def __eq__(self, other):
        return type(self) is type(other) and self.value == other.value

rawDescription: Python Multiprocessing: Reloading module in child effecting parent


code:
# insert the line in the Text widget
t.insert(tk.END, out)
# force widget to display the end of the text (follow the input)
t.see(tk.END)
# force refresh of the widget to be sure that thing are displayed
t.update_idletasks()

rawDescription: Display realtime output of a subprocess in a tkinter widget


rawDescription: Python pandas multiindex getting info from series


code: w = Entry(optionFrame, textvariable=var)

rawDescription: Labelling "Entry" in Tkinter

description: Labelling "Entry" in Tkinter


code: parser.add_argument('--w', nargs='+', help='word help')

rawDescription: How to implement command line switches to my script?

description: Implement command line switches to my script


code:
def Solver(puzzle):
   Changed = False

rawDescription: python sudoku puzzle? checking puzzle before and after

description: Python sudoku puzzle? checking puzzle before and after


code:
non_blanks = (line for line in fin if line.strip())
fout.writelines(islice(non_blanks, None, None, 2))

rawDescription: Read every second line and print to new file


code:
d = {}
for num in datasource:
    d.setdefault(key, set()).add(num)

rawDescription: Creating a dictionary and adding a set as its value


code:
import xml.etree.ElementTree as ET

top = ET.Element('top')
child = ET.SubElement(top, 'child')
child.text = 'some text'

tree = ET.ElementTree(top)
tree.write('output.xml')

rawDescription: Dump elementtree into xml file

description: Dump elementtree into xml file


code:
def show_word(self):
    """ Shows the word behind the cell """
    self.hidden = not self.hidden
    self.button["text"] = str(self)

    if mem.choice1 is None:
        mem.choice1 = [self.word, self.hidden]
    else:
        mem.choice2 = [self.word, self.hidden]
        self.check(mem.choice1, mem.choice2)

def check(self, choice1, choice2):
    """ Checks if the chosen words are a pair """
    if choice1 != choice2:
        self.show_word() # Infinite recursion!!

rawDescription: Something wrong without any error - Includes Tkinter


code:
for key in b:
    a[key].append(33)

rawDescription: Most efficient way to create a dictionary of empty lists in Python?


code: all(isinstance(x, int) for x in lst)

rawDescription: Python check if all elements of a list are the same type


code:
#define AF_INET         2       /* Internet IP Protocol         */
#define AF_INET6        10      /* IP version 6                 */
#define AF_PACKET       17      /* Packet family                */

rawDescription: How to get the physical interface IP address from an interface

description: Get the physical interface IP address from an interface


code:
from pyspark.sql import Row
l = sc.parallelize([1, 2, 3])
new_row = Row("new_col_name")
l_as_df = l.map(new_row).toDF()
new_df = df.join(l_as_df)

rawDescription: PySpark: Add a column to DataFrame when column is a list


rawDescription: Pandas multi-index slices for level names


code:
class Array(object):

    def __init__(self):
        #self.__lib = ...
        self.np_array = numpy.array(self._lib.get_arr())

    def __getitem__(self, key):
        self.np_array = numpy.array(self._lib.get_arr())
        return self.np_array.__getitem__(key)

    def __setitem__(self, key, value):
        self.np_array.__setitem__(key, value)
        self._lib.set_arr(new_arr.ctypes)

    def __getattr__(self, name):
        """Delegate to NumPy array."""
        try:
            return getattr(self.np_array, name)
        except AttributeError:
            raise AttributeError(
                 "'Array' object has no attribute {}".format(name))

rawDescription: How to implement an array-like property wrapper in python?

description: Implement an array-like property wrapper in python


rawDescription: Using Django ORM get_or_create with multiple databases


rawDescription: Delete pdf files in folders and subfolders with python?


code:
from tw2.core import Variable
from tw2.forms import Form

class FloatForm(Form):
    """Form using floating divisions allowing multiple fields per row.

    Fields having the 'aside' attribute set appear on the same row.

    Something like the following should be included in the site CSS file:

    form.floatform {
        margin-bottom: 1ex;
    }
    form.floatform div.row {
        clear: left;
        overflow: hidden;
        height: 100%;
        margin-top: 1.5ex;
    }
    form.floatform div.field {
        float: left;
        margin-right: 1em;
    }
    form.floatform label.fieldlabel {
        display: block;
    }
    form.floatform div.submit {
        margin-top: 3ex;
    }

    """

    template = "widgets.templates.float_form"

    child = Variable(default=FloatLayout)

    css_class = "floatform"

rawDescription: TurboGears2 - how to customize layout for new user form?


code:
parts = s.split(',')
if not all(is_numeric(part) for part in parts):
    result = []
else:
    result = [float(part) for part in parts]

rawDescription: Check if input is either digits or period


rawDescription: How to end a program properly with threads?

description: End a program properly with threads


code:
x=5
def app():
    exec("global x;x+=1")
    print(x)

app()

rawDescription: using exec() with python 3.2

description: Using exec() with python 3.2


code:
def answers(self, other):
    """DEV: true if self is an answer from other"""
    if other.__class__ == self.__class__:
        return self.payload.answers(other.payload)
    return 0

rawDescription: Scapy sr() with custom layers

description: Scapy sr() with custom layers


rawDescription: Why do Python regex spans extend one place past the actual match?


rawDescription: PySide Drop down menu

description: PySide Drop down menu


code:
import matplotlib
from pylab import *

data = np.arange(-50, 50).reshape(10, 10)
data = np.abs(data)
pcolor(data, cmap=cm.YlOrRd)
show()

rawDescription: Setting arbitrary color in pseudocolor plot with matplotlib


code:
from mytasks import add

metadata1 = 1
metadata2 = 2
myasyncresult = add.delay(1,2)
myasyncresult.get() == 3

rawDescription: Celery and custom consumers

description: Celery and custom consumers


code:
strings = ['SE,The Spiderwick Chronicles,"SPIDERWICK CHRONICLES, THE",movie,'
          ,'GB,Fast Friends,Burn Notice, S:4, E:2,episode,'
          ]
for string in strings:
    xs = string.split(',')
    country = xs[0]
    title1  = xs[1]
    title2  = ' '.join(xs[2:-2])
    mtype   = xs[-2]
    print [country, title1, title2, mtype]

rawDescription: Ambiguity in parsing csv file

description: Ambiguity in parsing csv file


code:
my_list = ["abra", "cada", "bra", "hum", "dee", "dum"]
it = iter(my_list)
for sli in zip(it,it,it):
    print("".join(sli))

rawDescription: How to retrieve groups of n items in list

description: Retrieve groups of n items in list


code:
import networkx as nx

G = nx.Graph()
G.add_edge(1, 2, weight=4.7)
G.add_edge(3, 4, weight=5.8)

for node1, node2, data in G.edges(data=True):
    print(data['weight'])

rawDescription: Elegant access to edge attributes in networkx


rawDescription: how to convert xml into list

description: Convert xml into list


code:
from itertools import groupby
from operator import itemgetter
phon = ["A","R","K","H"]
idx = [1,2,3,3]
[''.join([c for i, c in group]) for key, group in groupby(zip(idx, phon), itemgetter(0))]

rawDescription: Combine Python List Elements Based On Another List


code:
import matplotlib.pyplot as plt
from math import pi
im = plt.imread(image_name)
implot = plt.imshow(im)

for elem in data:
    # put a blue dot at (elem[0], elem[1]) with diameter elem[2]
    plt.scatter([elem[0]], [elem[1]], s=pi*(elem[2]**2)/4)

plt.show()

rawDescription: Python how to plot (x,y) data on a netcdf image


code:
import re
r = re.compile(r'User:\s([A-Za-z\-._/@]+)')
strs = '[<User: sachitad>, <User: awesome>]'
r.findall(strs)
strs1 = '[<User: mr--adhikari>, <User: awesome>]'
r.findall(strs1)
strs2 = '[<User: respect>]'
r.findall(strs2)
strs = '[<User: sa@chi.tad>, <User: awe_so/me>]'
r.findall(strs)

rawDescription: How to convert this list in a given format?

description: Convert this list in a given format


code:
N = 5
idx = np.arange(1, N) - np.tri(N, N-1, k=-1, dtype=bool)
idx

rawDescription: python leave-one-out estimation

description: Python leave-one-out estimation


code:
col_offset = 2
for (rownum, words) in enumerate(row_list):
    for (colnum, word) in enumerate(words):
        w_sheet.write(rownum, colnum + col_offset, word)

rawDescription: Python script not putting entire line in excel spreadsheet


rawDescription: Search string with re module in html page


rawDescription: Why does numpy's fromiter function require specifying the dtype when other array creation routines don't?


code:
new_settings[-1][termios.VTIME] = 20
new_settings[-1][termios.VMIN] = 0

rawDescription: Input not read in Python for Linux

description: Input not read in Python for Linux


code:
import re
strings = ["test", "check", "tick", "pic", "cow"]
for item in strings:
    print("{0} is {1}".format(item,
          "valid" if re.match(r"^(?!.*c(?![hk]))[^\W_]+$", item)
          else "invalid"))

rawDescription: python regex letter must be followed by another letter

description: Python regex letter must be followed by another letter


code:
import matplotlib.pyplot as plt

axs = plt.subplots(2, 2)[1]
axs[1,1].plot(rand(100))
zoomingBox(axs[1,1], [40,60,0.1,0.9], axs[0,0])
zoomingBox(axs[1,1], [10,30,0.1,0.9], axs[1,0], color='orange')

rawDescription: Use subplots to zoom into timeseries or how I can draw lines outside of axis borders


rawDescription: Pandas Dataframe: How to perform operation on 2 columns from different direction


code:
class Rental(models.Model):
    # ...
    class Meta:
        permissions = (
            ("can_edit_any", "Can edit any rentals"),
        )

rawDescription: Adding per-object permissions to django admin


code:
foo
import gzip
f = gzip.open('foo.bin.gz', 'wb')
f.write(foo.tostring())
f.close()

rawDescription: Create a zipfile directly from numpy array without an intermediary file


code:
def acorr(x, ax=None):
    if ax is None:
        ax = plt.gca()
    autocorr = np.correlate(x, x, mode='full')
    autocorr /= autocorr.max()

    return ax.stem(autocorr)

rawDescription: bug of autocorrelation plot in matplotlib‘s plt.acorr?

description: Bug of autocorrelation plot in matplotlib‘s plt.acorr


code:
a = 2           # points a to the integer object 2
a = 3           # points a to a different integer object, 3
b = [1, 2, 3]   # points b to a new list object [1, 2, 3]

rawDescription: When does python know an initialization is a copy, so that change at one place automatically changes another place?


code:
import json
import urllib.request
urlData = "http://api.openweathermap.org/data/2.5/weather?q=Boras,SE"
webURL = urllib.request.urlopen(urlData)
data = webURL.read()
encoding = webURL.info().get_content_charset('utf-8')
json.loads(data.decode(encoding))

rawDescription: Loading JSON object in Python using urllib.request and json modules


code: version, sdk = re.findall(r'(?:Version: |SDK )([\w.-]+)', s)

rawDescription: Regular Expression usage in python

description: Regular Expression usage in python


code:
from lxml import objectify
def add_string(parent, attr, s):
    if len(attr) == 1:
        setattr(parent, attr[0], s)
    else:
        child = getattr(parent, attr[0], None)
        if child is None:
            child = objectify.SubElement(parent, attr[0])
        add_string(child, attr[1:], s)
root = objectify.fromstring(xml)
add_string(root, ['MyElement1', 'Blah'], 'New')
add_string(root, ['MyElement17', 'Blah'], 'New')
add_string(root, ['MyElement1', 'Foo', 'Bar'], 'Hello')
root.MyElement1.Blah
root.MyElement17.Blah
root.MyElement1.Foo.Bar

rawDescription: Test the existence of an Element with lxml.objectify


code: text = u"aren't"

rawDescription: Handle Unicode characters with Python regexes


code:
class stripfile(file):
    def readline(self):
        return super(FileStripper, self).readline().strip()

parser = SafeConfigParser()
with stripfile('/path/to/file') as f:
    parser.readfp(f)

rawDescription: How can I remove the white characters from configuration file?

description: Remove the white characters from configuration file


code:
df2.index = r.index
df2
df2.unstack()

rawDescription: Python Pandas merge two data frames based on multiple values field


code:
from bs4 import BeautifulSoup # pip install beautifulsoup4

soup = BeautifulSoup(urllib2.urlopen(url)) # may use `cchardet` for speed
# ...

rawDescription: A good way to get the charset/encoding of an HTTP response in Python