code:
import operator

final_qs = reduce(operator.or_, qs_list)

rawDescription: Pythonic List Iteration

description: Pythonic List Iteration


code: unique_idx[mov_avg > 0.5]

rawDescription: Efficiently take moving average of sparse data and filter above threshold in python


code:
from itertools import groupby
[''.join(g) for k, g in groupby('AAAABBBCCD')]

rawDescription: How to split this string with python?

description: Split this string with python


code: df.index = df.index.map(lambda t: t.replace(year=2013, month=2, day=1))

rawDescription: Change date of a DateTimeIndex

description: Change date of a DateTimeIndex


rawDescription: How to parse lines in file in sequence/match adequate results using python, pyparsing?

description: Parse lines in file in sequence/match adequate results using python, pyparsing


code:
def func(dfg):
    return dfg.reset_index(level=1, drop=True).reindex(df1.index.levels[0], method='ffill')

df2.groupby(level=1).apply(func).swaplevel(i=0, j=1).sortlevel(0)

rawDescription: reindex pandas MultiIndex on specific level

description: Reindex pandas MultiIndex on specific level


code: os.system('/path/to/script.sh &')

rawDescription: Background process that will kill the current process


rawDescription: Counting occurrences in nested lists

description: Counting occurrences in nested lists


code:
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
for word in words:
    if word[0] in 'aeiou':
        print(word)

rawDescription: How to use Python to find out the words begin with vowels in a list?

description: Use Python to find out the words begin with vowels in a list


code:
trans_table = dict.fromkeys(map(ord,digits), None)
[i.translate(trans_table) for i in contents]

rawDescription: how to identify that anystring of list contains digits or not in python

description: Identify that anystring of list contains digits or not in python


code:
from collections import defaultdict
d=defaultdict(int, zip(range(1,10),range(50,61)))

rawDescription: How to construct a defaultdict from a dictionary?

description: Construct a defaultdict from a dictionary


code:
testmapping = {'dog': 1, 'cat': 2, ' ': 0}
testvar = testmapping.get(x)

rawDescription: possible to set variable with multiple if statments?

description: Possible to set variable with multiple if statments


code:
import random
lst = list(range(10))
random.seed('just some random seed') # set the seed
random.sample(lst, 4)
random.sample(lst, 4)
random.seed('just some random seed') # use the same seed again
random.sample(lst, 4)
random.sample(lst, 4)

rawDescription: python random sequence from list

description: Python random sequence from list


code:
def flatten(a):
    b = []
    for c in a:
        if isinstance(c, list) and any(isinstance(i, list) for i in c):
            b.extend(flatten(c))
        else:
            b.append(c)
    return b

rawDescription: Python flatten list (but not all the way)


code:
np.vstack((a,m))
#ValueError: all the input array dimensions except for the concatenation axis must match exactly

rawDescription: stacking sparse and dense matrices

description: Stacking sparse and dense matrices


code: ['This Boy', 'The Beatles', 'Meet The Beatles!', '3']

rawDescription: Reading ID3 tag and values from a text file


code: masterDF = masterDF.append(dataframe)

rawDescription: Error with dataframe append

description: Error with dataframe append


code:
def deref(reference):
    target = reference.dereference()
    if str(target.address) == '0x0':
        return 'NULL'
    else:
        return target

class cstringprinter:
    def __init__(self, value, maxlen=4096):
        try:
            ends = gdb.selected_inferior().search_memory(value.address, maxlen, b'\0')
            if ends is not None:
                maxlen = ends - int(str(value.address), 16)
                self.size = str(maxlen)
            else:
                self.size = '%s+' % str(maxlen)
            self.data = bytearray(gdb.selected_inferior().read_memory(value.address, maxlen))
        except:
            self.data = None
    def to_string(self):
        if self.data is None:
            return 'NULL'
        else:
            return '\"%s\"(%s)' % (str(self.data).encode('string_escape').replace('"', '\\"').replace("'", "\\\\'"), self.size)

class boxintprinter:
    def __init__(self, value):
        self.value = value.cast(gdb.lookup_type('struct boxint_st'))
    def to_string(self):
        return '(struct boxint_st)%s' % str(self.value['ival'])

class boxstringprinter:
    def __init__(self, value):
        self.value = value.cast(gdb.lookup_type('struct boxstring_st'))
    def to_string(self):
        return '(struct boxstring_st)%s' % (self.value['strval'])

class boxsequenceprinter:
    def __init__(self, value):
        self.value = value.cast(gdb.lookup_type('struct boxsequence_st'))
    def display_hint(self):
        return 'array'
    def to_string(self):
        return '(struct boxsequence_st)(%s)' % str(self.value['slen'])
    def children(self):
        value = self.value
        tag = str(value['tag'])
        count = int(str(value['slen']))
        result = []
        if tag == 'tag_none':
            for i in xrange(0, count):
                result.append( ( '#%d' % i, deref(value['valtab'][i]['ptag']) ))
        elif tag == 'tag_int':
            for i in xrange(0, count):
                result.append( ( '#%d' % i, deref(value['valtab'][i]['pint']) ))
        elif tag == 'tag_string':
            for i in xrange(0, count):
                result.append( ( '#%d' % i, deref(value['valtab'][i]['pstr']) ))
        elif tag == 'tag_sequence':
            for i in xrange(0, count):
                result.append( ( '#%d' % i, deref(value['valtab'][i]['pseq']) ))
        return result

def typefilter(value):
    "Pick a pretty-printer for 'value'."
    typename = str(value.type.strip_typedefs().unqualified())

    if typename == 'char []':
        return cstringprinter(value)

    if (typename == 'struct boxint_st' or
        typename == 'struct boxstring_st' or
        typename == 'struct boxsequence_st'):
        tag = str(value['tag'])
        if tag == 'tag_int':
            return boxintprinter(value)
        if tag == 'tag_string':
            return boxstringprinter(value)
        if tag == 'tag_sequence':
            return boxsequenceprinter(value)

    return None

gdb.pretty_printers.append(typefilter)

rawDescription: gdb pretty printing with python a recursive structure

description: Gdb pretty printing with python a recursive structure


code:
lambdas = un.def_unit('lambdas', format={'format' : r'\lambda'})
klambdas = un.def_unit('kilolambdas', 1e3 * lambdas, format={'format' : r'k\lambda'})

# equivalency (from_unit, to_unit, forward, backward)
lambdas_equivalencies = [
    (lambdas, un.s, lambda x: x/restfreq_hz, lambda x: x*restfreq_hz),
    (lambdas, un.m, lambda x: x/restfreq_hz * co.c.to(un.m/un.s).value, lambda x: x/co.c.to(un.m/un.s).value * restfreq_hz),
    (un.m, un.s, lambda x: x/co.c.to(un.m/un.s).value, lambda x: x*co.c.to(un.m/un.s).value),
]

rawDescription: Astropy Units equivalencies - interferometry baselines


code: [w[:-2] for w in list_of_words]

rawDescription: Slice every string in list in Python

description: Slice every string in list in Python


rawDescription: Python: sorting dictionary of dictionaries


rawDescription: List of (date, day_of_week) tuples

description: List of (date, day_of_week) tuples


code:
import subprocess
r = subprocess.call(['script', 'argument1', ...])

rawDescription: Python Scripts for mac, how to run a program and get value back


code:
tripplets = dict.setdefault(key1, {})
if t not in triplets:
    triplets[t] = (t, a, c)

rawDescription: Python: how to work with list to have unique values


code:
engine = pyttsx.init()
engine.setProperty('voice', voice_id)  # use whatever voice_id you'd like
engine.say('The quick brown fox jumped over the lazy dog.')

rawDescription: Changing the voice with PYTTSX module in python


rawDescription: Colletting element from different DataFrames into arrays


rawDescription: python descriptors sharing values across classes

description: Python descriptors sharing values across classes


code: np.array([np.arange(1, x+1) for x in limit_array])

rawDescription: Arrays generation from different arrays and arrays/numpy modules?


code: df

rawDescription: Most efficient way to loop through multiple csv files and calculate NYSE tick


code:
t('f()', setup='from __main__ import with_re_search as f', number=n) # 24.345079875027295
t('f()', setup='from __main__ import with_in as f',        number=n) # 1.1399168980424292
t('f()', setup='from __main__ import without_search as f', number=n) # 1.3967725560069084

rawDescription: Is it faster to check if a subtring exists before removing it?


rawDescription: Python multiple string replacement

description: Python multiple string replacement


rawDescription: Python - Retrieve and replace based on a regex


code:
operator.delitem(a, b)
operator.__delitem__(a, b)

rawDescription: Check for [] operator

description: Check for [] operator


code:
expr = infixNotation(operand,
        [
        (oneOf('* /'), 2, opAssoc.LEFT),
        (oneOf('+ -'), 2, opAssoc.LEFT),
        ])

rawDescription: Parse mathematical expressions with pyparsing


code:
usefulness = {}
significance = {}
difficulty = {}

rawDescription: How do I input the items in a list using a variable as the identifier?

description: Input the items in a list using a variable as the identifier


rawDescription: Compounded multiplier and divider in Python


code:
while True: #your wile

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
   #your code

rawDescription: When i make a pygame game and hover over it, the cursor turns into the loading thing


rawDescription: how to test if there is any word matched the string in Python

description: Test if there is any word matched the string in Python


code: GetLineFormSet = formset_factory(GetLine, extra=number_of_lines, max_num=10)

rawDescription: Using formset_factory in Django

description: Using formset_factory in Django


code: plot = list(plot)

rawDescription: Why is this python list showing empty in this certain case?


