code:
from Bio import SeqIO
for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"):
    print(seq_record.id)
    print(repr(seq_record.seq))
    print(len(seq_record))

rawDescription: Search Fasta file in python, return read efficiently


code:
s =  "I can't see you"
re.findall(r'\[.*?\]|.*?(?=\[|$)', s)[:-1]
s = "[greeting] Hello my friends [me] my name is John. [bow] nice to meet you."
re.findall(r'\[.*?\]|.*?(?=\[|$)', s)[:-1]

rawDescription: Split string with delimiters in Python

description: Split string with delimiters in Python


code:
file = drive.CreateFile({'title':'appdata.json', 'mimeType':'application/json'})
file.SetContentString('{"firstname": "John", "lastname": "Smith"}')
file.Upload() # Upload file
file.SetContentString('{"firstname": "Claudio", "lastname": "Afshar"}')
file.Upload() # Update content of the file

rawDescription: Google Drive SDK: I want to update a file, not create new one


code:
with open('large_file.txt') as f:
    pairs = (line.split()[:2] for line in f)
    processed_pairs = ((pair[0].split(':')[1], float(pair[1])) for pair in pairs)
    top_10_pairs = heapq.nlargest(10, processed_pairs, key=operator.itemgetter(1))

rawDescription: parsing a file so as to get the top 10 players.

description: Parsing a file so as to get the top 10 players.


code:
class SomeModelAdmin(admin.ModelAdmin):
    list_display = ['__unicode__', 'something_else']

admin.site.register(SomeModel, SomeModelAdmin)

rawDescription: make model __unicode__ method return to multiple colums

description: Make model __unicode__ method return to multiple colums


code:
import pandas
df = pandas.read_csv("test.csv")
df['FirstName'][df.ID == 103] = "Matt"
df['LastName'][df.ID == 103] = "Jones"

rawDescription: Python PANDAS, change one value based on another value


code:
x1 = min(x_points)
y1 = min(y_points)
x2 = max(x_points)
y2 = max(y_points)
cv2.rectangle(img, (x1,y1), (x2,y2), thickness=-1)

rawDescription: Polygon or free-form shape drawing with OpenCV Python


code:
from functools import lru_cache

@lru_cache(maxsize=100)  # definitely tweak maxsize as needed
def simplecache(y, x):
   ...

rawDescription: A fast way of getting a consistent random result without setting a new seed every time


code: slugify(u'My International Text: åäö')

rawDescription: Normalizing unicode text to filenames, etc. in Python


code:
stillWorking = 'Yes'
stillWorking == 'Yes', 'yes', 'YES', 'y', 'Y'

rawDescription: Logging data and how to do multiple responses and work with variables in python


code: [(x,y) for x in a for y in b]

rawDescription: is there a way to get the index for multiple lists python?

description: Is there a way to get the index for multiple lists python


code:
def find_words_and_remove(words, strings):
    strings_copy = strings[:]
    for i, word in enumerate(words):
        for string in strings:
            strings_copy[i] = _find_word_and_remove(word, string)
    return strings_copy

rawDescription: Erasing list of phrases from list of texts in python


code:
passes = {
    'Messi' : ['Iniesta', 'Xavi','Neymar', 'Xavi', 'Xavi'],
    'Iniesta' : ['Messi','Xavi', 'Neymar','Messi', 'Xavi'],
    'Xavi'  : ['Messi','Neymar','Messi','Neymar'],
    'Neymar' : ['Iniesta', 'Xavi','Iniesta', 'Xavi'],
}

rawDescription: Python Data Structure Selection

description: Python Data Structure Selection


rawDescription: How to quickly count number of 0(s) in a binary list?

description: Quickly count number of 0(s) in a binary list


rawDescription: In Pandas How to sort one level of a multi-index based on the values of a column, while maintaining the grouping of the other level


rawDescription: Implement this situation in numpy

description: Implement this situation in numpy


code:
filter = ['Like', 'Liked']

df.apply(lambda column:
    column[~(column.isnull() | column.isin(filter))].reset_index(drop=True)
)

rawDescription: Getting Dataframe from existing Dataframe after some filter


code: x = string.split("::")[-1]

rawDescription: How to use the regular Expression in python

description: Use the regular Expression in python


code:
def rec_get(d, k):
    if isinstance(d, dict):
        if k in d:
            yield d[k]
        else:
            for v in d.values():
                yield from rec_get(v, k)
    elif isinstance(d, list):
        for v in d:
            yield from rec_get(v, k)

print(list(rec_get(js, "addr_tag")))

rawDescription: Fetch specific data from JSON

description: Fetch specific data from JSON


code:
for x in range(3):
    print('.'*4)         # when you multiply a string with n, it produces n string

rawDescription: Printing 2D-array in a grid

description: Printing 2D-array in a grid


rawDescription: Pandas, groupby absolute month

description: Pandas, groupby absolute month


code: import pandas.io.data as web

rawDescription: Pandas DataFrame not working as intended


code:
from pyramid.config import Configurator

from sqlalchemy import engine_from_config

from .models import DBSession, Base

def main(global_config, **settings):
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

    config = Configurator(settings=settings,
                          root_factory='tutorial.models.Root')
    config.include('pyramid_chameleon')
    config.add_route('wiki_view', '/')
    config.add_route('wikipage_add', '/add')
    config.add_route('wikipage_view', '/{uid}')
    config.add_route('wikipage_edit', '/{uid}/edit')
    config.add_static_view('deform_static', 'deform:static/')
    config.scan('.views')
    return config.make_wsgi_app()

rawDescription: Read information stored in an .ini file

description: Read information stored in an .ini file


rawDescription: How to remove first item and last item using python

description: Remove first item and last item using python


code: format(num, '016b')

rawDescription: two's complement of numbers in python

description: Two's complement of numbers in python


code:
def rank3(x,y,z, ascending=True):
    return tuple(sorted((x,y,z), reverse=not ascending))

rawDescription: How to put numbers in ascending, return them in a tuple, and add another argument.(Python)

description: Put numbers in ascending, return them in a tuple, and add another argument.(Python)


code:
class unique_collection(non_unique_collection):

    # ...

    def overlap(self, other):
        if not isinstance(other, unique_ranked_collection):
            raise TypeError('expected an unique_ranked_collection')
        return super(unique_collection, self).overlap(other)

rawDescription: Forcing compatibility of inherited types (Python)


code:
from apps.app1.models import model1
model1.objects.create()
model1.objects.create()

rawDescription: How to move a model between two Django apps (Django 1.7)

description: Move a model between two Django apps (Django 1.7)


code: tmp = sp.call('clear',shell=True)

rawDescription: Python: Clear screen in shell

description: Python: Clear screen in shell


code:
class User:
    def __init__( self ):
        #this code is executed when the class is created
        self.b = random.choice([2309,1897,2307])

    def function( self ):
        #this code is owned by each User object
        user.getApple().eatTheApple(self.b, 2000, 50, 1, 8663, 4444)

rawDescription: Use a variable in a function

description: Use a variable in a function


rawDescription: Numpy Arrays: Slice y-values array based on threshold, then slice the x-values array correspondingly


code: list(a)

rawDescription: Output array after performing fast fast fourier transform of a data set


code:
def get_unicode(widget):
    streng = widget.get()
    try:
        streng = streng.decode('utf-8')
    except UnicodeEncodeError:
        pass
    return streng

rawDescription: UnicodeWarning: special characters in Tkinter


code: df2.index + pd.tseries.timedeltas.to_timedelta(18, unit='h')

rawDescription: Advanced Slicing of Intervals in Pandas Dataframe


code:
import os
class File(models.Model):
    title = models.CharField(max_length=400, help_text="Enter the title of the file, this will appear on the listings page")
    CATEGORY_CHOICES = (
        ('Image', 'Image'),
        ('PDF', 'PDF')
    )
    file_type = models.CharField(choices=CATEGORY_CHOICES, help_text="Please select a file type", max_length=200)
    file_upload = models.FileField(upload_to=get_upload_to)

    def delete(self, *args, **kwargs):
        path=self.file_upload.path
        os.remove(path)
        super(File,self).delete(*args, **kwargs)

rawDescription: Removing a file from the server once the entry has been removed


code:
parse_time('1h 30m')
to_time(90)
to_time(parse_time('1h 30m') + parse_time('30m'))

rawDescription: Pythonic way to add a list of time

description: Pythonic way to add a list of time


code:
class Particle():
    def __init__(self, startx, starty, col, pause):
        self.x = startx
        self.y = starty
        self.col = col
        self.sx = startx
        self.sy = starty
        self.pause = pause

    def move(self):
        if self.pause==0:
            if self.y < 0:
                self.x=self.sx
                self.y=self.sy

            else:
                self.y-=1

            self.x+=random.randint(-2, 2)

        else:
            self.pause-=1

rawDescription: Pygame particle effects

description: Pygame particle effects


code:
mydict = {}
for idx, item in enumerate(reader):
    mydict['var%i' %idx] = item

rawDescription: Python csvreader separate lines

description: Python csvreader separate lines


code:
import csv

specs = [[5, 0, "TypeA"],
         [11, 5, "TypeB"],
         [5, 16, "Charles"]]

with open("filename.txt") as infile, open("out.csv", "wb") as outfile:
    writer = csv.writer(outfile, quoting=csv.QUOTE_ALL)
    names = [s[-1] for s in specs]
    writer.writerow(names)
    for line in infile:
        row = [line[start:start+length] for length, start, name in specs]
        writer.writerow(row)

rawDescription: How to get txt file into CSV?

description: Get txt file into CSV


code:
my_library = ctypes.CDLL('my_library.so')
my_library.my_c_function(...)

rawDescription: Passing a Python Object to C module

description: Passing a Python Object to C module


code: ts = df1.prices

rawDescription: Data Cleaning Consequence on a Pre-Built Index


code:
import example
example.example()
# or
from example import example
example()

rawDescription: How can a Python module single file be installed using pip and PyPI?


rawDescription: EOL whilst scanning string literal - Python


code:
def getWordForm(phone_num):
    words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
             'eight', 'nine']
    return ' '.join([words[int(ch)] if ch.isnumeric() else ch for ch in phone_num])

rawDescription: Python - changing a 10 digit phone # to words with a list #Simplicity


code:
import json

scriptline = next((line for line in scripttag.string.splitlines()
    if 'Sw.preloadedData["overview"]' in line))
data = scriptline.split('=', 1)[1].strip(' ;')
data = json.loads(data)

rawDescription: How to make Python Dict from JSON data using BeautifulSoup

description: Make Python Dict from JSON data using BeautifulSoup


rawDescription: How to use only a specific amount of elements in a for loop

description: Use only a specific amount of elements in a for loop


rawDescription: Python find n-sized window around phrase within string


code:
L = [(1.23, 'Smith'), (2.34, 'Jones'), (3.45, 'de la Smith')]
sorted(L, key=lambda x:x[1].lower())

rawDescription: Python: sorting tuple by last name and handling lower cased first letters


code:
def bcdDigits(chars):
    for char in chars:
        char = ord(char)
        for val in (char >> 4, char & 0xF):
            if val == 0xF:
                return
            yield val

rawDescription: Python, how to decode Binary coded decimal (BCD)


code:
import clr
clr.AddReference("MyDll")
import System
import MyLib

myClassType = System.Type.GetType("MyLib.MyClass, MyDll")
method = myClassType.GetMethod("ExternalFunction")
numbersArray = System.Array[System.Double]([1.0, 2.0, 3.0])
parameters = System.Array[System.Object](["Benjamin",numbersArray])
method.Invoke(None,parameters)

