code:
n = 0
def factory():
    global n
    print('Factory called!')
    n += 1
    return n   #returns numbers 1, 2, 3, 4, ...

D = defaultdict(factory)
D[0]
D[0]   # the keys exists, thus the factory is not called.
D[1]
D[1]

rawDescription: How to read python dictionary and tuples

description: Read python dictionary and tuples


rawDescription: Python String Double Splitting?

description: Python String Double Splitting


code:
@app.route('/<path:path>')
def serve_page(path):
    return send_from_directory('client', path)

rawDescription: Serving static html file from another directory from flask restful endpoint


code:
class Photo(models.Model):
    publish_by = models.ForeignKey(User)
    name = models.CharField(max_length=40)
    desc = models.CharField(max_length=40)
    liked_by = models.ManyToManyField(User, related_name="likes")

rawDescription: Django Many-to-Many Relation or One-to-Many relation


code:
from threading import Timer

def giveaway():
    agive = 0
    enteredgiveaway = enteredgiveaway.rstrip()
    enteredgiveaway = enteredgiveaway.split(" ")
    gg = random.choice(enteredgiveaway)
    message("The winner of the giveaway is: " + gg)
    gg = ""
    enteredgiveaway = ""

rawDescription: Stay active while sleeping in Python

description: Stay active while sleeping in Python


rawDescription: Order a list of dictionaries in python

description: Order a list of dictionaries in python


code: H = dot(U, B+C) + 1j*dot(V, B-C)

rawDescription: Constraining the least squares fitting in python


code:
foo = str(foo.strip('"').strip())
safe_arg = '"%s"'%foo
if '"' in foo:
    if (len(shlex.split(safe_arg, False, False)) != 1): ...

rawDescription: Preventing Shell Injection on Windows

description: Preventing Shell Injection on Windows


code: "".join(map(chr, nums))

rawDescription: How to convert numbers into characters?

description: Convert numbers into characters


code: import cPickle as pickle

rawDescription: Saving an Object (Data persistence in Python)


code:
se1=set(x[1] for x in lstup1)
se2=set(x[1] for x in lstup2)
len(se1&se2)

rawDescription: Faster way to count number of matching 2nd elements between two list of tuples? - Python


code:
from bs4 import BeautifulSoup

html = myTargetElementObject.get_attribute("outerHTML")
soup = BeautifulSoup(html, "html.parser")
label = soup.strong
text_after = label.next_sibling

print(label.get_text(), text_after)

rawDescription: Selecting parent element text only using Selenium


code:
import sys

if sys.version_info.major < 3:
    input = raw_input

rawDescription: Printing elements related to information in 'dict'


rawDescription: Append tuple elements to a tuple of tuples in Python


code:
class CopyScope:
    def __init__(self,module):
        own_scope = self.__dict__
        for name,thing in vars(module).items():
            if isinstance(thing,FunctionType):
                setattr(self, name, copy_func(thing, own_scope))
            else:
                setattr(self, name, thing)
                #you could also do own_scope[name] = .. instead of setattr() but I prefer setattr()

rawDescription: Encapsulate the scope of an imported module


rawDescription: Get the column names of a python numpy ndarray


code:
if __name__ == '__main__':
    from threading import Thread
    import time
    import logging

    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(created)d - %(message)s')
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    logger.info("sleep")
    s = Sleep(3)
    logger.info("awake")

    def wake_it(sleeper):
        time.sleep(1)
        logger.info("wakeup!")
        sleeper.wake()

    logger.info("sleeping again")
    s = Sleep(60, immediate=False)
    Thread(target=wake_it, args=[s]).start()
    s.sleep()
    logger.info("awake again")

rawDescription: abortable sleep() in Python

description: Abortable sleep() in Python


code: medications = driver.find_elements_by_xpath("//input[contains(@id, 'Medications']")

rawDescription: Getting value of a class in selenium and python


code:
from math import log10
log10(1000)
log10(9999)

rawDescription: Python: Shorten ugly code?

description: Python: Shorten ugly code


rawDescription: How do I use pandas' rolling_std to consider two columns in its observation?

description: Use pandas' rolling_std to consider two columns in its observation


code:
def scanl(f, base, l):
    for x in l:
        base = f(base, x)
        yield base

rawDescription: Equivalent of Haskell scanl in python

description: Equivalent of Haskell scanl in python


rawDescription: Checking from Python which easy_install version is available?


code:
import csv
dataFile = open('names.csv','rb')
reader = csv.reader(dataFile, delimiter=',', quoting=csv.QUOTE_NONE)

[(row[0][0] + row[1]).lower() for row in reader if
                                      row[0] and row[1]]

rawDescription: (Simple Python) CSV input to usernames

description: (Simple Python) CSV input to usernames


code:
import csv

def try_convert_number(s):
    val = s.replace(',', '')
    try:
        return int(val)
    except ValueError:
        try:
            return float(val)
        except ValueError:
            return s
result = []
# in Python 2 use: with open('file.csv', 'rb') as f:
with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    if you_have_a_header_row:
        next(reader)
    for row in reader:
        result.append(map(try_convert_number, row))

rawDescription: python load csv file with quoted fields where commas are used as 1000s separator

description: Python load csv file with quoted fields where commas are used as 1000s separator


rawDescription: python list of dicts how to merge key:value where values are same?

description: Python list of dicts how to merge key:value where values are same


code:
+cat
-cat
-gophers
-hound
+gopher
+mouse

rawDescription: Compare two files report difference in python


code: cid.Cid2xy(csv_file, '1')

rawDescription: Using CSV file in python to print column


code:
indexed = enumerate(items)

shuffled = sorted(indexed, key=lambda iv: iv[0]+random.choice([-1, 1]))

# Remove the index, extract the values out again
result = [iv[1] for iv in shuffled]

rawDescription: python sort with adjacent difference

description: Python sort with adjacent difference


rawDescription: Python3x - Write a python script to run other python scripts?


code:
class FlaggedDoubleMapper :
    """Flagged Double Mapper"""

    def __init__ ( self, keys = [], vals = [], flags = [] ) :
        """Initializes a flagged double mapper with lists of keys, values and
        flags.
        """

        self._flg = {}     # Flags dictionary
        self._fwd = {}     # Forward dictionary
        self._bwd = {}     # Backward dictionary

        for key, val, flag in zip( keys, vals, flags ) :
            self.add( key, val, flag )

    def __repr__ ( self ) :
        """Representation bidict-style."""

        return 'fdm({})'.format( self._fwd )

    def contains ( self, key, val ) :
        """Returns True if and only if self contains the key-val binding."""

        try :
            return ( self._fwd[ key ] == val )
        except KeyError :
            return False

    def add ( self, key, val, flag ) :
        """Adds a flagged binding, overwriting all corresponding bindings."""

        try :
            _val = self._fwd[ key ]
            del self._bwd[ _val ]
        except KeyError :
            pass

        try :
            _key = self._bwd[ val ]
            del self._flg[ _key ]
            del self._fwd[ _key ]
        except KeyError :
            pass

        self._flg[ key ] = flag
        self._fwd[ key ] = val
        self._bwd[ val ] = key

    def remove ( self, key, *args ) :
        """Removes a binding.
         - remove( key ) will send a KeyError( key ) if no binding with key as a
         forward key is found.
         - remove( key, val ) will send a KeyError( key, val ) if no forward
         key-val binding is found.
        """

        try :
            _val = args[0]
            if ( _val != self._fwd[ key ] ) :   # Can raise a KeyError( key )
                raise KeyError( key, _val )
        except IndexError :
            _val = self._fwd[ key ]             # Can raise a KeyError( key )

        del self._flg[ key ]
        del self._fwd[ key ]
        del self._bwd[ _val ]

    def flag ( self, key, *args ) :
        """Returns the flag of a binding.
         - flag( key ) will send a KeyError( key ) if no binding with key as a
         forward key is found.
         - flag( key, val ) will send a KeyError( key, val ) if no forward
         key-val binding is found.
        """

        try :
            _val = args[0]
            if ( _val != self._fwd[ key ] ) :   # Can raise a KeyError( key )
                raise KeyError( key, _val )
        except IndexError :
            pass

        return self._flg[ key ]

rawDescription: Efficient both ways mapping in Python with flag values


code:
out = find_all(master, namecount)
print('\n'.join(out))

rawDescription: How to replace different blocks of text in all combinations using awk?

description: Replace different blocks of text in all combinations using awk


rawDescription: Python If Statement Never Evaluates to True


code: df.apply(lambda x: '&'.join([str(elem) for elem in x]))

rawDescription: Python, use "order by" inside a "group concat" with pandas DataFrame


rawDescription: Reverse certain rows in N by 2 array

description: Reverse certain rows in N by 2 array


code: max(d)

rawDescription: getting value of the maximum key in dictionary (python)

description: Getting value of the maximum key in dictionary (python)


code:
import quopri

incode = '=?ISO-8859-5?Q?=C0=D5=D5=E1=E2=E0_=BF=DB=D0=E2=D5=D6=D5=D9_?='
inencoding = incode[2:12]  # 'ISO-8859-5'
intext = incode[15:-2]
result = quopri.decodestring(intext).encode(inencoding)

rawDescription: Python decoding from iso-8859-5

description: Python decoding from iso-8859-5


code:
ds = [
    {'a':10, 'b': 0, 'c': 2},
    {'a':7, 'b': 4, 'c': 4},
    {'a':4, 'b': 5, 'c': 3} ]

merged = {}
for d in ds:
    for k, v in d.items ():
        if k not in merged: merged [k] = []
        merged [k].append (v)

print (merged)

rawDescription: List of values for duplicate keys in dictionary Python


code:
idents = set()
with open("identifiers.txt") as ids:
   for line in ids:
       idents.add(line.split()[1])

rawDescription: Finding lines by first value in text file in python


code:
if circle_1.collidepoint(x, y):
    # Lets the circle draw
    filled_1 = True
    width_1 = 0

    filled_2 = False
    filled_3 = False
    filled_4 = False
    width_2 = 2
    width_3 = 2
    width_4 = 2

    if filled_1 == True:
        circle_1 = pygame.draw.circle(screen, BLACK, [250, 230], 7, width_1)

# ... etc ...

rawDescription: pygame circle not changing

description: Pygame circle not changing


code:
sub = D                 # Start with the full dictionary
for i in key_list[:-1]:
    sub = sub[i]        # Move down a level

rawDescription: Dynamically delete an item from a nested dictionary


rawDescription: How to remove a column in a numpy array?

description: Remove a column in a numpy array


rawDescription: Split Sentence on Punctuation or Camel-Case


code:
def room_2():
    global riddle_monster_alive # declares this variable global, so room_2() can change the global value
    riddle_monster_alive = False # makes this variable False everywhere
    ... # continue as before.

rawDescription: How can I call a variable from a function within a different function?

description: Call a variable from a function within a different function


code: [key + ' '.join(values) for key, values in d.items()]

rawDescription: Extract partial duplicates from a list of lists; return single match with record of origin of each duplicate; Python


code:
keys="keys = {"+",".join([str(k) for k in python_dict])+"};"
values="values = {"+",".join([str(python_dict[k]) for k in python_dict])+"};"
fh=open("mfile.m","w")
fh.write("%s\n%s\n" % (keys,values))
fh.write( "c = containers.Map(keys, values);\n")
fh.close()

rawDescription: Retrieve python object with matlab

description: Retrieve python object with matlab


rawDescription: Complex numbers usage in python

description: Complex numbers usage in python


rawDescription: How to convert a list to dict using python

description: Convert a list to dict using python