code:
import csv
with open('data.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(zip(dates, closes))

rawDescription: Two Lists Into One Dictionary Python

description: Two Lists Into One Dictionary Python


rawDescription: Equivalent of "in" keyword or subquery in pandas


code:
import bs4
import re

thehtml = '''

My keywords :  some text

some other words :  some other words

    '''
soup = bs4.BeautifulSoup(thehtml)
k = soup.find(text=re.compile("My keywords")).next_sibling['href']
print(k)

rawDescription: how to get the context of a search in BeautifulSoup?

description: Get the context of a search in BeautifulSoup


code: sorted(yourdict.items(), key=lambda item: int(item[0].split()[0]))

rawDescription: Sort Python Dictionary by first four characters in Key


code:
class HtmlBuilder(object):

    def __init__(self):
        self.doc = None

    def createHtml(self):
        name = input("\nEnter the name for your HTML-page: ")
        self.doc = open(name + ".html", 'w')

    def createTitle(self):
        print (t[0], file=self.doc) #<!DOCTYPE html>
        print (t[1], file=self.doc) #<html>
        print (t[2], file=self.doc) #<head>
        title = input("Enter your title here: ")
        print ("  <title>",title,"</title>", file=doc)
        print (t[3], file=self.doc) #</head>

    def Dispose(self):
        self.doc.flush()
        self.doc.close()

rawDescription: global name 'doc' is not defined, trouble withvcall from one function to annother

description: Global name 'doc' is not defined, trouble withvcall from one function to annother


code:
def computePI(throws):
    radius = 1
    ontarget = 0
    offtarget = 0
    numthrows = 0
    for throw in range(throws):
        x = random.uniform(-1.0,1.0)
        y = random.uniform(-1.0,1.0)
        hyp = math.hypot(x,y)
        if hyp <= radius:
            ontarget += 1
            numthrows+=1
        else:
            offtarget += 1
            numthrows+=1
    pi = (ontarget/throws)*4
    return(pi)

def main ():
    throws = 100
    while throws <= 10000000:
        difference = computePI(throws) - math.pi
        print('{first} {last}'.format(first="Num =", last=throws),end = "    ")
        print('{first} {last}'.format(first="Calculated Pi =", last=computePI(throws)),end = "    ")
        if difference < 0:
            print('{first} {last}'.format(first="Difference =", last=round(difference,6)))

        if difference > 0:
            print('{first} +{last}'.format(first="Difference =", last=round(difference,6)))
        throws *= 10
main()

rawDescription: Running a function multiple times and printing the results for each separate run


code:
mask = start_indices[:,None] <= np.arange(data.shape[1])
(data * mask).sum(axis=1)

rawDescription: Sum rows of numpy array where start index of each sum comes from another array


code:
import numpy as np
import pandas as pd
np.random.seed(2015)
N = 10
frame = pd.DataFrame({'eventdatetime':pd.date_range('2000-1-1', periods=N, freq='T'),
                  'seconds': np.random.randint(60, size=N)})
frame.loc[::2, 'seconds'] = np.nan

frame["s_eventdatetime"] = (
    frame["eventdatetime"] - np.array(frame['seconds'].fillna(0), dtype='timedelta64[s]'))

rawDescription: Apply time shift on Pandas DataFrame from another column


code:
orders = Order.objects.filter(exhibition=data).values()
formset = CourierFormSet(initial=orders)

rawDescription: Multiple text fields with id's in django


code:
from itertools import cycle

plaintext = input('enter message: ')
keyword = input('enter keyword: ')

def chr_to_int(char):
    return 0 if char == 'z' else ord(char)-96
def int_to_chr(integer):
    return 'z' if integer == 0 else chr(integer+96)
def add_chars(a, b):
    return int_to_chr(( chr_to_int(a) + chr_to_int(b) ) % 26 )

def vigenere(plaintext, keyword):
    keystream = cycle(keyword)
    ciphertext = ''
    for pln, key in zip(plaintext, keystream):
        ciphertext += add_chars(pln, key)
    return ciphertext

ciphertext = vigenere(plaintext, keyword)
print(ciphertext)

rawDescription: vigenere cipher - not adding correct values

description: Vigenere cipher - not adding correct values


code:
a = [1, 3, 5]
b = [2, 4]
# The first argument is the index to insert it at.
# The second is the actual item to be inserted.
a.insert(1, b[0]) # [1, 2, 3, 5]
a.insert(3, b[1]) # [1, 2, 3, 4, 5]

rawDescription: Is it possible to insert specific sections of one list into a specific location in another list?


code:
a = {ID1: [10], ID2: [10]}
id, val = (ID2, 13)

if id not in a.keys():
    a[id] = []

a[id].append(val)
if len(a[id]) > 2:
    a[id].pop(0)

def count(a, id):
    if id not in a.keys():
        return 0
    else:
        return len(a[id])

rawDescription: python list, working with multiple elements

description: Python list, working with multiple elements


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

cont = requests.get("http://www.physagreg.fr/schemas-figures-physique-svg-tikz.php").text

soup = BeautifulSoup(cont)
base_url = "http://www.physagreg.fr/"

h5s = soup.find_all("h5", limit=6)
for h5 in h5s:
    # find first table after
    table = h5.find_next("table")
    # find all h3 elements in that table
    for h3 in table.select("h3"):
        print(h3.text)
        img = h3.find_next("img")
        src, title = img["src"], img["title"]
        # join base url and image url
        img_url = urljoin(base_url, src)
        # open file using title as file name
        with open(title, "w") as f:
           # requests the img url and write content
            f.write(requests.get(img_url).content)

rawDescription: Parsing a tag in HTML

description: Parsing a tag in HTML


code:
def eyeForI(word):
    result = ""  # create an empty string so we can add to it
    for c in word:  # c will be set to each character in turn
        if c == 'i':
            result += 'eye'  # add the word to the end of result
        else:
            result += c  # add the letter to the end of result
    return result
assert eyeForI("William") == "Weyelleyeam"  # test it works

rawDescription: Replacing a letter with a word

description: Replacing a letter with a word


code: arr[rows][:, cols]

rawDescription: Python. Remove from array (presented as list of lists) rows and columns by condition


code:
while fruitList:
    print(min(fruitList))
    fruitList.remove(min(fruitList))

rawDescription: How to use for and while loop to sort in alphabetical order using python?

description: Use for and while loop to sort in alphabetical order using python


code:
import sys
sys.version_info
sys.version_info.major

rawDescription: which python is running?

description: Which python is running


code:
class CommandManager:
  @classmethod
  def execute(cls, command, *args, **kw):
    # import the command module
    commands_mod = __import__("commands", globals(), locals(), [command])
    mod = getattr(commands_mod, command)
    return mod.command_cls(*args, **kw).execute()

rawDescription: Auto register a class when it's defined (but without importing it anywhere)


rawDescription: How to get relevant month and date by inputting only the day of year in python

description: Get relevant month and date by inputting only the day of year in python


code: key = int(key)

rawDescription: Python simple if or logic statement

description: Python simple if or logic statement


code:
def conv_sym(o):
    o = o.replace('11','a')
    o = o.replace('12','b')
    o = o.replace('13','c')
    o = o.replace('14','d')
    o = o.replace('15','e')
    o = o.replace('21','f')
    o = o.replace('22','g')
    o = o.replace('23','h')
    o = o.replace('24','i')
    o = o.replace('25','j')
    o = o.replace('31','k')
    o = o.replace('32','l')
    o = o.replace('33','m')
    o = o.replace('34','n')
    o = o.replace('35','o')
    o = o.replace('41','p')
    o = o.replace('42','q')
    o = o.replace('43','r')
    o = o.replace('44','s')
    o = o.replace('45','t')
    o = o.replace('51','u')
    o = o.replace('52','v')
    o = o.replace('53','w')
    o = o.replace('54','x')
    o = o.replace('55','y')
    o = o.replace('61','z')
    o = o.replace('62',' ')
    return o

enc_str = "41114444"
dec_str = ""
while len(enc_str) > 0:
    sym = enc_str[:2]
    dec_str += conv_sym(sym)
    enc_str = enc_str[2:]
print (dec_str)

rawDescription: Decryption algorithm for a previously made encryption algorithm - python


code:
eq.replace(
lambda x: x.is_Symbol and S(x.name).is_Number,
lambda x: S(x.name))
_.atoms(Number)

rawDescription: Classifying free symbols from expressions


code: CELERY_RESULT_BACKEND = 'database'

rawDescription: Django Celery Periodic Tasks Run But RabbitMQ Queues Aren't Consumed


rawDescription: How to apply multiple functions to numpy array?

description: Apply multiple functions to numpy array


code:
from tornado.concurrent import Future

def async_fetch_future(url):
    http_client = AsyncHTTPClient()
    my_future = Future()
    fetch_future = http_client.fetch(url)
    fetch_future.add_done_callback(
        lambda f: my_future.set_result(f.result()))
    return my_future

rawDescription: Can't call result() on futures in tornado


code:
#! /usr/bin/env python
# Rename PCRaster map stack with names following prefix.yyymmmdd to stack with valid
# PCRaster time step numbers
# Johan van der Knijff
#
# Example input stack:
#
# precip.19810101
# precip.19810102
# precip.19810103
# precip.19810104
# precip.19810105
#
# Then run script with following arguments:
#
# python renpcrstack.py precip 1
#
# Result:
#
# precip00.001
# precip00.002
# precip00.003
# precip00.004
# precip00.005
#

import sys
import os
import argparse
import math
import datetime
import glob

# Create argument parser
parser = argparse.ArgumentParser(
    description="Rename map stack")

def parseCommandLine():
    # Add arguments
    parser.add_argument('prefix',
                        action="store",
                        type=str,
                        help="prefix of input map stack (also used as output prefix)")
    parser.add_argument('stepStartOut',
                        action="store",
                        type=int,
                        help="time step number that is assigned to first map in output stack")

    # Parse arguments
    args = parser.parse_args()

    return(args)

def dateToJulianDay(date):

    # Calculate Julian Day from date
    # Source: https://en.wikipedia.org/wiki/Julian_day#Converting_Julian_or_Gregorian_calendar_date_to_Julian_day_number

    a = (14 - date.month)/12
    y = date.year + 4800 - a
    m = date.month +12*a - 3

    JulianDay = date.day + math.floor((153*m + 2)/5) + 365*y + math.floor(y/4) \
        - math.floor(y/100) + math.floor(y/400) - 32045

    return(JulianDay)

def genStackNames(prefix,start,end, stepSize):
    # Generate list with names of all maps
    # map name is made up of 11 characters, and chars 8 and 9 are
    # separated by a dot. Name starts with prefix, ends with time step
    # number and all character positions in between are filled with zeroes

    # define list that will contain map names
    listMaps = []

    # Count no chars prefix
    charsPrefix = len(prefix)

    # Maximum no chars needed for suffix (end step)
    maxCharsSuffix = len(str(end))

    # No of free positions between pre- and suffix
    noFreePositions = 11 - charsPrefix - maxCharsSuffix

    # Trim prefix if not enough character positions are available
    if noFreePositions < 0:
        # No of chars to cut from prefix if 11-char limit is exceeded
        charsToCut = charsPrefix + maxCharsSuffix - 11
        charsToKeep = charsPrefix - charsToCut

        # Updated prefix
        prefix = prefix[0:charsToKeep]

        # Updated prefix length
        charsPrefix = len(prefix)

    # Generate name for each step

    for i in range(start,end + 1,stepSize):

        # No of chars in suffix for this step
        charsSuffix = len(str(i))

        # No of zeroes to fill
        noZeroes = 11 - charsPrefix - charsSuffix

        # Total no of chars right of prefix
        charsAfterPrefix = noZeroes + charsSuffix

        # Name of map

        thisName = prefix + (str(i)).zfill(charsAfterPrefix)
        thisFile = thisName[0:8]+"." + thisName[8:11]

        listMaps.append(thisFile)

    return listMaps

def main():
    # Parse command line arguments
    args = parseCommandLine()
    prefix = args.prefix
    stepStartOut = args.stepStartOut

    # Glob pattern for input maps: prefix + dot + 8 char extension
    pattern = prefix + ".????????"

    # Get list of all input maps based on glob pattern
    mapsIn = glob.glob(pattern)

    # Set time format
    tfmt = "%Y%m%d"

    # Set up dictionary that will act as lookup table between Julian Days (key)
    # and Date string
    jDayDate = {}

    for map in mapsIn:
        baseNameIn = os.path.splitext(map)[0]
        dateIn = os.path.splitext(map)[1].strip(".")

        # Convert to date / time format
        dt = datetime.datetime.strptime(dateIn, tfmt)

        # Convert date to Julian day number
        jDay = int(dateToJulianDay(dt))

        # Store as key-value pair in dictionary
        jDayDate[jDay] = dateIn

    # Number of input maps (equals number of key-value pairs)
    noMaps = len(jDayDate)

    # Create list of names for output files
    mapNamesOut = genStackNames(prefix, stepStartOut, noMaps + stepStartOut -1, 1)

    # Iterate over Julian Days (ascending order)

    i = 0

    for key in sorted(jDayDate):
        # Name of input file
        fileIn = prefix + "."+ jDayDate[key]

        # Name of output file
        fileOut = mapNamesOut[i]

        # Rename file
        os.rename(fileIn, fileOut)

        print("Renamed " + fileIn + " ---> " + fileOut)

        i += 1

main()

rawDescription: renaming pcraster mapstack

description: Renaming pcraster mapstack


code:
from multiprocessing import Process, Manager

def f(d):
    d[1] = [[1]]
    if 2 in d:  # NOTE: You don't need to use `keys()`. `dict` support `in` operator.
       d[2] = d[2] + [[2]]
    else:
       d[2] = [[2]]
    d[3] = [[3]]

if __name__ == '__main__':

    with Manager() as manager:
        d = manager.dict()

        p1 = Process(target=f, args=(d,))
        p2 = Process(target=f, args=(d,))
        p1.start()
        p2.start()
        p1.join()
        p2.join()

        print(d)

rawDescription: Modifying a shared dict object among processes doesn't work


code:
class CustomInput(TextInput):

    max_chars = NumericProperty(10)

    def insert_text(self, substring, from_undo=False):
        if not from_undo and (len(self.text)+len(substring) > self.max_chars):
            return
        super(CustomInput, self).insert_text(substring, from_undo)

rawDescription: Kivy: Is there a "BoundedString" property available for TextInputs?


code:
import pygame
import sys
import time

pygame.init()

size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load("ball.gif")
ballrect = ball.get_rect()

screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()

time.sleep(5)

rawDescription: Frame buffer module of python

description: Frame buffer module of python


code:
f = open("/path/to/file", "w")
f.seek(size  - 1)
f.write("\x00")
f.close()

rawDescription: how can you overwrite a file line with zeros

description: Overwrite a file line with zeros


code:
from string import maketrans
complementTrans = maketrans("ACTG", "TGAC")

poolA =  ['AAG', 'TAC', 'CGG', 'GAT', 'TTG', 'GTG', 'CAT', 'GGC', 'ATT', 'TCT']
[codon.translate(complementTrans) for codon in poolA]

rawDescription: Converting letters using a dictionary

description: Converting letters using a dictionary


rawDescription: pass special character from the command line

description: Pass special character from the command line


code:
with open('infile_name','r') as input_file:
    lines = input_file.readlines()
    lines.sort()
    output_file = open('outfile_name', 'w')
    output_file.writelines(lines)

rawDescription: How can I re-arrange orders of lines based on alphabet in Python

description: Re-arrange orders of lines based on alphabet in Python


code:
import sql  # the patched version (file is named sql.py)
sql.write_frame(df, 'table_name', con, flavor='postgresql')

rawDescription: How to write DataFrame to postgres table?

description: Write DataFrame to postgres table


rawDescription: Save list of table of numbers from Python into format easily readable by Mathematica?


code:
import re

result = re.split(r'\s+(?=[A-Z])', inputstr)
print('\n'.join(result))

rawDescription: re.sub matching pattern but not getting the desired output

description: Re.sub matching pattern but not getting the desired output


code: {{gettext("message")}}

rawDescription: serving i18n js using babel, django, & jinja2

description: Serving i18n js using babel, django, & jinja2


code:
class Number:
    def __new__(cls, value):
        if cls is not __class__:
            # Subclass, create an instance
            return super().__new__(cls)
        if isinstance(value, complex):
            return Complex(value)
        elif isinstance(value, (int, float)):
            return Real(value)
        else:
            raise TypeError('Ну ты и мудак!!!')
    def __init__(self, value):
        self.value = value

class Real(Number):
    def __new__(cls, value):
        if cls is not __class__:
            # Subclass, create an instance
            return super().__new__(cls, value)
        if isinstance(value, int):
            return Int(value)
        elif isinstance(value, float):
            return Float(value)
        else:
            raise TypeError('Ты больше не можешь вести себя так!!!')

class Complex(Number):
    pass

class Int(Real):
    pass

class Float(Real):
    pass

number = Number(6.6)
isinstance(number, Float)

rawDescription: In python 3, how to create child class instance using some magic in parent __new__?


code:
from itertools import starmap
from operator import sub
sum(starmap(sub,zip(nums[1:],nums)))/float(len(nums)-1)

rawDescription: Clunky calculation of differences between an incrementing set of numbers, is there a more beautiful way?


code:
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import re
import time

def get_choice():
    print('MAIN MENU')
    print('1. Plot Graph A')
    print('2. Plot Graph B')
    print('3. Plot Graph C')
    print('4. History')
    print('5. Exit/Quit')

    choice = raw_input('Please choose an option: ')
    if choice == '1':
        import plotA
    elif choice == '2':
        import plotB
    elif choice == '3':
        import plotC
    elif choice == '4':
        import history
    elif choice == '5':
        exit()
    else:
        print('Try Again')
        get_choice()

if __name__ == '__main__':
    get_choice()

rawDescription: creating a text menu, user can't enter option again

description: Creating a text menu, user can't enter option again


rawDescription: Equality without using operator

description: Equality without using operator


code:
webapp2_config = {
    "webapp2_extras.auth": {
        "user_model": "models.MyUser"
    },
    # etc.
}

app = webapp2.WSGIApplication(routes, config=webapp2_config)

rawDescription: GAE webapp2 delete all UserTokens (drop all sessios) for specific user


code:
filepath = '/var/log/apache2/error.log'
localpath = 'C:\\remote\\NewFile.log'
sftp.get(filepath, localpath)

rawDescription: I want to retrieve multiple logs from a server with minimum lines of code


rawDescription: Python Regexes differ in Pythex vs. console


code:
from core.myresources import BookResource

dataset = BookResource().export()

rawDescription: Django Import Export: Documentation cannot be understood


code:
import matplotlib.pyplot as plt

plt.scatter(xs, ys)
plt.show()

rawDescription: Print float (x,y) data in a graph with Python


code:
def get_best_missions(x):

    n = len(x)

    p = [0 for i in range(n)]

    for i in range(1,n):
        j = i - 6

        if j < 0:
            p[i] = sum(x[0:i])
        else:
            p[i] = max(p[i], p[j] + x[j+1] + x[j+2] + x[j+3] + x[j+4] + x[i - 1])

    return max(p)

rawDescription: Dynamic Programming: Mission Per Day, Scheduling for Maximum Profit


code:
import os, sys

rootdir = os.path.dirname(os.path.abspath(__file__))
lib = os.path.join(rootdir, 'lib')
sys.path.append(lib)

rawDescription: Python on Appengine using BeautifulSoup ImportError: No module named bs4


code:
def skip_line_with(it, name):
    # Yield lines until find the line with `name`
    for line in it:
        if line.startswith(name):
            break  # Do not yield the line => skip the line
        yield line

    # Yield lines after the line
    for line in it:
        yield line

with open('a.txt') as fin, open('b.txt', 'w') as fout:
    fout.writelines(skip_line_with(fin, 'Name 2,'))

rawDescription: Find the first instance of a variable in a .txt file and delete the line it is in


rawDescription: Write lists of different size to csv in columns in Python


rawDescription: How to retrieve a time stamp with the right formatting from a sql database using python

description: Retrieve a time stamp with the right formatting from a sql database using python


code: df.groupby(['c0'])['c6'].sum().apply(lambda x: 'abc' + x.astype(str)).reset_index()

rawDescription: How to append a string to int/float dataframes in Pandas

description: Append a string to int/float dataframes in Pandas


code:
import numpy as np

probs = np.array([.5 ,.56 ,.47 ,.55 ,.59 ,.59 ,.38])
nsims = 500000

chance = np.random.uniform(size=(nsims, 7))

teamAWins = (chance > probs[None, :]).astype('i4')
teamBWins = 1 - teamAWins

teamAwincount = {}
teamBwincount = {}
for ngames in range(4, 8):
    afilt = teamAWins[:, :ngames].sum(axis=1) == 4
    bfilt = teamBWins[:, :ngames].sum(axis=1) == 4

    teamAwincount[ngames] = afilt.sum()
    teamBwincount[ngames] = bfilt.sum()

    teamAWins = teamAWins[~afilt]
    teamBWins = teamBWins[~bfilt]

teamAwinprops = {k : 1. * count/nsims for k, count in teamAwincount.iteritems()}
teamBwinprops = {k : 1. * count/nsims for k, count in teamBwincount.iteritems()}

rawDescription: monte carlo simulation python

description: Monte carlo simulation python


code:
# Create your Range column to be filled in later.
df['Range'] = '|'
for index, row in df.iterrows():
  for ix, list in conditions.iteritems():
    # Create a list of the outcomes of checking whether the
    # value for each condition column is greater than the
    # df_base_val average.
    truths = [row[column] > df_base_val[column] for column in list]
    # See if all checks evaluated to True
    if sum(truths) == len(truths):
      # If so, set the 'Range' column's value for the current row
      # to the appropriate 'range_name'
      df.ix[index, 'Range'] = df.ix[index, 'Range'] + range_name_list[ix] + "|"
# Fill in all rows where no conditions were met with 'Not_in_Range'
df['Range'][df['Range'] == '|'] = 'Not_in_Range'

rawDescription: Pandas compare each row to reference row - certain columns only


rawDescription: Adding legend to pandas.dataframe.plot when y option is used


code:
board = [[0]*3 for _ in range(3)]
board

rawDescription: How to initialise a 2D array in Python?

description: Initialise a 2D array in Python


code:
form = SupplyTypeForm(request.POST or None,
                      initial={'service_type': User.DUAL_SUPPLIER})

rawDescription: django model form initial value on choicefield

description: Django model form initial value on choicefield


code: tokens = '(?:' + '|'.join([OPS, SQ, DQ, WS, NON_SPECIAL]) + ')'

rawDescription: Match open and close brackets in garbled string


code:
def parse(lines):
    result = dict()

    for line in lines:
        cur_dict = result
        for field in line.strip("/").split("/"):
            cur_dict = cur_dict.setdefault(field, {})

    return result

rawDescription: How to convert a list of slash separated strings into a nested dictionary?

description: Convert a list of slash separated strings into a nested dictionary


rawDescription: Python Regex matching choice between "\*" (literal Asterisk char) OR "\s" (Space)


code:
pan = pd.Panel(D, items=T_index, major_axis=N_index, minor_axis=P_index)
# <class 'pandas.core.panel.Panel'>
# Dimensions: 10 (items) x 20 (major_axis) x 3 (minor_axis)
# Items axis: 0.0 to 9.0
# Major_axis axis: 0 to 19
# Minor_axis axis: x to z

rawDescription: How to create an index on a ndarray using pandas

description: Create an index on a ndarray using pandas


code:
import re
exp = re.compile('(\w+\.\w+)|(\w+,\s?\w+)')
map(exp.findall, abc)

rawDescription: Is there a way for checking a certain pattern in a list?


code:
def get_divisors(r: int) -> list:
    return [i if r % i == 0 else 0 for i in range(1, r+1)]

get_divisors(4)
[1, 2, 0, 4]
sum(get_divisors(4))
7

rawDescription: How to stop a loop?

description: Stop a loop


code:
list1 = []
race_time = input("Enter a race time: ")
while race_time != "no more races":
    list1.append(float(race_time))
    race_time = input("Enter a race time: ")
print(min(list1))

rawDescription: Python homework - take list of times and print the fastest time


code:
def Tr1(T, Tc1):
    result = T/Tc1
    print("Relative temperature 1: ", result)
    return result

rawDescription: Saving output of a function as a variable and using it in another function


code:
from collections import namedtuple
Project = namedtuple('Project', 'id url name key')

rawDescription: Automatically convert JSON to Object on Flask Request


code:
def formatted_print(D):
    list_tuples=sorted(D.items(), key=lambda x: (-x[1], x[0]))

    for items in list_tuples:
        x="{0:10s}{1:6.2f}".format(items[0],items[1])
        print(x)

rawDescription: To reverse a dictionary and display values


code:
a=np.array(['1', '2'])
np.logical_xor(a, np.zeros(a.shape))

rawDescription: Python numpy XOR return NotImplemented

description: Python numpy XOR return NotImplemented


code:
from descartes import PolygonPatch
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize = [10,10], dpi = 300)
ax = fig.add_subplot(111)
offset_x = lambda xy: (xy[0] + 0.1, xy[1])
offset_y = lambda xy: (xy[0], xy[1] - 0.5)
for i,j in enumerate(geo_polygons):
    ax.add_patch(PolygonPatch(j, alpha=0.5))
    plt.annotate('polygon {}'.format(i + 1), xy= offset_y(tuple(j.centroid.coords[0])))