numbersArray = parameters[1] # an updated Arg2 can be retrieved from parameters array

rawDescription: Python .net framework reference argument Double[]&


code:
soup = BeautifulSoup('''\

    some text

    some target text

    foo bar

    some more text

    select me, ooh, pick me!

    fooed the bar!

''')
soup.select('#div2 br + br')[0]
soup.select('#div2 br + br')[0].previous_sibling

rawDescription: Python HTML Parsing Between two tags

description: Python HTML Parsing Between two tags


code: longer_words_count = sum(len(word) >= 4 for word in sentence.split())

rawDescription: Count each list element with min 4 chars


code:
for result in myresults['result']:
    db.megas.update( { '_id': result['_id'] },
        { '$pull': { 'items': { 'item': result['minitem'] } } } )

rawDescription: MongoDB: Find the minimum element in array and delete it


code:
from   subprocess import Popen
import subprocess

def call_browse(url):
    fp  = 'C:\Program Files\Google\Chrome\Application\\'
    tsk = Popen([fp+"Chrome.exe",url ],shell=True)
    time.sleep(10)
    Popen('taskkill /F /IM Chrome.exe')

url ='https://docs.python.org/2/library/subprocess.html'
call_browse(url)

rawDescription: Python : New Url instead of New Webbrowser


code:
Base = sqlalchemy.ext.declarative.declarative_base()
class MyObject(Base):
    x = Column(Float)
    y = Column(Float)

    pos = PointProperty('x', 'y')

rawDescription: storing list/tuples in sqlite database with sqlalchemy

description: Storing list/tuples in sqlite database with sqlalchemy


code: A.my_attr == B.my_attr == 'foo'

rawDescription: python - class instance variable inherence and class variable inherence

description: Python - class instance variable inherence and class variable inherence


code:
def show_comment_form(request, item_id):
    form = MyCommentForm(initial={'item_drop_down':item_id})

rawDescription: Populating form field based on query/slug factor


rawDescription: Merging one-by-many CSV files in Python

description: Merging one-by-many CSV files in Python


rawDescription: Using .format() with tuples instead of dictionaries


code:
def as_dict_and_total(l):
    d, s = {}, 0
    for i in l:
        d[i] = len(i)
        s += len(i)
    return d, s

rawDescription: python create a set / dict / list and the sum of its values from a single list comprehension

description: Python create a set / dict / list and the sum of its values from a single list comprehension


rawDescription: Printing Binary in Python

description: Printing Binary in Python


code:
conditions = [diff > 0, diff < 0]
choices = [1, 0]

rawDescription: New colum in pandas, based on another colums last value


code:
import sys, os
from PySide import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        menu = self.menuBar().addMenu(self.tr('File'))
        menu.addAction(self.tr('Hello World'))

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    translator = QtCore.QTranslator(app)
    translator.load('i18n/tr_de', os.path.dirname(__file__))
    app.installTranslator(translator)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

rawDescription: PySide Qt tr() does not translate, context wrong?


code:
from itertools import product
markers = ["-", "--", "x"]
colors = ["b", "g", "r", "c", "m", "y", "k"]
[a + b for a, b in product(colors, markers)]

rawDescription: plotting many graphs with matplotlib

description: Plotting many graphs with matplotlib


code:
class Foo():
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

        def generate_bar():
            return x + y + z

        self.bar = generate_bar()

rawDescription: How do I define a Python method that I only want to use in the __init__ method, i.e., that is not accessible from outside the class definition?

description: Define a Python method that I only want to use in the __init__ method, i.e., that is not accessible from outside the class definition


code:
customers['customer1'].append(('milk', 3))
customers['customer1'].append(('bread', 5))
customers['customer2'].append(('cereal', 7))

rawDescription: Populating a Python dictionary

description: Populating a Python dictionary


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

x = linspace(0,5,200)
ax.plot(x, interp(x))
ax.plot(x1, y1[:,0], 'o')

rawDescription: Interpolating array columns with PiecewisePolynomial in scipy


code: prices = soup.findAll('div', class_=match_both)

rawDescription: Issue in scraping data from a website using beautiful soup


code:
class Reg(models.Model):
    name = models.CharField(max_length=32, primary_key=True)
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
        related_name='%(app_label)s_%(class)s_reg', null=True)
    ...

    def get_absolute_url(self):
        return reverse('core:profile', user_id=self.id)

rawDescription: get_absolute_url with parameters

description: Get_absolute_url with parameters


code:
plt.hist2d(x, y)
plt.colorbar()
plt.show()

rawDescription: 2D Histogram out of array data set

description: 2D Histogram out of array data set


code:
...
if os.isfile(package):
    with open(app_path + "/" + package) as f:
        # use this idiom instead. It saves you from having to close the file
        # and possibly forgetting (or having your program crash first!)
        for line in f:
            if "-Version=" in line:
                version = line  # do you want the whole line?
                                # or just "3.8.1"
                break  # no reason to read any more lines of the file
...

rawDescription: Reading for a specific value in a file

description: Reading for a specific value in a file


rawDescription: Replace specific values in a matrix using Python


code:
import numpy as np
from scipy.optimize import fmin
import math

def f(x):
    exp = (math.pow(x[0], 2) + math.pow(x[1], 2)) * -1
    return math.exp(exp) * math.cos(x[0] * x[1]) * math.sin(x[0] * x[1])

fmin(f,np.array([0,0]))

rawDescription: Find minimum and maximum values of a function


code: P(is_divisible_by_13) & is_palindrome

rawDescription: Pointfree function combination in Python


code: OrderedDict([(4, 'Hello'), (3, 'World'), (5, 'Bah')])

rawDescription: Append key value pair to a dictionary

description: Append key value pair to a dictionary


rawDescription: Feign focus in Selenium chrome browser

description: Feign focus in Selenium chrome browser


rawDescription: Python - Same variable in if statement

description: Python - Same variable in if statement


code:
import numpy as np
np.random.seed(1)

# Each array with have 20 random points this time
x, y, z = np.random.random((3, 20))

# We're solving Ax = B
A = np.column_stack([np.ones(len(x)), x, x**2, y, y**2])
B = z

# Solve the system of equations.
result, _, _, _ = np.linalg.lstsq(A, B)
a, b, c, d, e = result

rawDescription: Fit data to curve using polyfit with multiple variables in python using numpy polyfit


code:
x, y, z = [], [], []
for d, sublist in enumerate(productID):
    for entry in sublist:
        if entry.startswith(u'sku'):
            x.append(map[entry])
            y.append(name[d])
            z.append(priceID[d][entry].get(u'e'))

rawDescription: Creating an increasing list in Python

description: Creating an increasing list in Python


rawDescription: A function that displays a search from another function; dictionaries?


code:
def addTags(functionHere):
    def wrapper(*args):
        return "NumberTag" + functionHere(*args) + "NumberTagOver"
    return wrapper

rawDescription: Decorators in Python

description: Decorators in Python


code:
Sentence = str(input("Type in the sentence here:")).split(" ")
indexed_sentence = list(map(lambda x: Sentence.index(x), Sentence))

rawDescription: Replace the words in a list with the position of each word


code:
# old
"WEB-INF/library/JARFILE-45.33.jar:/properties/somefile.property"
# new
"WEB-INF/library/JARFILE-45\.33\.jar:/properties/somefile\.property"

rawDescription: Python : To list files if my keyword contains using regular expression


code:
def factors(n):
    result = []

    for i in range(1, n + 1):
        if n % i == 0:
            result.append(i)

    return result

rawDescription: How many factors in an integer

description: How many factors in an integer


code:
def x(frame):
    frame.sort('Timestamp', inplace=True)
    frame['Delta'] = frame['Timestamp'] - frame['Timestamp'].shift(1)
    return frame

df.groupby(['User Id'], group_keys=False).apply(x)

rawDescription: Create column relative to other values in same column (time since last transaction) Pandas


code:
# A Student object will just take care of tracking the name and speed.
# Classes like this in Python (with no methods) are often better represented
# by a namedtuple from the collections package.
class Student(object):

    def __init__(self, name="", speed=0):
        self.name = name
        self.speed = speed

# The Class object will represent a group of students.
# The students are tracked via a dictionary where the key is the name of
# the student and the value is the Student object.
class Class(object):

    def __init__(self):
        """ Create an empty dictionary for the students """
        self.students = {}

    def add_student(self, student):
        """ Add a student to the "roster".  The student name will be the
            key and the Student instance will be the value """
        self.students[student.name] = student

    def remove_student(self, name):
        """ Remove a student if they exist.  If they exist and are removed
            return True.  If they do not exist, return False """
        if name in self.students:
            del self.students[name]
            return True
        return False

    def average(self):
        """ Get the average speed of the students.
            The self.student.values() will be the values of the self.students
            dictionary, which means it will be a list of students.
            For each of the students, get their speed.  Sum those speeds
            and divide by the number of students.
            The fancy syntax of [x for x in y] below is called a list comprehension """
        return sum(student.speed for student in self.students.values()) / len(self.students)

def print_students(group):
    for i, student in enumerate(group.students.values()):
        print("#%d: Name: %s, Typing Speed (wpm): %d" % (i+1, student.name, student.speed))

def print_speed(group):
    for i, student in enumerate(group.students.values()):
        print("#%d: Typing Speed (wpm): %d" % (i+1, student.speed))

def add_student(group):
    new_name = ""
    typing_speed = None
    while not new_name:
        new_name = input("What is the student's name? ")
    while typing_speed in ("", None):
        typing_speed = input("What was the last typing speed? ")
        try:
            typing_speed = float(typing_speed)
        except:
            print("Please enter a number")
            typing_speed = None
            continue
    # We have a valid name and value speed, so create a Student and add them to the Class
    group.add_student(Student(new_name, typing_speed))

if __name__ == "__main__":
    group = Class()

    while True:
        print("Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit")
        choice = input(" >> ")

        if choice == '1':
            add_student(group)
            continue

        if choice == '2':
            del_name = input("What name would you like to remove? ")
            if group.remove_student(del_name):
                print("%s removed." % del_name)
            else:
                print("Name not found.")
            continue

        if choice == '3':
            print_students(group)
            continue

        if choice == '4':
            print_speed(group)
            continue

        if choice == '5':
            print("Average score for class: %0.2f" %(group.average()))
            continue

        if choice == '6':
            print('Happy Typing!')
            break

        print("That's not an option. Please try again.")

rawDescription: deleting a name from a list input by user and averaging a class score

description: Deleting a name from a list input by user and averaging a class score


code:
import urllib
from collections import OrderedDict

from rest_framework import serializers, relations

class SubNamespaceURLField(relations.HyperlinkedIdentityField):
    """Refers to a child namespace of the object, as pointed by view_name
    """
    def __init__(self, namespace, *args, **kwargs):
        self.namespace = namespace.strip('/')
        super().__init__(*args, **kwargs)

    def field_to_native(self, obj, field_name):
        base = super().field_to_native(obj, field_name)
        return urllib.parse.urljoin(base, self.namespace) + '/'

class HALNestedLinksField(relations.HyperlinkedIdentityField):
    """ Tries to represent a list of nested links on the resource a
    HAL-compliant way.

    See http://stateless.co/hal_specification.html
    """
    def __init__(self, endpoints, *args, **kwargs):
        """
        :param endpoints list of url suffixes leading to nested operations on
                         the resource (ex: ['preview', 'check'])
        """
        self.endpoints = endpoints
        super().__init__(*args, **kwargs)

    def get_attribute(self, obj):
        return obj

    def to_representation(self, value):
        links = OrderedDict()
        prefix = super().to_representation(self.get_attribute(value))
        for i in self.endpoints:
            # We consider if it contains a dot its a content-type indication,
            # so no trailing slash
            if '.' in i:
                suffix = ''
            else:
                suffix = '/'
            links[i] = {'href':
                        urllib.parse.urljoin(prefix, i) + suffix}
        return links