code: ['Izgleda da novi update za 8 pod nazivom Threshold ce zapravo biti win9.. pa ako nekoga zanima više malo evo vam linka : http://www.pcgamer.com/2014/01/20/wi...ame=0&ns_fee=0\r\ni malo opsirnije o threshold-u http://winsupersite.com/windows-8/th...hip-april-2015', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor Sneaky\n\n\nIzgleda da novi update za 8 pod nazivom Threshold ce zapravo biti win9.. pa ako nekoga zanima više malo evo vam linka : http://www.pcgamer.com/2014/01/20/wi...ame=0&ns_fee=0\r\ni malo opsirnije o threshold-u http://winsupersite.com/windows-8/th...hip-april-2015\n\n\n\nIzgleda da su prihvatili logiku Appla i da stancaju verzije i malo po malo "cokaju", nekako mi se cini logicnije nego svako 5 g izbacivat op OS koji u danasnem svitu androida/iosa/wpa teze prolazi naplatu. Nije da su direktno usporedivi, ali ljudi su drski pa je tesko odvojit vece pare za OS.', 'Ja bi prije rekao da su shvatili da su malo zaj* za Win8, pa da isprave stetu - lakse je izbaciti novu verziju.\nSlicno kao i sa Vistom.', 'Tocno to. Win8 (8.1) je meni osobno isto kao i WinME i Vista. U biti MS napravi svaku drugu generaciju Winsa kvalitetno jer popravlja prethodnu koju za*ere maksimalno sa novim features-ima ', 'Nek oni meni samo refreshaju izgled desktopa sa novim ikonama, explorer elementima i animacijama i ja sam zadovoljan \n\nI da, još bolju cloud i WP9 integraciju.', 'Da, fakat je idiocki izbacivat Service packove, kad možeš pičiti nove OS-ove \n\nKako ono beše:\nWin 2000 - SP4\nWin XP - SP3\nVista - SP2\nWin 7 - SP1\nWin 8 - Win 8.1   ', 'meni više smeta to što još nisu uveli novi filesystem koji se mislim da još od viste obećava, a ne nekakve vizualne gluposti', 'nije se nista obecavalo od viste\r\nono sto je bio WinFS nije bio novi FS nego NTFS + "layer" baze podataka koja je vukla metadata iz fajlova\n\r\nmozes si to sranje i instalirat na xp-u (beta 1) pa vidjet sta je to\n\r\nu svakom slucaju ja preskacem i win9\r\nsumnjam da ce ista novog pridonjeti ako ne i jos gore cim pocne sve vise integracija sranja koje nitko normalan netreba\n\r\nako se nevaram win8 ima strgani nacin loginova (slagalica, face reckognition), nebi se cudio da 9-tka bude samo profinjenija 8-ica\r\nsa popravljenim tim stvarima\r\ncak bi i ReFS mogao vidjeti svjetlost posto ga samo nude na serverima kao test\n\r\nali to su samo minarne stvari, to mene ne zanima :P\r\nak  ce jasit i dalje metro sranja i tviter i assbook integracije i bing pizd***e\r\nonda ostajem na 7-ici ', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor Drug Brko\n\n\nWin 2000 - SP4\n\n\n\nSa zadnjim rollupom, skoro 5, ali uzmi da je NT 4 imao 6+1 komada, tako da ti je tablica dobra. ', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor Bubba\n\n\nSa zadnjim rollupom, skoro 5, ali uzmi da je NT 4 imao 6+1 komada, tako da ti je tablica dobra. \n\n\n\nMa znam da je bio rollup za win2000, sjećam se da sam 2005 slipstreamao cd sa tim updateom, al nije SP. \nXP SP3 nakon instalacije OS-a ima još oko 1GB updateova sa neta, Win 7 isto. Vjerojatno i vista \nSad će bit za win 8.1 bit 100 MB i odma će doći win 9 ', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor Drug Brko\n\n\nMa znam da je bio rollup za win2000, sjećam se da sam 2005 slipstreamao cd sa tim updateom, al nije SP.\n\n\n\nnije SP jer oni nisu htjeli da bude SP\r\njer kad izbace SP onda moraju produljiti rok podrske OS-a\n\r\nzato XP i nece imati SP4 iako ima tonu patcheva nakon SP3-a\r\nkao sto i vista nece dobit SP3 a win "7" SP2\n\r\nsvaki SP ih kosta minimalno novih 3 godina podrske sto se neuklapa u njihovu ideju\r\nsvake 2 godine novi OS\n\r\nzasto bi davali besplatne SP-ove kad mogu u istom roku naplacivati novi OS', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor Baja 001\n\n\nIzgleda da su prihvatili logiku Appla i da stancaju verzije i malo po malo "cokaju", nekako mi se cini logicnije nego svako 5 g izbacivat op OS koji u danasnem svitu androida/iosa/wpa teze prolazi naplatu. Nije da su direktno usporedivi, ali ljudi su drski pa je tesko odvojit vece pare za OS.\n\n\n\nS druge strane, Appleovi updateovi se više ne naplaćuju. Prvo su smanjili cijenu, a 10.9 je besplatan. Dovoljno je kupit hardware.', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor IcyTexx\n\n\nS druge strane, Appleovi updateovi se više ne naplaćuju. Prvo su smanjili cijenu, a 10.9 je besplatan. Dovoljno je kupit hardware.\n\n\n\nNaplati se kroz hw, ali svakako idu na taj mobilni trend izbacivanja.', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor IcyTexx\n\n\nS druge strane, Appleovi updateovi se više ne naplaćuju. Prvo su smanjili cijenu, a 10.9 je besplatan. Dovoljno je kupit hardware.\n\n\n\nS druge strane appleovi updateovi su smeće. To ti kažem s punom odgovornošću kao dugogodišnji profesionalni korisnik (FCP7 itd.). Trenutno imamo predzadnju generaciju njihovih Mac Pro 6 jezgrenih đubradi i nakon upgrejda na Mavericse sve je ošlo u tri pm. Popis je predugačak...a imaš dovoljno o tome i na netu.\n\n\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor Baja 001\n\n\nNaplati se kroz hw, ali svakako idu na taj mobilni trend izbacivanja.\n\n\n\nTako je. Dovoljno je baciti oko na cjenik.', 'Zato kažem dovoljno je kupit hardware... U Americi su im laptopi pojeftinili. Kad ću ići sad u 5. mj u Ameriku opet ću kupit jednog jer sam im voljan dati taj price premium. Prije dvije godine sam im dao više radi kvalitete izrade, a kroz korištenje sad bi im dao više radi OS-a. Vise ne naplaćuju ni svoj "Office" software. Gledao sam i u PC svijetu ne mogu naći zamjenu njihovom 15" MBP Retina. Barem po mojim kriterijima. Ako netko nadje "retina" laptop od 15" koji je jednako debeo kao i MBPR, da je metalan, a ne plastican, sa mu jednako ili duže traje baterija, istih ili jačih specifikacija sa PCIE storageom za iste ili manje pare skidam mu kapu. A od Windowsovih DPI postavki mi bude zlo.\n\nS druge strane, Windows 8 kosta $120. A on je cvijeće, ha? Osnovni Office $130. Evo čekam u redu da im iskeširam pare...\n\nNo neću sad ulazit u to budući da je ovo MS tema, samo ce se krenut ljutit ljudi.\n\n@gnujko vjerujem ti, mene nije zahvatilo bas puno problema kod Mavericksa, a isto nisam "običan" korisnik. Budem pogledao o kakvim se problemima tu radi.', 'moguce je da windows 8.2 ne bude 8.2 nego windows 9\nali nadam se da ce poboljsat i destop i metro u isto vrijeme jer dosta stvari koje na destopu imas nema u metrou sto bi stvarno koristilo pogotovo samo za RT verziju kao npr explorer\n\nali budemo vidjeli, brat mi je bio na mvp summitu i nisu puno govorili o novim windowsima', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor Metlina\n\n\ni nisu puno govorili o novim windowsima\n\n\n\nzato sto ih jos nisu ni poceli "raditi"\r\nsad se jos uvjek fokusiraju na ovo: http://wzascok.livejournal.com/12774.html', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor Metlina\n\n\nmoguce je da windows 8.2 ne bude 8.2 nego windows 9\nali nadam se da ce poboljsat i destop i metro u isto vrijeme jer dosta stvari koje na destopu imas nema u metrou sto bi stvarno koristilo pogotovo samo za RT verziju kao npr explorer\n\nali budemo vidjeli, brat mi je bio na mvp summitu i nisu puno govorili o novim windowsima\n\n\n\n100% ne bude bilo Win8.2, ide se na Threshold (Windows 9).\n\nImaš Metro verziju File Managera, SkyDrive (OneDrive).\n\nMVP-ovi su pod NDA pa nit ne smiju pričati o takvim stvarima \n\nEDIT: I Threshold je počeo sa developmentom.', 'http://youtu.be/VF4Eva_4UNE', '\n\r\nnije 9 nego 10 \n\r\nslike i tekst http://thenextweb.com/microsoft/2014...es-windows-10/\n\r\nstižu sredinom 2015.', 'Jednostavno smo priznali da smo zajebali ', 'Tema bi se trebala preimenovat u Windows 10 ', '\n\n\n\n\nvolio bih zamijeniti sedmicu, vidjet ćemo sada hoću li ', 'Odlicno, taman dovoljno dugo dok ne izguram ove w7 sa zaobilazenjem w8  \n\n90-tih sam furo windows 3.1 pa nesto jako malo W95 a koristio  W98, WNT tj. W2000 smo isto zaobisli pa WXP, SP1 i SP2 a SP3 i W Vistu isto debelo zaobisao. \n\nMislim da mi je windows vista najgore legla od svih ti windowsa.\nE sad ostaje nada da ce ovi w10 biti na razini w7...', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor mamutarka\n\n\nhttp://youtu.be/VF4Eva_4UNE\n\n\n\nNe kuzim, kao, ovo je neki "novi" super feature?\n\r\nOpen/CreateWindowsStation() i Create/SwitchDesktop() su funkcije podrzane u Windows API-ju jos od Windowsa 2000, dakle, cijelih 14 godina, rekli bi smo - old news.\n\r\nDrugim rijecima, svaki nemusti programer je mogao napraviti ovo bez nekih vecih problema i poteskoca, sto i jesu radili jer ovakvi programcici postoje "oduvijek".\n\r\nNadam se da ipak imaju u planu neki novi ozbiljniji feature, tipa WinFS ili stogod drugo, jer ovo je smijesno i za pokazivati, a kamo li stavljati kao novi ficur novih Windowsa... :\\', 'http://youtu.be/84NI5fjTfpQ', 'http://blogs.windows.com/bloggingwin...ng-windows-10/', 'mergao dvije teme, windows 9 i windows 10 u jednu...\nOvdje će izaći tech preview:\nhttp://windows.microsoft.com/hr-hr/w...ew-coming-soon', 'Čim vidim ono tablet sučelje, imam osjećaj da neću mjenjat sedmicu još ohoho', '\nCitiraj:\n\n\n\n\r\n\t\t\t\t\tAutor ivan77\n\n\nČim vidim ono tablet sučelje, imam osjećaj da neću mjenjat sedmicu još ohoho\n\n\n\nBezveze si skeptičan, meni se na kraju i svidio metro. Pogotovo što imaš aplikacije iz store-a koje su prilično zanimljive, od nogometnih rezultata preko tečajne liste do aplikacije koja streama svjetske televizije tipa BBC bez da ti treba proxy, hola i slično.']

rawDescription: Parsing forum posts with python3 and beautiful soup


code:
import json
d = [1, 2, 3, 4]
json_str = json.dumps(d) # json_str = "[1, 2, 3, 4]"

rawDescription: JSON and AJAX with Python

description: JSON and AJAX with Python


code:
class AdvancedGenerator(SimpleGenerator):
    @classmethod
    def get_description(cls):
        desc = super(AdvancedGenerator, cls).get_description()
        return desc + ' Advanced(tm)'

AdvancedGenerator.get_description()

rawDescription: How to call a parent class's @classmethod from an overridden @classmethod in Python?

description: Call a parent class's @classmethod from an overridden @classmethod in Python


code:
def get_barcode_rotated(value, width, barWidth = 0.05 * units.inch, fontSize = 30, humanReadable = True):

    barcode = createBarcodeDrawing('Code128', value = value, barWidth = barWidth, fontSize = fontSize, humanReadable = humanReadable)

    drawing_width = width
    barcode_scale = drawing_width / barcode.width
    drawing_height = barcode.height * barcode_scale

    drawing = Drawing(drawing_width, drawing_height)
    drawing.scale(barcode_scale, barcode_scale)
    drawing.add(barcode, name='barcode')

    drawing_rotated = Drawing(drawing_height, drawing_width)
    drawing_rotated.rotate(90)
    drawing_rotated.translate(0, -drawing_height)
    drawing_rotated.add(drawing, name='drawing')

    return drawing_rotated

rawDescription: Code128 Barcode as HTML Image Tag with Data URI Scheme in Python


code:
from lxml import html
doc = html.document_fromstring('
Hello
world!
')

for br in doc.xpath("*//br"):
    br.tail = " " + br.tail if br.tail else " "

doc.text_content()

rawDescription: Adding spaces on word boundaries in text extraction with lxml


code:
for d in range(1, n - 1):
    print(c + ' ' * (m - 2) + c)

rawDescription: Printing a frame in python

description: Printing a frame in python


code:
def flatten(lst):
    for x in lst:
        if isinstance(x, str):
            yield x
        else:
            for y in flatten(x):
                yield y

rawDescription: Python - Convert array with list with different sizes to string


code:
import itertools as it
import re

def find_columns(lines, pat = r' '):
    '''
    Usage:
    widths = find_columns(lines)
    for line in lines:
        if not line: continue
        vals = [ line[widths[i]:widths[i+1]].strip() for i in range(len(widths)-1) ]
    '''
    widths = []
    maxlen = max(len(line) for line in lines)
    for line in lines:
        line = ''.join([line, ' '*(maxlen-len(line))])
        candidates = []
        for match in re.finditer(pat, line):
            candidates.extend(range(match.start(), match.end()+1))
        widths.append(set(candidates))
    widths = sorted(set.intersection(*widths))
    diffs = [widths[i+1]-widths[i] for i in range(len(widths)-1)]
    diffs = [None]+diffs
    widths = [w for d, w in zip(diffs, widths) if d != 1]
    if widths[0] != 0: widths = [0]+widths
    return widths

def report(text):
    for key, group in it.groupby(text.splitlines(), lambda line:line.startswith('ID')):
        lines = list(group)
        if key:
            print('\n'.join(lines))
        else:
            # r' (?![a-zA-Z])' defines a column to be any whitespace
            # not followed by alphabetic characters.
            widths = find_columns(lines, pat = r'\s(?![a-zA-Z])')
            for line in lines:
                if not line: continue
                vals = [ line[widths[i]:widths[i+1]] for i in range(len(widths)-1) ]
                vals = [v if v.strip() else v[1:]+'0' for v in vals]
                print('|'.join(vals))

text = """\
ID = 1234

Hello World              135,343    117,668    81,228
Another line of text    (30,632)              (48,063)
More text                  0         11,205       0
Even more text                       1,447       681

ID = 18372

Another table                        35,323              38,302      909,381
Another line with text                 13                  15
More text here                                              7           0
Even more text here                   7,011               1,447        681
"""

report(text)

rawDescription: How can I replace blank entries in a text table with 0 in Python?

description: Replace blank entries in a text table with 0 in Python


code:
def read_file(polyfilename):
    with open(polyfilename) as f:
        return Polynomial(*[[int(x) for x in line.split()] for line in f])

rawDescription: creating class instances from a text file in python

description: Creating class instances from a text file in python


code: eq = Eq(eq.lhs/phi(t).diff(t), eq.rhs/phi(t).diff(t))

rawDescription: Sympy: solve a differential equation

description: Sympy: solve a differential equation


code: datas = soup.findAll(match_either)

rawDescription: Issue with designing function for data scraping using BS4


rawDescription: How to efficiently create a SparseDataFrame from a long table?

description: Efficiently create a SparseDataFrame from a long table


code: user_language = getattr(__import__('localizable.%s' % language), language)

rawDescription: Import by file/module name in GAE

description: Import by file/module name in GAE


code:
from rx import Observable
xs = Observable.range(1, 10)
q = xs.where(lambda x: x % 2 == 0).select(lambda x: -x)
q.subscribe(print)

rawDescription: How to use Reactive Extensions (Rx) LINQ in Python?

description: Use Reactive Extensions (Rx) LINQ in Python


code:
x = 10000 #or whatever number
QtCore.QTimer.singleShot(10000 + x, lambda: self.Box.append("Text3"))

rawDescription: Python, PySide sleep without stalling the whole program?


code:
Flags: 0
Start: 0
End: 1
MaxCount: 1

rawDescription: Optional arguments in Python Script for Notepad++


rawDescription: Adding multiple values to an existing dictionary as SETS


code: any(substring in string for substring in substring_list)

rawDescription: Python: How to check a string for substrings from a list?


code: rm -f /var/lib/mylink

rawDescription: distutils setup.py and %post %postun

description: Distutils setup.py and %post %postun


code:
buy_ratio = (abs(df["Buy"])  > abs(df["Sell"])) * df["Price"] / df["Buy"]
sell_ratio = (abs(df["Buy"])  <= abs(df["Sell"])) * df["Price"] / df["Sell"]
df["Ratio"] = buy_ratio + sell_ratio

rawDescription: Pandas Dataframe row by row fill new column


code:
def foo(x):
    return x[0] + x[1] ** 2

rawDescription: A performance concern when using minimizing a two-parameter function with scipy


code:
#! /usr/bin/env python3
# https://en.wikipedia.org/wiki/Newton's_method
import sys

def formula(*array):
    calculate = lambda x: sum(c * x ** p for p, c in enumerate(array))
    calculate.coefficients = array
    return calculate

def derivative(function):
    return (p * c for p, c in enumerate(function.coefficients[1:], 1))

x0 = 1
f = formula(-2, 0, 1)
fprime = formula(*derivative(f))
tolerance = 1e-10
epsilon = sys.float_info.epsilon
maxIterations = 20

for i in range(maxIterations):
    denominator = fprime(x0)
    if abs(denominator) < epsilon:
        print('WARNING: Denominator is too small')
        break
    newtonX = x0 - f(x0) / denominator
    if abs(newtonX - x0) < tolerance:
        print('The root is', newtonX)
        break
    x0 = newtonX
else:
    print('WARNING: Not able to find solution within the desired tolerance of', tolerance)
    print('The last computed approximate root was', newtonX)

rawDescription: Given f, is there an automatic way to calculate fprime for Newton's method?


code:
vector = [0] * len(characteristics) # initialize all zero, correct length
for k in observation["characteristics"]:
    if  k in chardict:
        vector[ chardict[k]] = 1

rawDescription: Efficient way of marking which elements of a smaller list are in a larger list (Python)


code:
def auto_instantiator(*args, **kwargs):
    def decorator(cls):
        return cls(*args, **kwargs)
    return decorator

rawDescription: Anonymous Inner Class in Python

description: Anonymous Inner Class in Python


code: idx["url"][url_node["url"]] = url_node

rawDescription: Indexing nodes in neo4j in python

description: Indexing nodes in neo4j in python


code: os.system('echo "%s" | hadoop fs -put - /path/to/file/in/hdfs.txt' %(json.dump(json_string)))

rawDescription: Save JSON to HDFS using python

description: Save JSON to HDFS using python


code:
geoConstraint
fred

rawDescription: How do I use the GeometryConstraint class?

description: Use the GeometryConstraint class


code:
def staff_users_only(function):
  def wrap(request, *args, **kwargs):

        profile = request.session['user_profile']
        if profile is True: #then its a staff member
             return function(request, *args, **kwargs)
        else:
            return HttpResponseRedirect('/')

  wrap.__doc__=function.__doc__
  wrap.__name__=function.__name__
  return wrap

rawDescription: How to test that a view is only accessed by staff users in Django

description: Test that a view is only accessed by staff users in Django


code:
comment = '#' + restOfline
validLine.ignore(comment)

rawDescription: Verify CSV against given format

description: Verify CSV against given format


code:
from itertools import cycle
slices = cycle((slice(1, None), slice(None, -1)))
[int(s[c]) for s, c in zip(qtyList, slices)]

rawDescription: Splitting or pulling only integers in an array - python


rawDescription: Looking for the fastest way to find the exact overlap between two arrays of equal length in numpy


code:
def email_sort_key(email):
    """Find two pieces of info in the email, and return them as a tuple."""
    # ...search, search...
    return "location", "incident_date"

rawDescription: Sort list of strings by substring using Python


code:
def find_max_gmtime_timestamp():
    ts = 1
    overflow = GmtimeOverflowTable()
    assert overflow[float('+inf')] and not overflow[ts]
    while not overflow[ts]:
        ts *= 2
    ts = binary_search(overflow, BOUNDARY, ts//2, ts)
    max_ts = ts - 1
    assert overflow[max_ts+1] and not overflow[max_ts]
    return max_ts

rawDescription: Get the highest possible gmtime for any architecture


code:
for i in range(nrows//2): #loop through the first half of rows
    the_matrix.append([space]*ncols) # the default row
    idx1,idx2 = i , ncols - 1 - i  #left and right indexes
    the_matrix[-1][idx1] = the_matrix[-1][idx2] = mark #set our indices

rawDescription: Drawing an X in a 2D array - Python

description: Drawing an X in a 2D array - Python


code:
import numpy as np
input_a = 3
input_b = np.array([1,2,3,4,5])

input_b[input_b > input_a] = input_a

print(input_b)
# [1 2 3 3 3]

rawDescription: Getting the minimum from elements of a Numpy array and a float


rawDescription: what is the efficient way to work with matrix in numpy

description: What is the efficient way to work with matrix in numpy


code:
s = slice(3, 3, None)
it = iter(xrange(s.start or 0, s.stop or 200, s.step or 1))
next(it)

rawDescription: Why is the Python version of itertools.islice not working?


code:
def search(L, val):
    answer = []
    for i, sub in enumerate(L):
        for j,num in enumerate(sub):
            if num==val:
                answer.append([i,j])
    return answer

rawDescription: Print Location of Value within a list of lists Python


code:
for i,j in zip(parts1, parts2):
    plt.plot([i.index[0], j.index[-1]], [i.values[0,1], j.values[-1,1]])
plt.show()

rawDescription: Pandas plotting lines from different columns ignoring values


code:
dic['canada']['population'] = '150M+'
mutate_dic(dic, 'canada', 'population', '150+')

rawDescription: python, how to update the dictionaries by mutating its format?

description: Python, how to update the dictionaries by mutating its format


code: tkFont.Font(..., size=-height)

rawDescription: How to derive the font size from a height constraint?

description: Derive the font size from a height constraint


code:
class GuideFormUpdateView(UpdateView):
    model = Guide
    form_class = forms.GuideForm
    template_name_suffix = '_update_form'
    success_url = reverse_lazy('Guides')

rawDescription: How to make django crispy form to hide a particular field?

description: Make django crispy form to hide a particular field


code: x = subprocess.Popen(['echo', '$$']); x.wait()

rawDescription: Issues with subprocess.Popen() replacing os.system()


code:
class TheClass:
    def __init__():
         self.variable = 0

    def method(self):
        if self.variable == 9:
            #do these things
             self.variable = 0
        elif self.variable > 9:
            self.variable += 1
            #do these things until its time to
            #do the other stuff

rawDescription: in Python Is there ever a good time to use a global variable inside a class?

description: In Python Is there ever a good time to use a global variable inside a class


code:
def get_Windows_name():
    import subprocess, re
    o = subprocess.Popen('systeminfo', stdout=subprocess.PIPE).communicate()[0]
    try: o = str(o, "latin-1")  # Python 3+
    except: pass
    return re.search("OS Name:\s*(.*)", o).group(1).strip()

print(get_Windows_name())

rawDescription: How to determine Windows Edition in Python with using Squish QT?

description: Determine Windows Edition in Python with using Squish QT


code:
class foo:
    index = BatesNumber()

    def __init__(self, ttu):
        self.id = next(index)
        self.next_update = ttu
        self.ttu = ttu

    def __lt__(self, other):
        return (self.next_update, self.id) < (other.next_update, other.id)

    # ideally you'd also write __eq__, __gt__, etc. methods, but heapq only needs __lt__

    def update(self):
        self.next_update += self.ttu
        # maybe do other update stuff here?

rawDescription: Vectorising a decrement operation on a list of objects


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

A = np.random.random((20,20))
B = np.random.random((20,20))

array_1 = A/B    # A and B are 2 arrays, same shape etc ..

fig1 = plt.figure()
ax1  = plt.subplot(121)
fig_step1 = ax1.imshow(array_1, interpolation='nearest')
fig1.colorbar(fig_step1,ax=ax1)
ax1.set_xlabel("X (arcmin)")
ax1.set_ylabel("Y (arcmin)")
ax1.set_title("Without limits")

ax2  = plt.subplot(122)
fig_step2 = ax2.imshow(array_1, interpolation='nearest', vmin=0, vmax=1)
fig1.colorbar(fig_step2, ax=ax2)
ax2.set_xlabel("X (arcmin)")
ax2.set_ylabel("Y (arcmin)")
ax2.set_title("With limits")

rawDescription: Set the colorbar in function of data

description: Set the colorbar in function of data


code:
class Participant(models.Model):
    user = models.ForeignKey(User)
    score = models.IntegerField()

    def get_score_above_below(self, n):
        try:
            above = Participant.filter(score__lt=self.score).order_by('-score')[:n]
        except ObjectDoesNotExist:
            above = Participant.filter(score__lt=self.score).order_by('-score')
        try:
            below = Participant.filter(score__gt=self.score).order_by('-score')[:n]
        except ObjectDoesNotExist:
            below = Participant.filter(score__gt=self.score).order_by('-score')

        entries = list(above) + [self] + list(below)
        return [(part.user, part.score) for part in entries]

rawDescription: Django Get Range in Queryset

description: Django Get Range in Queryset


code:
document = '''
Build 110

Feb-25				Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States
cpupm keyword mode extensions - PSARC/2008/777
 CPU Deep Idle Keyword - PSARC/2008/663

'''
fix_urls(document,"http://www.opensolaris.org/os/community/on/flag-days/all/")

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

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


code:
def generate_all_factorizations(factors):
    seen = set()
    res = []
    for f in _generate_all_factorizations(factors):
        f = tuple(sorted(f))
        if f in seen:
            continue
        seen.add(f)
        yield f

rawDescription: Algorithm to find ALL factorizations of an integer


code:
df1
df2

rawDescription: Fill a Pandas dataframe using information from another Pandas dataframe


code:
class C:
    foo = []

a = C()
b = C()
c = C()

a.foo = ['hello']
b.foo.append('world')

print(C.foo) # ['world']

print(a.foo) # ['hello']
print(b.foo) # ['world']
print(c.foo) # ['world']

rawDescription: How are Python Class attributes different from PHP static class properties?


code:
class A(object):
    def __init__(self, x, y):
        self.xy = [x, y]

    @property
    def pos(self):
        return self.xy

    @pos.setter
    def pos(self, xy):
        self.xy = xy

    @property
    def x(self):
        return self.xy[0]

    @x.setter
    def x(self, x):
        self.xy[0] = x

    @property
    def y(self):
        return self.xy[1]

    @y.setter
    def y(self, y):
        self.xy[1] = y

rawDescription: properties that are lists, assigning to index

description: Properties that are lists, assigning to index


code:
import requests  # Install `requests` if you want to use my example code

session = requests.session()  # So your cookies persist across requests
response = session.post('your_url', data={
    'q': 'search string'
}).text

rawDescription: Programmatically login a Python web crawler


code:
for x in range(4):
    for y in range(4):
        entryList[x][y].after(300,lambda x=x,y=y : changebg(x,y))

rawDescription: Python: change entry colour dynamically with Tkinter


code: items_dict = {x: to_string_and_select(x) for x in we_need_this}

rawDescription: list comprehension with some equal action python

description: List comprehension with some equal action python


code:
import numpy as np
def is_prime(n):
    if n < 2:
        return True
    for i in np.arange(2, n-1):
        if (n%i) == 0:
            return False
    return True

def select_and_sum(group):
    n = len(group)
    r = range(n)
    primes = [j for j in r if is_prime(j) == True]
    return group.iloc[primes].sum()

s.groupby(level=0).apply(select_and_sum)

rawDescription: Filter by rank of one index level in Pandas?


rawDescription: How to set bin content in a hist2d (matplotlib)

description: Set bin content in a hist2d (matplotlib)


code: spend_cols = ['spend_30day', 'spend_90day', 'spend_365day']

rawDescription: Applying similar functions across multiple columns in python/pandas


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

rawDescription: create mask of non-nan matrix intersections

description: Create mask of non-nan matrix intersections


code:
# canvas will be a surface that captures the entirety of the "action"
canvas = pygame.Surface((800, 600))
# the following are your "camera" objects
# right now they are taking up discrete and even portions of the canvas,
# but the idea is that they can move and possibly cover overlapping sections
# of the canvas
p1_camera = pygame.Rect(0,0,400,300)
p2_camera = pygame.Rect(400,0,400,300)
p3_camera = pygame.Rect(0,300,400,300)
p4_camera = pygame.Rect(400,300,400,300)

rawDescription: how to create a 4-way split screen in pygame

description: Create a 4-way split screen in pygame


code:
import argparse

def call_command(name, *args, **options):
    """
    Calls the given command, with the given options and args/kwargs.
    standalone simulation of django.core.mangement call_command
    """
    command = name
    """
    ....
    """
    # Simulate argument parsing to get the option defaults (see #10080 for details).
    parser = command.create_parser('', name)
    if command.use_argparse:
        # Use the `dest` option name from the parser option
        opt_mapping = {sorted(s_opt.option_strings)[0].lstrip('-').replace('-', '_'): s_opt.dest
                       for s_opt in parser._actions if s_opt.option_strings}
        arg_options = {opt_mapping.get(key, key): value for key, value in options.items()}
        defaults = parser.parse_args(args=args)
        defaults = dict(defaults._get_kwargs(), **arg_options)
        # Move positional args out of options to mimic legacy optparse
        args = defaults.pop('args', ())
    else:
        # Legacy optparse method
        defaults, _ = parser.parse_args(args=[])
        defaults = dict(defaults.__dict__, **options)
    if 'skip_checks' not in options:
        defaults['skip_checks'] = True

    return command.execute(*args, **defaults)

class BaseCommand():
    def __init__(self):
        self.use_argparse = True
        self.stdout= sys.stdout
        self.stderr=sys.stderr
    def execute(self, *args, **kwargs):
        self.handle(*args, **kwargs)
    def handle(self, *args, **kwargs):
        print('args: ', args)
        print('kwargs: ', kwargs)
    def create_parser(self, *args, **kwargs):
        parser = argparse.ArgumentParser()
        self.add_arguments(parser)
        return parser
    def add_arguments(self, parser):
        parser.add_argument('--type', required=True)
        parser.add_argument('--update', action='store_true')
        parser.add_argument('--optional', default='default')
        parser.add_argument('foo')
        parser.add_argument('args', nargs='*')

if __name__=='__main__':

    testcmd = BaseCommand()
    # testcmd.execute('one','tow', three='four')

    call_command(testcmd, '--type','typevalue','foovalue', 'argsvalue', update=True)

    args = ['--type=argvalue', 'foovalue', '1', '2']
    kwargs = {
        'solr_url': 'http://127.0.0.1...',
        'type': 'opinions',
        'update': True,
        'everything': True,
    }
    call_command(testcmd, *args, **kwargs)

rawDescription: call_command argument is required

description: Call_command argument is required


code:
{'state': 'Alabama', 'other_value': 3}
{'state': 'Alaska', 'other_value': 2}

rawDescription: How do I make a dictionary from a Python counter with the right keys?

description: Make a dictionary from a Python counter with the right keys


rawDescription: In Django I have a complex query where I need only the unique values through a foreign key, is this possible?


code:
from subprocess import Popen, PIPE

cat_proc = '/usr/bin/cat'

consumers = (Popen([cat_proc], stdin = PIPE, stdout = open('consumer1', 'w')),
             Popen([cat_proc], stdin = PIPE, stdout = open('consumer2', 'w')),
             Popen([cat_proc], stdin = PIPE, stdout = open('consumer3', 'w'))
)

producer = Popen([cat_proc, 'inputfile'], stdout = PIPE)

while True:
    byte = producer.stdout.read(1024)
    if not byte: break
    for consumer in consumers:
        consumer.stdin.write(byte)

rawDescription: Multiple processes reading from the same pipe asynchronously


code:
def group_details(request, group_id):
    group = get_object_or_404(Group, pk=group_id)
    return render_to_response('group_details.html',
                              {'group': group})

rawDescription: How do I access the properties of a many-to-many "through" table from a django template?

description: Access the properties of a many-to-many "through" table from a django template


code:
y.strip("'")
y.strip("'") in x

rawDescription: Finding if string is substring of some string in python: a special case


code: res = 'something_tag' in your_tag

rawDescription: Python, how to compare substrings?

description: Python, how to compare substrings


code: print([line.split() for line in [' '.join(group) for group in data]])

rawDescription: Split element in string into segments

description: Split element in string into segments


code: aud = dict((tuple(a[:3]), i) for i, a in enumerate(A))

rawDescription: python union of 2 nested lists with index

description: Python union of 2 nested lists with index


code:
class ilist(list):
    def __init__(self,r=list(),dft=None):
        list.__init__(self,r)
        self.dft=dft
    def __getitem__(self, n):
        while len(self) <= n:
            self.append(self.dft)
        return super(ilist, self).__getitem__(n)

il = ilist()
il[3]
il
il[2] = 5
il
il[2]

rawDescription: Is there a simple way to override the list object's method __getitem__?


code:
from itertools import groupby
lst.sort(key=lambda x: x[3])
d = {}
for x, y in groupby(lst, key=lambda x: x[3]):
    y = list(y)
    d[len(y)] = y

print(d)

rawDescription: Finding occurence in list of lists

description: Finding occurence in list of lists


code:
from bs4 import Comment

def allnext(comment):
    curr = comment
    while True:
        curr = curr.next_sibling
        if isinstance(curr, Comment):
            return
        yield curr

rawDescription: Split html document in pieces parsing html comments with BeautifulSoup


rawDescription: Is a Python function stored as an object?


code:
sexpression = [dummyfunction,1,2,3]
sexpression[0](*sexpression[1:])

rawDescription: getting string representation of function from a list having function name and arguments

description: Getting string representation of function from a list having function name and arguments


code:
#!/usr/bin/env python3
import wave

with wave.open('ecg.wav') as wavfile, open('ecg.mit16', 'wb') as output_file:
    assert wavfile.getnchannels() == 1 # mono
    assert wavfile.getsampwidth() == 2 # 16bit
    output_file.writelines(iter(lambda: wavfile.readframes(4096), b''))

rawDescription: Floating point to 16 bit Twos Complement Binary, Python


code: item['stats']['championsKilled']

rawDescription: How to read data from Json in Python

description: Read data from Json in Python


rawDescription: Python: Difference between 'global' & globals().update(var)


code: subprocess.call([cmd1, cmd2], cwd=path)

rawDescription: Need to make Subprocess communication better


rawDescription: Pattern for multiplicity in python

description: Pattern for multiplicity in python


code:
d = {'mykey': 'myval'}
my_strings = ['key1_key2_key3', 'key54_key6_key85_key86',
              'key1_key2_key3', 'key1_key2',
              'key54_key6_key85_key86', 'key103_key508_key2',
              ]
master_d = {}

for path in my_strings:
    tmp = master_d
    for key in path.split('_'):
        tmp = tmp.setdefault(key, {})
    tmp.setdefault('my_list', []).append(d)

from pprint import pprint
pprint(master_d)

rawDescription: How do I append to the correct deeply-nested list?

description: Append to the correct deeply-nested list


code: db = type("DB", (Transformation, DB), {})(arg1, arg2, ...)

rawDescription: Is it possible to emulate Scala's traits in Python?


code:
import numpy as np
n = 5
g = my_func()
for i in range(n):
    with open('test{}.txt'.format(i), 'ab') as f:
        np.savetxt(f, g, fmt='%.0f', newline=" ")

rawDescription: How to create and write to multiple files in Python?

description: Create and write to multiple files in Python


rawDescription: Using Django time/date widgets in custom form


code:
def foo():
    'use foo.var here'
    # things

foo.var = 0

rawDescription: how to define a global variable to be used in a function of an imported file?

description: Define a global variable to be used in a function of an imported file


code:
import pandas as pd
import io

text = b"""Start_Location  End_Location    Date
OFFICE          HOME            3-Apr-15
OFFICE          HOME            3-Apr-15
HOME            SHOPPING    3-Apr-15
HOME            SHOPPING    4-Apr-15
HOME            SHOPPING    4-Apr-15
SHOPPING    HOME            5-Apr-15
SHOPPING    HOME            5-Apr-15
HOME            SHOPPING    5-Apr-15"""

locations = ["HOME", "OFFICE", "SHOPPING"]

df = pd.read_csv(io.BytesIO(text), delim_whitespace=True)
g = df.groupby("Start_Location")
for name, df2 in g:
    globals()["df_" + name.lower()] = df2

rawDescription: Create multiple dataframe using for loop in python 2.7


code:
with open("lib_install.log", "w") as pip_log:
    subprocess.Popen(["pip", "show", "pytest"], stdout=pip_log, stderr=pip_log)

current_version = "not installed properly" # This will not necessarily be
                                           # executed after the Popen is done.

rawDescription: Python: with open does not read anything the second time


rawDescription: Python: using Self and adding methods to an object on the fly


code: rows = [['']*5 for i in range(5)]

rawDescription: Why does using multiplication operator on list create list of pointers?


code: df['index'].where(df['X'] == 'A')

rawDescription: find previous max index in data frame with conditional statement

description: Find previous max index in data frame with conditional statement


code: ax.set_xlim( min(your_data) - 10, None )

rawDescription: Add padding between bars and Y-Axis

description: Add padding between bars and Y-Axis


code:
import logging

# ============================================================================

class VehicleCounter(object):
    def __init__(self, shape, divider):
        self.log = logging.getLogger("vehicle_counter")

        self.height, self.width = shape
        self.divider = divider

        self.vehicle_count = 0

    def update_count(self, matches, output_image = None):
        self.log.debug("Updating count using %d matches...", len(matches))

# ============================================================================

rawDescription: Counting Cars OpenCV + Python Issue

description: Counting Cars OpenCV + Python Issue


code: {c: [x[0] for x in g16.nodes(data=True) if x[1]['color'] == c] for c in colors}

rawDescription: creating dictionary containing list values using a comprehension

description: Creating dictionary containing list values using a comprehension


code:
StrLevel = input("Would you like a low, medium, or high random number? ")
if StrLevel == "low":
    intRnumber = "5"
elif StrLevel == "medium":
    intRnumber = "50"
elif StrLevel == "high":
    intRnumber = "500"
else:
    print("Invalid input, please input low, medium, or high!")

rawDescription: invalid syntax, how to fix?

description: Invalid syntax, how to fix


rawDescription: how to work with strings and integers as bit strings in python?

description: Work with strings and integers as bit strings in python


code:
class Folder(models.Model):
    title = models.CharField( max_length=255 )

    @property
    def latest_10_messages(self):
        # order by id decreasing and get top 10
        return self.message_set.order_by('-id')[:10]

rawDescription: Django ORM, latest items/messages by groups/folders


code:
func1 = print_on_entry(func1)
func2 = print_on_entry(func2)
func3 = print_on_entry(func3)

rawDescription: How to print graph call as tree?

description: Print graph call as tree


rawDescription: Removing Ttk Notebook Tab Dashed Line

description: Removing Ttk Notebook Tab Dashed Line


code:
themap={"one":"1", "two":"2"}
themap["one"]    # evaluates to the string "1"

rawDescription: A map of string replacements in Python2.7


code:
from flask import render_template

@app.route('/path')
@validate_token
def path(token=None):
    return render_template('path.html', token=session['token'])

rawDescription: How to limit one session from any browser for a username in flask?

description: Limit one session from any browser for a username in flask


code:
class WorkflowForm(forms.Form):
    new_user = forms.BooleanField(required=False, initial=True)
    user = ModelChoiceField(queryset=User.objects.all())
    description = forms.CharField(required=False, widget=forms.Textarea)

    def __init__(self, user, *args, **kwargs):
        super(WorkflowForm, self).__init__(*args, **kwargs)
        self.fields['user'].queryset = User.objects.all()
        self.fields['user'].widget.attrs['style'] = 'display:none'
        self.fields['user'].widget.attrs['id'] = 'user_choice'
        self.fields['new_user'].widget.attrs['onclick'] = "javascript:toggleDiv('user_choice');"

rawDescription: Django Forms : disable field if booleanfield is checked


code:
import numpy as np
na = np.arange(10000).reshape((5,2,10,10,10))
new_na = np.reshape(na, (na.shape[0], np.prod(na.shape[1:])))
new_na.shape

rawDescription: Numpy Convert N dimensional array into two dimensional array


code:
class Item(models.Model):
    id    = models.PositiveIntegerField(primary_key=True)
    title = models.TextField()

class Information(models.Model):
    approved           = models.BooleanField(default=False)
    multipurpose_field = models.ForeignKey(Item)

rawDescription: Is it possible to use a PositiveIntegerField as a foreign key in Django?


code: meth = lambda self, key=key: self.__dict__[key]

rawDescription: python scope issue with anonymous lambda in metaclass

description: Python scope issue with anonymous lambda in metaclass


code: start = datetime(today.year, today.month, today.day, tzinfo=tz.tzutc())

rawDescription: Determine start and end time of current day (UTC -> EST -> UTC) ; Python


rawDescription: How can i use multiple lists as arguments in a function and receive them differently?

description: Use multiple lists as arguments in a function and receive them differently


code:
return [Attribute(name=attr['internalname'], value=attr['value'])
        for attr in attributes if attr['internalname'] in attributenames]

rawDescription: Pythonic way using list comprehension

description: Pythonic way using list comprehension


rawDescription: Verify all fields are entered correctly

description: Verify all fields are entered correctly


rawDescription: Filtering statistics from facebook ads api using the python sdk


code:
l1 = itertools.zip_longest(list1, *list2, fillvalue='')

l2 = list(zip(*l1))
l2

rawDescription: Best way to merge a 2d list and a 1d list in Python?

description: Merge a 2d list and a 1d list in Python


code:
gevents_revents = [handler(*args) for handler, args in zip(arg_list, handlers)]
all_gevents, all_revents = zip(*gevents_revents)
self.GameEvents.extend(e for sublist in all_gevents for e in sublist)
self.RealEvents.extend(e for sublist in all_revents for e in sublist)

rawDescription: Gathering multiple multiple lists together


rawDescription: A list of string replacements in Python

description: A list of string replacements in Python


code:
from pylab import *

subplot(121)
imshow(pix)
subplot(122)
imshow(region_pix)
show()

rawDescription: Use Python / PIL or similar to shrink whitespace


code:
images = np.uniques(a['image']) # gets unique values of the column named 'image'
b = np.empty(len(images), dtype = a.dtype)
for i, image in enumerate(images):
    m = a['image'] == image
    b[i] = (image,) + tuple(a[m][n].mean() for n in a.dtype.names[1:])

rawDescription: Calculate mean of elements in array with same "identifier"


code:
next = history.next()
if next is not None:
    stringvar.set(next)

rawDescription: Undo and Redo in an Tkinter Entry widget?


code:
new['action'] = 'buy'
#        date action  price
# 3  20150104    buy     10
# 5  20150106    buy      9

rawDescription: Insert rows according to value of columns in pandas dataframes


code:
def r_string(s1, s2):
    #s1 is string to order
    #s2 string map to follow
    map_ = {s.lower():s.istitle() for s in s2}
    new_string = ''.join([s.upper() if map_[s] else s for s in s1.replace(' ', '')])

    return new_string

print(r_string('string me', 'TrinGsMe'))

rawDescription: Ordering a string based on another string


rawDescription: Can't get selenium click to work on python


code:
import numpy as np
import re

def equations(specie, elements):
    result = []
    for x in specie:
        formula = parse_formula(x)
        result.append(extracting_columns(formula, elements))
    return np.array(result)

def extracting_columns(formula, elements):
    return [formula.get(e, 0) for e in elements]

def parse_formula(formula):
    elts = iter(re.split(r'([A-Z][a-z]*)',formula)[1:])
    return {element:toint(num) for element, num in zip(*[elts]*2)}

def toint(num):
    try:
        return int(num)
    except ValueError:
        return 1

print(equations(['OH', 'CO2','C3O3','H2O3','CO','C3H1'], ['H', 'C', 'O']))

rawDescription: Arrays to Matrix numpy

description: Arrays to Matrix numpy


code:
import pytest
scenarios = [
    [
        # dct
        {'A': 'C', 'R': 'E', 'D': 'A', 'L': 'R', 'C': 'D'},
        # wanted
        "A",
        # expected (result)
        {'A': 'C', 'D': 'A'},
    ],
    [
        # dct
        {'A': 'C', 'R': 'E', 'D': 'A', 'L': 'R', 'C': 'D'},
        # wanted
        "E",
        # expected (result)
        {'R': 'E'},
    ],
    [
        # dct
        {'A': 'C', 'R': 'E', 'D': 'A', 'L': 'R', 'C': 'D'},
        # wanted
        "D",
        # expected (result)
        {'D': 'A', 'C': 'D'},
    ],
    [
        # dct
        {'A': 'C', 'R': 'E', 'D': 'A', 'L': 'R', 'C': 'D'},
        # wanted
        "nothere",
        # expected (result)
        {},
    ],
    [
        # dct
        {'A': 'C', 'R': 'E', 'D': 'A', 'L': 'R', 'C': 'D'},
        # wanted
        "A",
        # expected (result)
        {'A': 'C', 'D': 'A'},
    ],
]

# replace with real implementation
def get_key_or_val_itms(dct, wanted):
    # something comes here
    return result

@pytest.mark.parametrize("scenario", scenarios)
def test_it(scenario):
    dct, wanted, expected = scenario
    assert get_key_or_val_itms(dct, wanted) == expected

rawDescription: Python - using dictionary to count keys and values


code:
render_file = "C:/Where/Ever/Your/Maya_Scene_Files/Are/your_RENDER_file.mb"
cmds.file(rename=render_file)
cmds.file(force=True, save=True, options='v=1;p=17', type='mayaBinary')

import sys
from os import path
from subprocess import Popen

render_project = r"C:/Where/Ever/YourRenderProjectFolder"
renderer_folder = path.split(sys.executable)[0]
renderer_exec_name = "Render"
params = [renderer_exec_name]
params += ['-percentRes', '75']
params += ['-alpha', '0']
params += ['-proj', render_project]
params += ['-r', 'mr']
params += [render_file]
p = Popen(params, cwd=renderer_folder)
stdout, stderr = p.communicate()

rawDescription: use external python script to open maya and run another script inside maya

description: Use external python script to open maya and run another script inside maya


code:
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
from matplotlib.dates import MonthLocator

monthsFmt = DateFormatter("%m '%y")

data = pd.DataFrame(dict(Month = [201101, 201102, 201103, 201104],
                         Value = [5.5, 4.9, 5.1, 6.7]))

datetime_list = [datetime.strptime(str(s), "%Y%m") for s in data['Month']]

ax = plt.subplot(111)
ax.plot_date(datetime_list, data["Value"])
ax.xaxis.set_major_formatter(monthsFmt)

rawDescription: Pyplot line with numerical month labels

description: Pyplot line with numerical month labels


code:
result = groups.agg(
    {(k1, k2): funcs[k1] for k1, k2 in itertools.product(lev1,lev2)})

rawDescription: Aggregate group with multi-level columns


code: 'mv' '*.pdf' 'test.pdf'

rawDescription: Python Command line execution

description: Python Command line execution


code:
from django.db.models import Case, When, IntegerField

Thing.objects.annotate(tag_is_known=Case(
    When(tags__name__in=['foo', 'bar'], then=1),
    default=0,
    output_field=IntegerField()
))

rawDescription: Order a django queryset by ManyToManyField = Value


code:
for c in range(COLS):
    studentInfo = [] # Info per-student
    student =(input("enter student Name: "))
    studentInfo.append(student)

    for r in range (ROWS):
        course=input("Enter course Code: ")
        studentInfo.append(course)
        # ...
        # ...

    number.append(studentInfo)

rawDescription: Python transform current list into 2d

description: Python transform current list into 2d


code:
re.search(r'[ .a-zA-Z]+', 'Miami').group(0)
re.search(r'[ .a-zA-Z]+', 'San Francisco').group(0)
re.search(r'[ .a-zA-Z]+', 'Chi. Cubs').group(0)

rawDescription: Python scraper regex that allows spaces and periods


code:
import itertools as IT
import pandas as pd

chunksize = 10 ** 5
chunks = pd.read_csv(filename, chunksize=chunksize, header=None)
chunks = IT.takewhile(lambda chunk: chunk['B'].iloc[-1] < 10, chunks)
df = pd.concat(chunks)
mask = df['B'] < 10
df = df.loc[mask]

rawDescription: conditional row read of csv in pandas

description: Conditional row read of csv in pandas


code:
def doTheyRhyme ( word1, word2 ):
  # first, we don't want to report 'glue' and 'unglue' as rhyming words
  # those kind of rhymes are LAME
  if word1.find ( word2 ) == len(word1) - len ( word2 ):
      return False
  if word2.find ( word1 ) == len ( word2 ) - len ( word1 ):
      return False

  return word1 in rhyme ( word2, 1 )

rawDescription: Find rhyme using NLTK in Python

description: Find rhyme using NLTK in Python


rawDescription: split csv column entry on space using python

description: Split csv column entry on space using python


code:
from random import random
from multiprocessing import Process
from sys import exit
from time import sleep

def add_something(i):

    # Sleep to simulate the long calculation
    sleep(random() * 30)

    exitcode = i + 1
    print(exitcode)
    exit(exitcode)

def run_my_process():

    # Start up all of the processes
    processes = []
    for i in range(100):
        proc = Process(target=add_something, args=[i])
        processes.append(proc)
        proc.start()

    # Wait for the desired process result
    done = False
    while not done:
        for proc in processes:
            if proc.exitcode == 90:
                done = True
                break

    # Kill any processes that are still running
    for proc in processes:
        if proc.is_alive():
            proc.terminate()

if __name__ == '__main__':
    run_my_process()

rawDescription: Python Multiprocessing help exit on condition


code:
delta = times[i + 1] - times[i]
print ((delta.days * 24 * 60 * 60 + delta.seconds) * 1000 + delta.microseconds / 1000)

rawDescription: Python: Parsing timestamps and calculating time differences in milliseconds


code:
from django.test import TestCase
from sys import modules

current_module = modules[__name__]

def test_pass(self, *args, **kw):
    self.assertEqual(1, 1)

def test_fail(self, *args, **kw):
    self.assertEqual(1, 2)

# Create a hundred ...
for i in xrange(100):
    # ... of a stupid TestCase class that has 1 method that passes if `i` is
    # even and fails if `i` is odd
    klass_name = "Test_%s" % i
    if i % 2:  # Test passes if even
        klass_attrs = {
            'test_something_%s' % i: test_pass
        }
    else:      # Fail if odd
        klass_attrs = {
            'test_something_%s' % i: test_fail
        }
    klass = type(klass_name, (TestCase,), klass_attrs)

    # Set the class as "child" of the current module so that django test runner
    # finds it
    setattr(current_module, klass_name, klass)

# This prevents Nose from seeing them as tests after the loop is over.
test_pass = None
test_fail = None

rawDescription: Run specific Django tests (with django-nose?)


code:
@register.filter(name='show_student')
def show_student(obj, d):
    show = True
    for key, val in d.iteritems():
        if hasattr(obj, key):
            obj_val = getattr(key, obj)
            if obj_val != val:
                show = False
                break
        else:
            show = False
            break
    return show

rawDescription: How can i match values from dictionary in Django template

description: Match values from dictionary in Django template


code:
grade = request.session['grade']
teacher = request.session['teacher']

rawDescription: Sending parameters to view when submitting a form in Django


rawDescription: Weighting values based on variables

description: Weighting values based on variables


code:
if value < 1:
    foo = None
else:
    foo = Test(value)

rawDescription: return something other than the object on creation of object

description: Return something other than the object on creation of object


code:
df = pd.DataFrame(range(5), list('ABCDE'), columns=['a'])
mask = (df.a%2 == 0)
mask
df[mask]
df.loc[mask]
df.iloc[mask]  # Due to this question, this will give a ValueError (in 11.1)

rawDescription: What is the most idiomatic way to index an object with a boolean array in pandas?


code:
def yield_un(l):
    seen = set()
    for i, ele in enumerate(l):
        if ele not in seen:
            yield (i,ele)
        seen.add(ele)

rawDescription: Remove duplicates in python list but remember the index


rawDescription: Collapse mutiple rows of a dataframe into one row - based on a unique key


code:
def isleaf(self):
    """Return True of this is a leaf tree."""
    return self.isexternal()

rawDescription: Trade off between code duplication and performance


code: buf = (c_char * sizeof(f)).from_buffer_copy(f)

rawDescription: How to copy bytes from a ctypes Structure to a buffer created from create_string_buffer

description: Copy bytes from a ctypes Structure to a buffer created from create_string_buffer


code:
# create_admin.py
import os
if "ADMIN_USER" in os.environ and "ADMIN_PASSWORD" in os.environ:
    from django.contrib.auth.models import User
    user=User.objects.create_user(os.environ['ADMIN_USER'], password=os.environ['ADMIN_PASSWORD'])
    user.is_superuser=True
    user.is_staff=True
    user.save()

rawDescription: Heroku app.json set default django admin password


code:
btn = QPushButton()
btn.sizePolicy().horizontalPolicy()
btn.sizePolicy().verticalPolicy()

rawDescription: Automatically ajust QWidget height

description: Automatically ajust QWidget height


code: streetno = {"1":"Sachine Tendulkar", "2":"Dravid", "3":"Sehwag", "4":"Laxman","5":"Kohli"}

rawDescription: Hash Map in Python

description: Hash Map in Python


code: #!/usr/bin/env arch -x86_64 /usr/bin/python2.6

rawDescription: Running python 64 with shebang (#!) on Mac


code:
def get_count_query(self):
    q = Asset.query.join(StatusLabel).filter(StatusLabel.status == 'Deployable', or_(
                                             Asset.assigned_to.isnot(None)),
                                             Asset.deleted_at.is_(None))

    return self.session.query(func.count('*')).select_from(q.subquery())

rawDescription: SQLAlchemy func.count with filter

description: SQLAlchemy func.count with filter


rawDescription: Reshaping a table in python

description: Reshaping a table in python


code:
import xml.etree.cElementTree as etree

tree = etree.parse('input.xml')
for elem in tree.findall('//tag-Name'):
    if elem.text == 'oldName':
        elem.text = 'newName'
# some output options for example
tree.write('output.xml', encoding='utf-8', xml_declaration=True)

rawDescription: Python Manipulate and save XML without third-party libraries


code:
import pandas as pd
from StringIO import StringIO

x = '''
longitude,latitude
degrees_east,degrees_north
-142.842,-1.82
-25.389,39.87
-37.704,27.114
'''

content = StringIO(x.strip())

def read_csv(content):
    columns = next(content).strip().split(',')
    units = next(content).strip().split(',')
    obs = pd.read_table(content, sep=",\s*", header=None)
    obs.columns = ['{c} ({u})'.format(c=col, u=unit)
                   for col, unit in zip(columns, units)]
    return obs

obs = read_csv(content)
print(obs)
#    longitude (degrees_east)  latitude (degrees_north)
# 0                  -142.842                    -1.820
# 1                   -25.389                    39.870
# 2                   -37.704                    27.114
print(obs.dtypes)
# longitude (degrees_east)    float64
# latitude (degrees_north)    float64

rawDescription: Associating units with Pandas DataFrame

description: Associating units with Pandas DataFrame


code: mydict = {line.split()[0]: line.split()[1] for line in myfile}

rawDescription: converting a list of strings into a tuple

description: Converting a list of strings into a tuple


code:
import io
buf = io.StringIO(msg)
buf.readline()
buf.readline()
len(buf.read())

rawDescription: Python readline() from a string?

description: Python readline() from a string


code: print(DT.timedelta(0, 4560))

rawDescription: Difference of two timedelta objects, with timezones


code: plot(stl(dCPI, "periodic"))

rawDescription: Seasonal Adjustment in R or Python

description: Seasonal Adjustment in R or Python


code:
from django.db.models import Sum

class Data(models.Model):
    ...

    # Method used by `get_current_year_sales` and `get_last_year_sales`
    # to stay DRY. Not for use directly in admin.
    def get_year_sales(self, year):
        qs = self.model._default_manager.filter(year=year)
        sales_agg = qs.aggregate(Sum('sales'))
        return sales_agg['sales__sum']

    # Method used by `get_current_quarter_sales` and `get_last_quarter_sales`
    # to stay DRY. Not for use directly in admin.
    def get_quarter_sales(self, year, quarter):
        qs = self.model._default_manager.filter(year=year, quarter=quarter)
        sales_agg = qs.aggregate(Sum('sales'))
        return sales_agg['sales__sum']

    def get_current_year_sales(self):
        return self.get_year_sales(datetime.now().year)
    get_current_year_sales.short_description = 'Sales (Current Year)'

    def get_last_year_sales(self):
        return self.get_year_sales(datetime.now().year-1)
    get_last_year_sales.short_description = 'Sales (Last Year)'

    def get_current_quarter_sales(self):
        # Determine current quarter logic here as `current_quarter`
        # `quarter_year` will likely be same as current year here,
        # but will need to be calculated for previous quarter
        return self.get_quarter_sales(quarter_year, current_quarter)
    get_current_quarter_sales.short_description = 'Sales (Current Quarter)'

    def get_current_quarter_sales(self):
        # Logic here to determine last quarter as `last_quarter`
        # Logic to determine what year last quarter was in as `quarter_year`
        return self.get_quarter_sales(quarter_year, last_quarter)
    get_last_quarter_sales.short_description = 'Sales (Last Quarter)'

rawDescription: Custom columns using Django admin

description: Custom columns using Django admin


code: timeit.timeit("map(template.__mod__, signals)", 'from __main__ import template, signals')

rawDescription: Python, optimizing a list comprehension for string concatenation


rawDescription: Python: why are * and ** faster than / and sqrt()?


code: from module import desired_object

rawDescription: Accessing an object created in another module using python


code:
import re

invalid_escape = re.compile(r'\\([1-3][0-7]{2}|[1-7][0-7]?)')  # octal digits from 1 up to FF
def replace_with_codepoint(match):
    return chr(int(match.group(0)[1:], 8))

def repair(brokenjson):
    return invalid_escape.sub(replace_with_codepoint, brokenjson)

rawDescription: Parsing JSON using Pandas - issue with additional \ escape characters


code:
x = np.random.randn(1000)
y = np.random.randn(1000)+5
plt.hist2d(x, y, bins=40, cmap='hot')
plt.colorbar()

rawDescription: Controlling the Range of a Color Matrix Plot in Matplotlib


code:
a = [1, 2]
b = list(a)
id(a)
id(b)

rawDescription: python function incrementing variable in list for no obvious reason

description: Python function incrementing variable in list for no obvious reason


code: local_maxima(xval, yval)

rawDescription: Finding local maxima of xy data point graph with numpy?


code: ','.join(['"{0}"'.format(item) for item in y])

rawDescription: Python - How do I add the backslash characters when formatting a JSON string?


code: True

rawDescription: Duplicates in a dictionary (Python)

description: Duplicates in a dictionary (Python)


code:
if sys.platform in [ 'win32', 'win64' ] :
    libs = static_resolver(libs)
    libinc += [ r'/mingw/lib' ] # it seems some people require this
    incdir = [ path_join(ffmpegpath, 'include') ]
else:
    incdir = [ path_join(ffmpegpath, 'include'), "/usr/include" , "./include" ]

rawDescription: how do i install pyffmpeg on windows 10

description: Install pyffmpeg on windows 10


code: np.where(fs >= 0.75)[0].size

rawDescription: Want to count the number of values in a column that meet a condition


code:
print(b.base.base is x)
# True

rawDescription: Size of numpy strided array/broadcast array in memory?


code: d.columns = L

rawDescription: Reshaping pandas DataFrame

description: Reshaping pandas DataFrame


code:
lst = [1, 2, 3]
len(set(lst)) != len(lst)
lst = [1, 2, 2]
len(set(lst)) != len(lst)

rawDescription: How to check for duplicates with less time in a list over 9000 elements by python

description: Check for duplicates with less time in a list over 9000 elements by python


rawDescription: How to assign to workers a proxy that requires user name - password and a custom user agent?

description: Assign to workers a proxy that requires user name - password and a custom user agent


code:
import numpy as np
from collections import Counter

nucleotid_bases = ('C', 'A', 'T', 'G', '.')
results = []
checksum = []
with open('datafile.txt') as f:
    for line in f:
        fields = line.split()  # splits by consecutive whitespace, empty records will be purged
        chrom, pos = [int(fields[x]) for x in (0,1)]
        results.append([chrom,pos])  # start by building the current record
        allele1, allele2 = [fields[i] for i in (3,4)]
        checksum.append([allele1, allele2])  # you wanted to keep these, most likely for debugging purposes?
        popA = fields[3:26]  # population size: 2*23
        popB = fields[26:36]  # population size: 2*10
        for population in (popA, popB):
            summary = Counter(population) # traverses the line only once - much more efficient!
            base_counts = [ sum(summary[k] for k in summary.keys() if base in k) for base in nucleotid_bases]
            for index, base_name in enumerate(nucleotid_bases):
                # Double the count when there is an exact match, e.g. "A/A" -> "A"
                # An 'in' match can match an item anywhere in the string: 'A' in 'A/C' evaluates to True
                base_counts[index] += summary[base_name]
            results[-1].extend(base_counts)  # append to the current record
results = np.array(results, dtype=np.float)  # shape is now (x, 12) with x the amount of lines read
results[:, 2:7] /= 46
results[:, 7:] /= 20

rawDescription: How can I assign scores to a list of datapoints and then output values > 2 standard deviations from the mean in python?

description: Assign scores to a list of datapoints and then output values > 2 standard deviations from the mean in python


rawDescription: Compare lists, the order of content within a given column is unimportant


code:
async def foo():
    await asyncio.sleep(1)

rawDescription: How to use async/await in Python 3.5?

description: Use async/await in Python 3.5


code: sum(counts)/len(counts)

rawDescription: Average time a substring occurs

description: Average time a substring occurs


code:
from pyspark.sql.functions import count, col, sum, lit, min, max

# Select only arrival times
arrivals = df.select("arrival_time")

# This is almost identical as before
start = df.agg(min("arrival_time")).first()[0]
end = df.agg(max("arrival_time")).first()[0]

get_key = get_key_(start)
time_range = get_key(end) - get_key(start) + 1.0

# But we'll need offset as well
offset = start - int(start)

# and define a bucket column
bucket = (col("arrival_time") - offset).cast("integer") + offset

line_per_sec = (df
    .groupBy(bucket)
    .agg(count("*").alias("cnt"))
    .agg((sum("cnt") / lit(time_range)).alias("mean")))

line_per_sec.show()

 ## +----+
 ## |mean|
 ## +----+
 ## | 1.8|
 ## +----+

rawDescription: Using Apache-Spark to analyze time series


code:
def use_np_randint(length, num_point):
    return nprandint(1, length, num_points)

rawDescription: sampling integers uniformly efficiently in python using numpy/scipy

description: Sampling integers uniformly efficiently in python using numpy/scipy


code:
import numpy as np
X = iris.data
mask = np.array([True, False, True, True])
X_masked = X[:, mask]

rawDescription: Remove a specific feature in scikit learn


rawDescription: Python Equivalent to Ruby's #each_cons?

description: Python Equivalent to Ruby's #each_cons


code:
def change_colour():
    c = user.get()
    for wid in label_frame.winfo_children():
        wid.configure(bg = c)

rawDescription: How to change the colour of everything in a tkinter GUI at once

description: Change the colour of everything in a tkinter GUI at once


rawDescription: How to select group's rows having the greatest index

description: Select group's rows having the greatest index


code:
import uuid
uuid.uuid4().hex

rawDescription: what is the best way to generate a reset token in python?

description: What is the best way to generate a reset token in python


code:
def parse_summary(self, response):
    # ...

    links = [urljoin(response.url, link) for link in summary_links]
    return self._dispatch_summary_request(item, links)

def parse_chap_summary_link(self, response):
    item = response.meta['item']

    # ... collect summary into the item field

    return self._dispatch_summary_request(item, response.meta['summary_links'])

def _dispatch_summary_request(self, item, links):
    try:
        next_link = links.pop()
    except IndexError:
        # no links left
        return item
    else:
        # TODO: it might happen that one request fails and to not lose the item
        # the request must have an errback callback to handle the failure and
        # resume the next summary request.
        return Request(next_link, meta={'item': item, 'summary_links': links},
                       callback=self.parse_chap_summary_link)

rawDescription: Multiple Data Under One Heading with Scrapy


code: [line.split(None, 5)[-2:] for line in file.readlines()]

rawDescription: extract a number and the string after it

description: Extract a number and the string after it


code:
try:
    post = SellPost.objects.get(slug=post_name_slug)
    context_dict['post'] = post
except SellPost.DoesNotExist:
    pass

rawDescription: Django: Querying to ImageField all images are being rendered


code:
tokens = (
    'NAME','NUMBER',
    )

literals = ['=','+','-','*','/', '(',')']

# Tokens

t_NAME    = r'[a-zA-Z_][a-zA-Z0-9_]*'

def t_NUMBER(t):
    r'\d+'
    t.value = int(t.value)
    return t

t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex
lex.lex(debug=1)

# Parsing rules

precedence = (
    ('left','+','-'),
    ('left','*','/'),
    ('right','UMINUS'),
    )

# dictionary of names
names = { }

def p_statement_assign(p):
    'statement : NAME "=" expression'
    names[p[1]] = p[3]

def p_statement_expr(p):
    'statement : expression'
    print(p[1])

def p_expression_binop(p):
    '''expression : expression '+' expression
                  | expression '-' expression
                  | expression '*' expression
                  | expression '/' expression'''
    if p[2] == '+'  : p[0] = p[1] + p[3]
    elif p[2] == '-': p[0] = p[1] - p[3]
    elif p[2] == '*': p[0] = p[1] * p[3]
    elif p[2] == '/': p[0] = p[1] / p[3]

def p_expression_uminus(p):
    "expression : '-' expression %prec UMINUS"
    p[0] = -p[2]

def p_expression_group(p):
    "expression : '(' expression ')'"
    p[0] = p[2]

def p_expression_number(p):
    "expression : NUMBER"
    p[0] = p[1]

def p_expression_name(p):
    "expression : NAME"
    try:
        p[0] = names[p[1]]
    except LookupError:
        print("Undefined name '%s'" % p[1])
        p[0] = 0

def p_error(p):
    if p:
        print("Syntax error at '%s'" % p.value)
    else:
        print("Syntax error at EOF")

import ply.yacc as yacc
yacc.yacc()

import logging
logging.basicConfig(
    level=logging.INFO,
    filename="parselog.txt"
)

while 1:
    try:
        s = raw_input('calc > ')
    except EOFError:
        break
    if not s: continue
    yacc.parse(s, debug=1)

rawDescription: Help me find an appropriate ruby/python parser generator


code:
from socketserver.tcp.server import TCPServer
from socketserver.tcp.server.forking import ForkingTCPServer
...

rawDescription: Python: one single module (file .py) for each class?


code:
import subprocess
subprocess.call(['osascript', '-e',
'tell app "System Events" to shut down'])

rawDescription: Computer Shut Off Python 3.4

description: Computer Shut Off Python 3.4


rawDescription: time.localtime() - how does it work? Brief questions on how to use it too - super easy stuff!

description: Time.localtime() - how does it work? Brief questions on how to use it too - super easy stuff!


code:
import collections

...
set_quals = set(qualsin) # This is set([0, 1, 2, 3, 4, 5])
counts = collections.Counter(qualsin) # This is Counter({3: 5, 2: 4, 0: 1, 1: 1, 4: 1, 5: 1}) which acts like a dictionary
for quals in set_quals:
    d = [quals, counts[quals]] # use the name from the set and the value from the Counter
    wrtr.writerow(d)

rawDescription: Iterate over a list that contain duplicate elements


rawDescription: Getting the row index for a 2D numPy array when multiple column values are known


rawDescription: Python 2.7, AT command response, strange HEX


rawDescription: Is there a way to use asyncio.Queue in multiple threads?


code:
locsOne = {1:[100], 2:[200], 3:[250]}
locsTwo = {}
for k1 in locsOne:
    v1 = locsOne[k1][0]
    locsTwo[k1] = {k2: abs(v1 - locsOne[k2][0]) for k2 in locsOne
                   if k1 != k2 and abs(v1 - locsOne[k2][0]) <= 450}
print(locsTwo)

rawDescription: Evaluating values within a dictionary for different keys


code:
import re
re.match(r'[a-zA-Z0-9-]+$', 'foo-bar')
re.match(r'[a-zA-Z0-9-]+$', 'Foo9bar')
re.match(r'[a-zA-Z0-9-]+$', 'Foo+bar')

rawDescription: How to ignore special characters except "-" in python3?

description: Ignore special characters except "-" in python3


rawDescription: max second element in tuples python

description: Max second element in tuples python


rawDescription: Put in a column this phrases

description: Put in a column this phrases


code:
def join(self, player):
    with self.condition:
        self.players.append(self)
        self.condition.notify()

rawDescription: Multiplayer Gaming via python

description: Multiplayer Gaming via python


code:
print(a)
2
print(b)
2

rawDescription: How to convert string to variable in python

description: Convert string to variable in python


code: myfunc("the string")

rawDescription: making "string".functions() functions python

description: Making "string".functions() functions python


code:
s
s.index = s.index.get_level_values(0).values + ' ' + s.index.get_level_values(1)
s.index

rawDescription: How to combine a hierarchical date and time index into a single datetime index in Pandas?

description: Combine a hierarchical date and time index into a single datetime index in Pandas


code:
from numpy import array
a = array([3,4,5,6])
b = array([0,1,0,1])
b==1

rawDescription: How to quickly grab specific indices from a numpy array?

description: Quickly grab specific indices from a numpy array


code:
def eval_polynomial(p,x):
    return sum((a*x**i for i,a in enumerate(p)))

def multiply_by_one_term(p, a, k):
    return [0]*k + [a*i for i in p]

rawDescription: How can I create functions that handle polynomials?

description: Create functions that handle polynomials


rawDescription: Assigning histogram bin to each data point


rawDescription: Choose list according to list name which is variable in python


code: array([ 10.,  12.,  14.]) # == np.linspace(smallest, largest, num_edges)

rawDescription: How to group by a range of values in pandas?

description: Group by a range of values in pandas


rawDescription: Fastest Way to Sum Individual Columns

description: Fastest Way to Sum Individual Columns


code:
#bsd socket polling
#I make all the relevant flags more C like to match the kqueue man pages
from select import kevent, kqueue
from select import KQ_EV_ADD as EV_ADD, KQ_EV_ONESHOT as EV_ONESHOT
from select import KQ_EV_EOF as EV_EOF

from .common import Client_Thread #a parent class who's implementation is irrelevant to the question, lol

class BSD_Client(Client_Thread):
    def __init__(self, *args):
        Client_Thread.__init__(self, *args)
        #Make a kqueue object for the thread
        kq = kqueue()
        #Make a one-shot kev for this kqueue for when the kill socket is
        #connected to. The connection is only made once, so why not tell
        #that to our kqueue? The default filter is EVFILT_READ, so we don't
        #need to specify that. The default flag is just EV_ADD.
        kill_kev = kevent(self.kill_fd, flags=EV_ADD|EV_ONESHOT)
        #using defaults for the client socket.
        client_kev = kevent(self.client_sock)
        #we only need to keep track of the kqueue's control func.
        #This also makes things prettier in the run func.
        self.control = kq.control
        #now, we add thel list of events we just made to our kqueue.
        #The first 0 means we want a list of at most 0 length in return.
        #the second 0 means we want no timeout (i.e. do this in a
        #non-blocking way.)
        self.control([client_kev, kill_kev], 0, 0)

    def run(self):
        while True:
            #Here we poll the kqueue object.
            #The empty list means we are adding no new events to the kqueue.
            #The one means we want a list of at most 1 element. Then None
            #Means we want block until an event is triggered.
            events = self.control([], 1, None)
            #If we have an event, and the event is for the kill socket
            #(meaning somebody made a connection to it), then we break the
            #loop and die.
            if events and events[0].ident == self.kill_fd:
                self.die()
                break
            #If all that is left is an EOF in our socket, then we break
            #the loop and die. Kqueues will keep returning a kevent
            #that has been read once, even when they are empty.
            if events and events[0].flags & EV_EOF:
                self.die()
                break
            #Finally, if we have an event that isn't for the kill socket and
            #does not have the EOF flag set, then there is work to do. If
            #the handle client function (defined in the parent class) returns
            #1, then we are done serving a page and we can die.
            if events and self.handle_client():
                self.die()
                break
        client.close()

rawDescription: Python kqueue with multiple events

description: Python kqueue with multiple events


rawDescription: Matplotlib Window Size, Title, etc

description: Matplotlib Window Size, Title, etc


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

x = np.linspace(0, 6 * np.pi, 300)
y = np.cos(x)

y1 = np.ma.masked_where(y > 0.7, y)

y2 = y.copy()
y2[y > 0.7] = np.nan

fig, axes = plt.subplots(nrows=3, sharex=True, sharey=True)
for ax, ydata in zip(axes, [y, y1, y2]):
    ax.plot(x, ydata)
    ax.axhline(0.7, color='red')

axes[0].set_title('Original')
axes[1].set_title('Masked Arrays')
axes[2].set_title("Using NaN's")

fig.tight_layout()

plt.show()

rawDescription: Draw / Create Scatterplots of datasets with NaN


code:
import csv
import networkx as nx

G = nx.DiGraph()
with open('network_nodes.csv') as f:
    node_list = csv.reader(f)
    for row in node_list:
        G.add_edge(row[0],row[1])
        G.node[row[0]]['value'] = float(row[2])
        G.node[row[1]]['value'] = float(row[3])

G.nodes(data=True) #print out

rawDescription: Plot nodes values in Networkx (Python)?

description: Plot nodes values in Networkx (Python)


code: {k: v for k, v in zip (keys, values) }

rawDescription: Obtain a dict from an array of keys and one array of values


code:
with open('path_to_file.json', 'a') as file:
    for item in data:
        line = json.dumps(item)
        file.write(line + '\n')
file.close()

rawDescription: How to cache in IPython Notebook?

description: Cache in IPython Notebook


rawDescription: Pandas: Convert DataFrame Column Values Into New Dataframe Indices and Columns


code: b = Button(root, image=play, command=on_button, relief=FLAT)

rawDescription: Button made of an image - Tkinter

description: Button made of an image - Tkinter


rawDescription: How to plot histogram of multiple lists?

description: Plot histogram of multiple lists


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    # maybe other here
    'app.context_processors.top_products',
)

rawDescription: How can I send data to a base template in Django?

description: Send data to a base template in Django


code:
a2 += [x + '_111' for x in a1 if all(x not in y for y in a2)]
a2

rawDescription: partial match between two arrays in python

description: Partial match between two arrays in python


code:
import sys
import pickle
import urllib2

request = urllib2.Request('http://ecal.forexpros.com/e_cal.php?duration=weekly')
response = urllib2.urlopen(request) # Make the request
# Grab everything before the dynabic double-click link
htmlString = response.read().split('<iframe src="http://fls.doubleclick')[0]

try:
    file = pickle.load( open( 'D:\\Download\\htmlString.p', 'r'))
    if pickle.load( open( 'D:\\Download\\htmlString.p', 'r')) == htmlString:
        print("Values haven't changed!")
        sys.exit(0)
    else:
        pickle.dump( htmlString, open( 'D:\\Download\\htmlString.p', "w" ) )
        print('Saving')
except IOError:
    pickle.dump( htmlString, open( 'D:\\Download\\htmlString.p', "w" ) )
    print('Created new file.')

rawDescription: How to check if the value on a website has changed

description: Check if the value on a website has changed


code: z = -f + g * h

rawDescription: product of two functions

description: Product of two functions


code: self.files = self.options.get('--files', NoneFound).split(',')

rawDescription: In Python, what is a minimal way of assigning a value to a variable depending on whether a dictionary contains a key?


code:
config = {
    'color' : 'red',
    'numbers' : [5, 8],
    re.compile( "^spam" ) : 'eggs'
}

rawDescription: How can I read Perl data structures from Python?

description: Read Perl data structures from Python


code:
import argparse
import sys
import C

def main(args):
    valB1 = args.param1B
    valB2 = args.param2B
    # do stuff
    return 0

if __name__ == '__main__':
    parser = C.create_parser()
    args = parser.parse_args()
    sys.exit(main(args))

rawDescription: Python: "importing" input arguments

description: Python: "importing" input arguments


code:
from operator import methodcaller
s = Series(date_range(Timestamp('now'), periods=2))
s
s.map(lambda x: x.strftime('%d-%m-%Y'))
s.map(methodcaller('strftime', '%d-%m-%Y'))

rawDescription: Get MM-DD-YYYY from pandas Timestamp

description: Get MM-DD-YYYY from pandas Timestamp


code:
from fuzzywuzzy import fuzz

max_ratio = 90

c = [i for i, v in enumerate(a)
     if not any(map(lambda x: fuzz.ratio(v, x)>=max_ratio, b))]

rawDescription: Subtract List B from List A, but keeping the List A index and using difflib string similarity


code: decorated = [(order[index], names[index]) for index in range(len(order))]

rawDescription: How can I sort list by second element without using lambda?

description: Sort list by second element without using lambda


code: from __future__ import print_function

rawDescription: Better method of writing stdout to file

description: Better method of writing stdout to file


code: newdic = {key:[i*1000 if key != 'x' 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


rawDescription: how to auto-update a Django page only when required?

description: Auto-update a Django page only when required


rawDescription: How to delete certain words from a variable or a list python

description: Delete certain words from a variable or a list python


rawDescription: How to transfer images to client using Python BaseHttpRequestHandler in Windows?

description: Transfer images to client using Python BaseHttpRequestHandler in Windows


code: self.circumference = 2 * pi * self.r

rawDescription: Using descriptor class to raise RuntimeError when user tries to change object's value


code:
def to_float(item):
    try:
        return float(item)
    except ValueError:
        return item

def formatter(lines):
    for line in lines:
        if not line.strip(): continue
        yield [to_float(item) for item in line.split()]

dct = {}
with open('data') as f:
    for row in formatter(f):
        dct[tuple(row[:3])] = row[5:7]

print(dct)

rawDescription: Using numpy loadtext

description: Using numpy loadtext


rawDescription: Remove HTML child inside its parent

description: Remove HTML child inside its parent


rawDescription: Index 2D numpy array by a 2D array of indices without loops


code: sorted(x) == sorted(y)

rawDescription: Determine if 2 lists have the same elements, regardless of order?


code:
final_distances,predecessors = ShortestPath(graph,start)
path = end
while end != start:
    end = predecessors[end]
    path = '%s->%s' % (end, path)
return path

rawDescription: Finding nodes between two nodes

description: Finding nodes between two nodes


code:
def int_to_bool_list(num):
    return [bool(num & (1<<n)) for n in range(4)]

rawDescription: Convert 4-bit integer into Boolean list

description: Convert 4-bit integer into Boolean list


code:
from __future__ import division
int(1/2)

rawDescription: Truncated versus floored division in Python


rawDescription: Matplotlib boxplot without outliers

description: Matplotlib boxplot without outliers


code:
cols = [c for c in df.columns if c not in {'Type', 'Val'}]
df2 = df.set_index(cols + ['Type']).unstack('Type')
df2
df2.columns = df2.columns.levels[1]
df2.columns.name = None
df2
df2.reset_index()

rawDescription: Pandas DataFrame: transforming frame using unique values of a column


code: d = {k: sum(d[k] for d in dicts) for k in dicts[0]}

rawDescription: Sum corresponding elements of multiple python dictionaries


code:
import itertools

def next_prev(f):
  values = itertools.imap(f, itertools.count())
  prv, nxt = itertools.tee(values)
  nxt.next()
  return itertools.izip(prv, nxt)

rawDescription: Recurrence sequence in Java / Python / Mathematica


rawDescription: Run a python script from another python script using IF __name__ == "__main__" statement


code: CDEFGHIJKL

rawDescription: Python mmap.move()

description: Python mmap.move()


rawDescription: How to not start the next day with datetime while adding a timedelta?

description: Not start the next day with datetime while adding a timedelta


rawDescription: What is purpose of meshgrid in Python?

description: What is purpose of meshgrid in Python


rawDescription: How I can do Google search, using Grab

description: How I can do Google search, using Grab


code:
page = 'one two one three\n' * 10
list(page)
page[0].split()
page[3].split()

rawDescription: Complex Python List Comprehension

description: Complex Python List Comprehension


code:
# inside views.py

import html_utils

def view_images(request):
    # ...

    images_html = [html_utils.image_to_html(image) for image in images]

    # ...

    return render_to_response('images_template.html', {
        'images_html': images_html
    }, context_instance=RequestContext(request))

rawDescription: How can I efficiently render an image in Django?

description: Efficiently render an image in Django


code:
def score_ngrams(self, score_fn):
    """Returns a sequence of (ngram, score) pairs ordered from highest to
    lowest score, as determined by the scoring function provided.
    """
    return sorted(self._score_ngrams(score_fn),
                  key=_itemgetter(1), reverse=True)

rawDescription: How to get PMI scores for trigrams with NLTK Collocations? python

description: Get PMI scores for trigrams with NLTK Collocations? python


code:
patt = re.compile("foo (?P<name>[0-9]+)?")
patt.search("blah foo 999 bar").groupdict()
patt.search("blah foo bar").groupdict()

rawDescription: Multiple same name group definitions or if system


code: abcdefghijklmnopqrst

rawDescription: python if a list is over 20 characters shorten it to 20 if it is less than 20 characters, add 0s to make it 20

description: Python if a list is over 20 characters shorten it to 20 if it is less than 20 characters, add 0s to make it 20


code: ['Split', 'this', 'text', 'in', 'seven', 'separate', 'words']

rawDescription: How to Tokenize A Text By Regular Expression In Python


code: y, x = np.mgrid[-1:1:self.width*1j, -1:1:self.height*1j]

rawDescription: Streamplot mgrid - Python

description: Streamplot mgrid - Python


code: data = ast.literal_eval(args.data)

rawDescription: Escaped string of bytes to bytestring

description: Escaped string of bytes to bytestring


rawDescription: Function to return a list of strings as a proper case


code:
s = '100022441\t@DavidBartonWB Guarding Constitution\n100022441\tRT@frankgaffney 2nd Amendment Guy.'
s.split('\t')

rawDescription: Python multiprocessing: Reading a file and updating a dictionary