rawDescription: Conditionally combine columns in pandas data frame


rawDescription: Python returns list but to variable, but variable is null


code: A = A - A.multiply(B)

rawDescription: Bulk zeroing of elements in a scipy.sparse_matrix


code:
def foo_bar(x, y, z):
    return 2*x, 3*y, 4*z

x = 3
y = 4
z = 5
x, y, z = foo_bar(x, y, z)
print(y)  # prints 12

rawDescription: Send by ref/by ptr in python?

description: Send by ref/by ptr in python


code:
a.view('i8,i8,i8').sort(order=['f1'], axis=0) #<-- returns None
a

rawDescription: sorting arrays in numpy by column

description: Sorting arrays in numpy by column


code:
class visitor(object):
      def __init__(self, obj_id):
          data_obj = _find_data_instance( obj_id )
          data_obj.accept(self)

      def visit( self, data_obj):
          if isinstance(data_obj, typeA):
               self.visit_typeA( dataobj)

      def visit_typeA(self, dataobj):
          """Formats the data for typeA"""
          ...

rawDescription: Visitor pattern in python

description: Visitor pattern in python


rawDescription: Fast Numpy calculation of a slight variation of the repeat and choose functions


code:
def unzip(source_filename, dest_dir):
    with zipfile.ZipFile(source_filename) as zf:
        for member in zf.infolist():
            zf.extract(member, dest_dir)

rawDescription: Unzipping with python's ZipFile lib give a strange result


code:
class Special_Tab(QtGui.QTabWidget):
    start_comp = QtCore.pyqtSignal()
    kill_thread = QtCore.pyqtSignal()
    def __init__(self, parent, tmp_so):
        QtGui.QTabWidget.__init__(self, parent)
        self.special_object = tmp_so
        self.grid = QtGui.QGridLayout(self)
        # matplotlib figure put into tab
        self.fig = figure.Figure()
        self.plot = self.fig.add_subplot(111)
        self.line, = self.plot.plot(0, 0, 'r-')
        self.canvas = FigureCanvas(self.fig)
        self.grid.addWidget(self.canvas)
        self.canvas.show()
        self.canvas.draw()
        self.canvas_BBox = self.plot.figure.canvas.copy_from_bbox(self.plot.bbox)
        ax1 = self.plot.figure.axes[0]
        thread = QtCore.QThread(parent=self)
        self.worker = Worker(self.special_object)
        self.worker.moveToThread(thread)
        self.worker.update_signal.connect(self.update_GUI)
        #        self.worker.done_signal.connect(?)
        self.start_comp.connect(self.worker.process_on_special_object)
        self.kill_thread.connect(thread.quit)
        thread.start()

    @QtCore.pyqtSlot(special_object)
    def update_GUI(self, tmp_so):
        """
        have the tab update it's self
        """
        # change the GUI to reflect changes made to special_object
        self.line.set_data(tmp_so.X, tmp_so.Y)
        self.plot.draw_artist(self.line)
        self.plot.figure.canvas.blit(self.plot.bbox)

    def start_computation(self):
        self.start_comp.emit()

    def closeEvent(self, ce):
        self.kill_thread.emit()
        QtGui.QTabWidget.closeEvent(self, ce)

rawDescription: Tabs with long processes in GUI all calling the same instance? [EDITED-QThread and QObject for passing objects to GUI]


code:
from math import *

EPSILON = 1e-12
def solve_bisection(fn, xmin,xmax,epsilon = EPSILON):
  while True:
      xmid = (xmin + xmax) * 0.5
      if (xmax-xmin < epsilon):
        return xmid
      fn_mid = fn(xmid)
      fn_min = fn(xmin)
      if fn_min*fn_mid < 0:
          xmax = xmid
      else:
          xmin = xmid

'''
Found something similar at this gamedev question:
http://gamedev.stackexchange.com/questions/11116/kepler-orbit-get-position-on-the-orbit-over-time?newreg=e895c2a71651407d8e18915c38024d50

Equations taken from:
https://en.wikipedia.org/wiki/Kepler%27s_laws_of_planetary_motion#Position_as_a_function_of_time
'''
def SolveOrbit(rmax, rmin, t):
  # calculation precision
  epsilon = EPSILON
  # mass of the sun [kg]
  Msun = 1.9891e30
  # Newton's gravitational constant [N*m**2/kg**2]
  G = 6.6740831e-11
  # standard gravitational parameter
  mu = G*Msun
  # eccentricity
  eps = (rmax - rmin) / (rmax + rmin)
  # semi-latus rectum
  p = rmin * (1 + eps)
  # semi/half major axis
  a = p / (1 - eps**2)
  # period
  P = sqrt(a**3 / mu)
  # mean anomaly
  M = (t / P) % (2*pi)
  # eccentric anomaly
  def fn_E(E):
    return M - (E-eps*sin(E))
  E = solve_bisection(fn_E, 0, 2*pi)
  # true anomaly
  # TODO: what if E == pi?
  def fn_theta(theta):
    return (1-eps)*tan(theta/2)**2 - ((1+eps)*tan(E/2)**2)
  theta = solve_bisection(fn_theta, 0, pi)
  # if we are at the second half of the orbit
  if (E > pi):
    theta = 2*pi - theta
  # heliocentric distance
  r = a * (1 - eps * cos(E))
  return theta, r

def DrawPlanet(name, rmax, rmin, t):
  SCALE = 1e9
  theta, r = SolveOrbit(rmax * SCALE, rmin * SCALE, t)
  x = -r * cos(theta) / SCALE
  y = r * sin(theta) / SCALE
  planet = Circle((x, y), 8)
  ax.add_artist(planet)

rawDescription: How do I plot a planet's orbit as a function of time on an already plotted ellipse?

description: Plot a planet's orbit as a function of time on an already plotted ellipse


code:
for number in numbers:
    if number < 0:
        ...

rawDescription: Python - Identify a negative number in a list


code:
websites_to_read = ('http://example.com',
                    'http://example.org',)

mapping_of_sites_to_html = {} # create the `dict`

for website_url in websites_to_read:
    mapping_of_sites_to_html[website_url] = htmlfrom(website_url)

rawDescription: How do I set my own global variables using input() in python 3.3?

description: Set my own global variables using input() in python 3.3


rawDescription: Changing ASCII values in a list

description: Changing ASCII values in a list


code:
import re
p = re.compile(r"\b(foo|bar|baz)\b")
p.sub("---", "foo XfooX bar YbarY baz ZbazZ")
# => '--- XfooX --- YbarY --- ZbazZ'

rawDescription: How to use \b or ^ alongwith pattern to replace complete word?

description: Use \b or ^ alongwith pattern to replace complete word


code:
from functools import wraps

def reset_to_none(func):
    @wraps(func)
    def wrapper(*args, **kw):
        args = [arg if not isinstance(arg, str) or arg else None for arg in args]
        kw = {k: arg if not isinstance(arg, str) or arg else None for k, arg in kw.items()}
        return func(*args, **kw)
    return wrapper

rawDescription: How to check function argument values in python?

description: Check function argument values in python


code: _ + np.timedelta64(2, 'h')

rawDescription: Convert dataframe with odd timestamp to timeseries with pandas


code: soup = BeautifulSoup()

rawDescription: Creating an XML document with BeautifulSoup


code:
indices
residual

rawDescription: NumPy: Vectorize finding closest value in an array for each element in another array


code:
category = next((
    k for x in soup.find_all('a')
      for k, v in categories.iteritems()
      if v in x['href']
), None)

rawDescription: Making multiple if statements less verbose


code:
a = SomeClass(5)
a.some_variable # Just as expected
b = SomeClass(10)
b.some_variable # This is its own variable
b.some_variable = 20 # This won't change 'a'
a.some_variable # Hasn't changed

rawDescription: How to avoid variable to be persistent across many requests?

description: Avoid variable to be persistent across many requests


code:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Other(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

rawDescription: Django Releationship between multiple fields


code:
my_list = [tuple(i) for i in my_list]
sorted(set(my_list))

rawDescription: How do I remove identical items from a list and sort it in Python?

description: Remove identical items from a list and sort it in Python


code:
import pymongo
conn       = pymongo.Connection('localhost', 27017)
database   = conn["Hello"]
collection = database["MyTable"]

rawDescription: Writing a simple MongoDB module in python


rawDescription: How to create a memoryview for a non-contiguous memory location?

description: Create a memoryview for a non-contiguous memory location


code: sudo(command, user=sudouser)

rawDescription: Fabric: do everything as a particular user


code:
array([[False, False, False, False],
       [False, False, False, False],
       [False, False, False,  True],
       [False, False,  True,  True]], dtype=bool)

rawDescription: Zero out matrix higher diagonal using numpy


code:
test_data = [{'location': 'store 2', 'quality': 3}]
X_test = vec.transform(test_data)
model.predict(X_test)

rawDescription: Generating numpy arrays for scikit linear regression model


code:
df
df.loc[:, 'foo'] = 0
df

rawDescription: use column name as condition for where on pandas DataFrame

description: Use column name as condition for where on pandas DataFrame


code:
import operator
mylist.sort(key=operator.itemgetter(2), reverse=True)

rawDescription: How to sort a list of tuples by the alphabetical ordering of one of its elements

description: Sort a list of tuples by the alphabetical ordering of one of its elements


rawDescription: f2py -- prevent array reordering

description: F2py -- prevent array reordering


rawDescription: python split string based on regular expression

description: Python split string based on regular expression


code:
similarity = 0
for b_token, b_value in docb:
    if b_token in doca_dic:
        similarity += doca_dic[b_token] * b_value

rawDescription: Document Similarity: Comparing two documents efficiently


code:
if t < MILLISECOND:
    return "{time} us".format(time=t)
elif t < SECOND:
    return  "{time} ms".format(time=t//MILLISECOND)
elif t < MINUTE:
    return  "{time} seconds".format(time=t//SECOND)
...

rawDescription: Converting time efficiently in Python

description: Converting time efficiently in Python


code:
from pyramid.security import _get_registry, Allowed
from pyramid.interfaces import IRouteRequest, IRequest, IViewClassifier, ISecuredView, IView
from zope.interface import providedBy
def route_view_execution_permitted(context, request, route_name, name=''):
    reg = _get_registry(request)
    context_iface = providedBy(context)
    request_iface = reg.queryUtility(
        IRouteRequest,
        name=route_name,
        default=IRequest)
    provides = (IViewClassifier, request_iface, context_iface)

    view = reg.adapters.lookup(provides, ISecuredView, name=name)
    if view is None:
        view = reg.adapters.lookup(provides, IView, name=name)
        if view is None:
            raise TypeError('No registered view satisfies the constraints. '
                            'It would not make sense to claim that this view '
                            '"is" or "is not" permitted.')
        return Allowed(
            'Allowed: view name %r in context %r for route %r (no permission defined)' %
            (name, context, route_name))
    return view.__permitted__(context, request)

rawDescription: Check if current user has permission for pyramid service?


code:
for files in zip_files:
    with zipfile.ZipFile(files, 'r') as myzip:
        list1, list2 = [], [] # Notice these are outside the loop
        for logfile in myzip.namelist():
            with myzip.open(logfile) as f:
                for line in f:
                    try:
                        parsed = json.loads(line[:-2])
                    except ValueError as e: # Presumably we only wish to catch json value errors
                        pass
                    else:
                        if ("key1" in parsed
                            and "val1" in parsed['key1']['key2']
                            and "val2" in parsed['key3']):
                            list1.append(parsed['key1'])
                            list2.append(parsed['key3'])

        # Write only once
        df = pd.DataFrame(list2).join(pd.DataFrame(list1))
        df['col1'] = df['col1'].apply(lambda x: ','.join(str(i) for i in x))
        df.drop_duplicates(inplace=True)
        df.to_csv(csvout, header=None, index=False)

rawDescription: More Efficient way to parse JSON and convert to CSV in Python


code:
new_list = []
for k in list1:
  new_list.append(list2[k]) #lookup the value in list2 at the index given by list1

rawDescription: Convert list of list into one big list pyhton


code:
# Add all rows from df4 that don't currently exist in df1
result = pd.concat([df1, df4[~df4.index.isin(df1.index)]])

rawDescription: Pandas concatenate, with no duplicate indices or columns


rawDescription: Calculate mean of sub arrays within a larger 3D array in Python


rawDescription: Get entities from NLTK.tree result

description: Get entities from NLTK.tree result


code:
df2 = df1[['hist', 'name', 'type']]
df2

rawDescription: Use Pandas.groupby to select a row in a group with some criteria?


code:
from zipshapes import zipShapefile

def main():
    items = 'shp_folders.txt'

    with open(items, 'r') as f:
        for line in f:
            zipShapefile(line.rstrip())

if __name__ == '__main__':
    main()

rawDescription: loop through path list held in txt

description: Loop through path list held in txt


code:
def smartcopy(filestocopy, dest_path, show_progress = False):
    """Determines what buffer size to use with copy()
       Setting show_progress to True calls back display_progress()"""
    #filestocopy is a list of dictionaries for the files needed to be copied
    #dictionaries are used as the fullpath, st_mtime, and size are needed
    if len(filestocopy.keys()) == 0:
        return None
    #Determines average file size for which buffer to use
    average_size = 0
    for key in filestocopy.keys():
        average_size += int(filestocopy[key]['size'])
    average_size = average_size/len(filestocopy.keys())
    #Smaller buffer for smaller files

    if show_progress:
        progress_callback = lambda pos, total: display_progress(pos, total, key)
    else:
        progress_callback = None

    #Bigger buffer for bigger files
    if average_size < 1024*10000: #Buffer sizes determined by informal tests on my laptop
        buffer = None
    else:
        buffer = 1024 * 2600

    for key, value in filestocopy.iteritems():
        #dest_path+key is the destination path, as the key is the relative path
        #and the dest_path is the top level folder
        copy(value['fullpath'], dest_path+key, buffer, callback=progress_callback)

rawDescription: Is there a better way to feed different parameters into a function with if-statements?


code: zeroth_ifd, exif_ifd, gps_ifd = pyxif.load(file_path)

rawDescription: Write EXIF-data from TIF (read with exifread) to JPEG-file using PIL (Pillow)


rawDescription: Type-Checking in Functions between Python 2.7 and Python 3.3


code: dic = {'foo': Tree(), 'foobar': lambda: dic['foo'].branch()}

rawDescription: defining values in dictionary based on other values there

description: Defining values in dictionary based on other values there


code:
from __future__ import division
import sys
import math
sys.argv=["Main"]
import Tkinter
from Tkinter import *

def CalcRpmRatio():
    rpmMax = rpmMaxSet.get()
    rpmMin = rpmMinSet.get()
    rpmPoint = rpmPointSet.get()
    newrpmMax = rpmMax- rpmMin
    result = rpmPoint / newrpmMax
    showResult = Label (mGui, text=str(ResultCount)+". "+str(result)).pack()
    global ResultCount
    ResultCount +=1

    return

ResultCount = 1
mGui = Tk()
mGui.geometry('400x150+200+200')
mGui.title('RPM To Percent Calc')
rpmMaxSet = DoubleVar()
rpmMinSet = DoubleVar()
rpmPointSet = DoubleVar()
rpmMaxSetLabel = Label(mGui, text='Max RPM').pack()
rpmMaxSetEntry = Entry(textvariable=rpmMaxSet) .pack()
rpmMinSetLabel = Label(mGui, text='Min RPM').pack()
rpmMinSetEntry = Entry(textvariable=rpmMinSet) .pack()
rpmMinPointLabel = Label(mGui, text='Point RPM').pack()
rpmPointSetEntry = Entry(textvariable=rpmPointSet) .pack()

mButton = Button(mGui, text='Calculate', command = CalcRpmRatio, fg = 'white', bg='black').pack()
mGui.mainloop()

rawDescription: Making a Tkinter calculator that gives back percent at a given point in a interval


code:
import numpy as np
np.frombuffer("abcdefgh", "uint8").sum()

rawDescription: Python sum of ASCII values of all characters in a string


code:
import time
time.time.func_name
time.time.__name__

rawDescription: How to get a function name as a string in Python?

description: Get a function name as a string in Python


code:
import odbc
db = odbc.odbc('dsn/user/password')

rawDescription: How to connect to a SQL Server database in Anaconda

description: Connect to a SQL Server database in Anaconda


code:
try:
    processes = []
    # Start all processes at once
    for element in some_list:
        processes.append(Popen(SOME_COMMAND, stdout=PIPE, stderr=PIPE))
    # Fetch their results sequentially
    for process in processes:
        cmd_res = process.communicate()
        # Process your result here
except KeyboardInterrupt:
    for process in processes:
        try:
            process.terminate()
        except OSError:
            pass

rawDescription: Do not print stack-trace using Pool python


code:
def getNGramBeginsWords(nGram, length):
    with open('/home/will/workspace/Genie/src/resources/TWL06.txt', 'r') as wlist:
        nGram = nGram.upper()
        words = []
        length = int(length) # force to an int
        assert isinstance(n, int) # or do this if you prefer to get an exception on all invalid input
        for line in wlist:
            stripline = line.strip().upper() # you keep doing this
            #you should be using `endswith` instead of the slice
            if (len(stripline) == length) and stripline.endswith(nGram):
                words.append(stripline)
        return words

rawDescription: Passing in Global Variables in Python

description: Passing in Global Variables in Python


code:
sns.regplot(x="total_bill", y="tip", data=tips,
                marker='o', color='red', scatter_kws={'s':20})

rawDescription: How to change the point size for regplot(), seaborn's scatter plot function (python)

description: Change the point size for regplot(), seaborn's scatter plot function (python)


code:
if opt1:
    my_array = array1
elif opt2:
    my_array = array2
else:
    my_array = []

for x in my_array:
    ...

rawDescription: Different for-"definitions/conditions but same execution code


rawDescription: Merging of two dictionaries

description: Merging of two dictionaries


rawDescription: Creating a feature dictionary for Python machine learning (naive bayes) algorithm


code:
(lambda random_list: [
    (x, y, not random_list.index(y))
    for x in some_list
    for y in random_list])(
        random_list=random.sample([1, 2, 3, 4, 5], random.choice([1, 2, 3])))

rawDescription: Python: list comprehension which references an internally generated list


rawDescription: Python removing duplicate lines

description: Python removing duplicate lines


code: webpage-category/page

rawDescription: Improving a python snippet

description: Improving a python snippet


code:
links = soup.find_all('a')
links = [link for link in links
         if link["href"].startswith("http://www.conakat.com/map/?p=")]
zips = soup.find_all('i')

for l, z in zip(links, zips):
    f.writerow((l.contents[0], z.contents[0]))

rawDescription: Python BeautifulSoup Print Info in CSV

description: Python BeautifulSoup Print Info in CSV


code:
reg = re.compile( r"(.)\1{2,}")
reg.sub(r'\1\1', 'fooo baaaar actuallly')

rawDescription: Python how to eliminate 3 or more consequent letter


code: SESSION_EXPIRE_AT_BROWSER_CLOSE = True

rawDescription: how to count how many times a user logs in?

description: Count how many times a user logs in


code:
print("Inside B - Before Importing")
import c
print("Inside B - After Importing")

rawDescription: Python - I have to reimport modules when treating a script as a module


code:
#! /usr/bin/env python

''' Make random DNA sequences

    Sequences consist of random subsequences of the letters 'ACGT'
    as well as short sequences of 'N', of random length up to 200.
    Exactly 1000 'N's separate sequence blocks.
    All sequences may contain newlines chars

    Takes approx 3 seconds per megabyte generated and saved
    on a 2GHz CPU single core machine.

    Written by PM 2Ring 2015.03.23
'''

import sys
import random
from linebuffer import LineBuffer

#Set seed to None to seed randomizer from system time
random.seed(37)

#Output line width
linewidth = 120

#Subsequence base length ranges
minsub, maxsub = 15, 300

#Subsequences per sequence ranges
minseq, maxseq = 5, 50

#random 'N' sequence ranges
minn, maxn = 5, 200

#Probability that a random 'N' sequence occurs after a subsequence
randn = 0.2

#Sequence separator
nsepblock = 'N' * 1000

def main():
    #Get number of sequences from the command line
    numsequences = int(sys.argv[1]) if len(sys.argv) > 1 else 2
    outname = 'DNA_sequence.txt'

    lb = LineBuffer(outname, linewidth)
    for i in xrange(numsequences):
        #Write the 1000*'N' separator between sequences
        if i > 0:
            lb.write(nsepblock)

        for j in xrange(random.randint(minseq, maxseq)):
            #Possibly make a short run of 'N's in the sequence
            if j > 0 and random.random() < randn:
                lb.write(''.join('N' * random.randint(minn, maxn)))

            #Create a single subsequence
            r = xrange(random.randint(minsub, maxsub))
            lb.write(''.join([random.choice('ACGT') for _ in r]))
    lb.close()

if __name__ == '__main__':
    main()

rawDescription: Python splitting with string as delimiter


code:
def devoice(char):
    return unicodedata.normalize('NFD', char)[0]

rawDescription: Is there any way to do "logical" transformations between Japanese kana characters with different diacritical marks?


code:
from django.db import models
from django.contrib.auth.models import AbstractUser

class MyUser(AbstractUser):
    # We inherit all those nifty things from AbstractUser
    registration_date = models.DateTimeField(auto_now_add=True)

rawDescription: How to extend the django User model?

description: Extend the django User model


code:
with open('shops.txt', 'w') as s:
    for l in lines:
        s.write(l)

rawDescription: Python: How to replace the last word of a line from a text file?


rawDescription: Round to a given number in Python

description: Round to a given number in Python


code:
from inspect import ismethod

class Example:
    def method_a(self):
        return [('key_a1', 'val_a1'), ('key_a2', 'val_a2')]

    def method_b(self):
        return [('key_b1', 'val_b1'), ('key_b2', 'val_b2')]

    def collect_data(self):
        data = {}
        for attr in dir(self):
            if not attr.startswith('_') and attr != 'collect_data':
                possible_method = getattr(self, attr)
                if ismethod(possible_method):
                    data.update(possible_method())
        return data

rawDescription: Calling methods inside class to modify list


code:
def commonPrefix(a, b):
  i = 0
  while i < len(a) and i < len(b) and a[i] == b[i]:
    i += 1
  return i

def eachWithPrefix(v):
  p = ''
  for x in v:
    yield commonPrefix(p, x), x
    p = x

rawDescription: How to group strings with similar beginnings in a sorted list?

description: Group strings with similar beginnings in a sorted list


code: linesplit = [elem.strip().split('   ') for elem in data]

rawDescription: Readlines() and calculations in for loop


rawDescription: Lookahead assertion with dot

description: Lookahead assertion with dot


code:
import os
os.system('ssh -t -t myname@myserver "ls && pwd"')

rawDescription: SSH and Screen with a Python script

description: SSH and Screen with a Python script


code:
import urllib2
import re

replacements = dict()
for url in ece_url_list:
    response = urllib2.urlopen(url)
    html = response.read()
    replacements[url] = re.findall('\<meta content="(http:\/\/www\.telegraaf\.nl.*\.html)"', html)[0]

rawDescription: Extracting links with regex from source code; Python


code:
import scrapy

class AmazonItem(scrapy.Item):
    Name = scrapy.Field()
    Source = scrapy.Field()

class carSpider(scrapy.Spider):
    imgcount = 1
    name = "car"
    allowed_domains = ["ebay.com"]

    def start_requests(self):
        yield scrapy.Request("http://www.ebay.com/sch/Cars-Trucks-/6001/i.html", self.parse)

        for page in range(2, 3):
            yield scrapy.Request("http://www.ebay.com/sch/Cars-Trucks-/6001/i.html?_pgn=%d&_skc=50&rt=nc" % page,
                                 callback=self.parse,
                                 dont_filter=True)

    def parse(self, response):
        for car in response.xpath('//a[@class="vip"]'):
            item = AmazonItem()

            item['Name'] = car.xpath("@title").extract()[0]
            item['Source'] = car.xpath("@href").extract()[0]

            yield item

rawDescription: Why does python scrapy yields duplicated items in my code?


code:
from string import letters, digits, whitespace, punctuation
s = "aaa; sf = fa = bla http://wa"
s.translate(None, letters+digits+whitespace)

rawDescription: How to just keep punctuation with a string in python?

description: Just keep punctuation with a string in python


rawDescription: Customize compile function in python?

description: Customize compile function in python


code:
A = np.random.randn(3,4,5) # Random 3x4x5 matrix -- your temp matrix
B = np.random.randint(0, 10, 3*4*5).reshape(3,4,5) # your conv matrix with altitudes from 0 to 9
C = np.zeros((3,10,5)) # your new matrix

z, y, x = np.indices(A.shape)
C[z, B[z, y, x], x] = A[z, y, x]

rawDescription: Python numpy grid transformation using universal functions


code:
def summation(calc_termo, linf, prox, lsup):
    soma = 0

    while linf <= lsup:
        soma = soma + calc_termo(linf)
        linf = prox(linf)

    return soma

summation(inner_function, 1, lambda x: x + 1, 5)

rawDescription: Lambdas and sums Python

description: Lambdas and sums Python


code:
s = Series(pd.to_datetime(nanos))
s

rawDescription: Pandas DatetimeIndex vs to_datetime discrepancies


code:
count = 0
while condition:
    ...
    count += 1

rawDescription: Using enumerate function in while loops

description: Using enumerate function in while loops


code:
unordered = [s for s in main_streets if s not in ordered]
for i in range(len(unordered)):
    for (j, s) in enumerate(unordered):
        if s.nodes[0] == ordered[-1].nodes[-1]:
            ordered.append(unordered.pop(j))
            break

rawDescription: How to classify a list of objects having an intersecting list of values

description: Classify a list of objects having an intersecting list of values


rawDescription: Finding the consecutive zeros in a numpy array


code:
from tkinter import *
import random

class Game():
    def __init__(self):
        root = Tk()
        root.geometry("1350x730")

        global tile_frame_column  # the labels that go on the screen of letters
        tile_frame_column = {}

        global tile_frame_column_counter
        global newvar1 # x coordinate
        global newvar2 # y coordinate

        tile_frame_column_counter = 0
        newvar1 = 50
        newvar2 = 50

        tiles_letter = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

        def drawBoard():
            global tile_frame_column_counter
            global newvar1
            global newvar2
            for x in range(1):
                for y in range(1):
                    if not tiles_letter:
                        return
                    else:
                        rand = random.choice(tiles_letter)
                        tile_frame_column[tile_frame_column_counter] = Label(root, text=rand, font="Helvetica 16 bold")
                        tile_frame_column[tile_frame_column_counter].place(x = newvar1, y = newvar2)
                        tile_frame_column_counter+=1
                        if newvar2 > 300:
                            newvar1 += 50
                            newvar2 = 50 # to start at the next column
                        else:
                            newvar2 += 50
                        tiles_letter.remove(rand)
                        root.after(1000, drawBoard)
        root.after(1000, drawBoard)
        root.mainloop()

app=Game()

rawDescription: python: after method - screen loads with everything on it already

description: Python: after method - screen loads with everything on it already


code:
import urllib2
from collections import defaultdict

f=urllib2.urlopen("http://www.mbnet.com.pl/dl.txt")
list = range(1,50)
counter=defaultdict(int)  # use defaultdict here

for lines in f:
    tab_lines=lines.split(" ")
    formated_tab=tab_lines[-1].strip().split(',')
    for i in formated_tab:
        if int(i) in list:
            counter[i] += 1  # don't worry, be happy :)
sumall=sum(counter.values())
for number, value in counter.items():
    print ('Number {} drawn {} times and it is {}% of all').format(number,value,100*value/sumall)

rawDescription: Python Counter doesn't count

description: Python Counter doesn't count


code: {MyClass(1): MyClass(1)}

rawDescription: python __repr__

description: Python __repr__


code:
fake_path = '/wrong:' +\
            '/wrong/path/two:' +\
            '/docker/path/one:' +\
            '/other/docker/path'

@mock.patch.dict('os.environ', {'PATH': fake_path})
@mock.patch('os.listdir')
@mock.patch('os.access')
@mock.patch('os.path.exists')
@mock.patch('os.path.isfile')
def test_queryPATH(self,
                   mock_isfile,
                   mock_exists,
                   mock_access,
                   mock_listdir,
                   mock_environ):

    mock_isfile.return_value = True
    mock_access.return_value = True
    mock_exists.return_value = True
    mock_listdir.return_value = [
        'somebin',
        'another_bin',
        'docker']

    target_paths = [
        '/docker/path/one/docker',
        '/other/docker/path/docker']

    def isPathToDockerCommand(path):
        return True

    self.assertEqual(
        target_paths,
        checks.queryPATH(isPathToDockerCommand))

rawDescription: Testing strategy for my function using mock


rawDescription: how to get uploaded file name in django

description: Get uploaded file name in django


code:
hits = []
while True:
    events = calendar_acc.events().list(calendarId='My_Calendar_ID', pageToken=page_token).execute()
    for event in events['items']:
        if "Search Term" in event['summary']:
           hits.append((dateutil.parser.parse(event['start']['dateTime']), event['summary']))

    page_token = events.get('nextPageToken')
    if not page_token:
        break

rawDescription: Python Google Calendar sort by date

description: Python Google Calendar sort by date


code:
from sklearn.externals import joblib
joblib.dump(tfidf_svm, 'model.pkl')

rawDescription: How to use save model for prediction in python

description: Use save model for prediction in python


code:
import Script1 as sc1

var = sc1.passVars()

rawDescription: Run Python script from another and pass the variables and output


rawDescription: GitPython tags sorted

description: GitPython tags sorted


code: values = dict(title='titleVar', content='contentVar')

rawDescription: storing template replacement values in a separate file

description: Storing template replacement values in a separate file


code:
def downup(word):
    if len(word) <= 1:
        return [word]
    return [word] + downup(s[1:]) + [word]

rawDescription: Scheme to Python: most elegant translation of a recursive procedure?


code:
from itertools import islice
from collections import defaultdict
import re

data = defaultdict(list)
with open(filename) as fin:
    header = next(fin, '').split()
    for line in fin:
        m = re.match(r'(\d+) lines.*(\b\w+)$', line)
        if m:
            data[m.group(2)].extend(islice(fin, int(m.group(1))))

rawDescription: Python: split a large text file by many headers


code: df[df.index.hour == 8]

rawDescription: Python pandas: how to get hour from timestamp in dataframe?


code:
while True:
    pass  # The pass is needed syntactically

rawDescription: Continue and pass: what's the difference?


rawDescription: PyQt: Activate QListWidget Item

description: PyQt: Activate QListWidget Item


rawDescription: How to reverse geocode serverside with python, json and google maps?

description: Reverse geocode serverside with python, json and google maps


rawDescription: python list.iteritems replacement

description: Python list.iteritems replacement


code:
rng = pd.date_range('1/1/2011', periods=90, freq='M')
df = pd.DataFrame({'value':range(1,91),'date':rng})

rawDescription: Calculating year over year growth by group in Pandas


code:
y
x2 > y

rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code:
import time

while True:
     print('*', flush=True, end='\r')
     time.sleep(0.5)
     print(' ', flush=True, end='\r')
     time.sleep(0.5)

rawDescription: Make a blinking busy indicator on python shell


code:
s = [1, 2, 1, 4, 5, 2, 3, 2, 4, 5, 3, 1, 4, 2]
[x for x in random.choice([p for c in itertools.combinations(s, 3) for p in itertools.permutations(c) if len(set(c)) == 3])]
[x for x in random.choice([p for c in itertools.combinations(s, 3) for p in itertools.permutations(c) if len(set(c)) == 3])]
[x for x in random.choice([p for c in itertools.combinations(s, 3) for p in itertools.permutations(c) if len(set(c)) == 3])]

rawDescription: Python Random List Comprehension

description: Python Random List Comprehension


code:
v = b'\x8c\x00'
print(' '.join(['{:02x}'.format(i) for i in v]))

rawDescription: Left pad hex list

description: Left pad hex list


code:
from rest_framework import viewsets

from .models import User
from .serializers import UserSerializer

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        if self.kwargs.get('pk', None) == 'me':
            self.kwargs['pk'] = self.request.user.pk
        return super(UserViewSet, self).get_object()

rawDescription: DRF - make an resource alias /me for current user


rawDescription: Select a specific column in a DF and a random column (python3, pandas)


code:
df
df.iloc[df.index.get_level_values('A') == 1]

rawDescription: selecting from multi-index pandas

description: Selecting from multi-index pandas


code: data = []

rawDescription: Finding the top 10 and converting it from centimeters to inches - Python


code:
import re
string1 = 'one.two.three.four.five.six.eight'
string2 = 'one.two.hello.four.five.six.seven'
re.sub(r'^one\.two\.\w+\.four', '', string1)
re.sub(r'^one\.two\.\w+\.four', '', string2)

rawDescription: Python: strip a wildcard word

description: Python: strip a wildcard word


code:
import logging
rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao', (), False)

rawDescription: How to get the level of the logging record in a custom logging.Handler in Python?

description: Get the level of the logging record in a custom logging.Handler in Python


rawDescription: Numpy array broadcasting with vector parameters


rawDescription: Order tuple elements

description: Order tuple elements


code:
#tracetest.py

def what():
    return 3

def hey():
    return what()

def yo():
    return hey()

import trace
tracer = trace.Trace()
tracer.run("yo()")
r = tracer.results()
r.write_results()

rawDescription: Getting a python traceback without an exception


code:
vals = np.array([1, 2, 6, 8, 9])
out = np.empty(masks.shape,dtype=object)
out

rawDescription: "Unsparsing" numpy Arrays with Given Masks


JSON!

brothersNames: Kim David Ron

address: London

Simba

type: Lion

rawDescription: how to Change dictionary values in python file

description: Change dictionary values in python file


code:
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import FirefoxProfile

profile = FirefoxProfile("C:\\Path\\to\\profile")
driver = webdriver.Firefox(profile)

rawDescription: How do you use credentials saved by the browser in auto login script in python 2.7?

description: Use credentials saved by the browser in auto login script in python 2.7


code:
datetime.datetime.strptime(a, '%Y-%m-%d').date()       # 8.87us

datetime.date(*map(int, a.split('-')))                 # 1.28us

rawDescription: A faster strptime?

description: A faster strptime


code:
import json
data = json.loads(args_json)
len(data)

rawDescription: Scrapy hxs.select() not selecting all results


rawDescription: Docx to pdf using openoffice headless way too slow


code:
scipy.sparse.csgraph.floyd_warshall(np.matrix(
    [[False, False, True],
     [False, False, True],
     [True, True, False]]
).astype(int))

rawDescription: Square matrix length of path in Python

description: Square matrix length of path in Python


rawDescription: Simple string encounter

description: Simple string encounter


code:
import sched
import datetime
import time

s = sched.scheduler(time.time, time.sleep)

def dotoday():
    now = datetime.date.now()
    stime = now.time()

    # Schedule "first" every 3 minutes from 22:00 to 22:57
    if stime < datetime.time(22, 0):
        stime = datetime.time(22, 0)
    while stime <= datetime.time(22, 57):
        s.enterabs(stime, 1, first, ())
        stime += datetime.timedelta(0, 180)

    # Schedule "second" every 3 minutes from 23:00 to 23:57
    stime = datetime.time(23, 0)
    while stime <= datetime.time(23, 57):
        s.enterabs(stime, 1, second, ())
        stime += datetime.timedelta(0, 180)

    # Schedule "dotoday" to run tomorrow
    midnight = now.replace(hour=0, minute=0, second=0)
    tomorrow = midnight + datetime.timedelta(1, 0)
    s.enterabs(tomorrow, 1, dotoday, ())

dotoday()
s.run()

rawDescription: Complete a task during certain time frames within a python script


code: namedPi = Record(*tuplePi)

rawDescription: How to cast tuple into namedtuple?

description: Cast tuple into namedtuple


code: print (df.pivot(index='business_id', columns='user_id', values='stars').fillna(0))

rawDescription: Rearrange a pandas data frame to create a 2d ratings matrix


code:
def calculate_factorial_multi(number):
    prime = [True]*(number + 1)
    result = 1
    for i in xrange (2, number+1):
        if prime[i]:
            #update prime table
            j = i+i
            while j <= number:
                prime[j] = False
                j += i
            #calculate number of i in n!
            sum = 0
            t = i
            while t <= number:
                sum += number/t
                t *= i
            result *= i**sum
    return result

rawDescription: Calculating the factorial without trailing zeros efficiently?


code: fig.suptitle(r'H$_2$ Emission from GJ832')

rawDescription: Force LaTeX font to match default matplotlib font


code:
def find_by_date(haystack, needle):
    for email, email_date in haystack:
        if email_date == needle:
            yield email

rawDescription: How to efficiently select entries by date in python?

description: Efficiently select entries by date in python


code:
from itertools import cycle, islice
from functools import partial

def pyramid(n):
    c = cycle("abc")       #cycle returns items in cycle
    max_width = (2*n) - 1  #determine the max width(bottom row)
    f = partial("{:^{width}}".format, width=max_width)
    for i in range(1, n+1):
        print (f(" ".join(islice(c, i))))

rawDescription: Triangle made out of 'abc' [python]

description: Triangle made out of 'abc' [python]


code:
dfrm
dfrm.A.unique()
dfrm.A.unique()/len(dfrm.A)
dfrm.E.unique()/len(dfrm.E)
len(dfrm.A.unique())/len(dfrm.A)
len(dfrm.E.unique())/len(dfrm.E)

1.0*len(dfrm.E.unique())/len(dfrm.E)

rawDescription: Pandas - Identify % of unique entries per column


code:
class ComplexTypes:
    LIST_N = 'LIST'
    MAP_N  = 'MAP'
    SET_N  = 'SET'

rawDescription: Python: Grouped constants with possibility to iterate over group


code: return lambda x: all( f(x) for f in f_array )

rawDescription: Can you dynamically combine multiple conditional functions into one in Python?

description: Dynamically combine multiple conditional functions into one in Python


code:
try:
    u = payload["actor"]["username"]
except (AttributeError, KeyError):
    u = ""

rawDescription: python .get() and None

description: Python .get() and None


code:
d = {'a':1, 'b':3, 8:'c'}

x = input()
from string import digits
if x in digits:
    x = int(x)
if x in d.values():
    print('In a dictionary', x)

if x in d:
    print ("In keys!")

rawDescription: Verifying If key or value exists in dictionary, works for char and fails for number


rawDescription: How can I pairwise sum two equal-length tuples

description: Pairwise sum two equal-length tuples


rawDescription: Plotting non-standard axes

description: Plotting non-standard axes


code:
def getColour(self,glyphRef, value):
    (triple, hexstr) = askcolor()
    if hexstr:
        glyphRef.config(bg=hexstr)
        self.colourDict[value] = hexstr

rawDescription: Python/tKinter/ttk - passing an object on button click


code:
newList = list(permutations([1, 2, 2]))
newList[0]
newList[3]

rawDescription: manipulating the output of itertools.permutations in python

description: Manipulating the output of itertools.permutations in python


code:
def fc_recursive_solve(board, N, P, Q, row, col, outputFile, timeout):
    if time.clock() >= timeout:
        return "timeout"

    while row < N and board[row][col][0] != 0: #find next blank
        if col == N-1:
            row = row + 1
            col = 0
        else:
            col = col + 1

    if row == N: #solved
        return board

    for num in vals:
        if constraintCheck(row, col, num, P, N, Q, board):
            new_board = copy.deepcopy(board)
            new_board[row][col][0] = num
            if propagate_fc(new_board, N, P, Q, row, col, num):
                new_board[row][col][1] = [num]
                result = fc_recursive_solve(new_board, N, P, Q, row, col, outputFile, timeout)
                if result is not None and result != "timeout":
                    return result
        return None

rawDescription: Backtracking in sudoku solver failing

description: Backtracking in sudoku solver failing


code:
def find_index(table, letter):
    for r_index, row in enumerate(table):
        if letter in row:
            return (r_index, row.index(letter))

rawDescription: Python-Location of a letter in a two dimensional string


code:
class ChoiceDescriptor(object):
    def __init__(self, key, choices):
        self.key = key
        self.storage = "_%s" % key
        self.choices = set(choices)

    def __get__(self, instance, cls=None):
        if instance is None:
            return self
        return getattr(instance, self.storage)

    def __set__(self, instance, value):
        value = value.lower()
        if value not in self.choices:
            raise ValueError(
                "'%s' is not a valid value for '%s'" % (value, self.key))
        setattr(instance, self.storage, value)

class SomeClass(object):
    haircolor = ChoiceDescriptor("haircolor",
        ['blonde', 'brunette', 'brown', 'black', 'auburn', 'red'])
    eyecolor = ChoiceDescriptor("eyecolor",
        ['green', 'blue', 'brown', 'gray'])

rawDescription: How to associate a property-like object with a dict value in python

description: Associate a property-like object with a dict value in python


code:
a = 'ABCDE'
bs = ['xy', (1,2,3), ['apple']]
it = itertools.izip(*([a] + [itertools.cycle(b) for b in bs]))
list(it)

rawDescription: izip_longest with looping instead of fillvalue

description: Izip_longest with looping instead of fillvalue


code:
from requests import request, HTTPError

from django.core.files.base import ContentFile

def save_profile_picture(strategy, user, response, details,
                         is_new=False,*args,**kwargs):

    if is_new and strategy.backend.name == 'facebook':
        url = 'http://graph.facebook.com/{0}/picture'.format(response['id'])

        try:
            response = request('GET', url, params={'type': 'large'})
            response.raise_for_status()
        except HTTPError:
            pass
        else:
            profile = user.get_profile()
            profile.profile_photo.save('{0}_social.jpg'.format(user.username),
                                   ContentFile(response.content))
            profile.save()

rawDescription: Save facebook profile picture in model using python-social-auth


code:
class SearchHandler(webapp.RequestHandler):
    def get(self):
        search_string = self.request.get("search_string", None)
        if not search_string:
            raise Exception("Missing Param")
        tags = [t.strip() for t in search_string.split(",")]
        if tags:
            query = Main.all()
            query.filter("tag_list IN", tags)
            query.order("-total_value")

        # Handle your results

rawDescription: How do I add search parameters to search page url?

description: Add search parameters to search page url


code:
# -*- coding: utf-8 -*-
# errbacks.py
import scrapy

# from scrapy.contrib.spidermiddleware.httperror import HttpError
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError

class ErrbackSpider(scrapy.Spider):
    name = "errbacks"
    start_urls = [
        "http://www.httpbin.org/",              # HTTP 200 expected
        "http://www.httpbin.org/status/404",    # Not found error
        "http://www.httpbin.org/status/500",    # server issue
        "http://www.httpbin.org:12345/",        # non-responding host, timeout expected
        "http://www.httphttpbinbin.org/",       # DNS error expected
    ]

    def start_requests(self):
        for u in self.start_urls:
            yield scrapy.Request(u, callback=self.parse_httpbin,
                                    errback=self.errback_httpbin,
                                    dont_filter=True)

    def parse_httpbin(self, response):
        self.logger.error('Got successful response from {}'.format(response.url))
        # do something useful now

    def errback_httpbin(self, failure):
        # log all errback failures,
        # in case you want to do something special for some errors,
        # you may need the failure's type
        self.logger.error(repr(failure))

        #if isinstance(failure.value, HttpError):
        if failure.check(HttpError):
            # you can get the response
            response = failure.value.response
            self.logger.error('HttpError on %s', response.url)

        #elif isinstance(failure.value, DNSLookupError):
        elif failure.check(DNSLookupError):
            # this is the original request
            request = failure.request
            self.logger.error('DNSLookupError on %s', request.url)

        #elif isinstance(failure.value, TimeoutError):
        elif failure.check(TimeoutError):
            request = failure.request
            self.logger.error('TimeoutError on %s', request.url)

rawDescription: How do I catch errors with scrapy so I can do something when I get User Timeout error?

description: Catch errors with scrapy so I can do something when I get User Timeout error


code: newKey = key[rand:rand + length]

rawDescription: How do I move a specific part of a string to a new string

description: Move a specific part of a string to a new string


code:
from functools import wraps
def set_return_type(typeobj):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            return typeobj(func(*args, **kwargs))
        return wrapper
    return decorator
@set_return_type(float)
def test():
    return 1
test()

rawDescription: A decorator-creating class

description: A decorator-creating class


code:
def rot(l1,l2):
    from collections import deque
    if l1 == l2:
        return True
    # if length is different we cannot get a match
    if len(l2) != len(l1):
        return False
    # if any elements are different we cannot get a match
    if set(l1).difference(l2):
        return False
    l2,l1 = deque(l2),deque(l1)
    for i in range(len(l1)):
        l2.rotate() # l2.appendleft(d.pop())
        if l1 == l2:
            return True
    return False

rawDescription: Check if a list is a rotation of another list that works with duplicates


code:
for i in a:
    idList[i] = startPt
    startPt += increment

rawDescription: is there a way to speed up this python program? (short)

description: Is there a way to speed up this python program? (short)


code:
for s in ws:
    for l in s.lemmas:
        if l.name != "flabbergasted":
            print(l.name)

rawDescription: Python : Error in comparing strings

description: Python : Error in comparing strings


code:
import random

class Event(object):
    def __init__(self):
        self.car = None

class Car(object):
    def __init__(self, isBlue, length):
        self._isBlue = isBlue
        self._length = length

    def isBlue(self):
        return self._isBlue

    def length(self):
        return self._length

    def __str__(self):
        return '{} car of {} m long.'.format('blue' if self.isBlue() else 'non-blue ', self.length())

rawDescription: In Python, what would be a clear, efficient way to count things in regions?


code:
df = pd.DataFrame({"uid": np.arange(10**6)})
for col in range(6):
    df["dc{}".format(col)] = np.random.randint(0,2,len(df))

rawDescription: How to speed up complex/difficult data filtering in pandas

description: Speed up complex/difficult data filtering in pandas


code:
for line in fileObj:
       splitline = line.rstrip().split(',')
       date, name, time, data1, data2, data3 = splitline[0:4] + splitline[18:20]

rawDescription: How to take multiple slices of a line from a file in python?

description: Take multiple slices of a line from a file in python


rawDescription: What's a variable in a inner function definition in python?


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

from collections import Counter

word_list = ['hello', 'hello', 'hi', 'hello', 'hello']

c = Counter(word_list)

print(c)

rawDescription: How to count elements in a list and return a dict?

description: Count elements in a list and return a dict


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

v1 = -1+2*np.random.rand(50,150)
fig,ax = plt.subplots()
p = ax.imshow(v1,interpolation='nearest',cmap=plt.cm.RdBu)
cb = plt.colorbar(p,shrink=0.5)
ax.set_xlabel('Day')
ax.set_ylabel('Depth')
cb.set_label('RWU')
plt.show()

rawDescription: Two different color colormaps in the same imshow matplotlib


code:
def dfs(x):
    if isleaf(x):
        yield x
        return
    for y in x[1]:
        yield from dfs(y)

rawDescription: Inserting an element in list, at exact location, without array sizing in Python?


code:
def tabsplit(file_object):
    for line in file_object:
        yield line.split("\t")

rawDescription: Reading from file using dict comprehensions


code: links = [a['href'] for a in soup.find_all('a',href=re.compile('http.*\.mp3'))]

rawDescription: Finding all Audio Links in a page using python


code:
from PySide.QtCore import QObject, QUrl, Slot
from PySide.QtGui import QApplication
from PySide.QtWebKit import QWebPage, QWebSettings

qapp = QApplication([])

def load_source(url):
    page = QWebPage()
    page.settings().setAttribute(QWebSettings.AutoLoadImages, False)
    page.mainFrame().setUrl(QUrl(url))

    class State(QObject):
        src = None
        finished = False

        @Slot()
        def loaded(self, success=True):
            self.finished = True
            if self.src is None:
                self.src = page.mainFrame().toHtml()
    state = State()

    # Optional; reacts to DOM ready, which happens before a full load
    def js():
        page.mainFrame().addToJavaScriptWindowObject('qstate$', state)
        page.mainFrame().evaluateJavaScript('''
            document.addEventListener('DOMContentLoaded', qstate$.loaded);
        ''')
    page.mainFrame().javaScriptWindowObjectCleared.connect(js)

    page.mainFrame().loadFinished.connect(state.loaded)

    while not state.finished:
        qapp.processEvents()

    return state.src

rawDescription: How would you give Chrome's version of a webpage to python?


rawDescription: using python join to join first element of each list

description: Using python join to join first element of each list


rawDescription: django ModelMultipleChoiceField (default values)

description: Django ModelMultipleChoiceField (default values)


code: ((cl != cl.shift()) & cl).cumsum() * cl

rawDescription: Pandas Label Sequences of 1 in a 0-1 valued Series


code:
import operator
operator.gt(2,1)

rawDescription: Python: Why does the int class not have rich comparison operators like `__lt__()`?


code:
class MyGlobals(object):
    x = 0

rawDescription: make variable global to multiple files in python

description: Make variable global to multiple files in python


code:
import pygame, sys, time

pygame.init()
red = (255, 0, 0)
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption('MyGame')
move_x = 200
move_y = 200

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                move_x -= 10

            if event.key == pygame.K_RIGHT:
                move_x += 10
        # pygame.Rect.move(10, 10)
    gameDisplay.fill([0,0,0]) # The line added.
    pygame.draw.rect(gameDisplay, red, [move_x, move_y, 10, 10])
    pygame.display.update()
    pygame.display.flip()

rawDescription: Pygame the rectangle is not moving?

description: Pygame the rectangle is not moving


code: print(" ".join(map(str,l)))

rawDescription: list with numbers and strings to single string python

description: List with numbers and strings to single string python


code:
import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)

rawDescription: How do I remove a substring from the end of a string in Python?

description: Remove a substring from the end of a string in Python


code: df.drop(df.columns[1:], axis=1)

rawDescription: Python Pandas - Main DataFrame, want to drop all columns in smaller DataFrame


code:
ax.plot(d1, 1, marker=align_marker('>', halign='left'), ms=20,
        clip_on=False, color='k', transform=ax.get_xaxis_transform())
ax.plot(d2, 1, marker=align_marker('<', halign='right'), ms=20,
        clip_on=False, color='k', transform=ax.get_xaxis_transform())

rawDescription: Align matplotlib scatter marker left and or right


rawDescription: Python multiply sequence trick

description: Python multiply sequence trick


rawDescription: Pandas, groupby and summing over specific months


rawDescription: List of dicts as Pandas column

description: List of dicts as Pandas column


code:
arr == np.array([1,3,9])
np.in1d(arr, [1,3,9]).reshape(arr.shape)

rawDescription: comparing ndarray with values in 1D array to get a mask

description: Comparing ndarray with values in 1D array to get a mask


rawDescription: Rotation of colorbar tick labels in matplotlib


code:
line = s[i]
match = re.search(motif, line)
if match:
    selection.append(line[match.end():match.end()+5])

rawDescription: Selecting item in a string from a starting point retrieved via regex (Python)


rawDescription: Get specific value from a formatted string in Python


code:
counter = 0
while True:
    [x, y, z][counter]()
    counter = counter % 3  # reset to 0 every 3rd iteration

rawDescription: Inside a range how can I internally count up to 3?


code:
import codecs
lines = list(codecs.open('report.csv', 'r', encoding='UTF-16'))
import pprint
pprint.pprint(lines[:8])

rawDescription: Weird characters in exported csv files when converting


code: {key:value for (key,value) in db.iteritems() for item in value if item['name']=='bob'}

rawDescription: Join Python dictionaries with a matching key:value pair


code:
def loadList():
    # Fill all the list first , make the readRecord() return eof (True or False).
    while readRecord():
        pass

    # than process data (check for zip code) this will run it only one time
    # but you can put it in a loop to repeat the action.
    processRecords()

rawDescription: Having trouble parsing a txt file into a list full of zip codes in my zipcode lookup program


code:
payload = {
    "filter": {
        "date": "pastThirtyDays",
        "lineitem": {
            "buyType": "RTB",
            "name": list_of_names,
        }
    },
    "metrics": ["cost"],
    "dimensions": ["date", "lineItem"],
}
payload = json.dumps(payload)

rawDescription: Python creating a string using \ and send it in a json request


code:
from PySide import QtGui

app = QtGui.QApplication([])
window = QtGui.QMainWindow()
window.setStyleSheet('/*\n some comment */\n\nbackground-color:black;\n\r\t\n')
window.show()

app.exec_()

rawDescription: Pyside setStyleSheet() and long lines?

description: Pyside setStyleSheet() and long lines


code:
import re

class Replace:
    def __init__(self):
        self.count = 0
    def __call__(self, match):
        self.count += 1
        if self.count > 1:
            return '5'
        else:
            return match.group()

value = "assessments"
nval = re.sub(r's', Replace(), value, flags=re.IGNORECASE)
print(nval)

rawDescription: Python RegEx substitution of all but first instance found


code:
main_window.grid_rowconfigure(1, weight=1)
main_window.grid_columnconfigure(1, weight=1)

rawDescription: Python using Tkinter moving Labels and Entry boxes


code:
('Sempahore acquired by:', 'Thread-1')
('Sempahore acquired by:', 'Thread-2')
('executing:', 1)
('Sempahore acquired by:', 'Thread-3')
('executing:', 2)
('Sempahore acquired by:', 'Thread-4')
('executing:', 3)
('Sempahore acquired by:', 'Thread-5')
('executing:', 4)
('executing:', 5)
('end of execution:', 1)
('Sempahore released by:', 'Thread-1')
('Sempahore acquired by:', 'Thread-6')
...

rawDescription: how to automatically release a semaphore in a thread after run() is executed?

description: Automatically release a semaphore in a thread after run() is executed


code: from selenium.webdriver.support.ui import WebDriverWait

rawDescription: Does selenium not work with & in url

description: Does selenium not work with & in url


code:
import re
import ruamel.yaml as yaml
from ruamel.yaml.reader import Reader
from ruamel.yaml.resolver import BaseResolver, Resolver
from ruamel.yaml.scanner import RoundTripScanner
from ruamel.yaml.parser_ import Parser
from ruamel.yaml.composer import Composer
from ruamel.yaml.constructor import RoundTripConstructor
from ruamel.yaml import RoundTripLoader
from ruamel.yaml.compat import to_str

yaml_str = """\
categories: {1: Yes, 2: No}
increasing: [00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10]
"""

class MyResolver(BaseResolver):
    pass

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:bool',
    re.compile(u'''^(?:true|True|TRUE|false|False|FALSE)$''', re.X),
    list(u'tTfF'))

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:float',
    re.compile(u'''^(?:
     [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
    |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
    |\\.[0-9_]+(?:[eE][-+][0-9]+)?
    |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
    |[-+]?\\.(?:inf|Inf|INF)
    |\\.(?:nan|NaN|NAN))$''', re.X),
    list(u'-+0123456789.'))

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:int',
    re.compile(u'''^(?:[-+]?0b[0-1_]+
    |[-+]?[0-9]+
    |[-+]?0o?[0-7_]+
    |[-+]?(?:0|[1-9][0-9_]*)
    |[-+]?0x[0-9a-fA-F_]+
    |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
    list(u'-+0123456789'))

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:merge',
    re.compile(u'^(?:<<)$'),
    [u'<'])

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:null',
    re.compile(u'''^(?: ~
    |null|Null|NULL
    | )$''', re.X),
    [u'~', u'n', u'N', u''])

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:timestamp',
    re.compile(u'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
    |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]?
    (?:[Tt]|[ \\t]+)[0-9][0-9]?
    :[0-9][0-9] :[0-9][0-9] (?:\\.[0-9]*)?
    (?:[ \\t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X),
    list(u'0123456789'))

MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:value',
    re.compile(u'^(?:=)$'),
    [u'='])

# The following resolver is only for documentation purposes. It cannot work
# because plain scalars cannot start with '!', '&', or '*'.
MyResolver.add_implicit_resolver(
    u'tag:yaml.org,2002:yaml',
    re.compile(u'^(?:!|&|\\*)$'),
    list(u'!&*'))

class MyRoundTripConstructor(RoundTripConstructor):
    def construct_yaml_int(self, node):
        value = to_str(self.construct_scalar(node))
        value = value.replace('_', '')
        sign = +1
        if value[0] == '-':
            sign = -1
        if value[0] in '+-':
            value = value[1:]
        if value == '0':
            return 0
        elif value.startswith('0b'):
            return sign*int(value[2:], 2)
        elif value.startswith('0x'):
            return sign*int(value[2:], 16)
        elif value.startswith('0o'):
            return sign*int(value[2:], 8)
        #elif value[0] == '0':
        #    return sign*int(value, 8)
        elif ':' in value:
            digits = [int(part) for part in value.split(':')]
            digits.reverse()
            base = 1
            value = 0
            for digit in digits:
                value += digit*base
                base *= 60
            return sign*value
        else:
            return sign*int(value)

MyRoundTripConstructor.add_constructor(
    u'tag:yaml.org,2002:int',
    MyRoundTripConstructor.construct_yaml_int)

class MyRoundTripLoader(Reader, RoundTripScanner, Parser,
                      Composer, MyRoundTripConstructor, MyResolver):
    def __init__(self, stream):
        Reader.__init__(self, stream)
        RoundTripScanner.__init__(self)
        Parser.__init__(self)
        Composer.__init__(self)
        MyRoundTripConstructor.__init__(self)
        MyResolver.__init__(self)

for ch in list(u'yYnNoO'):
    del Resolver.yaml_implicit_resolvers[ch]

data = yaml.load(yaml_str, Loader=MyRoundTripLoader)
print(data['increasing'])

rawDescription: Can't parse YAML correctly

description: Can't parse YAML correctly


code:
def is_allowed(time_rated, duration):
    durations = {'day': 86400, 'week': 604800}
    if duration in durations and isinstance(time_rated, int):
        time_difference = time.time() - time_rated
        return time_rated > durations[duration]
    return False

rawDescription: comparing unix timestamps in python

description: Comparing unix timestamps in python


code:
df.columns = pd.to_datetime(df.columns)
df

rawDescription: How to use pandas to group pivot table results by week?

description: Use pandas to group pivot table results by week


rawDescription: Python: Converting HEX string to bytes

description: Python: Converting HEX string to bytes


code:
row = ['city', 'state', 'zip', 'zippostal', 'company']
custom_join(row, [0, 1, 2], [3], [4])
custom_join(row, [-1, 0, 2], [1], [-2])

rawDescription: Merge Items in List from different areas Python


rawDescription: python unique list based on item

description: Python unique list based on item


code:
from itertools import groupby

def splitter(text, separators):
    grouped = groupby(text, lambda c: c in separators)
    return [''.join(g) for k,g in grouped if not k]

rawDescription: How can I simplify this function?

description: Simplify this function


code:
Updated
#Add extensions that requires NumPy to build
if is_Numpy_installed():
   import numpy
   numpy_include_dir = numpy.get_include()
   EXTENSIONS.append(
      Extension('Bio.Cluster.cluster',
              ['Bio/Cluster/clustermodule.c',
               'Bio/Cluster/cluster.c'],
              include_dirs=[numpy_include_dir, '/usr/local/lib64/python2.7/site-packages/numpy/core/include/'],
              ))
   EXTENSIONS.append(
      Extension('Bio.KDTree._CKDTree',
              ["Bio/KDTree/KDTree.c",
               "Bio/KDTree/KDTreemodule.c"],
              include_dirs=[numpy_include_dir, '/usr/local/lib64/python2.7/site-packages/numpy/core/include/'],
              ))
   EXTENSIONS.append(
      Extension('Bio.Motif._pwm',
              ["Bio/Motif/_pwm.c"],
              include_dirs=[numpy_include_dir, '/usr/local/lib64/python2.7/site-packages/numpy/core/include/'],
              ))

rawDescription: Changing Biopython include path for compilation during pip installation


code:
from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer()
X = vec.fit_transform(input_data)

from sklearn.linear_model import LogisticRegressionCV
lr_cv = LogisticRegressionCV()
lr_cv.fit(X, y_input)

X_new = vec.transform(new_data)
y_new = lr_cv.predict(X_new)

rawDescription: How to transform new input data using dictVectorize and using the model?

description: Transform new input data using dictVectorize and using the model


code:
import operator
stats = {'a':1000, 'b':3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]

rawDescription: Getting key with maximum value in dictionary?


code: mnX += cnA

rawDescription: Modify numpy array column by column inside a loop


code:
d = {'Changes': [{'StartColumn': 34, 'StartLine': 8, 'EndLine': 8, 'NewText': '\n        ', 'EndColumn': 34}, {'StartColumn': 13, 'StartLine': 9, 'EndLine': 9, 'NewText': '', 'EndColumn': 17}, {'StartColumn': 13, 'StartLine': 10, 'EndLine': 10, 'NewText': '', 'EndColumn': 17}]}
d["Changes"].sort(key=lambda x: x["EndLine"], reverse=True)
d["Changes"]

rawDescription: Python ordering a dictionary value

description: Python ordering a dictionary value


code: [item for item in x if item not in y]

rawDescription: Python list subtraction operation

description: Python list subtraction operation


rawDescription: Python remove everything after a space with hex \x00


rawDescription: Order of operations and fast computation in Python


code:
df['Time'] = df.Day + " " + df.Hour

df.drop(["Day","Hour"],axis=1,inplace=True)
print(df)

rawDescription: Extract specified area from DataFrame

description: Extract specified area from DataFrame


code: c = np.setdiff1d(np.union1d(a, b), np.intersect1d(a, b))

rawDescription: Numpy: find the the non-intersecting values of two arrays


rawDescription: Iterate through rows in pandas dateframe in a cleaner way using .iterrows() and keep track of rows inbetween specific values


code:
import scipy.stats as ss
res = ss.ttest_ind_from_stats(df2.avg, df2.stdev, df2.n, df2.avg_2, df2.stdev_2, df2.n_2, equal_var=False)

rawDescription: pandas: t-test and p-value of month over month mean difference in aggregated dataframe using groupby function

description: Pandas: t-test and p-value of month over month mean difference in aggregated dataframe using groupby function


code:
detect_language(u'Hello world!')
detect_language(u'తెలుు')
detect_language(u'हिन्दी')

rawDescription: How to detect unicode character range in Python?

description: Detect unicode character range in Python


rawDescription: Return dict of attribute name and value of type


code:
import tkinter
import mbox

root = tkinter.Tk()

Mbox = mbox.Mbox
Mbox.root = root

D = {'user':'Bob'}

b_login = tkinter.Button(root, text='Log in')
b_login['command'] = lambda: Mbox('Name?', (D, 'user'))
b_login.pack()

b_loggedin = tkinter.Button(root, text='Current User')
b_loggedin['command'] = lambda: Mbox(D['user'])
b_loggedin.pack()

root.mainloop()

rawDescription: Correct way to implement a custom popup tkinter dialog box


rawDescription: Initializing a large list of booleans in Python


code:
def f(x): # define this according to your function.
    return x*x

def integrate(func, a, b, width):
    total = 0
    i = a
    while i <= b:
        total += func(i)
        i += width
    return total * width

width = 0.01
integral = integrate(f, 0, 100, width)
print(integral)

rawDescription: How to numerically integrate f(x) between a lower and an upper bound?

description: Numerically integrate f(x) between a lower and an upper bound


code: app = application(urls, globals())

rawDescription: web.py: How to selectively hide resources with 404s for any HTTP method?

description: Web.py: How to selectively hide resources with 404s for any HTTP method


code: out = np.empty_like(arr)

rawDescription: Iterating a function over the RGB values of individual pixels


rawDescription: Calculating the number of years in a pandas dataframe


code:
from matplotlib.lines import Line2D
from matplotlib.gridspec import GridSpec
from enum import Enum

class Location(Enum):
    EastOutside = 1
    WestOutside = 2
    NorthOutside = 3
    SouthOutside = 4

class Legend:
    def __init__(self, figure, plotAxes, location: Location):
        self.figure = figure
        self.plotAxes = plotAxes
        self.location = location

        # Create a separate subplot for the legend. Actual location doesn't matter - will be modified anyway.
        self.legendAxes = figure.add_subplot(1, 2, 1)
        self.legendAxes.clear() # remove old lines
        self.legendAxes.set_axis_off()

        # Add all lines from the plot to the legend subplot
        for line in plotAxes.get_lines():
            legendLine = Line2D([], [])
            legendLine.update_from(line)
            self.legendAxes.add_line(legendLine)

        if self.location == Location.EastOutside:
            self.legend = self.legendAxes.legend(loc = "center left")
        elif self.location == Location.WestOutside:
            self.legend = self.legendAxes.legend(loc = "center right")
        elif self.location == Location.NorthOutside:
            self.legend = self.legendAxes.legend(loc = "lower center")
        elif self.location == Location.SouthOutside:
            self.legend = self.legendAxes.legend(loc = "upper center")
        else:
            raise Exception("Unknown legend location.")

        self.UpdateSize()

        # Recalculate legend size if the size changes
        figure.canvas.mpl_connect('resize_event', lambda event: self.UpdateSize())

    def UpdateSize(self):
        self.figure.canvas.draw() # draw everything once in order to get correct legend size

        # Extract legend size in percentage of the figure width
        legendSize = self.legend.get_window_extent().inverse_transformed(self.figure.transFigure)
        legendWidth = legendSize.width
        legendHeight = legendSize.height

        # Update subplot such that it is only as large as the legend
        if self.location == Location.EastOutside:
            gridspec = GridSpec(1, 2, width_ratios = [1 - legendWidth, legendWidth])
            legendLocation = 1
            plotLocation = 0
        elif self.location == Location.WestOutside:
            gridspec = GridSpec(1, 2, width_ratios = [legendWidth, 1 - legendWidth])
            legendLocation = 0
            plotLocation = 1
        elif self.location == Location.NorthOutside:
            gridspec = GridSpec(2, 1, height_ratios = [legendHeight, 1 - legendHeight])
            legendLocation = 0
            plotLocation = 1
        elif self.location == Location.SouthOutside:
            gridspec = GridSpec(2, 1, height_ratios = [1 - legendHeight, legendHeight])
            legendLocation = 1
            plotLocation = 0
        else:
            raise Exception("Unknown legend location.")

        self.legendAxes.set_position(gridspec[legendLocation].get_position(self.figure))
        self.legendAxes.set_subplotspec(gridspec[legendLocation]) # to make figure.tight_layout() work if that's desired

        self.plotAxes.set_position(gridspec[plotLocation].get_position(self.figure))
        self.plotAxes.set_subplotspec(gridspec[plotLocation]) # to make figure.tight_layout() work if that's desired

rawDescription: Legend outside the plot in Python - matplotlib


code:
def tryCreateUser():
    for title, button in self.buttons.items():
        print("Title is {}, button obj is {}".format(title, button))

rawDescription: Pyqt4 accessing objects when creating a dynamic form


code:
handles, labels = ax.get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
ax.legend(by_label.values(), by_label.keys(), loc='upper center', shadow=True)

rawDescription: Legend format lost after using: ax.legend(handles, labels )


code:
PORT = 50000
MAGIC = "fna349fn" #to make sure we don't confuse or get confused by other programs

rawDescription: Python service discovery: Advertise a service across a local network


code:
def __connectionistModel_vec(self, g, t):
    """
        Returning the ODE system
    """
    g_ia_s = np.zeros(self.nGenes * self.nCells)

    g_2d = g.reshape((self.nCells, self.nGenes))
    W = np.array(self.Params["W"])
    mData = np.array(self.mData)
    g_ia_s = np.zeros((self.nCells, self.nGenes))

    for a in xrange(0, self.nGenes):
        g_ia = self.Params["R"][a] *\
            self.__sigmoid( (W[a*self.nGenes:(a+1)*self.nGenes]*g_2d).sum(axis=1) +\
                self.Params["Wm"][a]*mData +\
                self.Params["h"][a] ) -\
            self.Params["l"][a] * g_2d[:,a]
        g_ia[0] += self.Params["D"][a] * ( - 2*g_2d[0,a] + g_2d[1,a] )
        g_ia[-1] += self.Params["D"][a] * ( g_2d[-2,a] - 2*g_2d[-1,a] )
        g_ia[1:-1] += self.Params["D"][a] * ( g_2d[:-2,a] - 2*g_2d[1:-1,a] + g_2d[2:,a] )

        g_ia_s[:,a] = g_ia

    return g_ia_s.ravel()

rawDescription: How do I improve the speed of this code? (Solving ODEs with scipy.integrate.odeint)

description: Improve the speed of this code? (Solving ODEs with scipy.integrate.odeint)


code:
s = ''.join(r"""
foo\tbar\n
baz\tqux\n
""".splitlines())

rawDescription: How can I create a single raw string from multiple literals in Python?

description: Create a single raw string from multiple literals in Python


code:
mystring = """Hello
World!"""
mystring

rawDescription: inverted comma and string in python

description: Inverted comma and string in python


code:
z = []
for y in x:
    if y>256:
        z.append(y-256)
    else:
        z.append(y)

rawDescription: Tuple Subtract statement in Python

description: Tuple Subtract statement in Python


code: df.loc[df.index.year == 2007]/df.loc[df.index.year == 2009].values

rawDescription: Pandas: Divide two rows by each other

description: Pandas: Divide two rows by each other


code: X = numpy.loadtxt('somefile.csv', delimiter=',')

rawDescription: Pythonic way to populate numpy array

description: Pythonic way to populate numpy array


code:
import timeit
def d_reduce(lst):
    reduce(lambda r, d: r.update(d) or r, lst, {})

def d_chain(lst):
    dict(chain.from_iterable(imap(methodcaller('iteritems'), lst)))

def d_comp(lst):
    {k: v for d in lst for k, v in d.iteritems()}

timeit.timeit('f(lst)', 'from __main__ import lst, d_reduce as f')
timeit.timeit('f(lst)', 'from __main__ import lst, d_chain as f')
timeit.timeit('f(lst)', 'from __main__ import lst, d_comp as f')

rawDescription: Python - Convert list of single key dictionaries into a single dictionary


code:
DOMAIN_DEPTHS = {'amazon.com': 1, 'homedepot.com': 4}
DEPTH_LIMIT = 3

rawDescription: Scrapy set depth limit per allowed_domains


code:
from gi.repository import Gtk, Gdk

window = Gtk.Window()
window.connect("destroy", Gtk.main_quit)
screen = Gdk.Screen.get_default()
css_provider = Gtk.CssProvider()
css_provider.load_from_path('style.css')
priority = Gtk.STYLE_PROVIDER_PRIORITY_USER
context = Gtk.StyleContext()
context.add_provider_for_screen(screen, css_provider, priority)
entry = Gtk.Entry(text='Testing..')
window.add(entry)
window.show_all()
Gtk.main()

rawDescription: gtk+ python entry color

description: Gtk+ python entry color


code: df = pd.DataFrame(list(rows))

rawDescription: Read flat file to DataFrames using Pandas with field specifiers in-line


code:
from lxml import etree

tree = etree.Element('div', attrib={'attr':'val', 'U00022':''})
etree.tostring(tree)
'<div U00022="" attr="val"/>'

# parse as self-closing tag
etree.tostring(tree, method='xml')
'<div U00022="" attr="val"/>'
# parse as normal HTML
etree.tostring(tree, method='html')
'<div U00022="" attr="val"></div>'

rawDescription: parse any HTML to XML using html5lib

description: Parse any HTML to XML using html5lib


code: tuple((a, b, date.strftime('%Y-%m-%d %H:%M:%S')) for (a, b, date) in Tuple)

rawDescription: How to apply a function to an element at a particular position in every tuple inside a tuple of tuples?

description: Apply a function to an element at a particular position in every tuple inside a tuple of tuples


code:
with open("data.txt") as fh:
    fh.next()
    for line in fh:
        line = line.split()  # This split works equally well for tabs and other spaces
        do_something(line[2:])

rawDescription: python: database formatted in txt e skip first line and first two columns

description: Python: database formatted in txt e skip first line and first two columns


code: open("your_modified_file.tsv", "w").write( "\n".join(arrs) )

rawDescription: increment 1 in the sixth column after every twenty lines

description: Increment 1 in the sixth column after every twenty lines


code:
[defaults]
python=3

rawDescription: In CMD "python" starts Python 3.3, "py" starts Python 2.7, how do I change this?


rawDescription: How do I set the increment in a graph in matplotlib

description: Set the increment in a graph in matplotlib


code:
import os
import re
qualifier = re.sub(r'[-_]+', '', os.environ['BUILD_ID'])[0:12]

rawDescription: How to use Jenkins Environment variables in python script

description: Use Jenkins Environment variables in python script


code:
def flip(p):
    return 'H' if random.random() < p else 'T'

rawDescription: How do I simulate flip of biased coin in python?

description: Simulate flip of biased coin in python


code:
def application():
    print("="*20)
    print("Enter 0 to multiply two numbers")
    print("Enter 1 to divide two numbers")
    print("Enter -1 to quit the application")
    print("="*20)

application() # added
choice=input("Enter you choice:- ")

while choice!=-1:

    first_number=input("Enter 1st number:-") # moved
    second_number=input("Enter 2nd number:- ") # moved

    if choice==0:
        multiply=first_number*second_number
        print(str(first_number)+ " multiply by "+str(second_number)+ " is equal to " + str(multiply))
    elif choice==1:
        divide=first_number/second_number
        print(str(first_number)+ " divided by "+str(second_number)+ " is equal to " + str(divide))
    else:
        print("Invalid option.")

    application()
    choice=input("Enter your choice:- ")

print("Quit the application")

rawDescription: Indeteminate While Loop

description: Indeteminate While Loop


code:
authors = []
num_authors = int(raw_input("How Many Authors? "))
for i in range(num_authors):
    authors.append(raw_input("Enter Author's Name ({}): ".format(i+1)))

rawDescription: How to format inputted data and output it

description: Format inputted data and output it


code:
from sympy import S
type(S.Zero).mro()

rawDescription: Sympy classes Zero, One and NegativeOne, why they exist?


code:
p = Product()
p.product_name = 'test product'
p.product_id = 1
session.add(p)
pic1 = ProductPicture()
pic1.product_id = p.product_id
pic1.picture_type = 'main'
pic1.url = 'http://example.com/p1.main.png'
session.add(pic1)
pic2 = ProductPicture()
pic2.product_id = p.product_id
pic2.picture_type = 'option'
pic2.url = 'http://example.com/p1.option1.png'
session.add(pic2)
pic3 = ProductPicture()
pic3.product_id = p.product_id
pic3.picture_type = 'option'
pic3.url = 'http://example.com/p1.option2.png'
session.add(pic3)
session.commit()
[(pic.picture_type, pic.url) for pic in p.product_pictures]
[(pic.picture_type, pic.url) for pic in p.main_pictures]
[(pic.picture_type, pic.url) for pic in p.option_pictures]

rawDescription: SQLAlchemy one to many relationship, how to filter the collection


code:
def sortlh(lst_input):
    lst = list(lst_input) # make a copy of lst_input
    for i, x in enumerate(lst):
        lowest, i_lowest = min((n, j) for j, n in enumerate(lst) if j >= i)
        lst[i], lst[i_lowest] = lst[i_lowest], lst[i]  # swap
    return lst

test = [9,8,7,6,5,4,3,2,1]
assert sortlh(test) == sorted(test)
test = [1,3,2,4,5,7,6,9,8]
assert sortlh(test) == sorted(test)

rawDescription: Selection Sort (low to high) python

description: Selection Sort (low to high) python


code:
type(find)
find
type(find[0])

rawDescription: Web scraper returning list of elements

description: Web scraper returning list of elements


rawDescription: Django query for items that have a unique field


code:
import rasterio
with rasterio.open(fname, 'r') as r:
    T0 = r.affine

rawDescription: How to I get the coordinates of a cell in a geotif?


code:
from Tkinter import *
import ttk

# In Python 3.x
#from tkinter import *
#from tkinter import ttk

root = Tk()

pane = PanedWindow(orient=VERTICAL)
pane.pack()

upper_container = Frame(pane)
upper_container.pack()

left_tree = ttk.Treeview(upper_container)
left_tree.pack(side=LEFT)
right_tree = ttk.Treeview(upper_container)
right_tree.pack(side=LEFT)

lower_tree = ttk.Treeview(pane)
lower_tree.pack()

pane.add(upper_container)
pane.add(lower_tree)

root.mainloop()

rawDescription: Python multiple treeviews

description: Python multiple treeviews


rawDescription: O(n) Java algorithm to find odd-number-out in array (not odd numbers)


rawDescription: Using difflib SequenceMatcher ratio to merge in Pandas


code:
for i in range(len(A)): #generate pairs
    for j in range(i+1,len(A)):
        if np.array_equal(A[i],A[j]): #compare rows
            if np.array_equal(A[:,i],A[:,j]): #compare columns
                print (i, j),
        else: pass

rawDescription: finding identical rows and columns in a numpy array

description: Finding identical rows and columns in a numpy array


code:
order = []
mapping = {}
for outer, inner, value in t:
    if outer not in order:
        order.append(outer)
    mapping.setdefault(outer, {})[inner] = value

result = [(k, mapping[k]) for k in order]

rawDescription: how can I convert python tuple to dict

description: Convert python tuple to dict


rawDescription: Best strategy for storing precomputed sunrise/sunset data?


code:
open('file.txt', 'w').write('Hello, world!')
s = os.stat('file.txt')
s.st_size
s.st_blocks * 512

rawDescription: How to determine file's extended attributes and resource forks with their size on Mac OSX?

description: Determine file's extended attributes and resource forks with their size on Mac OSX


code:
with open("myFile.txt","r") as readfile, open("outFile.txt","w") as outfile:
    for line in readfile:
        if line.count("(") != line.count(")") or line.count('"') % 2 != 0:
            outfile.write(line)

rawDescription: Determine if a line has parenthesis or quotes that are not closed in python


code:
import itertools

def nwise(iterable, n=2):
    "s->(s_0,s_1, ..., s_n), (s_1,s_2,..., s_n+1), ... "
    ntup = itertools.tee(iterable, n)
    for i, item in enumerate(ntup):
        for ii in range(i):
            next(item, None)
    return itertools.izip(*ntup)

rawDescription: Referencing list entries within a for loop without indexes, possible?


code: resident_names = [input("Name of resident {}: ".format(i)) for i in range(1, residents + 1)]

rawDescription: Variables based on input

description: Variables based on input


code: same = object()

rawDescription: In a decorator how can I pass the function I'm decorating as an argument?


code:
[next((i for i, (a, b) in
    enumerate(izip(islice(s, start1, None), islice(s, start2, None)))
        if a != b),
    length - max((start1, start2)))
 for start1, start2 in izip(pos, islice(pos, 1, None))]

rawDescription: Longest common prefix using buffer?

description: Longest common prefix using buffer


code:
import pygame

# Just a definition of a few colours
class Colour(object):
    WHITE = (255, 255, 255)
    GREY  = (128, 128, 128)
    BLUE  = ( 64, 128, 255)

# GuiObject is just a rectangle with a colour at the moment (for testing purposes).
class GuiObject(object):
    def __init__(self, rect, colour):
        self.rect   = rect
        self.colour = colour

    def render(self, screen):
        pygame.draw.rect(screen, self.colour, self.rect)

def main():
    ############################################################################
    # Initialise
    pygame.init()
    screen = pygame.display.set_mode((800, 600))

    # if render_type = 0 then render GuiObjects using a for loop
    # if render_type = 1 then render GuiObjects separately.
    render_type = 0

    gui_objects = [
        ("hpbar_bg", GuiObject(( 0,  0, 150, 600), (Colour.BLUE))),
        ("enemy_hpbar", GuiObject((10, 10, 200, 400), (Colour.WHITE))),
    ]

    ############################################################################
    # Main loop
    while True:
        ########################################################################
        # Event Handling
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit(0)

        ########################################################################
        # Render
        screen.fill((0, 0, 0))

        # Here, I render the GuiObjects.
        if render_type == 0:
            # This for loop no longer messes up overlapping.
            for key, value in gui_objects:
                value.render(screen)

        pygame.display.flip()

if __name__ == "__main__":
    main()

rawDescription: Pygame: Rect Objects Don't Render Properly in For Loops


code:
edgesList = []
for featureId in edges:
    coordinates = edges[featureId]
    c0, c1 = coordinates

    n0 = nodes[c0]
    n1 = nodes[c1]

    edgesList.append((featureId, n0, n1))

rawDescription: Speed up finding matches between two dictionaries (Python)


code:
data_dict[9] # access data10
#or
data_list[9]

rawDescription: Load many text files in a loop in arrays with different names with numpys loadtxt


rawDescription: Multiple format options in Python

description: Multiple format options in Python


code:
class InternDict(dict):

    def __setitem__(self, key, value):
        if isinstance(value, str):
            super(InternDict, self).__setitem__(key, intern(value))
        else:
            super(InternDict, self).__setitem__(key, value)

rawDescription: size efficient dictionary(associative array) implementation

description: Size efficient dictionary(associative array) implementation


code: return "gzip {0.path}".format(Wrapper(some_object, context))

rawDescription: Extra arguments for __str__ and __format__


code:
class ExampleElement(Element):
    loader = XMLFile(FilePath('template.xml'))

    extraContent = XMLFile(FilePath('extra-content.xml'))

    @renderer
    def content(self, request, tag):
        return self.extraContent.load()

rawDescription: How to dump html string into a python twisted template

description: Dump html string into a python twisted template


rawDescription: BYTE to python C-Type structure Conversion Issue


code:
import cPickle as pickle
from random import randint  # for testing
import os

# needed if not run in -u mode
#if os.name == 'nt':  # put stdout into binary mode on Windows
#    import sys, msvcrt
#    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

class OtherClass(object):
    def __init__(self, files):
        self.files = files
        self.download()

    def download(self):
        files = [fn for fn in self.files if fn != '.' and fn != '..']
        successful = []
        unsuccessful = []
        for fn in files:
            if randint(0, 1) % 2:  # simulate random download success
                successful.append(fn)
        for fn in files:
            if fn not in successful:
                unsuccessful.append(fn)
        results = {  # package lists into single object
            'successful': successful,
            'unsuccessful': unsuccessful
        }
        print(pickle.dumps(results))  # send object by writing it to stdout

instance = OtherClass(['.', '..', 'file1', 'file2', 'file3', 'file4'])

rawDescription: How to get subprocess.Popen to work correctly?

description: Get subprocess.Popen to work correctly


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

rawDescription: How do I create a namespace package in Python?

description: Create a namespace package in Python


code:
from ghost import Ghost
ghost = Ghost()

rawDescription: Installing Ghost.py

description: Installing Ghost.py


code:
new_version = DatabaseVersion(version=version + 1)
db.session.add(new_version)
db.session.commit()

rawDescription: Sqlalchemy explicit locking of Postgresql table


code: my_2d_list = zip(*columns)

rawDescription: Convert a column in a list to number, keeping other columns unchanged


rawDescription: Using python mocking library on sqlalchemy


rawDescription: Is "join" slower in 3.x?

description: Is "join" slower in 3.x


code:
lis = []

def ppend(n):
    if n.rest is not None:  # the first if statement appears unnecessary
        lis.append(n.first)
        ppend(n.rest)
    return lis  # or don't return it but simply refer to lis where you need to

rawDescription: appending LinkedLists items to list using Recursion

description: Appending LinkedLists items to list using Recursion


rawDescription: Length cutting through file handling

description: Length cutting through file handling


code:
return render_to_response('results.html',
    {'data': sorted(results_dict.items())})

rawDescription: How to render an ordered dictionary in django templates?

description: Render an ordered dictionary in django templates


rawDescription: Generate pixel matrices from characters in string


code: {u'sentence1': 'Satz1', u'sentence2': 'Satz2'}

rawDescription: Combine two lists of lists into a dictionary python


code: ax.legend(ells, ['label1', 'label2', 'label3'])

rawDescription: Label plotted ellipses

description: Label plotted ellipses


rawDescription: Calling specific version of python from PHP


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

with open("EURGBP DATA.txt") as f:
    data = f.read()

    data = data.split('\n')

    x = [row.split()[0] for row in data]
    y = [row.split()[1] for row in data]

index = [i for i,val in enumerate(x)]

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Plot DAta")
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_xticklabels(x)
ax1.plot(index ,y, c='r', label='the data')
leg = ax1.legend()
plt.locator_params(nbins=len(index)-1)
plt.show()

rawDescription: Simple Python plot -currency and dates

description: Simple Python plot -currency and dates


code:
import pandas as pd
df = pd.DataFrame({'level': [0, 1, 2, 1, 2, 3, 3, 1, 2],
                   'name': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'B', 'C']})

parent = dict()
mother = []
for index, row in df.iterrows():
    parent[row['level']] = row['name']
    mother.append(parent.get(row['level']-1))
df['mother'] = mother
print(df)

rawDescription: Mapping values into a new dataframe column


code:
import sys

def methoddecorator(func):
     callingframe = sys._getframe(1)
     classname = callingframe.f_code.co_name

rawDescription: Is there a way apply a decorator to a Python method that needs informations about the class?


code:
def login_required(role="ANY"):
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):

            if not current_user.is_authenticated():
               return current_app.login_manager.unauthorized()
            urole = current_app.login_manager.reload_user().get_urole()
            if ( (urole != role) and (role != "ANY")):
                return current_app.login_manager.unauthorized()
            return fn(*args, **kwargs)
        return decorated_view
    return wrapper

rawDescription: Implementing Flask-Login with multiple User Classes


rawDescription: How to get the file name and show it on Qlistwidget?

description: Get the file name and show it on Qlistwidget


code:
def myfunc(*args, **kwargs):
    ...

rawDescription: How to efficiently unravel arguments to a database in Python

description: Efficiently unravel arguments to a database in Python


code:
new_classes = []
if issubclass(thing, AuthenticatedApiTestCase):
    class NewClasS(thing):
        base_url = something_new

    new_classes.append(NewClass)

rawDescription: Python Metaprogramming. Generating massive amount of similar tests where a variable value is changed


code:
prefix = 'Name: '
s[len(prefix):].split(', ' + prefix)

rawDescription: Regex extract element after string

description: Regex extract element after string


code:
'zara' > 'marco'
sorted(['zara', 'marco'])

rawDescription: Max() function does not return largest value in Python 3.4


code:
some= 1
list= 2
of= 3
vars= 4
dict( (name,eval(name)) for name in ['some','list','of','vars'] )

rawDescription: How to get a variable name as a string in Python?

description: Get a variable name as a string in Python


rawDescription: Simulate static variables in python with closures


code: arr

rawDescription: Using numpy's genfromtxt to load a triangular matrix with python


code:
class UserProfile(models.Model):
    user = models.OneToOneField(User)

    @property
    def profile(self):
        return self.get_profile()

    def __str__(self):
          return "%s's profile" % self.user

rawDescription: How does passing a lambda function for a property() work when extending Django's user model?


code: [y for (x, y) in zip(a, msg) if x < 0]

rawDescription: simple dropping elements from the list in python

description: Simple dropping elements from the list in python


rawDescription: In Python with a nested dictionary should I check the type? What other approach can I use?


code:
from itertools import product
lsts = [['A','G'],['A','C','G'],'T']
[''.join(combo) for combo in product(*lsts)]

rawDescription: Generate permutations of a list of lists with variable lengths


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

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

rawDescription: How do I server a specific directory with possible sub directories in Django 1.7?

description: Server a specific directory with possible sub directories in Django 1.7


code: np.where((a>b) & (np.roll(a, 1) < np.roll(b, 1)))

rawDescription: How do I compare two arrays element-wise in Python using specific rules?

description: Compare two arrays element-wise in Python using specific rules


code:
result = {}
for d in alist:
    for key, value in d.items():
        result.setdefault(key, []).append(value)

rawDescription: concatenate dictionaries over a key

description: Concatenate dictionaries over a key


rawDescription: regex - matching number with optional range

description: Regex - matching number with optional range


rawDescription: Skipping JSON output in a loop

description: Skipping JSON output in a loop


code: db.insert({ 'text' : title , 'createdAt': datetime.datetime.utcnow()} )

rawDescription: Meteor / python / mongoDB - How do I update the mongoDB from a backround running process?


rawDescription: Python matplotlib histogram: edit x-axis based on maximum frequency in bin


rawDescription: HMAC-SHA1 URL encryption in VBA produces incorrect output


code: s2 = s1[:s.rfind('\n')]  #This picks up the newline after "everything"

rawDescription: Parse multi-line string up until first line with certain character


code:
lengths = np.array([4, 3, 5, 2])
np.concatenate(map(np.arange, lengths))

rawDescription: repeat array in arbitary length

description: Repeat array in arbitary length


code:
Shapes = [[shape1-Corners],[CenterX, CenterY],
          [shape2-Corners],[CenterX, CenterY],
          [shape3-Corners],[CenterX, CenterY],
          [...]
          [shapeN-Corners],[CenterX, CenterY]]

rawDescription: Data structure in python containing shapes corners and centroids


rawDescription: when using groupby with multiple columns, how to NOT drop an unobserved combination of columns

description: When using groupby with multiple columns, how to NOT drop an unobserved combination of columns


code:
hostname = domain
while True:
    first, _, end = hostname.rpartition('.')
    if '-' in end:
        break
    hostname = first

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

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


rawDescription: Upload Images to Amazon S3 using Django

description: Upload Images to Amazon S3 using Django


code:
s = 'http://www.domain.com/?s=some&two=20'
s.split('&')

rawDescription: Python - How to cut a string in Python?

description: Python - How to cut a string in Python


code:
import sys
print(sys.platform)

import os
print(os.name)

rawDescription: How do I check what platform (OS) im running in Python 2.7?

description: Check what platform (OS) im running in Python 2.7


code:
from glob import glob

pattern = "D:\\report\\shakeall\\*.txt"
filelist = glob(pattern)

rawDescription: How to import files from specific directory, not using os.path in Python

description: Import files from specific directory, not using os.path in Python


code: [x for x in (k.replace('\n', '').strip() for k in foo) if x]

rawDescription: Reuse modified key in list comprehension


code:
[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

rawDescription: find first list item that matches criteria

description: Find first list item that matches criteria


code:
class _Deadnodes(lrucacheExtension.NodeCache):
    pass

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


code:
from glob import glob

for file in sorted(glob('path/file.*'))[::90]:
    ...

rawDescription: loop over files in python?

description: Loop over files in python


code:
included = set(range(1000)) - excluded
result_int = random.choice(list(included))

rawDescription: Generating a random string of fixed length where certain values are prohibited