rawDescription: @list_route and @detail_route nested routes do not appear in Browseable API


rawDescription: Update initial condition in ODE solver each time step


code:
column1 = [ x[0] for x in lst]
column2 = [ x[1] for x in lst]

rawDescription: How to convert column data from text file into list in Python?

description: Convert column data from text file into list in Python


code:
x = C().f  # produces a bound method
x() # invokes the bound method

rawDescription: Getting and storing methods of a python class


code:
def sph2cart(r, theta, phi):
   return(r*math.cos(theta)*math.cos(phi), r*math.cos(theta)*math.sin(phi),
          r*math.sin(theta))

rawDescription: Distance between two points including elevation


code:
type(locals())
dir(locals())
getattr(locals(), 'keys')

rawDescription: Python getattr from locals() fails with AttributeError


code:
t = Transaction(account="my private account", amount=+1000)
t
t.amount
t.amount += 1

rawDescription: Objects With No Behavior

description: Objects With No Behavior


rawDescription: Using fancy indexing to get one value from each column of a numpy matrix


rawDescription: How to make a binary decomposition of pandas.Series column

description: Make a binary decomposition of pandas.Series column


code:
X = np.outer( A[:,n], rowb )
X[:,n] += np.dot( A, colb )

rawDescription: NumPy Matrix Multiplication Efficiency for Matrix With Known Structure


rawDescription: Python 3.4.1 Find different keep the same


code:
elem = driver.find_element_by_id("ctl00_DefaultPlaceholder_ComboFiltroPersonalizado_B-1")
elem.click()

rawDescription: Select a hidden item using Selenium Python


code:
def findGrid(dfp):
    c = dfc[(dfp['x'] > dfc['minx']) &
            (dfp['x'] < dfc['maxx']) &
            (dfp['y'] > dfc['miny']) &
            (dfp['y'] < dfc['maxy'])].Code

    if len(c) == 0:
        return None
    else:
        return c.iat[0]

rawDescription: Find points in cells through pandas dataframes of coordinates


code:
def hyst(x, th_lo, th_hi, initial = False):
    hi = x >= th_hi
    lo_or_hi = (x <= th_lo) | hi
    ind = np.nonzero(lo_or_hi)[0]
    if not ind.size: # prevent index error if ind is empty
        return np.zeros_like(x, dtype=bool) | initial
    cnt = np.cumsum(lo_or_hi) # from 0 to len(x)
    return np.where(cnt, hi[ind[cnt-1]], initial)

rawDescription: How to find zero crossings with hysteresis?

description: Find zero crossings with hysteresis


code:
x, y = 2,3
[[(i,j) for j in range(y)] for i in range(x)]

rawDescription: What does this nested for-loops compacted into a single line mean? - python


code:
from contextlib import contextmanager
from io import BytesIO
import sys

@contextmanager
def capture_stdout_unicode(codec='UTF-8'):
    output = BytesIO()
    output.encoding = codec
    orig, sys.stdout = sys.stdout, output
    try:
        yield output
    finally:
        sys.stdout = orig

rawDescription: UnicodeEncodeError when printing from Django


code:
if __name__ == '__main__':
    import sys
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 5
    simul(n)

rawDescription: Simulate several rounds of rock, paper and scissors


code:
total = 0
for line in alldatainfile1:
  linesplit.split("   ") #3 whitespaces, since you got it that way
  total = total + line[1]
print("total of column1: " + total)

rawDescription: How to open read-write file and recreate the file?

description: Open read-write file and recreate the file


code:
image1 = 'encoded image data...'
image2 = 'encoded image data...'

rawDescription: Python tkinter image

description: Python tkinter image


code: listName = [range(0, x + 1) for z in range(y + 1)]

rawDescription: reassigning row/list in a 2d list in python

description: Reassigning row/list in a 2d list in python


code:
y = np.arange(30).reshape(5, 6)
xs = [0, 2, 4]
ys = [0, 1]
np.array([y[xy] for xy in itertools.product(xs, ys)])
y[np.array(xs)[:, None], ys]
y[np.array(xs)[:, None], ys].ravel()

rawDescription: NumPy fancy indexing of a multidimensional array: case not covered (explicitly) by documentation


rawDescription: Getting TypeError when trying to concatenate 'str' and 'NoneType' objects


code:
def parse(self, response):
    if 'person.xml' in response.url:
        item = PersonItem()
    elif 'product.xml' in response.url:
        item = ProductItem()
    else:
        raise Exception('Could not determine item type')

rawDescription: How to crawl only two pre-defined pages, but they scrape different items?

description: Crawl only two pre-defined pages, but they scrape different items


rawDescription: How to align the bar and line in matplotlib two y-axes chart?

description: Align the bar and line in matplotlib two y-axes chart


code: [elem for elem in b if any(map(lambda test: re.search(r'\b' + re.escape(elem) + r'\b', test), a))]

rawDescription: string comparison on 2 lists

description: String comparison on 2 lists


code: [list(combinations(a,i)) for i in range(n, len(a)+1)]

rawDescription: how to find combinations of elements with minimum length of N using itertools-Python

description: Find combinations of elements with minimum length of N using itertools-Python


code:
"{0:<10s}".format(truncate("Foo", 10))
"{0:<10s}".format(truncate("Foo Bar Baz", 10))

rawDescription: Python .format slice long string and add dots


code:
import operator
operator_hooks = [name for name in dir(operator) if name.startswith('__') and name.endswith('__')]

rawDescription: How to catch any method called on an object in python?

description: Catch any method called on an object in python


code:
new=numpy.zeros_like(arr)
part=arr[3:7, 3:7]
i,j=part.shape
new[:i,:j]=part
new

rawDescription: How to get a padded slice of a multidimensional array?

description: Get a padded slice of a multidimensional array


rawDescription: Json organization

description: Json organization


code:
sql = "UPDATE analysen SET Nummer = %s WHERE Link like %s"
for n in numbers:
    cursor.execute(sql, [n, '%{}%'.format(n)])

rawDescription: Python Mysqldb update operation with variables


code:
import csv
from itertools import groupby

# assuming Python 2
with open("source.csv", "rb") as fp_in, open("final.csv", "wb") as fp_out:
    reader = csv.reader(fp_in)
    writer = csv.writer(fp_out)
    grouped = groupby(reader, lambda x: x[0])
    for key, group in grouped:
        rows = list(group)
        rows = [rows[0], rows[-1]]
        columns = zip(*(r[1:] for r in rows))
        use_values = [max(c) for c in columns]
        new_row = [key] + use_values
        writer.writerow(new_row)

rawDescription: What is the most efficient way with Python to merge rows in a CSV which have a single duplicate field?


code:
from itertools import combinations

d = {'A':12, 'B':3, 'C':14, 'D':15, 'E':21, 'F':9, 'G':16}

result = []
for l in range(2, len(d)):
    for x in combinations(d.items(), l):
        keys = []
        sum_values = 0

        for key, value in x:
            keys.append(key)
            sum_values += value

        if sum_values == 30:
            result.append(keys)

print(result)

rawDescription: Is it possible to split a dictionary and group the values then return each group with respective key?


code:
minimi = dict.fromkeys(('left', 'bottom'), float('inf'))
maximi = dict.fromkeys(('right', 'top'), float('-inf'))
for x in rect:
    for key in minimi:
        if getattr(x, key) < minimi[key]: minimi[key] = getattr(x, key)
    for key in maximi:
        if getattr(x, key) > maximi[key]: maximi[key] = getattr(x, key)

rawDescription: How to simplify repetitive list comprehensions in python?

description: Simplify repetitive list comprehensions in python


code: re.findall(r'<[^>]+>', text)

rawDescription: How to eliminate html tags?

description: Eliminate html tags


code:
print(file.read())
for line in file:
    ...

rawDescription: Why is the command line file not getting the lines?


code:
import numpy as np

# just do something random
X = np.random.random(1000000)

def my_filter(X):
    Y = np.empty(len(X))
    Y[0] = X[0]
    for i in range(1, len(X)):
        Y[i] = max(.99*Y[i-1], X[i])
    return Y

rawDescription: Iteratively-defined Numpy Array Creation


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

rawDescription: Unify list items pairwise

description: Unify list items pairwise


rawDescription: regex patterns and lists in python

description: Regex patterns and lists in python


rawDescription: Increment Numpy array with repeated indices


code:
self.__q = gevent.queue.Queue()
self.__request_processing_greenlet = gevent.spawn(process_requests, self.__q)

rawDescription: Gevent async server with blocking requests


rawDescription: How do I reverse the order of PriorityQueue in python?

description: Reverse the order of PriorityQueue in python


code:
import collections
class Conf(collections.namedtuple('Conf', 'data')):
    def __getitem__(self, attr):
        return super(Conf, self).__getitem__(0)[attr]
Conf({'x': 'y'})['x']

rawDescription: Why inheriting from namedtuple results in infinite recursion in this case?


code:
def repeat(word, num):
    for i in range(1,num+1):
        print('+'.join(word for _ in range(i)))

rawDescription: Python simple string cycle

description: Python simple string cycle


code:
from collections import Counter
results = Counter("this is fun")
r = results.most_common()
what_i_want = [(y, x) for x, y in r]
what_i_want

rawDescription: Modifying Output from collections.Counter using Python


code:
del df2['year']
df1.merge(df2, how='left').merge(df3, how='left')

rawDescription: Complicated pandas merge operation

description: Complicated pandas merge operation


code:
reader = csv.csvreader(csvfile)
result = np.array([[magic(col) for col in row] for row in reader])

rawDescription: Reading CSV files in numpy where delimiter is ","


code:
from plone.app.portlets.portlets.navigation import Renderer as NavigationRenderer

class MyRenderer(NavigationRenderer):

    _template = ViewPageTemplateFile('template/my_navi_template.pt')

rawDescription: how to replace default navigation portlet with my template

description: Replace default navigation portlet with my template


code:
# Axes settings (make the spines invisible, remove all ticks and set title)
ax = plt.gca()
[sp.set_visible(False) for sp in ax.spines.values()]
ax.set_xticks([])
ax.set_yticks([])

rawDescription: Making networkx plot where edges only display edited numeric value, not field name


code:
import io
with io.open('your_file', 'r', encoding='your_file_encoding') as f:
    lines = f.readlines()

rawDescription: Reading file stops at halfway

description: Reading file stops at halfway


code:
import inspect

class key_memoized(object):
    def __init__(self, func):
       self.func = func
       self.cache = {}

    def __call__(self, *args, **kwargs):
        key = self.key(args, kwargs)
        if key not in self.cache:
            self.cache[key] = self.func(*args, **kwargs)
        return self.cache[key]

    def normalize_args(self, args, kwargs):
        spec = inspect.getargs(self.func.__code__).args
        return dict(kwargs.items() + zip(spec, args))

    def key(self, args, kwargs):
        a = self.normalize_args(args, kwargs)
        return tuple(sorted(a.items()))

rawDescription: Is there a pythonic way to support keyword arguments for a memoize decorator in Python?


code:
import re
inputstring = '''This is "it", isn't\nit?'''
re.sub(r'''['"\n\\]''', lambda m: '\\{:X} '.format(ord(m.group())), inputstring)
print(re.sub(r'''['"\n\\]''', lambda m: '\\{:X} '.format(ord(m.group())), inputstring))