for i,j in enumerate(geo_points):
    ax.add_patch(PolygonPatch(j.buffer(0.07),fc='orange',ec='black'))
    plt.annotate('point {}'.format(i + 1), xy= offset_x(tuple(j.coords[0])))
ax.set_xlim(0, 9)
ax.set_ylim(0, 7)
ax.set_aspect(1)
plt.show()

rawDescription: Apply a pairwise shapely function on two numpy arrays of shapely objects


code:
User.objects.filter(to_user__from_user=user, to_user__status=1) # user as from_user
User.objects.filter(from_user__to_user=user, from_user__status=1) # user as to_user
User.objects.filter(following=user) # those who are followed by `to_user` user

rawDescription: Django asymettrical self through relationship query


rawDescription: XPath locate child following sibling

description: XPath locate child following sibling


rawDescription: Python: Remove top 'n' keys from a dictionary


code:
Builder.load_string("""
#:import ListItemButton kivy.uix.listview.ListItemButton
#:import ListAdapter kivy.adapters.listadapter.ListAdapter

<ListViewModal>:
    size_hint: None, None
    size: 400, 400
    ListView:
        size_hint: .8, .8
        adapter:
            ListAdapter(data=["Item #{0}".format(i) for i in range(100)], cls = ListItemButton)
""")

rawDescription: Kivy: Why does ListView declare differently in .kv file?


code:
import pyparsing as pyp
import itertools

integer = pyp.Word(pyp.nums)
ip_addr = pyp.Combine(integer+'.'+integer+'.'+integer+'.'+integer)

def snort_parse(logfile):
    header = (pyp.Suppress("[**] [")
              + pyp.Combine(integer + ":" + integer + ":" + integer)
              + pyp.Suppress(pyp.SkipTo("[**]", include = True)))
    cls = (
        pyp.Suppress(pyp.Optional(pyp.Literal("[Classification:")))
        + pyp.Regex("[^]]*") + pyp.Suppress(']'))

    pri = pyp.Suppress("[Priority:") + integer + pyp.Suppress("]")
    date = pyp.Combine(
        integer+"/"+integer+'-'+integer+':'+integer+':'+integer+'.'+integer)
    src_ip = ip_addr + pyp.Suppress("->")
    dest_ip = ip_addr

    bnf = header+cls+pri+date+src_ip+dest_ip

    with open(logfile) as snort_logfile:
        for has_content, grp in itertools.groupby(
                snort_logfile, key = lambda x: bool(x.strip())):
            if has_content:
                tmpStr = ''.join(grp)
                fields = bnf.searchString(tmpStr)
                print(fields)

snort_parse('snort_file')

rawDescription: Parsing Snort Logs with PyParsing

description: Parsing Snort Logs with PyParsing


code:
from collections import defaultdict
busdict = defaultdict(list)
...
...
busdict[bus].append(i)

rawDescription: What is the best way to append lists inside a dict?


code:
args=parser.parse_args('-k mass 100 inf -k spin 0.5 1.0'.split())

Namespace(kwarg=[['mass', '100', 'inf'], ['spin', '0.5', '1.0']])

rawDescription: using a variable keyword for an optional argument name with python argparse

description: Using a variable keyword for an optional argument name with python argparse


code:
sequence = "ATATAGACATCGAATACTAATAGCATACAGTCCAAATTCGGAGCCCGACATTCTTCGATAACGACCGCTGATTATATGGGGCTCCGTCTACTCTAGGAGTTCTTGGCTGAGCCCTTCTAATTACCCACCGGGTGGCACACCAAGGACCGAAAAACCGTGGCCCGTGGGGAAAGTATCAGAACGGTACGGACCGTTTTTCCACCTCAAGGGACACCTTTGTCCCCGCCAATTATGCCAACCTCTCATAGTATTATATCTCCTCAATTTCTATGTGCGCAGTGTCTGTATGTTAGGACGCGCATGCACTGAAATGGCGATAGTGTGAATACATAGGTCATCTTGTGCCAGTGGCTGACTGATCGTCTACAAGTGACAATGCTGTGAATAACAAGATTGTGCACATGTCTAACCCGTGAGCTGGAGCTCCATAGCTATGGAGCTCCAGCTCACGGGTTAGACATTTTACAGTAGCGTACATTTCTGGCCGACCAACAGTGCATGGAGTTCAAGGCACATCCTTACTAAATTCTCCGTGTCCAGATTTAACAGCGAAGACGCTTTCCACGGACACAAGTATGAAAAGCGGCCGAAGGGGTCATTTGGACCAATGGACTGTTAGCGATACGCAAGAGTGAAAGGCGGGCGATCCACATTACAAATCCCTATCAGGACTGCGAATAAGATTTTCCTGAATATGAGTGGTGTGGACAGAGCTATGTTTTTCGAATTCCGCACACTCGAGTGCGCGGCCTTCTCAGAGTTTTAAACTTTGCCTGGGTACTGATTATTATAGTCCAAGTAGAATAGTCACTCTATATTTTTAATAGAATGCGGGTGACACCGGCAAGAGAACCGAGCATTT"

start = 'ATG'
stop = ('TAA', 'TGA', 'TAG')
stop_positions = []
start_positions = []

# Normal direction
for i in range(len(sequence)): # Create the index value
    if sequence[i:].startswith(start): # Check if there is a methionine in this position.
        start_positions.append(i)
    else:
        for stop_codon in stop:
            if sequence[i::].startswith(stop_codon): # Check if there is a stop in this position.
                stop_positions.append(i)
                break

rawDescription: Creating a List of Lists for Three Reading Frames


code: ts

rawDescription: Create multiple columns in pandas aggregation function


code:
import requests
s = requests.Session()
s.params = {'access_token': 'foobarbaz'} # so you don't have to specify it every time
query = ('{"user_sex":"SELECT sex FROM user WHERE uid=me()",'
         '"friends":"SELECT uid, name FROM user WHERE uid IN '
         '(SELECT uid2 FROM friend WHERE uid1 = me()) '
         'AND not (sex in (SELECT sex FROM #user_sex)) '
         ' ORDER BY name"}')
s.get('https://graph.facebook.com/fql', params={'q': query})

rawDescription: Python requests urlencode not working?

description: Python requests urlencode not working


rawDescription: Pandas MultiIndex levels custom sort

description: Pandas MultiIndex levels custom sort


rawDescription: Numpy put array in Nth dimension

description: Numpy put array in Nth dimension


code:
import numpy as np
import scipy.stats as stats
nan = np.nan
A = np.array([1, nan, 8, nan, nan, 4, 6, 1])
B = np.array([8, 5, 8, nan, 5, 9, 5, 3])
C = np.array([A, B])
C
stats.nanmean(C)

rawDescription: Average arrays with Null values

description: Average arrays with Null values


code:
df1 = pd.DataFrame.from_csv(StringIO(s1), sep='\s+',parse_dates=['file_date']  )
df2 = pd.DataFrame.from_csv(StringIO(s2), sep='\s+',parse_dates=['file_date']  )

rawDescription: python merge panda dataframes keep dates

description: Python merge panda dataframes keep dates


rawDescription: Regex help needed for splitting CSV file


code: resultList = map(lambda x: foo(x) if x > 0 else bar(x), listOfNumbers)

rawDescription: Python map() with cases

description: Python map() with cases


code:
def myfunction(a, b, c):
    pass # im doing this later

rawDescription: Function that does nothing in Lua

description: Function that does nothing in Lua


code:
a = 1
b = 2
c = (1, 2)
def foo():
    global a, b
    a, b = 1, 2

def bar():
    global c
    c = (1, 2)

dis.dis(foo)
dis.dis(bar)

rawDescription: How to verify if one step is Atomic operation in python or now

description: Verify if one step is Atomic operation in python or now


code: G

rawDescription: iterating over lists finding standard deviation of each point

description: Iterating over lists finding standard deviation of each point


code:
values = [0, 1, 2]
sys.getrefcount(values) #two references so far: shell and `values`
values[1] = values     #created another reference to the same object but a cyclic one
sys.getrefcount(values) # references increased to 3
values[1] is values  # yes both point to the same obejct

rawDescription: Python:how to understand assignment and reference?


code:
def paint_blue(shape):
    print("BLUE!")

def paint_red(shape):
    print("RED!")

paint_funcs = {
    "blue": paint_blue,
    "red": paint_red,
}

def paint(color, shape):
    return paint_funcs[color](shape)

rawDescription: Python call a package submodule with variable module name


code: 'hey @pssdbt, thats not what i wanted!'

rawDescription: Linking a @username in Django Template Variables


rawDescription: Editing an attribute reffering to a list of classes


rawDescription: How do I capture multiple patterns from a line in python?

description: Capture multiple patterns from a line in python


code:
import numpy as np

def asvoid(arr):
    """
    View the array as dtype np.void (bytes).

    This views the last axis of ND-arrays as np.void (bytes) so
    comparisons can be performed on the entire row.
    http://stackoverflow.com/a/16840350/190597 (Jaime, 2013-05)

    Some caveats:
        - `asvoid` will work for integer dtypes, but be careful if using asvoid on float
        dtypes, since float zeros may compare UNEQUALLY:
        >>> asvoid([-0.]) == asvoid([0.])
        array([False], dtype=bool)

        - `asvoid` works best on contiguous arrays. If the input is not contiguous,
        `asvoid` will copy the array to make it contiguous, which will slow down the
        performance.

    """
    arr = np.ascontiguousarray(arr)
    return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))

def nodistinctcols(M):
    MT = asvoid(M.T)
    uniqs = np.unique(MT)
    return len(uniqs)

X = np.array([np.random.randint(2, size = 16) for i in xrange(2**16)])

print("nodistinctcols(X.T) {}".format(nodistinctcols(X.T)))

rawDescription: Speed up counting number of distinct columns


code:
import random
def grid_maker(h, v):
    return [
        [str(random.randint(1, 100)) for _ in range(v)]
        for _ in range(h)
    ]
print ('\n'.join(' '.join(row) for row in grid_maker(6, 5)))

rawDescription: Random number grid 4 x 6 Python 3

description: Random number grid 4 x 6 Python 3


rawDescription: trying to mask 2D numpy arrays based on values in one column

description: Trying to mask 2D numpy arrays based on values in one column


rawDescription: Count the number of times a particular string appears in a given word


code:
@gen.coroutine
def async_fetch(url, method='GET', headers={}, body=None):
    async_http_client = AsyncHTTPClient()
    http_request = HTTPRequest(url, method=method, headers=headers, body=body)
    http_response = yield client.fetch(http_request)
    raise gen.Return(http_response)  # That's how return looks in tornado

class MyHandler(RequestHandler):
    @gen.coroutine
    def get():
        ...
        response = yield async_fetch('http://example.org')
        ...

rawDescription: How to make a wrapper that simplifies requests with tornado AsyncHTTPClient?

description: Make a wrapper that simplifies requests with tornado AsyncHTTPClient


rawDescription: Calling a class function inside of __init__


code:
from collections import OrderedDict

mydict = OrderedDict ( {'KYS_Q1AA_YouthSportsTrustSportParents_P':
            OrderedDict ( {'KYS_Q1AA':
                OrderedDict ( [ ('chart_layout', '3'),
                 ('client_name', 'Sport Parents (Regrouped)'),
                 ('sort_order', 'asending'),
                 ('chart_type', 'pie'),
                 ('powerpoint_color', 'blue'),
                 ('crossbreak', 'Total')
                 ] ) } ) } )