rawDescription: Encoding a string the CSS way with python


code: word = ~(and_op | or_op) + Word(alphanums + '.-/&')

rawDescription: pyparsing one query format to another one

description: Pyparsing one query format to another one


code:
# (Add the same code as above to get and validate the input string)
print(sum(int(digit_str) for digit_str in input_str))

rawDescription: Python: How to use a Variable Integer to Call a Specific Part of a String


code:
def deserialize_business(csv_line):
    """
    Distills structured business information from given raw CSV line.
    Returns a dictionary like {name, phone, owner,
    btype, yoe, headings[], outlets[], category}.
    """

    pieces = [piece.strip("[[\"\']] ") for piece in line.strip().split(',')]

    name = pieces[0]
    phone = pieces[1]
    owner = pieces[2]
    btype = pieces[3]
    yoe = pieces[4]

    # after yoe headings begin, until substring Outlets Address
    headings = pieces[4:pieces.index("Outlets Address")]

    # outlets go from substring Outlets Address until category
    outlet_pieces = pieces[pieces.index("Outlets Address"):-1]

    # combine each individual outlet information into a string
    # and let ``deserialize_outlet()`` deal with that
    raw_outlets = ', '.join(outlet_pieces).split("Outlets Address")
    outlets = [deserialize_outlet(outlet) for outlet in raw_outlets]

    # category is the last piece
    category = pieces[-1]

    return {
        'name': name,
        'phone': phone,
        'owner': owner,
        'btype': btype,
        'yoe': yoe,
        'headings': headings,
        'outlets': outlets,
        'category': category,
    }

rawDescription: Reformat csv file using python?

description: Reformat csv file using python


code:
SequenceMatcher(None, string.split(), pattern.split()).ratio()
# => 0.7368421052631579

rawDescription: Partial Regex Matching

description: Partial Regex Matching


code:
from math import sin, cos, radians, pi
def point_pos(x0, y0, d, theta):
    theta_rad = pi/2 - radians(theta)
    return x0 + d*cos(theta_rad), y0 + d*sin(theta_rad)

rawDescription: Python: find a x,y coordinate for a given point B using the distance from the point A (x0, y0) and the angle


code:
def f(x, y):
    return sin(x)*cos(y)

all_derivatives = get_derivatives(f)

rawDescription: Take Python Function and Generate All Derivatives


rawDescription: Print from List Python

description: Print from List Python


code:
def tup2float(tup):
    return float('.'.join(str(x) for x in tup))

rawDescription: Converting tuple to integer

description: Converting tuple to integer


code: my_list = [None for _ in range(10)]

rawDescription: Google App Engine template loop through two variables


code:
from itertools import izip_longest
total = [sum(x) for x in izip_longest(*allLists, fillvalue=0)]

rawDescription: Sum lists of variable lengths element-wise


code: activation = tf.add(tf.mul(X, W), b)

rawDescription: How to make simple logistic regression in tensorflow?

description: Make simple logistic regression in tensorflow


code:
import numpy as np
import pylab as plt

# This fails since carr[0,0] is of type numpy.int64
carr = np.array([[0,0,0,1],[0,0,1,1],[0,1,0,1]]) # RGBA color array
carr[1] = np.repeat(np.nan,4)

pts = np.array([[1,2],[1,3],[2,2]]).T
plt.scatter(pts[0],pts[1],c=carr,s=500)

rawDescription: Exclude points from plotting by color definition?


code: file_out.write(" ".join(["%s" %i for i in [A, B, C, D, E]]))

rawDescription: save a txt file in Python, some tips to improve my code

description: Save a txt file in Python, some tips to improve my code


code:
from Tkinter import *
import socket
import tkFont
#User Interface---------------------------------------
root = Tk()
root.title("MY GUI")
root.geometry("372x414+510+175")
root.resizable(width=FALSE, height=FALSE)
'''FONTS------------------------------------------------'''
label_f = tkFont.Font(family="Trebuchet MS", size="12" )
entry_f = tkFont.Font(family ="Courier", size = "12")
'''IP-----------------------------'''
target = Label(root, text="Target IP Adress:",font= label_f).grid(row=0, column=0, sticky='w')
userIP = StringVar()
tar_ent = Entry(root, width = "33", font=entry_f, textvariable = userIP)
tar_ent.grid(row=1, column=0, sticky='WE', columnspan=2)
'''Port ------------------------------'''
custom = Label(root, text = "Custom port scanner (Enter like 23,80,etc.)", font=label_f).grid(row=2, column=0, sticky='w')
userPort = StringVar()
cus_port = Entry(root, width="33", font=entry_f, textvariable=userPort)
cus_port.grid(row=3, column=0, sticky='WE', columnspan=2)
'''Results--------------------------'''
space = Label(root, text="")
space.grid(row=5, column=0)
console = Text(root, width=35, height=16)
console.grid(row=6, column=0, sticky="WE")

scrollbar = Scrollbar(root, command=console.yview)
console.config(yscrollcommand=scrollbar.set)
scrollbar.grid(row=6, column=1, sticky='Ns')

root.mainloop()

rawDescription: Can't get this scrollbar to work with Text widet in Tkinter?


code:
from timeit import timeit

noc = 100
tocat = "a"
def f_call():
    pass

def loop_only():
    for i in range(noc):
        pass

def concat_method():
    s = ''
    for i in range(noc):
        s = s + tocat

def list_append():
    s=[]
    for i in range(noc):
        s.append(tocat)
    ''.join(s)

def list_append_opt():
    s = []
    zap = s.append
    for i in range(noc):
        zap(tocat)
    ''.join(s)

def list_comp():
    ''.join(tocat for i in range(noc))

def concat_method_buildup():
    s=''

def list_append_buildup():
    s=[]

def list_append_opt_buildup():
    s=[]
    zap = s.append

def function_time(f):
    return timeit(f,number=1000)*1000

f_callt = function_time(f_call)

def measure(ftuple,n,tc):
    global noc,tocat
    noc = n
    tocat = tc
    loopt = function_time(loop_only) - f_callt
    buildup_time = function_time(ftuple[1]) -f_callt if ftuple[1] else 0
    total_time = function_time(ftuple[0])
    return total_time, total_time - f_callt - buildup_time - loopt*ftuple[2]

functions ={'Concat Method\t\t':(concat_method,concat_method_buildup,True),
            'List append\t\t\t':(list_append,list_append_buildup,True),
            'Optimized list append':(list_append_opt,list_append_opt_buildup,True),
            'List comp\t\t\t':(list_comp,0,False)}

for i in range(5):
    print("\n\n%d concatenation\t\t\t\t10'a'\t\t\t\t 100'a'\t\t\t1000'a'"%10**i)
    print('-'*80)
    for (f,ft) in functions.items():
        print(f,"\t|",end="\t")
        for j in range(3):
            t = measure(ft,10**i,'a'*10**j)
            print("%.3f %.3f |" % t,end="\t")
        print()

rawDescription: Python string 'join' is faster(?) than '+', but what's wrong here?


code:
test_contains = lambda value, search: s.contains(search)
db.search(User.name.test(test_contains, 'Columbia'))

rawDescription: In Python, how do I search a TinyDB database for substrings in the values?


code:
pipeline = [
    {'$project': {'last_status': { '$arrayElemAt': [{ '$slice': [ "$status", -1 ] }, 0 ]} }},
    {'$match': {'last_status.status_code':'scode'}}
]

agg_cursor = Order.objects.aggregate(*pipeline)

result = [ Order.objects.get(id=order['_id']) for order in agg_cursor ]

rawDescription: Mongoengine filter query on list embedded field based on last index


rawDescription: Subsetting a 2D numpy array

description: Subsetting a 2D numpy array


code: result_alt = color_map[color_map_idx_row, color_map_idx_col]

rawDescription: Optimizing or replacing array iteration with python loop by numpy functionality


code: odds = [convert(item.get_text(strip=True)) for item in row.find_all('span', class_='odds')]

rawDescription: converting string list of fractions into float from scraped html / cleanest method

description: Converting string list of fractions into float from scraped html / cleanest method


code:
df.index = MultiIndex.from_product([['a','b'],[1,2]])
df
df.loc['a']
df.loc[['a']]

rawDescription: Selecting rows with similar index names in Pandas


code:
from threading import Thread

def notifier():
    global clicks # whatever variable you're accessing
    while True:
        if _clicks != clicks:
            _clicks = clicks
            print(_clicks)

t = Thread(target=notifier)
t.start()

rawDescription: How do I get a variable from a running python function

description: Get a variable from a running python function


code:
class DocLink(models.Model):
    trann = models.ForeignKey(Transaction)
    t_link = models.CharField(max_length=2000)
    t_display = models.CharField(max_length=1000)
    p_display = models.CharField(max_length=300)
    p_link = models.CharField(max_length=2000)
    def __str__(self):
        return self.link

    def save(self, *args, **kwargs):
        if not self.t_link:
            pass # TODO set self.t_link based on trann

        super(DocLink, self).save(*args, **kwargs)

rawDescription: Django: Creating editable default values for model instance based on foreignkey existance


code:
import datetime
date = datetime.datetime.strptime('2012-02-11' , '%Y-%m-%d')
if date.isoweekday() == 6:
    date += datetime.timedelta(days=2)

date
date.strftime('%Y-%m-%d')   # if you want a string again

rawDescription: Convert string into Date type on Python

description: Convert string into Date type on Python


code: headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

rawDescription: Unable to make post request using request library python


code:
import sys

color = "\x1b[32m{}\x1b[m"
sys.ps1 = color.format(sys.ps1)
sys.ps2 = color.format(sys.ps2)

# We don't want variables to be around in our interactive sessions.
del color
del sys

rawDescription: Python configuration of interactive shell


code:
def series_chunk(chunk):
    jfile = json.loads(chunk)
    zipcode = jfile['zipcode']
    datetime = jfile['current']['proc_time']
    triggers = jfile['triggers']
    return pd.Series([jfile['zipcode'], jfile['current']['proc_time'], jfile['triggers']])

dfs = []
for fin in glob.glob('*.txt'):
    with open(fin) as f:
        df = pd.concat([series_chunk(chunk) for chunk in lines_per_n(f, 5)], axis=1)
        dfs.append(dfs)

df = pd.concat(dfs, ignore_index=True)

rawDescription: Create pandas dataframe from json objects


code:
from fuzzyparsers import parse_date
parse_date('jun 17 2010') # my youngest son's birthday

rawDescription: Identify that a string could be a datetime object


code: files.sort(key=lambda f: int(re.search("(\d+)", f).group(1)))

rawDescription: How can I isolate part of a string in a list of strings and sort the list with it? (in Python)

description: Isolate part of a string in a list of strings and sort the list with it? (in Python)


code:
#!/bin/python

import sys
import numpy as np
import math
import decimal
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from matplotlib import rcParams