def listRecursive (d, key):
    for k, v in d.items ():
        if isinstance (v, OrderedDict):
            for found in listRecursive (v, key):
                yield found
        if k == key:
            yield v

for found in listRecursive (mydict, 'powerpoint_color'):
    print (found)

rawDescription: Find a given key's value in a nested ordered dict python


code: df

rawDescription: How to merge two columns together in Pandas

description: Merge two columns together in Pandas


code: newdic = {key:[i*1000 if key not in ('x','y') else i for i in val] for key,val in dic.items()}

rawDescription: looping over keys and values, process the key values and store them back another dictinory in Python

description: Looping over keys and values, process the key values and store them back another dictinory in Python


code:
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
        }

rawDescription: How to markup form fields with <div class='field_type'> in Django

description: Markup form fields with <div class='field_type'> in Django


code:
def print_hello_world(*args):
    print(*args)

print_hello_world(hello, world, how, are, you, 'today', 'you', 'can', 'add', 'many things here')

rawDescription: How can I insert all the variable in a function automatically in python?

description: Insert all the variable in a function automatically in python


code:
class UserModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
         return obj.get_full_name()

rawDescription: Change Django ModelChoiceField to show users' full names rather than usernames


code:
nones_at = find_indices(y_values, None)
x_values = remove_at(x_axis, nones_at)
y_values = remove_at(y_values, nones_at)
pyplot.plot(x_values, y_values)

rawDescription: Can I put a value in a y-series to prevent matplotlib plotting a value for that x-value?

description: Put a value in a y-series to prevent matplotlib plotting a value for that x-value


code: return (myobject for _ in (0,))

rawDescription: Single object iterator

description: Single object iterator


code:
dis.dis('7. ** i')
dis.dis('pow(7., i)')
dis.dis('math.pow(7, i)')

rawDescription: Exponentials in python x.**y vs math.pow(x, y)


code:
@dec1
@dec2
def some(f):
    pass

rawDescription: Can I combine two decorators into a single one in Python?

description: Combine two decorators into a single one in Python


code:
df["c"] = df["c"].astype(object)
df.loc[df.isnull().any(axis=1), "c"] = np.nan
df

rawDescription: How can I non-iteratively place a NaN in a DataFrame column if there is a corresponding NaN in any other columns?

description: Non-iteratively place a NaN in a DataFrame column if there is a corresponding NaN in any other columns


code:
yyi=np.repeat(yi,N)
xxi=np.repeat(xi[None,:],N,0).flatten()

rbfi=interpolate.Rbf(xreg,yreg,z,function='linear')
zzi=rbfi(xxi,yyi).reshape(N,N)

rawDescription: Unable to interpolate data using Rbf in Scipy


code:
from pprint import pprint
pprint(l)
pprint(d, indent=2)

rawDescription: Is there a function in Python to print all the current properties and values of an object?


code:
df = pd.DataFrame(np.array([(datetime.datetime.strptime(row[0], "%H:%M:%S"),
                  row[1]) for row in csvish]), columns=('time', 'value'))

rawDescription: How to get the mean over time value

description: Get the mean over time value


rawDescription: Difference operator between a List and a Set


code: c = numpy.rec.fromarrays([a, b], dtype=[('f', float), ('i', int)])

rawDescription: Sort a numpy array by another array, along a particular axis, using less memory


code:
def _communicate(self, input):
    stdout = None # Return
    stderr = None # Return

    if self.stdout:
        stdout = []
        stdout_thread = threading.Thread(target=self._readerthread,
                                         args=(self.stdout, stdout))
        stdout_thread.setDaemon(True)
        stdout_thread.start()
    if self.stderr:
        stderr = []
        stderr_thread = threading.Thread(target=self._readerthread,
                                         args=(self.stderr, stderr))
        stderr_thread.setDaemon(True)
        stderr_thread.start()

    if self.stdin:
        if input is not None:
            self.stdin.write(input)
        self.stdin.close()

    if self.stdout:
        stdout_thread.join()
    if self.stderr:
        stderr_thread.join()

    # All data exchanged.  Translate lists into strings.
    if stdout is not None:
        stdout = stdout[0]
    if stderr is not None:
        stderr = stderr[0]

    # Translate newlines, if requested.  We cannot let the file
    # object do the translation: It is based on stdio, which is
    # impossible to combine with select (unless forcing no
    # buffering).
    if self.universal_newlines and hasattr(file, 'newlines'):
        if stdout:
            stdout = self._translate_newlines(stdout)
        if stderr:
            stderr = self._translate_newlines(stderr)

    self.wait()
    return (stdout, stderr)

rawDescription: Python subprocess Popen.communicate() equivalent to Popen.stdout.read()?


code: set(i for i in a if a.count(i)>1)

rawDescription: Testing whether a string has repeated characters


code:
from itertools import count
c = count(0)
while condition:
    doSomething()
    next(c) # returns 0, +1 in further loops

rawDescription: Transform a while loop with counter into a more pythonic code


code:
def run_in_parallel(*functions):
    processes={}
    for function in functions:
        process=Process(target=function)
        process.start()
        processes[process.pid]=process
    # wait for any process to complete
    pid, status = os.waitpid(-1, 0)
    # one process terminated
    # join it
    processes[pid].join()
    del processes[pid]
    # terminate the rest
    for process in processes.itervalues():
        process.terminate()
    for process in processes.itervalues():
        process.join()

rawDescription: how to kill running subprocess while another subprocess is completed (in multiprocessing)

description: Kill running subprocess while another subprocess is completed (in multiprocessing)


code:
import numpy as np
import random as rd

def np_pi(n):
    x = np.random.random(n)
    y = np.random.random(n)

    return (x*x + y*y <= 1).sum()

def dart_board():
    x,y = rd.random(), rd.random()
    return (x*x + y*y <= 1)

def pi(n):
    s = sum([dart_board() for _ in range(n)])

rawDescription: Python efficient vectorization for Monte Carlo based Pi calculation


code:
storageMatrix[column,row][0] = 1
storageMatrix[column,row][4092] = 2

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


code:
column = v.feature_names_.index('foo') # Column mapping index of key 'foo'
values = X[:, column] # get values
X[:, column] = 0 # remove them from X

rawDescription: Extracting a feature by feature name in scikit dict vectorizer


code:
timeit.Timer("'\xff' in l", "from string import ascii_letters, digits, whitespace; l = list(ascii_letters + digits + whitespace)").timeit(999999)
timeit.Timer("'\xff' in s", "from string import ascii_letters, digits, whitespace; s = set(ascii_letters + digits + whitespace)").timeit(999999)
timeit.Timer("'\xff' in s", "from string import ascii_letters, digits, whitespace; s = ascii_letters + digits + whitespace").timeit(999999)

rawDescription: Why is string search fastest as compared to list search and set search?


code:
non_commutative_sympify('3*x*y - y*x - 2*x*y')
non_commutative_sympify('x*y*z - y*z*x - 2*x*y*z + z*y*x')

rawDescription: Non-commutative sympify (or simplify)

description: Non-commutative sympify (or simplify)


code: proc = subprocess.Popen(['echo', os.environ['MY_ENV_VAR']])

rawDescription: How to get PID via subprocess.Popen with custom environment variable?

description: Get PID via subprocess.Popen with custom environment variable


code:
import json
import requests

f = requests.get('https://example.com/file.txt')
resp=f.json()

keys=resp.keys()
for val in keys:
    print(resp[val])

rawDescription: Parsing a JSON file in Python

description: Parsing a JSON file in Python