def plot():
    N = 6
    ind = np.arange(N)
    ind_label = ['1X', '2X' , '3X' , '4X', '5X', '6X']

    y = [1.60, 1.65, 1.70, 1.75, 1.80]
    m1 = [1.62, 1.64, 1.64, 1.71, 1.7, 1.68]
    m2 = [1.61 , 1.7, 1.7, 1.8, 1.75, 1.75]
    m3 = [1.63 , 1.69, 1.7, 1.67, 1.64, 1.61]

    width = 0.2

    rcParams['text.usetex'] = True
    fig = plt.figure()
    ax = fig.add_subplot(111)

    rec_m1 = ax.bar(ind, m1, width, color='r', align='center')
    rec_m2 = ax.bar(ind+width, m2, width, color='g', align='center')
    rec_m3 = ax.bar(ind+width*2, m3, width, color='b', align='center')

    ax.set_ylabel('Value',fontsize=20)
    ax.set_xlabel('Matrix', fontsize=20)
    ax.tick_params(axis='both', labelsize=17)
    ax.set_xticks(ind+width)
    ax.set_xticklabels(ind_label, fontsize=18)
    ax.axis([-0.2, 5.6, 1.58, 1.82])

    ax.legend((rec_m1[0],rec_m2[0],rec_m3[0]),('Method 1','Method 2','Method 3'), loc="upper right",\
shadow=True)
    ax.set_xticklabels([r"$\left[ \begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right]$",
                        r"$\left[ \begin{array}{cc} 0 & 1 \\ 5 & 0 \end{array}\right]$",
                        r"$\left[ \begin{array}{cc} 0 & 1 \\ 10 & 0 \end{array}\right]$",
                        r"$\left[ \begin{array}{cc} 0 & 1 \\ 30 & 0 \end{array}\right]$",
                        r"$\left[ \begin{array}{cc} 0 & 1 \\ 50 & 0 \end{array}\right]$",
                        r"$\left[ \begin{array}{cc} 0 & 1 \\ 100 & 0 \end{array}\right]$"])
    ax.xaxis.set_tick_params(pad=15)

    plt.grid()
    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    plot()

rawDescription: Add matrix in X-axis using matplotlib

description: Add matrix in X-axis using matplotlib


code:
# server0.py

while True:
    try:
        msg = s.recv(zmq.NOBLOCK) # note NOBLOCK here
    except zmq.Again:
        # no message to recv, do other things
        time.sleep(1)
    else:
        print("received %r" % msg)
        if msg == 'quit':
            break

rawDescription: PyZMQ one-way communication

description: PyZMQ one-way communication


rawDescription: Adaptable descriptor in Python

description: Adaptable descriptor in Python


code: tcp[tcpflags] & tcp-syn != 0

rawDescription: Filter options for sniff function in scapy


code: cookie_dictionary = dict(res[0] for res in parse_ns_headers(session_cookies))

rawDescription: passing in cookie python requests

description: Passing in cookie python requests


code:
x = 'foo,bar'.split(',')
print(x)

# or directly:
print('foo,bar'.split(','))

rawDescription: How to return more than one value over multiple lines

description: Return more than one value over multiple lines


rawDescription: Search through list with duplicates

description: Search through list with duplicates


code: lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis]

rawDescription: How to construct a set out of list items?

description: Construct a set out of list items


code:
from datetime import datetime
from datetime import timedelta
import numpy as np

rawDescription: How to combine records based on date using python connected components?

description: Combine records based on date using python connected components


code:
filepath = "Media/DVD/image.jpg"
al_p4 = Image.open(filepath).resize((100, 150), Image.ANTIALIAS)
al_p4 = ImageTk.PhotoImage(al_p4)
print(filepath)

rawDescription: Python Tkinter - Find image file path from PhotoImage


code: idx = np.where(isclose(a, b, 0, atol))[0][0]

rawDescription: Find float in ndarray

description: Find float in ndarray


code:
#!/usr/bin/env python
from httplib import HTTPConnection
from multiprocessing.dummy import Pool # use threads
from urlparse import urlsplit

def getstatus(url):
    try:
        host, path = urlsplit(url)[1:3]
        conn = HTTPConnection(host)
        conn.request("HEAD", path)
        r = conn.getresponse()
    except Exception as e:
        return url, None, str(e) # error
    else:
        return url, r.status, None

p = Pool(20) # use 20 concurrent connections
for url, status, error in p.imap_unordered(getstatus, urls):
    if status != 404:
       print("{status} {url} {error}".format(**vars()))

rawDescription: Use httplib to check if a URL will return a certain page?


code:
def myfunc():
    x = 3
    class MyClass(object):
        y = x
    return MyClass

myfunc().y

rawDescription: Creating a class within a function and access a function defined in the containing function's scope


code:
class T(type):
    x = 5

class A(object):
    __metaclass__ = T

rawDescription: Can Python classes have members that are accessible, but not from an instance of the class?


code:
import matplotlib.pyplot as plt
y_data = [[1,1],[2,2],[3,3]]  #just some dummy data
x = [0,1]
for y in y_data:
    #generate id
    fig,ax = plt.subplots()  #create a new figure
    ax.plot(x,y)
    fig.savefig(filename + id)

rawDescription: matplotlib: creating new figure and saving to file

description: Matplotlib: creating new figure and saving to file


rawDescription: Accurate color blending in Matplotlib-Venn


code:
import re,sys

pat = re.compile("DV/DL += +([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)")
values = []
for line in open("input.out","r"):
    m = pat.search(line)
    if m:
        values.append(m.group(1))
outfile = open("out.csv","w")
outfile.write(",".join(values[-2:]))

rawDescription: python csv delimiter doesn't work properly

description: Python csv delimiter doesn't work properly


rawDescription: How combine two list into list of list at python?


code:
import pandas as pd
df = pd.read_csv("input.csv", index_col=0)  # or from another source

rawDescription: Coverting Index into MultiIndex (hierachical index) in Pandas


code:
class Foo():
    val = 0

    def f1(self):
        Foo.val += 1
    def f2(self):
        Foo.val += 1
    def f3(self):
        Foo.val += 1
    def all(self):
        self.f1()
        self.f2()
        self.f3()

f = Foo()
f1 = Foo()
f.all()
f1.all()
print(f.val)
6

rawDescription: What is the cleanest way to maintain the latest state of a variable which is used in multiple functions?


code:
x = [True, True, True, True]
[not y for y in x]
x = [False, True, True, False]
[not y for y in x]

rawDescription: How do I toggle a boolean array in Python?

description: Toggle a boolean array in Python


code:
class CharField(Field):
    description = _("String (up to %(max_length)s)")

    def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length))

rawDescription: Parameters for function CharField() In Django


rawDescription: Permutations of list of lists

description: Permutations of list of lists


code:
nodes = tree.values()
for node in nodes:
    if node.parent:
        if not hasattr(node.parent, 'children'):
            node.parent.children = []
        node.parent.children +=[ node ]

rawDescription: Python - Tree traversal question

description: Python - Tree traversal question


code:
def some_view(self):
    user_notifications = PromoNotification.objects.get_for_user(request.user)

rawDescription: Django - Limit users who view the items

description: Django - Limit users who view the items


code:
for order in Order.objects.prefetch_related('details'):
    types = order.details.values_list('product_type', flat=True)

rawDescription: Django query in One to Many relationship


code:
redirect_url = reverse('profile', args=[user.id])
return HttpResponseRedirect(redirect_url)

rawDescription: Django HttpResponseRedirect with int parameter


code:
json_data = {
    "declaration-list" : [
        { "declared-variable": "x0", "value": 1 },
        { "declared-variable": "x1", "value": 2 },
        { "declared-variable": "x2",
          "value" : {
              "operator": "set",
              "arguments": [
                  { "variable": "x0" },
                  { "variable": "x1" }
              ]
          }
        },
        { "declared-variable" : "x3",
          "value" : {
              "operator" : "set",
              "arguments" : [
                  {
                      "operator": "tuple",
                      "arguments": [ 1, 2 ]
                  },
                  {
                      "operator": "tuple",
                      "arguments": [ 3, 4 ]
                  }
              ]
          }
        },
    ]
}

def parse_declaration(declinfo):
    vname = declinfo['declared-variable']
    rvalue = parse_rvalue(declinfo['value'])
    return ('let', vname, rvalue)

def _rv_parse_set(valinfo):
    assert valinfo['operator'] == 'set'
    args = [parse_rvalue(a) for a in valinfo['arguments']]
    return ('set', args)

def _rv_parse_tuple(valinfo):
    assert valinfo['operator'] == 'tuple'
    args = valinfo['arguments']
    return ('tuple', args)

_rv_parser = {
    "set": _rv_parse_set,
    "tuple":_rv_parse_tuple,
}

def parse_rvalue(valinfo):
    try:
        if 'operator' in valinfo:
            op = valinfo['operator']
            return _rv_parser[op](valinfo)
        elif 'variable' in valinfo:
            return ('variable', valinfo['variable'])

    except TypeError:
        return ('value', valinfo)

def parse_json(json_data):
    declaration_list = json_data['declaration-list']

    for i in declaration_list:
        print(parse_declaration(i))

if __name__ == "__main__":
    parse_json(json_data)

rawDescription: Python tree storing expressions from json input file


code:
header=pd.MultiIndex.from_product([['location1','location2'],['S1','S2','S3']],names=['loc','S'])
df = pd.DataFrame(np.random.randn(5, 6), index=['a','b','c','d','e'], columns = header)

rawDescription: Giving a column multiple indexes/headers


code:
import numpy as np
from datetime import datetime,timedelta

start = datetime(2016, 1, 1)
end = datetime(2016, 2, 1)
delta = timedelta(days=1)
d = start
weekend = set([5, 6])

x = []
while d <= end:
    if d.weekday() not in weekend:
        x.append(d)
    d += delta

y = np.random.rand(len(x))*70

rawDescription: Showing entire X Axis Ticks in Graph

description: Showing entire X Axis Ticks in Graph


code: a = vars().get('x',y)

rawDescription: What is the most Pythonic way to provide a fall-back value in an assignment?


code:
# in file settings.py
AUTH_USER_MODEL = "myapp.MyUser"

rawDescription: Custom User's and implementations with forms


rawDescription: Pandas Time Series - add a value to the first value in each year


code:
a = input('Please enter the first string to compare:')
b = input('Please enter the second string to compare: ')
if len(a) !=  len(b):            # match the length first
    print ('Strings don\'t match')
else:
    count = 0                    #declare it outside of while loop
    while count < len(a):        #loop until count < length of strings
        if a[count] != b[count]:
            print ('Strings don\'t match! ')
            break
        count = count + 1
    else:
       print ("string match")

rawDescription: Python-Comparing two strings-Unable to loop through


code:
utm_sa = Query([utm1, SystemAdmin]).join(SystemAdmin, (utm1.user_id == SystemAdmin.id) & (utm1.is_admin == True))
utm_u = Query([utm2, User]).join(User, (utm2.user_id == User.id) & (utm2.is_admin == False))

rawDescription: SQLAlchemy mapping joined tables' columns to one object


code:
import pandas as pd
df = pd.DataFrame(["BEAR ESTOX X12 S", "BEAR ESTOX X15 S", "BEAR AXP UN 3X VON",
                   "BULL AXP UN x5 VON", "BEAR DAX X3 SG 2"], columns=["name"])

sg = {"S":"SEG", "SG":"SEG", "SEG":"www.societegenerale.com"}
vontobel = {"VON":"Vontobel","Vontobel":"www.vontobel.com"}

issuer = dict()
website = dict()
for dct in [sg, vontobel]:
    for key, val in dct.items():
        if val.startswith('www') or val.endswith('.com'):
            website[key] = val
        else:
            issuer[key] = val

df["issuer_spl"] = df.name.str.extract(r'(\S+\s+\S+)$')

for i in issuer:
    df.loc[df.issuer_spl.str.contains(i), "issuer"] = issuer[i]

df['website'] = df['issuer'].map(website)
print(df)

rawDescription: Key to Value to Key in Python Dictionary


code:
import matplotlib.pyplot as plt
import numpy as np
x_values = [0.1, 0.3, 0.4, 0.2]
y_values = ["word 1", "word 2", "word 3", "word 4"]
y_axis = np.arange(1, 5, 1)

plt.barh(y_axis, x_values, align='center')
plt.yticks(y_axis, y_values)
plt.show()

rawDescription: Using text on y axis in matplotlib instead of numbers


rawDescription: How can I create two views function in a models Django

description: Create two views function in a models Django


code:
import pandas_datareader.data as pdata
df = pdata.get_data_yahoo('AAPL', start='2009-01-02', end='2009-12-31')
df.head()

rawDescription: New colum in pandas, based on another colums last value


rawDescription: Smart handling of Python array with many indices


rawDescription: Python Pandas: How can I group by and assign an id to all the items in a group?


code:
gridarray = np.zeros([3,3])

cols = np.random.random_integers(0,2,15)
rows = np.random.random_integers(0,2,15)
data = np.random.random_integers(0,9,15)

x = np.vstack([rows, cols])
temp = ndbincount(x, data, gridarray.shape)
gridarray = gridarray + temp
gridarray_counts = ndbincount(x, shape=gridarray.shape)

rawDescription: Row, column assignment without for-loop

description: Row, column assignment without for-loop


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
from matplotlib._png import read_png
from matplotlib.cbook import get_sample_data

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, .25)
Y = np.arange(-5, 5, .25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.winter,
                       linewidth=0, antialiased=True)

ax.set_zlim(-2.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fn = get_sample_data("./lena.png", asfileobj=False)
arr = read_png(fn)
# 10 is equal length of x and y axises of your surface
stepX, stepY = 10. / arr.shape[0], 10. / arr.shape[1]

X1 = np.arange(-5, 5, stepX)
Y1 = np.arange(-5, 5, stepY)
X1, Y1 = np.meshgrid(X1, Y1)
# stride args allows to determine image quality
# stride = 1 work slow
ax.plot_surface(X1, Y1, -2.01, rstride=1, cstride=1, facecolors=arr)

plt.show()

rawDescription: Matplotlib: how to add a base image to a 3D plot?


code:
import pygame
import sys

pygame.init()

window_size = (400, 400)

white = (255, 255, 255)

class Player():
    image = pygame.image.load('foo.png')
    rect = image.get_rect()

player = Player()

screen = pygame.display.set_mode(window_size)

done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    pressed = pygame.key.get_pressed()
    if pygame.K_LEFT in pressed:
        move = (-10, 0)
    player.rect = player.rect.move(move)
    if pygame.K_RIGHT in pressed:
        move = (10, 0)
    player.rect = player.rect.move(move)
    if pygame.K_UP in pressed:
        move = (0, -10)
    player.rect = player.rect.move(move)
    if pygame.K_DOWN in pressed:
        move = (0, 10)

rawDescription: constant movement in pygame

description: Constant movement in pygame


rawDescription: Inheritance and classes

description: Inheritance and classes


code:
open('uid_2014-10-13.py', 'w').write('print "Hello world!"\n')
import importlib
module = importlib.import_module('uid_2014-10-13')
module

rawDescription: Is it able to import from a module named uid_2014-10-13.py?


code:
coll = Application.GetService[DataManager]().Tables
crossSource = coll.Item["TABLE_NAME"]

rawDescription: Spotfire IronPython script: get Cross Table data


code: predicted = np.array(np.hsplit(predicted, face.shape[0]))

rawDescription: dealing with dimensions in scikit-learn tree.decisiontreeclassifier

description: Dealing with dimensions in scikit-learn tree.decisiontreeclassifier


code:
major, students = sorted(major_students.items(), key=lambda x: len(x[1]), reverse=True)[0]

print("Most Frequent Major is {} with {} students: {}".format(major, len(students), ', '.join(students)))

rawDescription: Python program - Help pairing elements together without using a dictionary


code: s.replace(0, np.nan, inplace=True)

rawDescription: Python: indexing pandas series by datetime


rawDescription: Removing duplicates from a list of lists based on a comparison of an element of the inner lists


code:
import numpy as np
from rpy2.robjects import r
import pandas.rpy.common as com
from pandas import DataFrame
a = np.array([range(5), range(5)])
df = DataFrame(a)
df = com.convert_to_r_dataframe(df)
r.assign("foo", df)
r("save(foo, file='here.gzip', compress=TRUE)")

rawDescription: Save 2d numpy array to R file format using rpy2


code:
from itertools import groupby
from operator import itemgetter

items = [
    ('name1', 10), ('name1', 30),
    ('name2', 5), ('name2', 7), ('name2', 3),
    ('name3', 10)
]

for name, rows in groupby(items, itemgetter(0)):
    with open(name + ".txt", "w") as outf:
        outf.write("\n".join(str(row[1]) for row in rows))

rawDescription: Opening and closing files in a loop

description: Opening and closing files in a loop


code: os.path.getsize('large.tar.gz') >> 20

rawDescription: How to get the size of tar.gz in (MB) file in python

description: Get the size of tar.gz in (MB) file in python


code:
for url in urls.split():
    webbrowser.open(url,new=new)

rawDescription: Dynamic Python Variables

description: Dynamic Python Variables


code:
for rownum in range (rows ):
    PrintingList.append([])
    newValues = raw_input().strip().split()
    PrintingList[rownum] += newValues

rawDescription: User input for triangles in python

description: User input for triangles in python


code:
for x in range(1000):
    open("file%03d.txt" % x,"w").write("some text")

rawDescription: How can I create 1000 files that I can use to test a script?

description: Create 1000 files that I can use to test a script


code:
import scipy.ndimage.filters as filter
a=np.arange(5,dtype=np.double)
filter.uniform_filter(a,size=3)
np.mean([0,0,1]) #ind0
np.mean([0,1,2]) #ind1
np.mean([1,2,3]) #ind2

rawDescription: Build an array by averaging n consecutive numbers in an array


code:
self.my_color = "green"
self.canvas.itemconfigure("all", fill=self.my_color)

rawDescription: Is there a way to have a "default color" with a canvas in Tkinter?


code:
df
df['truth'] = df.sum(axis=1) > 0
df

rawDescription: How can I compare results from two CSV files in Python with DictReader or Pandas? (Open to any other methods as well!)

description: Compare results from two CSV files in Python with DictReader or Pandas? (Open to any other methods as well!)


code:
import commands
def testFunc():
    cmd = "xterm"
    result = commands.getoutput(cmd)

rawDescription: Paramiko X11 mode with python programming


code:
list = Friend.objects.friends(self.request.user) \
                     .exclude(user__in=blocked_users)

rawDescription: Django, exclude() function on list

description: Django, exclude() function on list


code:
def log_entry(category, message):
    entry = scribe.LogEntry(category, message)
    socket = TSocket.TSocket(host='localhost', port=1463)
    transport = TTransport.TFramedTransport(socket)
    protocol = TBinaryProtocol.TBinaryProtocol(trans=transport,strictRead=False,
                                               strictWrite=False)
    client = scribe.Client(iprot=protocol, oprot=protocol)
    transport.open()
    result = client.Log(messages=[entry])
    transport.close()

rawDescription: Using python how to execute this code concurrently for multiple files?


code:
asg.Tags= [{'Key':'Name','Value':'MyTagName','PropagateAtLaunch':'true'},
  {'Key':'Version','Value':'123456','PropagateAtLaunch':'true'}]

rawDescription: Using troposphere for cloud formation, how do I add "propagate at launch" to tags


code: returned_values = [f() for f in to_call]

rawDescription: Do things in random order?

description: Do things in random order


code: testPath = files[:-len('.vbproj')]

rawDescription: Can't get simple loop working right

description: Can't get simple loop working right


code:
today = Days.Wednesday
print(today.next())
# Days.Thursday

rawDescription: Get next enumerator constant/property

description: Get next enumerator constant/property


code:
from StringIO import StringIO
sio = StringIO()
twill.set_output(sio)
html = show() # html+'\n' == sio.getvalue()

rawDescription: Using show() with twill spams the console with HTML


rawDescription: Groupby separate sum with commas

description: Groupby separate sum with commas


code:
def get_occurrences():
    for seq_patt in SequencePattern.seq_patterns:
        for occurrence in seq_patt.occurrences:
            yield occurrence
occurrences_by_text_order = sorted( get_occurrences() )

rawDescription: How to perform this sort operation in python

description: Perform this sort operation in python


code:
pd.pivot_table(df, columns='user_id', index='service',
               values=['bytes_uplink', 'bytes_downlink'], aggfunc=sum)

rawDescription: Calculate the duration of overlapping time ranges using pandas


code:
def addProducts(request):
    if request.POST:
        post = {}
        for key in request.POST:
            value = request.POST[key]
            try:
                value = json.loads(value)
            except Exception:
                pass
            post[key] = value
        doc = json.dumps(post)
    # the other code goes here

    return render("add_products.html", {
        "products": data,
    }, context_instance=RequestContext(request))

rawDescription: Django: json.dumps breaks JSON arrays

description: Django: json.dumps breaks JSON arrays


code:
def setText(doc, node, newText):
    textnode = doc.createTextNode(newText)
    node.appendChild(textnode)

rawDescription: How to set text on an xml node without any children in xml.minidom in python?

description: Set text on an xml node without any children in xml.minidom in python


rawDescription: Combining first elements of nested lists and summing the second elements


code: df = pd.DataFrame(my_list_of_dicts)

rawDescription: Python : append/merge dicts to pandas in a pythonic way


code: print(" " * num_spaces + "*"*num_asterisks)

rawDescription: remove asterisk symbol inside diamond shape

description: Remove asterisk symbol inside diamond shape


code: command = lambda key=key: self.AppendKey(key)

rawDescription: Looping buttons, forgets the button value


code:
def after_6_hours():
        print('6 hours passed.')

rawDescription: How to schedule a single-time event in Django in Heroku?

description: Schedule a single-time event in Django in Heroku


code: np.column_stack((portfolio, index))

rawDescription: Converting two lists into a matrix

description: Converting two lists into a matrix


code:
bytes = b"\x00\x00\x02\x01"
i = 0
for b in bytes:
    i <<= 7
    i += b     # Or use (b & 0x7f) if the last bit might not be zero.
print(i)

rawDescription: Working with bytes and binary data in Python


rawDescription: Converting functions into a methods of a class in python


code:
import re
p = re.compile(r'([a-zA-Z\s0-9]+)\s+([\d,.]+)([^, ]+)(?=,|$|\s)', re.MULTILINE | re.IGNORECASE)
test_str = "Vitamin A 6,000iu/kg, Vitamin D3 80iu/kg, Vitamin E PLUS 240iu/k"

re.findall(p, test_str)

rawDescription: python regex parsing data from extremely complicated ingredients string

description: Python regex parsing data from extremely complicated ingredients string


rawDescription: Python RegEx nested search and replace

description: Python RegEx nested search and replace


code:
melted = pd.melt(melted, id_vars=['Position'],
                 value_vars=['Item 1','Item 2'], var_name='Item')
#       Position    Item  value
# 0   Contractor  Item 1    1.0
# 1   Contractor  Item 1    1.0
# 2   Contractor  Item 1    NaN
# 3    President  Item 1    1.0
# 4    President  Item 1    1.0
# 5    President  Item 1    NaN
# 6   Contractor  Item 2    1.0
# 7   Contractor  Item 2    0.0
# 8   Contractor  Item 2    1.0
# 9    President  Item 2    1.0
# 10   President  Item 2    0.0
# 11   President  Item 2    1.0

rawDescription: Pandas Pivot Table with Fancy Stacking

description: Pandas Pivot Table with Fancy Stacking


code:
List = [['Name',[1, 4, 6]],
    ['Another Name', [1,2,5]]]
List[0].insert(1,"Another Value")
List

rawDescription: Python - is it possible to insert() into a list inside of a list?


code: X = np.hstack([np.column_stack([day]), X_month_dummies])

rawDescription: decision trees from features of multiple datatypes

description: Decision trees from features of multiple datatypes


rawDescription: Can I convert any string to float without losing precision in Python?

description: Convert any string to float without losing precision in Python


code:
# -*- coding: utf-8 -*-
import sys
import time

from PyQt4 import QtGui, QtCore

class SpriteAnimation(object):
    def __init__(self, image_path, sprite_width, sprite_height, label):
        pixmap = QtGui.QPixmap(image_path)

        width, height = pixmap.width(), pixmap.height()
        self.pixmaps = []
        for x in range(0, width, sprite_width):
            for y in range(0, height, sprite_height):
                self.pixmaps.append(pixmap.copy(x, y,
                                                sprite_width, sprite_height))
        self._current_frame = 0
        self.label = label

    def play(self, interval=100):
        self._timer = QtCore.QTimer(interval=interval,
                                    timeout=self._animation_step)
        self._timer.start()
    def _animation_step(self):
        self.label.setPixmap(self.pixmaps[self._current_frame])
        self.label.update()
        self._current_frame += 1
        if self._current_frame >= len(self.pixmaps):
            self._current_frame = 0

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.resize(100, 100)
        layout = QtGui.QVBoxLayout(self)
        label = QtGui.QLabel()
        layout.addWidget(label)
        # http://content.makeyourflashgame.com/pbe/tutorials/star-green.png
        self.animation = SpriteAnimation('star-green.png', 80, 80, label)
        self.animation.play()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQT4 and tiles animation

description: PyQT4 and tiles animation


rawDescription: zipping a python dict of lists

description: Zipping a python dict of lists


code:
n=100 # number of points in each vector
num_vects=25
vals=[]
for _ in range(num_vects):
    vals.append(np.random.normal(size=n))
np.cov(vals)

rawDescription: numpy covariance matrix

description: Numpy covariance matrix


code: print(list(iterable))

rawDescription: Is there any single function to print iterables values


rawDescription: Python: Decimal part of a large float

description: Python: Decimal part of a large float


code:
POS_CHOICES = [(p.id, p.name) for p in Position.objects.all()]
class EmployerForm(forms.Form):
    p_choices = forms.CharField(widget=forms.Select(choices=POS_CHOICES))

rawDescription: Django: ForeignKey to_field and db_column doesn't seem to work


code:
def in_frame(annotation):
    pyplot.show(block=False) # we need this to get good data on the next line
    bbox = annotation.get_bbox_patch()
    uleft_coord = (0, bbox.get_height())
    pnt = bbox.get_data_transform().transform_point(uleft_coord)
    return pyplot.gcf().get_window_extent().contains(*pnt)

rawDescription: How can I keep an annotation within the visible window?

description: Keep an annotation within the visible window


code: self.test1 = float(self.Mygrade.get())

rawDescription: Used a for loop to create a certain number of entry boxes but can only .get last value from last entrybox


code:
@api.one
@api.depends('child_ids', 'child_ids.value')
def _compute_value(self):
    if self.child_ids:
        self.value = sum(
            [child.value for child in self.child_ids])
    else:
        self.value = self.value_manual

rawDescription: How to make a field computed only if some condition is fulfilled in Odoo 8?

description: Make a field computed only if some condition is fulfilled in Odoo 8


code:
import dis
dis.dis('a=[]\nfor i in range(0,60000000):\n a.append(0)')

rawDescription: Different append of n item to list and [0]*n in python?


code:
class FoodFactory(object):
    @staticmethod
    def create_food(food_type, **kwargs):
        try:
            return FOOD_TYPES[food_type.lower()](**kwargs)
        except Exception:
            return None

rawDescription: Factory method for objects with many parameters


code:
rest, last = s.rsplit('.', 1)

'classes.students'
'grades'

rawDescription: Dot notation string manipulation

description: Dot notation string manipulation


code:
nx.draw(L, node_size=500)
plt.show()

rawDescription: networkx edge-to-node node-to-edge representation

description: Networkx edge-to-node node-to-edge representation


code:
c = NP.array(c, order="F")
c.flags

rawDescription: Is there an "enhanced" numpy/scipy dot method?


rawDescription: Accessing hierarchical columns in pandas after groupby


code:
from bs4 import Tag

def unwrapper(tags, keep = ('ul','li')):
    for el in tags:
        if isinstance(el,Tag):
            unwrapper(el) # recurse first, unwrap later
            if el.name not in keep:
                el.unwrap()

rawDescription: BeautifulSoup4 parse everything except specific tags


rawDescription: Conditional filtering of the csv file with duplicates in python


code:
def compare_colors(im1, im2, c1, c2):
    matches = np.all(im1==c1, -1) & np.all(im2==c2, -1)
    return matches.sum()

rawDescription: How do I avoid looping through an image pixel by pixel with opencv & numpy

description: Avoid looping through an image pixel by pixel with opencv & numpy


code:
from ctypes import *
foo = CDLL('./foo.so')
foo.foo.restype = py_object
foo.foo(b'foo.cpp')

rawDescription: C++ vector to Python 3.3

description: C++ vector to Python 3.3


rawDescription: Tag extra information to differentiate numbers in a list


code:
def printMaze(maze):
    print(maze)
    print('-'*80)

rawDescription: Python - matplotlib.pyplot ion() slow

description: Python - matplotlib.pyplot ion() slow


rawDescription: broken memoization code

description: Broken memoization code


code:
try:
    return (typeB for typeB in typeBlist if typeB.typeA == typeA).next()
except StopIteration:
    return None

rawDescription: if typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause?

description: If typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause


code:
from abc import ABCMeta, abstractmethod

class Shape:
  __metaclass__ = ABCMeta

  @abstractmethod
  def getArea(self):
    pass

class Rectangle (Shape):
  def getArea(self):
    return self.width * self.height

class Circle (Shape):
  def getArea(self):
    return math.pi*(self.radius**2)

rawDescription: Python Abstract Programming

description: Python Abstract Programming


code:
@capture
def foo(): return 'bar'

@capture
def foo(): return 'baz'

foo()
list(foo())
def bar():
    @capture
    def foo(): return 'bar'
    @capture
    def foo(): return 'baz'
    return foo

list(bar()())

rawDescription: Capture functions within a closure scope


code:
found = re.findall(regex, line)[0]
found

rawDescription: Python parsing list of string

description: Python parsing list of string


code:
' '.join(sample1.stripped_strings)
' '.join(sample2.stripped_strings)

rawDescription: Python: Parse all elements under a div

description: Python: Parse all elements under a div


code:
def commonElements(a1, a2):
    L = []
    for el in a1:
        if el in a2:
            L.append(el)
    L.sort()
    return tuple(L)

rawDescription: How do I find every element that is in both of two other lists?

description: Find every element that is in both of two other lists


rawDescription: Storing a variable number of values per item


rawDescription: Multiindex on DataFrames and sum in Pandas


rawDescription: reading binary data and retrieving per condition : working fine in Python 2.6.x but not in Python 3.2

description: Reading binary data and retrieving per condition : working fine in Python 2.6.x but not in Python 3.2


code:
def removeCloseItems(items, itemDistance):
    if items:
        lastOutput = items[0]
        yield items[0]
        for currentItem in items[1:]:
            if ((currentItem - lastOutput) > itemDistance):
                lastOutput = currentItem
                yield currentItem

rawDescription: Remove items from list if they are within a given range


code:
class Vector:
  def __init__(self, x = 0, y = 0, z = 0):
    self.x = x
    self.y = y
    self.z = z

  def __add__(self, other):
    return Vector(self.x + other.x, self.y + other.y, self.z + other.z)

rawDescription: class in python with method acting on self. inheritance

description: Class in python with method acting on self. inheritance


rawDescription: What would be a good way to pull the coefficients out of a string in Python?


rawDescription: Reading from a file directly into a 2D list python


code:
EXCHANGE_DATA = [('AIA', 'Auckair', 1.50),
            ('AIR', 'Airnz', 5.60),
            ('AMP', 'Amp',3.22),
            ('ANZ', 'Anzbankgrp', 26.25),
            ('ARG', 'Argosy', 12.22),
            ('CEN', 'Contact', 11.22),
            ('CNU', 'Chorus',3.01),
            ('DIL', 'Diligent', 5.3),
            ('DNZ', 'Dnz Property', 2.33),
            ('EBO', 'Ebos', 1.1)]

portfolio_str=input("Please list portfolio: ")
portfolio_str= portfolio_str.replace(' ','')
portfolio_str= portfolio_str.upper()
portfolio_list= portfolio_str.split(',')

rawDescription: Comparing user input with tuple value

description: Comparing user input with tuple value


rawDescription: Convert series of numbers to array in Python


code:
b = numpy.empty(a.shape, dtype=object)
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        b[i, j] = numpy.array([a[i, j]])

rawDescription: How can I create an array of 1-element arrays from an array?

description: Create an array of 1-element arrays from an array


code:
import random
n = 3
end  = 5
r = range(1,n) + range(n+1, end)
r
random.choice(r)
random.choice(r)

rawDescription: Choosing random integers except for a particular number for python?


code:
d['first_name']
d.get('first_name')
d.get('middle_name', 'No Middle Name')

rawDescription: Biopython class instance - output from Entrez.read: I don't know how to manipulate the output


code: counts, edges = numpy.histogram(data, bins=bins_arange)

rawDescription: Weighted mean in numpy/python

description: Weighted mean in numpy/python


code: d[(attrib_a, attrib_b)] = t

rawDescription: Python creating dictionary key from a list of items


code:
import config as baseConfig
config = dict(baseConfig, overriddenValue=etc)

rawDescription: Python pattern for sharing configuration throughout application


rawDescription: Subiterate over a tuple

description: Subiterate over a tuple


code:
pairs.sort(key=lambda x: (x[1], len(x[0])))
data = {v: k for k,v in pairs}
[(v,k) for k,v in data.items()]

rawDescription: Python3 Uniquify list of tuples based on only one of the values of the index


code:
switch(x=5, y=4)
switch(x=5)
# or
switch(z=5)

rawDescription: Python: Detect if certain variable is inputted into function argument


code:
from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    """
    >>> grouper(3, 'ABCDEFG', 'x')
    ["ABC", "DEF", "Gxx"]
    """
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Logical task for Python programmers. Make tuple of lists from list


rawDescription: Different way to create an instance method object in Python


code:
rng = pd.date_range('1/1/2000', periods=24, freq='H')
ts = pd.Series(pd.np.random.randn(len(rng)), index=rng)
ts.ix[ts.index.indexer_between_time(datetime.time(10), datetime.time(14))]

rawDescription: Pandas Drop Rows Outside of Time Range

description: Pandas Drop Rows Outside of Time Range


rawDescription: keeping the child and parent relationship while traversing a json tree in python

description: Keeping the child and parent relationship while traversing a json tree in python


code: sql = 'INSERT INTO table_name ({fields}) VALUES ({values})'

rawDescription: Python sql query insert data in columns

description: Python sql query insert data in columns


code:
My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"]
[word for line in My_list for word in line.split()]
sum(len(line.split()) for line in My_list)

rawDescription: Getting word count from a python list

description: Getting word count from a python list


code:
a = [1, 10, 40]
b = [15, 30]

srcs = [a, b]
dsts = [[], []]
prev_which = -1
while all(srcs):
    which = int(srcs[0][0] > srcs[1][0])
    elem = srcs[which].pop(0)
    if prev_which != which:
        dsts[which].append(elem)
    prev_which = which
for src, dst in zip(srcs,dsts):
    if src:
        dst.append(src.pop(0))
a, b = dsts

rawDescription: compare elements of two lists

description: Compare elements of two lists


code:
paragraph = 'The quick brown fox jumps over the lazy dog. I have two big dogs. Furry Dogs are the best. $%^Dogs love me.'
paragraph = ''.join(e for e in paragraph.lower() if e.isalnum() or e.isspace() or e=='.')
sentence_list = paragraph.split('.')
prev_word_list = []
for sentence in sentence_list:
    word_list = sentence.split()
    prev_word = ''
    for i,word in enumerate(word_list):
        if i == 0:
            pass
        else:
            if 'dog' in word.lower():
                prev_word = word_list[i-1]
                prev_word_list.append(prev_word)

rawDescription: how to find approximate words in python using find

description: Find approximate words in python using find


code:
chunk_size = 100
freq = repeater(line(dur / chunk_size, 200, 800), chunk_size)
bw = repeater(line(dur / chunk_size, 100, 240), chunk_size)

rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


code:
'It works: {:0.3f}'.format(1.1)
'And even with integers: {:0.3f}'.format(10000)

rawDescription: Keeping trailing 0 when converting from str to float


rawDescription: urllib2 read to Unicode

description: Urllib2 read to Unicode


code:
for field, loc in zip(fields, ['here', 'there']):
    field['location'] = loc
fields

rawDescription: How to update a list that contains values as dictionaries?

description: Update a list that contains values as dictionaries


rawDescription: Get links in list from string

description: Get links in list from string


code:
st = SubThing(arg1="foo", arg2="bar", arg3="baz", arg4="quux",
              ex_arg1=1, ex_arg2=6.02e23)

rawDescription: How to Extend Large Class Methods?

description: Extend Large Class Methods


code:
x = FreezableDict({'foo': 'bar', 'baz': 'bla'})
x
x['asdf'] = 'fdsa'
x
x.freeze()
x['hello'] = 'world'

rawDescription: Python: Freeze dict keys after creation

description: Python: Freeze dict keys after creation


rawDescription: How to store bash shell script in the JSON document effectively for Python script

description: Store bash shell script in the JSON document effectively for Python script


code: df = pd.merge(df1, df2, how='outer', sort=True)

rawDescription: Avoiding double counting in pandas merge


code:
tourneys = df['tournament'].unique()
player_dict = {}
for event in tourneys:
    ndf = df[df['tournament'] == event].copy()
    player_dict[event] = len(ndf['playerA'].append(ndf['playerB']).unique())

df['player_sum'] = df['tournament'].map(player_dict)

rawDescription: Pandas Dataframe add column based on counts of other columns


code:
# (c) 2014, Pierre-Yves KERVIEL <pierreyves.kerviel@orange.com>
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

# inidata is used to manage ini

import ansible.utils as utils
import ansible.errors as errors

class LookupModule(object):

    def __init__(self, basedir=None, **kwargs):
        self.basedir = basedir

    def run(self, terms, inject=None, **kwargs):
        terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject)

        if not isinstance(terms, dict):
            raise errors.AnsibleError("inidata lookup expects a dictionnary , got '%s'" %terms)

        ret = []
        for item0 in terms:
            if not isinstance(terms[item0], dict):
                raise errors.AnsibleError("inidata lookup expects a dictionary, got '%s'" %terms[item0])
            for item1 in terms[item0]:
                ret.append((item0, item1, terms[item0][item1]))

        return ret