code:
import numpy as np
import pyfftw
inarray = np.random.random(1000)
targarray = np.empty(len(inarray)//2+1, dtype='complex')
testarray = targarray  # just for checking the array wasn't overwritten
pyfftw.FFTW(inarray, targarray).execute()
targarray is testarray

rawDescription: needed: FFT implememtatin in Python using preallocated buffer to store results

description: Needed: FFT implememtatin in Python using preallocated buffer to store results


rawDescription: What is the proper way to shedule Celery tasks to maximize worker productivity?


code:
from timeit import timeit
d = {1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1}
timeit('''
new_d = {}
for item in d:
    if d[item] == 1:
         new_d[item] = d[item]
''', 'from __main__ import d')
timeit('new_d = {k:v for k, v in d.items() if v == 1}', 'from __main__ import d')

rawDescription: Performance of inverse dictionary mapping


rawDescription: Why the return value of functions being printed in Python?


code:
for i in range(10):
    random.choice((Add, Sub, Div))()

rawDescription: Accessing functions which have been placed in a list


code:
from operator import itemgetter
required_fields = ((v.creation_counter, k) for k,v in User._fields.iteritems() if v.required)
sorted_required_fields = map(itemgetter(1), sorted(required_fields, key=itemgetter(0)))
sorted_required_fields

rawDescription: Get required fields from Document in mongoengine?


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

num = 79
lat = 5 * np.random.random(num) + 33
lon = 10 * np.random.random(num) - 104

fig, ax = plt.subplots()
m = Basemap(projection='stere',lon_0=-95,lat_0=35.,lat_ts=40,
            llcrnrlat=33,urcrnrlat=38,
            llcrnrlon=-103.8,urcrnrlon=-94,
            resolution='h', ax=ax)

X,Y = m(lon,lat)
m.drawcoastlines()
m.drawstates()
m.drawcountries()
m.drawmapboundary(fill_color='lightblue')
m.drawparallels(np.arange(0.,40.,2.),color='gray',dashes=[1,3],labels=[1,0,0,0])
m.drawmeridians(np.arange(0.,360.,2.),color='gray',dashes=[1,3],labels=[0,0,0,1])

ax.scatter(X,Y)

for i, (x, y) in enumerate(zip(X, Y), start=1):
    ax.annotate(str(i), (x,y), xytext=(5, 5), textcoords='offset points')

plt.show()

rawDescription: Plot strings of text on Basemap in place of points in Python


rawDescription: Multiple Quotes in String

description: Multiple Quotes in String


code:
class Entry(object):
    def __init__(self, dataset, d):
        self.dataset = dataset
        self.d = d

    def parent(self):
        return self.dataset.parent_of(self)
    def related(self):
        if not self.dataset.related_dataset:
            raise ValueError("no related dataset specified")
        return self.dataset.related_dataset(self['fkey'])

    def __getitem__(self, k):
        return self.d.__getitem__(k)

    def __repr__(self):
        return "Entry(%s)" % repr(self.d)
    def __str__(self):
        return str(self.d)

class Dataset(object):
    def __init__(self, data):
        self.data = dict((k, Entry(self, v)) for (k,v) in data.items())
        self.related_dataset = None

    def set_related_dataset(self, dataset):
        self.related_dataset = dataset

    def entry(self, key):
        if isinstance(key, Entry): return key
        return self.data[key]
    def __call__(self, key):
        return self.entry(key)

    def parent_of(self, entry):
        entry = self.entry(entry)

        if not entry['parent']:
            return None
        return self.data[entry['parent']]

rawDescription: Python: I have a dual key list, which is the most effective storage object for retreival


code: datetime.date(int(year), int(month), [i for i in zip(*calendar.monthcalendar(int(year), int(month)))[list(calendar.day_name).index(day_name)] if i != 0][week_num])

rawDescription: Python strptime takes weekday name and returns tm_mday = 1 regardless of actual mday


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

D = B.C
x = D()
isinstance(x, B.C)

rawDescription: getting the class path or name space of a class in python even if it is nested

description: Getting the class path or name space of a class in python even if it is nested


code:
action = gtk.Action("ExamplePy",
        _("Clear document"),
        _("Clear the document"), None)
action.connect("activate", self.on_open_regex_dialog)
action_group = gtk.ActionGroup("ExamplePyPluginActions")
action_group.add_action(action)

rawDescription: How to add keyboard shortcuts / accelerator keys for a menu item created by a Gedit plugin

description: Add keyboard shortcuts / accelerator keys for a menu item created by a Gedit plugin


rawDescription: "Josephus-problm" using list in python

description: "Josephus-problm" using list in python


code: error: 'cannot set using a list-like indexer with a different length than the value'

rawDescription: Store numpy array in multiples cells of pandas dataframe (Python)


code:
from random import randrange

def sattoloCycle(items):
    i = len(items)
    while i > 1:
        i = i - 1
        j = randrange(i)  # 0 <= j <= i-1
        items[j], items[i] = items[i], items[j]
    return

rawDescription: Instead of continue, rerun function

description: Instead of continue, rerun function


code:
def doSomething():
    x = int (raw_input ("How many students will be entered? "))
    for count in range (x):
      name = raw_input ("What is your name? ")
      major = raw_input ("What is your major? ")
      year = raw_input ("and your year? ")
      print (name, major, year)

rawDescription: How to ask user for loop amount

description: Ask user for loop amount


code: previous.iloc[0] = 0

rawDescription: Pandas create time series from day counts


code:
##################################################
# file: EchoServer_types.py
#
# schema types generated by
#  "ZSI.generate.wsdl2python.WriteServiceModule"
#
##################################################

import ZSI
import ZSI.TCcompound
from ZSI.schema import (LocalElementDeclaration, ElementDeclaration,
                        TypeDefinition, GTD, GED)
from ZSI.generate.pyclass import pyclass_type

##############################
# targetNamespace
# urn:ZSI
##############################

class ns0:
    targetNamespace = "urn:ZSI"

    class Echo_Dec(ZSI.TCcompound.ComplexType, ElementDeclaration):
        literal = "Echo"
        schema = "urn:ZSI"
        def __init__(self, **kw):
            ns = ns0.Echo_Dec.schema
            TClist = [ZSI.TC.AnyType(pname=(ns,"value"),
                      aname="_value", minOccurs=1, maxOccurs=1,
                      nillable=False, typed=False,
                      encoded=kw.get("encoded"))]
            kw["pname"] = ("urn:ZSI","Echo")
            kw["aname"] = "_Echo"
            self.attribute_typecode_dict = {}
            ZSI.TCcompound.ComplexType.__init__(self,None,TClist,
                                                inorder=0,**kw)
            class Holder:
                __metaclass__ = pyclass_type
                typecode = self
                def __init__(self):
                    # pyclass
                    self._value = None
                    return
            Holder.__name__ = "Echo_Holder"
            self.pyclass = Holder

# end class ns0 (tns: urn:ZSI)

rawDescription: Are there any working examples of Zolera SOAP Infrastructure (ZSI)?


code:
import collections

sentence = "No, I shouldn't be glad, YOU should be glad."

d = collections.defaultdict(list)
words = sentence.split()
for k, v in zip(words[:-1], words[1:]):
   d[k].append(v)
print(d)

rawDescription: change sentence into dictionary in Python

description: Change sentence into dictionary in Python


rawDescription: [Python EVE]: Reading the request parameters values in Python EVE


code:
import csv
import datetime
import copy
from collections import defaultdict

with open(r"C:\Temp\test.csv") as i, open(r"C:\Temp\resuls.csv", "wb") as o:
    rdr = csv.reader(i)
    wrt = csv.writer(o)

    data, currdate = defaultdict(lambda:[0, 0, 0, 0]), None
    for line in rdr:
        date, name = datetime.datetime.strptime(line[0], '%d/%m/%Y'), line[7]

        if date != currdate or not currdate:
            for v in data.itervalues(): v[:2] = v[2:]
            currdate = date

        wrt.writerow(line + data[name][:2])

        data[name][3] += 1
        if line[6] == "1": data[name][2] += 1

rawDescription: Calculating number of occurrences and entering and appending them to csv


code:
test = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O"]

for i in reversed(test):
    if i not in ["C","D"]:
        test.remove(i)

print(test)

rawDescription: How can I loop through a list of strings?

description: Loop through a list of strings


code:
import matplotlib.pyplot as plt
import numpy as np
Bias=5;

x = np.linspace(-20, 20, 1000);
y = np.abs(np.sin(x))
y = y + Bias

plt.plot(x, y)
plt.grid()
plt.show()

rawDescription: How to bias an absolute sine wave in Python

description: Bias an absolute sine wave in Python


code:
from types import GeneratorType

def yield_next_two(seq):
    if not isinstance(seq, GeneratorType):
        for i in range(0, len(seq), 2):
            yield seq[i:i+2]
    else:
        while True:
            item1 = next(seq)
            try:
                item2 = next(seq)
                yield [item1, item2]
            except StopIteration:
                yield [item1]

pair_generator = yield_next_two(original)

quad_generator = yield_next_two(yield_next_two(original))

next(pair_generator)

next(quad_generator)

rawDescription: create sublists within sublists in python

description: Create sublists within sublists in python


rawDescription: Python3 input() floats list

description: Python3 input() floats list


code:
class Viewer:
    def save_image(self, image):
        # save to temporary file, and return filename
        return image._dump(format=self.get_format(image))
    def show_image(self, image, **options):
        # display given image
        return self.show_file(self.save_image(image), **options)
    def show_file(self, file, **options):
        # display given file
        os.system(self.get_command(file, **options))
        return 1

rawDescription: How to display an animated gif with Linux?

description: Display an animated gif with Linux


code: "%e" % n if n and log10(abs(n)) < -5 else ("%f" % n).rstrip("0")

rawDescription: Python float formatting - like "g", but with more digits


rawDescription: Python 3 string formatting with filler more than one character long


code:
class MessageListModel(QtGui.QStandardItemModel):
    def __init__(self, parent=None, *args):
        QtGui.QStandardItemModel.__init__(self, parent, *args)

    def data(self, index, role):
        if not index.isValid():
            return QtCore.QVariant()
        elif role != QtCore.Qt.DisplayRole:
            if role == QtCore.Qt.BackgroundRole:
                status = index.data(QtCore.Qt.UserRole)
                if status == True:
                    return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
                elif status == False:
                    return QtCore.QVariant(QtGui.QColor(QtCore.Qt.red))
        return QtGui.QStandardItemModel.data(self, index, role)

    def addItem(self, label, value):
        item = QtGui.QStandardItem(label)
        item.setEditable(False)
        item.setData(value, QtCore.Qt.UserRole)
        item.setData(0, QtCore.Qt.UserRole + 1)
        item.setDropEnabled(False)
        self.appendRow(item)

rawDescription: Message displaying in QListWidget/View on boolean condition


code:
def num_distinct_rows(M):
    return len(np.unique(asvoid(M)))

rawDescription: Speed up counting number of distinct columns


code:
import subprocess
process1 = subprocess.Popen(["ls", "-l"])
process2 = subprocess.Popen(["ls", "-l"])

rawDescription: How to interact with a Terminal in python

description: Interact with a Terminal in python


code:
from lxml.etree  import fromstring, HTMLParser

xml = fromstring(_html, HTMLParser())

a_tags = xml.xpath("//table[@id='yfncsumtab']//a")

paired = dict((a.xpath(".//text()")[0].strip(), a.xpath("./@href")[0]) for a in a_tags)
from pprint import pprint as pp
pp(paired)

rawDescription: Python: searching through html file grabbing <a> tags with the href and text content


rawDescription: how to decode and encode web page with python?

description: Decode and encode web page with python


rawDescription: Extracting Data From Python Classes

description: Extracting Data From Python Classes


rawDescription: Python: transform a list of lists of tuples


code:
for item in lst:
   do_something_to(item)
do_something_extra_special_to_last(lst[-1])

rawDescription: Iterate through Python list and do something on last element


code:
import random

df[random.sample(df.columns, 2)] * z

rawDescription: python: multiplication of array to pandas dataframe

description: Python: multiplication of array to pandas dataframe


code:
# coding: utf-8
import csv
D = {'name':u'马克','pinyin':u'mǎkè'}
f = open('out.csv','wb')
f.write(u'\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)
w = csv.DictWriter(f,sorted(D.keys()))
w.writeheader()
w.writerow({k:v.encode('utf8') for k,v in D.items()})
f.close()

rawDescription: Python DictWriter writing UTF-8 encoded CSV files


code:
class A(object):
  event = threading.Event()  # class variable, like yours
  def getEvent(self): return self.event

a = A()
a.getEvent()
a.getEvent().is_set()
b = A()
b.getEvent().set()
a.getEvent().is_set()
b.getEvent()

rawDescription: SOLVED: Custom Python Thread Pool Synchrnoization


code: fn(x, y)

rawDescription: Select a function in a Pythonic way

description: Select a function in a Pythonic way


code:
for vals in processed.values():
    vals.sort()
    current = 1
    while current < len(vals):
      if vals[current-1][1] > vals[current][0]:
        # current and previous ranges overlap, so merge previous and current values.
        vals[current-1:current+1] = [(vals[current-1][0], vals[current][1])]
        # Because we reduced the number of values in the list by 1,
        # current now points at the next interesting value.
      else:
        current += 1 # We didn't merge, so we must increment current

rawDescription: Python - Overlapping Ranges - Determine unique positions


code: [v for val, num in zip(df1.File, df1.Repeated) for v in [val]*num]

rawDescription: Python Pandas multiple occruences of a row in dataframe 1 into new column of dataframe 2


code:
from Bio import Entrez
seq = Entrez.efetch(db="nuccore",
                    id="229564415",
                    rettype="fasta",
                    seq_start=70731,
                    seq_stop=70780).readlines()

rawDescription: How do I extract a sequence from a genome based on homologues with a sequence?

description: Extract a sequence from a genome based on homologues with a sequence


code:
for p in itertools.product(*words):
    print("".join(p))

rawDescription: Python: How to produce only in sequence combinations from a list of string parts, with use being optional


code:
import csv
import os

f = open('csvpatpos.csv')

# open temp .csv file for output
out = open('csvtemp.csv','w')

csv_f = csv.reader(f)
for row in csv_f:
    # create a temporary list for this row
    temp_row = []

    # iterate through all of the items in the row
    for item in row:
        # add the zero filled value of each temporary item to the list
        temp_row.append(item.zfill(4))
    # join the current temporary list with commas and write it to the out file
    out.write(','.join(temp_row) + '\n')
out.close()
f.close()

rawDescription: python: adding a zero if my value is less then 3 digits long

description: Python: adding a zero if my value is less then 3 digits long


code:
import requests
from bs4 import BeautifulSoup as Soup

page = "http://www.zillow.com/homedetails/1630-Amalfi-Dr-Pacific-Palisades-CA-90272/20546602_zpid/"
response = requests.get(page)
soup = Soup(response.text,"lxml")
metas = soup.select("meta")

rawDescription: Unable to retrieve element of desired XPATH using BeautifulSoup


code: return True, a, b

rawDescription: Python return true - false and value

description: Python return true - false and value


code:
def walkPDFfiles(directory):
    for dirpath, dirs, files in os.walk(directory):
        for fname in files:
            name, ext = os.path.splitext(fname)
            if ext.lower() == '.pdf':
                yield os.path.join(dirpath, fname)

rawDescription: How to distinguish a PDF file from other files?

description: Distinguish a PDF file from other files


code: s = df['m'].replace({'March':0, 'April':1, 'Dec':3})

rawDescription: Custom sorting in pandas dataframe

description: Custom sorting in pandas dataframe


code:
s = ''
ord(s)
len(s)

rawDescription: python's string is unicode characters

description: Python's string is unicode characters


code:
for num,arr in generate_arrangements(data):
    print(num)
    print(arr)

rawDescription: Unpack a given number of items in Python?


code:
from multiprocessing.pool import ThreadPool
pool = ThreadPool(20)  # However many you wish to run in parallel

rawDescription: Speed up Python script's for loop

description: Speed up Python script's for loop


code: new_thing = Mything(**{"THISFIELD": "ABCD", "THATFIELD": 123, THIRDFIELD: "TEXT"})

rawDescription: Create class instance with unknown number of attributes


code:
root.title('Stopwatch') # set window title
root.geometry('400x300') # set window size
root.columnconfigure(0, weight=1) # children widgets may fill the whole space
root.rowconfigure(0, weight=1)
font.nametofont('TkDefaultFont').configure(size=25) # change default font size

rawDescription: How do you use a button as an input in python

description: Use a button as an input in python


rawDescription: Deleting files associated with model - django


code:
class ShareObject:
    def __init__(self):
        self.mutex = threading.Lock()
        self.data = None

    def get(self):
        with self.mutex: # with unlocks the mutex even if there is an error or return
            return self.data

    def set(self, data):
        with self.mutex:
            self.data = data

    # more methods

rawDescription: Using RLock inside shared object

description: Using RLock inside shared object


code:
titles = ['New', 'New']
ids = ['123', '123']
{'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]}

rawDescription: How do I make a JSON file out of a list in Python?

description: Make a JSON file out of a list in Python


code: original_ret_value, your_mobilityhelper = wifi.add(h1)

rawDescription: How to add a variable of a method of a class in aonther program in python?

description: Add a variable of a method of a class in aonther program in python


code: sum(c.BJValue() for c in hand)

rawDescription: How to approach implementing 'class Card' as required by Python textbook

description: Approach implementing 'class Card' as required by Python textbook


rawDescription: How to recursively add 1 to number 1000000 times without recursion limit change?

description: Recursively add 1 to number 1000000 times without recursion limit change


code:
from collections import defaultdict
import re

numbers = defaultdict(int)
with open('/path/to/textfile.txt') as f:
    for line in f:
        line = re.sub(r'\d+', '', line.rstrip())  # Remove numbers.
        numbers[line] += 1  # Increment number for the same line
        print('{}{}'.format(line, numbers[line]))

rawDescription: python managing redundant data by incrementing no. in a text file

description: Python managing redundant data by incrementing no. in a text file


rawDescription: How to create a new df.column based on 2+ conditions in Pandas without iteration?

description: Create a new df.column based on 2+ conditions in Pandas without iteration


code:
def split_list(l, sep):
    current = []
    for x in l:
        if x == sep:
            yield current
            current = []
        else:
            current.append(x)
    yield current

rawDescription: Splitting a list in python

description: Splitting a list in python


code:
def words(stream, start=-1): # you could replace the -1 with 0 and remove the +1
    for i in range(start+1): # it depend on whether you start counting with 0 or 1
        try:
            stream.next()
        except StopIteration:
            break
    for line in stream:
        yield line[:max(line.find(' '), 0) or None]

rawDescription: Python: read one word per line of a text file


code: (A.ravel()[:,None] == B.ravel()).any()

rawDescription: Check if 2 arrays have at least one element in common?


code:
g_unstacked = g.unstack()
g_unstacked

rawDescription: Pandas DataFrame.unstack() Changes Order of Row and Column Headers


code: next((i for i,d in enumerate(foo) if 'key4' in d), 'not found')

rawDescription: Find index in a list of dictionaries

description: Find index in a list of dictionaries


code: list(set(d))

rawDescription: element that appear more that once in the list in Python

description: Element that appear more that once in the list in Python


rawDescription: Beginner advice on how to use FTP or SSH? (django)


code:
items = [('this', 5, 'cm'), ('that', 3, 'mm'), ('other', 15, 'mm')]

found_items = [list(item) for item in items]

for i in range(len(found_items)):
    print (found_items[i])

new_value = int(input ("Enter new value: "))

for i in range(len(found_items)):
    recalculated_item = new_value * found_items[i][1]
    print (recalculated_item)

rawDescription: python 3 read array (list?) into new values

description: Python 3 read array (list?) into new values


code: refine(nfactor, Q.is_true(Abs(periodic_argument(1/polar_lift(s)**2, oo)) <= pi/2))

rawDescription: Simplify conditional integrals in SymPy

description: Simplify conditional integrals in SymPy


code:
result = [processing_funcs(subdata)[None,...] for subdata in input_data]
result = np.concatenate(result, axis=0)

rawDescription: Numpy matrices - how to handle arbitrary size


code:
seg5s=["| Spade |", "|♠♠♠♠♠♠♠|"]
seg5h=["| Heart |", "|♥♥♥♥♥♥♥|"]
seg5c=["| Clubs |", "|♣♣♣♣♣♣♣|"]
seg5d=["|Diamond|", "|♦♦♦♦♦♦♦|"]

rawDescription: Card generator game printing in a column, not a row


rawDescription: Bitwise operations on .ix (Pandas)

description: Bitwise operations on .ix (Pandas)


code:
link = doc.xpath('.//ul[@class = "myclass"]/li/a/@href')
txt= doc.xpath('.//ul[@class = "myclass"]/li/a/text()')

rawDescription: Get bulletted list in lxml

description: Get bulletted list in lxml


code:
from string import ascii_letters
ascii_letters
'123abdjihdkffyifbgh'.rstrip(ascii_letters)

rawDescription: Is there an elegant way to strip all alphabetic characters from the end of a string?


code:
from kivy.app import App
from kivy.uix.image import Image

class MyImage(Image):
    frame_counter = 0
    frame_number = 2 # my example GIF had 2 frames

    def on_texture(self, instance, value):
        if self.frame_counter == self.frame_number + 1:
            self._coreimage.anim_reset(False)
        self.frame_counter += 1

class MyApp(App):
    def build(self):
        return MyImage(source = "test.gif")

if __name__ == '__main__':
    MyApp().run()

rawDescription: Kivy Gif animation runs too often

description: Kivy Gif animation runs too often


code:
with  open("Anilinks.txt", "w") as f:
    for link in subtitles:
        x = link.find_all('a', limit=26)
        for a in x:
            if 'solidfiles.com' in a['href']:
                url = a['href']
                f.write(url+'\n')

rawDescription: Keep only certain lines in a text file using python


code:
while True: #infinite loop
   ipt = raw_input(' Enter a number: ')
   try:
      ipt = int(ipt)
      break  #got an integer -- break from this infinite loop.
   except ValueError:  #uh-oh, didn't get an integer, better try again.
      print ("integers are numbers ... didn't you know? Try again ...")

rawDescription: How to verify numbers in input with python?

description: Verify numbers in input with python


code:
with open('Database.txt') as f:
    print(json.load(f)['123'])

rawDescription: How to read a dictionary from a file in Python 2.7?

description: Read a dictionary from a file in Python 2.7


code: header = ['col_name1', 'col_name2', ... ]

rawDescription: Write a simple list into a new CSV file

description: Write a simple list into a new CSV file


code: filter(lambda x: x[1]>1 ,Counter(reduce(lambda x,y: x+y,map (lambda x : x.split("."),calls))).most_common())

rawDescription: Python finding most common pattern in list of strings


rawDescription: Create a matrix out of an array

description: Create a matrix out of an array


code:
# Py3 data conversions to bytes, for convenience
if comments is not None:
    comments = asbytes(comments)
if isinstance(delimiter, unicode):
    delimiter = asbytes(delimiter)
if isinstance(missing, unicode):
    missing = asbytes(missing)
if isinstance(missing_values, (unicode, list, tuple)):
    missing_values = asbytes_nested(missing_values)

rawDescription: Not understood behavior of Numpy genfromtxt


code:
r[keep]
xi[keep]

rawDescription: Applying conditions to python lists

description: Applying conditions to python lists


code:
class Rectangle:
    def __init__(self, height, width):
        self.height = height
        self.width = width

    def flipped(self):
        return Rectangle(self.width, self.height)

    def __repr__(self):
        return 'Rectangle({}, {})'.format(self.height, self.width)

rectangles = [Rectangle(1, 10), Rectangle(2, 20), Rectangle(3, 30)]

rawDescription: Python list of objects, get all 'orientations' of attributes


code: big_df = pd.concat([df for df in dictDF.itervalues()], ignore_index=True)

rawDescription: Pandas: Dict of data frames to unbalanced Panel


rawDescription: matplotlib problems plotting logged data and setting its x/y bounds

description: Matplotlib problems plotting logged data and setting its x/y bounds


code:
def three_consec (string, character):
    return (character * 3) in string

rawDescription: trying to find if a character appears successively in a string

description: Trying to find if a character appears successively in a string


code:
df.loc[df.Change != 1, ['A', 'B', 'C']] = numpy.nan
df
df.ffill()

rawDescription: Pandas DataFrame Repeat Value Based on a Condition


code: df.groupby(["TICKET_NUMBER", "ITEM"], sort=False, as_index=False)["TICKET_ROW"].first()

rawDescription: Pandas: filter unique values in groups

description: Pandas: filter unique values in groups


code:
import numpy as np

a = [0,0,0,0,0,0,1,1,2,1,0,0,0,0,1,0,1,2,1,0,2,3]

# Find indexes of all zeroes
index_zeroes = np.where(np.array(a) == 0)[0]

# Find discontinuities in indexes, denoting separated groups of zeroes
# Note: Adding True at the end because otherwise the last zero is ignored
index_zeroes_disc = np.where(np.hstack((np.diff(index_zeroes) != 1, True)))[0]

# Count the number of zeroes in each group
# Note: Adding 0 at the start so first group of zeroes is counted
count_zeroes = np.diff(np.hstack((0, index_zeroes_disc + 1)))

# Count the number of groups with the same number of zeroes
groups_of_n_zeroes = {}
for count in count_zeroes:
    if groups_of_n_zeroes.has_key(count):
        groups_of_n_zeroes[count] += 1
    else:
        groups_of_n_zeroes[count] = 1

rawDescription: Counting same elements in an array and create dictionary


code:
chars = u'\u4132'.encode('utf-16be')
chars
ord(chars[0])
'%x' % ord(chars[0])
hex(ord(chars[0]))
['%x' % ord(c) for c in chars]
[hex(ord(c)) for c in chars]

rawDescription: getting bytes from unicode string in python

description: Getting bytes from unicode string in python


code:
import re
string = "string.isnotimportant"
regex = '\w*(\W+)\w*' # the brackets in the regex mean that item, if matched will be stored as a group
x = re.search(regex, string)
x.groups() #remember the stored group above? well this accesses that group.
string = string.replace('.', '')
string += x.groups()[0] # here I basically append a letter to the end of string

rawDescription: How to find a non-alphanumeric character and move it to the end of a string in Python

description: Find a non-alphanumeric character and move it to the end of a string in Python


code:
with open('sequences.fasta') as fasta_file:  # Will close handle cleanly
    identifiers = []
    lengths = []
    for seq_record in SeqIO.parse(fasta_file, 'fasta'):  # (generator)
        identifiers.append(seq_record.id)
        lengths.append(len(seq_record.seq))

rawDescription: Biopython SeqIO to Pandas Dataframe

description: Biopython SeqIO to Pandas Dataframe


code: list_select_related = True

rawDescription: Access data from a related class in Django


code: my_dict = dict(zip(some_list_a, some_list_b))

rawDescription: Is it possible to create a dictionary inside a function using python?


code:
class TranslationInline(admin.TabularInline):
    model = Translation
    readonly_fields = ['language']

    def get_max_num(self, *args, **kwargs):
        return Language.objects.all().count()

    def get_min_num(self, *args, **kwargs):
        return self.get_max_num(*args, **kwargs)

    def get_initial(self, request):
        return [
            {'language': l}
            for l in Language.objects.exclude(pk__in=self.get_queryset(request))
        ]

@admin.register(Word)
class WordAdmin(admin.ModelAdmin):
    inlines = [TranslationInline]

    def _create_formsets(self, request, obj, change):
        formsets = []
        inline_instances = []
        prefixes = {}
        get_formsets_args = [request]
        if change:
            get_formsets_args.append(obj)
        for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args):
            prefix = FormSet.get_default_prefix()
            prefixes[prefix] = prefixes.get(prefix, 0) + 1
            if prefixes[prefix] != 1 or not prefix:
                prefix = "%s-%s" % (prefix, prefixes[prefix])
            formset_params = {
                'instance': obj,
                'prefix': prefix,
                'queryset': inline.get_queryset(request),
            }
            if hasattr(inline, 'get_initial'):
                formset_params['initial'] = inline.get_initial(request)
            if request.method == 'POST':
                formset_params.update({
                    'data': request.POST,
                    'files': request.FILES,
                    'save_as_new': '_saveasnew' in request.POST
                })
            formsets.append(FormSet(**formset_params))
            inline_instances.append(inline)
        return formsets, inline_instances

rawDescription: How can I use all objects in a table as a label - input in a model in Django's Admin?

description: Use all objects in a table as a label - input in a model in Django's Admin


rawDescription: Appending to a Series dynamically

description: Appending to a Series dynamically


rawDescription: Python: Combining two strings and selecting unique elements out of it


code:
if len(word_one) == len(word_two):
    return sum(c!=d for c,d in zip(word_one, word_two)) == 1
return False   # optional - often None will do instead

rawDescription: Comparing characters in a string

description: Comparing characters in a string


code:
class CalculateUserBannedMiddleware(object):

    def process_request(self, request):
        request.user_banned = HellBanList.objects.filter(condemned_id=request.user.id).exists()

rawDescription: How to pass self object to Global variable (Django views)

description: Pass self object to Global variable (Django views)


code: max(a, z - d) <= x <= min(b,z - c)

rawDescription: Sum of 2 elements from 2 ranges that will be one given number


code:
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'MyWidget.ui'
#
# Created: Fri Dec 28 03:45:13 2012
#      by: PyQt4 UI code generator 4.7.3
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(147, 125)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.lineEdit = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit.setObjectName("lineEdit")
        self.verticalLayout.addWidget(self.lineEdit)
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.verticalLayout.addWidget(self.pushButton)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 147, 25))
        self.menubar.setObjectName("menubar")
        self.menuMenu = QtGui.QMenu(self.menubar)
        self.menuMenu.setObjectName("menuMenu")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuMenu.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "Click Me", None, QtGui.QApplication.UnicodeUTF8))
        self.menuMenu.setTitle(QtGui.QApplication.translate("MainWindow", "Menu", None, QtGui.QApplication.UnicodeUTF8))

rawDescription: How to save a form from Qt Designer as a standalone app?

description: Save a form from Qt Designer as a standalone app


rawDescription: How to turn this simple 5 bytes back into 4 bytes ? (algorithm to convert 4 bytes into 5 bytes is known)

description: Turn this simple 5 bytes back into 4 bytes ? (algorithm to convert 4 bytes into 5 bytes is known)


rawDescription: stacking 2D matrix using Python

description: Stacking 2D matrix using Python


code:
unqID,idx,IDsums = np.unique(ID,return_counts=True,return_inverse=True)

value_sums = np.bincount(idx,value.ravel())

rawDescription: Summing data from array based on other array in Numpy


rawDescription: Joining ndarrays in Python where indices are floats and only approximately equal


code: any((c in badChars) for c in yourString)

rawDescription: Find which lines in a file contain certain characters


code:
import networkx as nx
G = nx.Graph()
G.add_edge(1,2,color='red')
G.edges(data=True)
G.add_edge(1,2,color='blue')
G.edges(data=True)
G[1][2]
G[1][2]['color']='green'
G.edges(data=True)

rawDescription: Add new attribute to an edge in networkx


code:
#!/usr/bin/env python
from __future__ import division
from datetime import datetime, timedelta

def to_millis(utc_time, epoch=datetime(1970,1,1)):
    td = utc_time - epoch
    assert td.resolution >= timedelta(microseconds=1)
    # return td.total_seconds()*1000 analog
    return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**3