rawDescription: How to write an Ansible task using with_dict in a loop (with_items)

description: Write an Ansible task using with_dict in a loop (with_items)


code:
for string in strings:
     string.replace("www.","")

rawDescription: Class returns empty list

description: Class returns empty list


code:
def bubbleSort(l):
  isSorted = False
  n = len(l)-1
  while not isSorted:
    isSorted = True
    for i in range(n):
      if l[i] > l[i+1]:
        isSorted = False
        l[i], l[i+1] = l[i+1], l[i]
    n-=1

def bubbleSort2(l):
  n = len(l)-1
  while not isListSorted(l):
    for i in range(n):
      if l[i] > l[i+1]:
        l[i], l[i+1] = l[i+1], l[i]
    n-=1

rawDescription: Bubble Sort following an algorithm

description: Bubble Sort following an algorithm


code:
x, y, z = symbols('x, y, z')
A = x*y*z
B = x*y

# This is the detail:
type(B)._diff_wrt = True
diff(A, B)

rawDescription: Partial symbolic derivative in Python

description: Partial symbolic derivative in Python


code:
@hp.setter
def hp(self, hp):
    self.__hp = max(0, min(hp, self.maxhp))

rawDescription: property of class doesnt restrict the attribute

description: Property of class doesnt restrict the attribute


code:
for item in teamlist:
    for sub_item in item:
        teamName = item[0]
    if user_input == teamName:
        sorted_lists = [x for x in zip(*sorted(zip(sub_item), key=lambda x: x[0]))]
        for sub_sub_item in sorted_lists[0]:
            print("    {:<25} {:^6} {:>8.2f}".format(sub_sub_item[1], sub_sub_item[0], sub_sub_item[2]))

rawDescription: Sorting a list of the form [(single value), [(tuple 1), (tuple2), ...], (another value),[...]]


code:
myDic = {}
for key,value in enumerate(mynestedlist,1):
    myDic["list"+str(key)] = value

rawDescription: Python: make new lists for all nested list items (level 1)


code:
def rev(num):
    def rec(num, tens):
        if num < 10:
            return num
        else:
            return num % 10 * tens + rec(num // 10, tens // 10)
    return rec(num, 10 ** int(log10(num)))

rawDescription: Python reverse integer using recursion

description: Python reverse integer using recursion


code:
class ChannelManager(models.Manager):
    def get_channel_list(self, acc):
        return self.filter(accountid=acc).values_list('name', flat=True)

class Channel(models.Model):
    name = models.CharField(max_length=200)
    accountid = models.CharField(max_length=34)

    objects = ChannelManager()

rawDescription: Django QuerySet with Models

description: Django QuerySet with Models


code: print(x.title() + " -  Small: $" + int(tiles[x])/2 + "  Medium: $" + tiles[x] + "  Large: $" + int(tiles[x])*(2))

rawDescription: How to fix the invalid syntax

description: Fix the invalid syntax


code: newfile.writelines([friend[u'name'] + "\n" for friend in friends])

rawDescription: Filter return results printed in text file python


rawDescription: In Python how do I create a data frame with a list that contains multiple levels of dictionaries?


code:
for i,row in enumerate(read):
    q=f.tell()/fsize
    if i%100==0:
        self.progress['value']=q
        self.progress.update_idletasks()
    #do stuff
else:
    self.progress['value']=q
    self.progress.update_idletasks()

rawDescription: Status bar for csv file read

description: Status bar for csv file read


code:
import random
import numpy as np
import pandas as pd
random.seed(1)
spec_df = pd.DataFrame(
    np.random.randint(10, size=(5,6)),
    columns=pd.MultiIndex.from_arrays([['foo','bar','foo','baz','baz','bar'],
                                       list('ABBCAD'),
                                   list('123123')]),
    index=pd.MultiIndex.from_arrays([['baz']*2+['qux']*3,
                                     list('CDCDC')]))

columns = spec_df.columns
seen = dict()
for col in columns:
    seen.setdefault(col[0], []).append(col)
cols = [random.choice(seen[firstcol]) for firstcol in seen]
print(spec_df[cols])

rawDescription: Pandas: How to iterate over level one and randomly select from level 2 then add subselection to dataframe


rawDescription: Optimize this python log-parsing code

description: Optimize this python log-parsing code


rawDescription: How to discard values in a python panda series?

description: Discard values in a python panda series


rawDescription: Detect definition path of a decorated function


code:
...
turtle.tracer(8,25)
for i in range(2):
    ...
tracer.update()
tracer.mainloop()

rawDescription: Turtle tracer arguments example trouble

description: Turtle tracer arguments example trouble


rawDescription: In Flask: How to access app Logger within Blueprint


code: #!/usr/bin/env python2.7

rawDescription: Setting default interpreter for a python script


code: matches = [r.match(domain) for r in (first_re, second_re, third_re) if r.match(domain)]

rawDescription: Is it possible to convert this map/filter code into list comprehension?


code: print("You can get %d%% back with text corrections" % wrong)

rawDescription: Invalid syntax with if

description: Invalid syntax with if


rawDescription: Python: Recursion to count up an array of size n


code: popen_cmd_shell(['su', '-c', 'ls', '-', 'root'])

rawDescription: Automating switching from normal user to root with subproccess in python


code:
def goodDecode(encodedPayload):
  if not hasattr(encodedPayload, 'encoding'):
    return encodedPayload
  encoding = encodedPayload.encoding
  payload = encodedPayload.payload
  if encoding and encoding.lower() != '7bit':
    payload = payload.decode(encoding)
  return payload

rawDescription: Writing and image attachment to datastore as an avatar: Is it possible?


rawDescription: Defining large list-within- list array

description: Defining large list-within- list array


rawDescription: Text search elements in a big python list


rawDescription: how to transform element then insert into numpy array

description: Transform element then insert into numpy array


code:
def sub_sums_ophion(arr, nrows, ncols):
    h, w = arr.shape
    h = (h // nrows)*nrows
    w = (w // ncols)*ncols
    arr = arr[:h,:w]
    return np.einsum('ijkl->ik', arr.reshape(h // nrows, nrows, -1, ncols))

rawDescription: Sums of subarrays

description: Sums of subarrays


code: XLE = XLE.set_index('time')

rawDescription: How to reindex csv data efficiently?

description: Reindex csv data efficiently


code:
class Location(models.Model):
    class Title:
        CLASSROOM = 'classroom'
        PLAYGROUND = 'playground'
        STAFF_ROOM = 'staff_room'

    BASE_LOCATION = Title.CLASSROOM

    TITLE_CHOICES = (
        (Title.CLASSROOM, 'Classroom'),
        (Title.PLAYGROUND, 'Playground'),
        (Title.STAFF_ROOM, 'Staff Room'),
    )

    user = models.ForeignKey(User,null=True)
    title = models.CharField('Incident Type', max_length=200,choices=TITLE_CHOICES,default=Title.CLASSROOM)
    parent_location_id = models.CharField('Parent Location', max_length=100, null=True, blank=True)
    is_active = models.BooleanField('Is Active', default=True)

def location_title(sender, instance, created, **kwargs):
    # Don't fire up on updates.
    if not created:
        return

    # Only handle new superusers.
    if not instance.is_superuser or not instance.is_active:
        return

    # Create a `Location` entry for new superuser.
    base = Location(user_id=instance.pk, title=Location.BASE_LOCATION)
    base.save()

    for value, _ in Location.TITLE_CHOICES:
        if value == Location.BASE_LOCATION:
            continue

        l = Location(user_id=instance.pk, title=value, parent_location_id=base.pk)
        l.save()

post_save.connect(location_title, sender=User)

rawDescription: create row of date while creating superuser

description: Create row of date while creating superuser


rawDescription: How to scrape dynamic content with Selenium?

description: Scrape dynamic content with Selenium


rawDescription: Logger.info never outputs

description: Logger.info never outputs


rawDescription: How to merge two grouped-by Pandas Dataframes by a common column(ID) together?

description: Merge two grouped-by Pandas Dataframes by a common column(ID) together