rawDescription: Equivalent of date.utc in python

description: Equivalent of date.utc in python


code: multiprocessing.map(apply,[(f,1) for f in functions])

rawDescription: Multiprocessing pool 'apply_async' only seems to call function once


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

# Generate some data...
x, y = np.mgrid[:141, :101]
z = np.cos(np.hypot(x, y))

# Plot the figure...
plt.pcolormesh(x, y, z, cmap=mpl.cm.Reds)

# Set the ticks and labels...
ticks = np.arange(x.min(), x.max(), 6)
labels = range(ticks.size)
plt.xticks(ticks, labels)
plt.xlabel('Hours')

plt.show()

rawDescription: Customize x-axis in matplotlib

description: Customize x-axis in matplotlib


code: re.search(r'Schedule \(1\)(.*?)\(2\)', data, flags=re.DOTALL).group(1)

rawDescription: Returning characters after regex has found match in python


code:
while True:
    GPIO.wait_for_edge(23, GPIO.RISING)
    GPIO.output(26, True)
    GPIO.wait_for_edge(23, GPIO.FALLING)
    GPIO.output(26, False)

rawDescription: How to code a through-beam sensor to detect LED using a Raspberry Pi?

description: Code a through-beam sensor to detect LED using a Raspberry Pi


code:
from itertools import count
c = count()
all(i < 10 for i in c)
next(c)

rawDescription: Implementing .all() for a list of booleans?


code:
from functools import partial
r = partial(runfile,"filename")
#now you can just type r()
r()

rawDescription: Easier way to run Python program in Pdev console without typing commands?


code: newton(func, x0=0, fprime=deriv, tol=1e-12)

rawDescription: Finding zeros of a complex function in SciPy/NumPy


code:
import re
s = 'score:0.86|taxid:9606(Human)|intact:EBI-999900'
re.search(r'taxid:(\d+)', s).group(1)

rawDescription: python regular expression substitute

description: Python regular expression substitute


code: self.button = Button(frame, text="Enter", command=self.reveal)

rawDescription: Tkinter widgets not appearing

description: Tkinter widgets not appearing


code:
from collections import defaultdict
l = [('a',1),('b',2),('a',3)]
d = defaultdict(list)
for pair in l:
    d[pair[0]].append(pair[1]) #add each number in to the list with under the correct key
for (k,v) in d.items():
    d[k] = sum(d[k])/len(d[k]) #re-assign the value associated with key k as the sum of the elements in the list divided by its length

rawDescription: converting list to dict and averaging the values of duplicates in python

description: Converting list to dict and averaging the values of duplicates in python


code:
import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()

requires = ['pyramid', 'WebError']

setup(name='test',
      version='0.0',
      description='test',
      long_description=README + '\n\n' +  CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pylons",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='',
      author_email='',
      url='',
      keywords='web pyramid pylons',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires=requires,
      tests_require=requires,
      test_suite="test",
      entry_points = """\
      [paste.app_factory]
      main = test:main
      """,
      paster_plugins=['pyramid'],
      )

rawDescription: best tool for building python distro with dependencies/resources

description: Best tool for building python distro with dependencies/resources


code:
from PyQt4 import QtGui
from PyQt4 import QtCore
import sys

def main():
    app     = QtGui.QApplication(sys.argv)
    tabs    = QtGui.QTabWidget()
    tab1    = QtGui.QWidget()
    tab2    = QtGui.QWidget()
    tab3    = QtGui.QWidget()
    tabs.addTab(tab1,"Tab 1")
    tabs.addTab(tab2,"Tab 2")
    tabs.addTab(tab3,"Tab 3")
    tabs.setWindowTitle('PyQt QTabWidget Add Tabs and Widgets Inside Tab')
    tabs.show()

    # This will set "Tab 2" to be shown when the application launches
    tabs.setCurrentIndex(1)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: PyQt - forcing one tab to appear first?

description: PyQt - forcing one tab to appear first


code:
d = {1:2,3:4,5:6}
for key,value in d.iteritems():
    d[key] = value + 1

d

rawDescription: Using FOR IN and dictionaries in PYTHON 2.7


rawDescription: round exponential float to 2 decimals

description: Round exponential float to 2 decimals


rawDescription: collapse a list of ndarray to a matrix

description: Collapse a list of ndarray to a matrix


code:
for path_flag in path_flags:
  if flag == path_flag:
    make_next_absolute = True
    break

  if flag.startswith( path_flag ):
    path = flag[ len( path_flag ): ]
    new_flag = path_flag + os.path.join( working_directory, path )
    break

rawDescription: YCM does not find my headers?

description: YCM does not find my headers


code:
def fun():
    a=[1, 2] #dynamic allocation
    a.append(3)
    return a[0]

rawDescription: I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?


rawDescription: Creating a correlation plot with matplotlib


code:
Output
aaabbbc89

rawDescription: Python - Replace list of characters with another list


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

rawDescription: Pythonic and efficient way to do an elementwise "in" using numpy


code:
value1 = request.GET.get('key1')
value2 = request.GET.get('key2')

rawDescription: Django - dictionary passed in redirect is not showing in template


code:
def rem(iterable):
   result = []
   seen = set()
   for x in iterable:
       if x in seen:
           result.append(x)
       else:
           seen.add(x)
   result.sort()
   return result

rawDescription: Returning a copy of the list in which one instance of every value is removed


code: obj=stack()

rawDescription: python Queue used in the below code

description: Python Queue used in the below code


code:
bounds = (0, 10, 29, 42, 53, 60, 67, 80)
columns = ([line[start:stop].rstrip() for start, stop in zip(bounds, bounds[1:])]
           for line in log.splitlines())
notconnected = (port for port, _, status, _, _, _, _ in columns
                if status == 'notconnected')

rawDescription: Parsing Cisco Output in Python

description: Parsing Cisco Output in Python


code: d

rawDescription: Creating an alternating dictionary with a loop in Python


code:
import logging
logging.basicConfig(level=logging.INFO) # <- in a real application,
                                           # should be set application-wide
                                           # from a config file

logger = logging.getLogger("CSV import")

result = {}
nlines = 0
ok = 0
warnings = 0
with open("my_file.csv") as f:
    f.readline() # Skip header. Assuming only one line of heading

    for row in (line.split() for line in f):
        nlines += 1
        try:
            k1,k2, val = row
            result.setdefault(k1,{})[k2] = val
            ok += 1
        except ValueError:
            logger.warning("Format mismatch: %s", row)
            warnings += 1
            # what to do next?

logger.info("%d lines read. %d imported. %d warnings",nlines,ok,warnings)

from pprint import pprint
pprint(result)

rawDescription: convert csv columns to dictionary in python

description: Convert csv columns to dictionary in python


code:
data = [
    (1,1,3),
    (1,2,2),
    (2,1,2),
    (2,4,1),
]

#import csv
#with open('data.csv') as f:
#    next(f) # Skip header
#    data = [map(int, row) for row in csv.reader(f)]
#    # Python 3.x: map(int, row) -> tuple(map(int, row))

n = max(max(user, item) for user, item, rating in data) # Get size of matrix
matrix = [[0] * n for i in range(n)]

for user, item, rating in data:
    matrix[user-1][item-1] = rating # Convert to 0-based index.

for row in matrix:
    print(row)

rawDescription: Python - convert edge list to adjacency matrix


rawDescription: Plotting function that returns complex values using pyplot